title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
CI: builds docs on every commit
diff --git a/ci/build_docs.sh b/ci/build_docs.sh index a038304fe0f7a..5de9e158bcdb6 100755 --- a/ci/build_docs.sh +++ b/ci/build_docs.sh @@ -10,11 +10,11 @@ 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 [ "$?" != "0" ]; then +# echo "Skipping doc build, none were modified" +# # nope, skip docs build +# exit 0 +# fi if [ "$DOC" ]; then
As I refer to the dev docs on PRs, let's build them for each commit temporarily. Will clean it up when I update https://github.com/pandas-dev/pandas/pull/19952
https://api.github.com/repos/pandas-dev/pandas/pulls/20343
2018-03-14T12:48:07Z
2018-03-14T12:48:30Z
2018-03-14T12:48:30Z
2018-04-09T13:15:07Z
Preliminary format refactor
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index eaab17513aaf4..687705640a467 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -92,8 +92,8 @@ import pandas.core.common as com import pandas.core.nanops as nanops import pandas.core.ops as ops -import pandas.io.formats.format as fmt import pandas.io.formats.console as console +import pandas.io.formats.format as fmt from pandas.io.formats.printing import pprint_thing import pandas.plotting._core as gfx @@ -1695,18 +1695,19 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, else: tupleize_cols = False - formatter = fmt.CSVFormatter(self, path_or_buf, - line_terminator=line_terminator, sep=sep, - encoding=encoding, - compression=compression, quoting=quoting, - na_rep=na_rep, float_format=float_format, - cols=columns, header=header, index=index, - index_label=index_label, mode=mode, - chunksize=chunksize, quotechar=quotechar, - tupleize_cols=tupleize_cols, - date_format=date_format, - doublequote=doublequote, - escapechar=escapechar, decimal=decimal) + from pandas.io.formats.csvs import CSVFormatter + formatter = CSVFormatter(self, path_or_buf, + line_terminator=line_terminator, sep=sep, + encoding=encoding, + compression=compression, quoting=quoting, + na_rep=na_rep, float_format=float_format, + cols=columns, header=header, index=index, + index_label=index_label, mode=mode, + chunksize=chunksize, quotechar=quotechar, + tupleize_cols=tupleize_cols, + date_format=date_format, + doublequote=doublequote, + escapechar=escapechar, decimal=decimal) formatter.save() if path_or_buf is None: @@ -1997,7 +1998,6 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None, - If False, never show counts. """ - from pandas.io.formats.format import _put_lines if buf is None: # pragma: no cover buf = sys.stdout @@ -2009,7 +2009,7 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None, if len(self.columns) == 0: lines.append('Empty %s' % type(self).__name__) - _put_lines(buf, lines) + fmt.buffer_put_lines(buf, lines) return cols = self.columns @@ -2096,7 +2096,7 @@ def _sizeof_fmt(num, size_qualifier): mem_usage = self.memory_usage(index=True, deep=deep).sum() lines.append("memory usage: %s\n" % _sizeof_fmt(mem_usage, size_qualifier)) - _put_lines(buf, lines) + fmt.buffer_put_lines(buf, lines) def memory_usage(self, index=True, deep=False): """Memory usage of DataFrame columns. diff --git a/pandas/io/formats/common.py b/pandas/io/formats/common.py deleted file mode 100644 index 5cfdf58403cc0..0000000000000 --- a/pandas/io/formats/common.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Common helper methods used in different submodules of pandas.io.formats -""" - - -def get_level_lengths(levels, sentinel=''): - """For each index in each level the function returns lengths of indexes. - - Parameters - ---------- - levels : list of lists - List of values on for level. - sentinel : string, optional - Value which states that no new index starts on there. - - Returns - ---------- - Returns list of maps. For each level returns map of indexes (key is index - in row and value is length of index). - """ - if len(levels) == 0: - return [] - - control = [True for x in levels[0]] - - result = [] - for level in levels: - last_index = 0 - - lengths = {} - for i, key in enumerate(level): - if control[i] and key == sentinel: - pass - else: - control[i] = False - lengths[last_index] = i - last_index - last_index = i - - lengths[last_index] = len(level) - last_index - - result.append(lengths) - - return result diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py new file mode 100644 index 0000000000000..4e2021bcba72b --- /dev/null +++ b/pandas/io/formats/csvs.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +""" +Module for formatting output data into CSV files. +""" + +from __future__ import print_function + +import csv as csvlib +import numpy as np + +from pandas.core.dtypes.missing import notna +from pandas.core.index import Index, MultiIndex +from pandas import compat +from pandas.compat import (StringIO, range, zip) + +from pandas.io.common import (_get_handle, UnicodeWriter, _expand_user, + _stringify_path) +from pandas._libs import writers as libwriters +from pandas.core.indexes.datetimes import DatetimeIndex +from pandas.core.indexes.period import PeriodIndex + + +class CSVFormatter(object): + + def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', + float_format=None, cols=None, header=True, index=True, + index_label=None, mode='w', nanRep=None, encoding=None, + compression=None, quoting=None, line_terminator='\n', + chunksize=None, tupleize_cols=False, quotechar='"', + date_format=None, doublequote=True, escapechar=None, + decimal='.'): + + self.obj = obj + + if path_or_buf is None: + path_or_buf = StringIO() + + self.path_or_buf = _expand_user(_stringify_path(path_or_buf)) + self.sep = sep + self.na_rep = na_rep + self.float_format = float_format + self.decimal = decimal + + self.header = header + self.index = index + self.index_label = index_label + self.mode = mode + self.encoding = encoding + self.compression = compression + + if quoting is None: + quoting = csvlib.QUOTE_MINIMAL + self.quoting = quoting + + if quoting == csvlib.QUOTE_NONE: + # prevents crash in _csv + quotechar = None + self.quotechar = quotechar + + self.doublequote = doublequote + self.escapechar = escapechar + + self.line_terminator = line_terminator + + self.date_format = date_format + + self.tupleize_cols = tupleize_cols + self.has_mi_columns = (isinstance(obj.columns, MultiIndex) and + not self.tupleize_cols) + + # validate mi options + if self.has_mi_columns: + if cols is not None: + raise TypeError("cannot specify cols with a MultiIndex on the " + "columns") + + if cols is not None: + if isinstance(cols, Index): + cols = cols.to_native_types(na_rep=na_rep, + float_format=float_format, + date_format=date_format, + quoting=self.quoting) + else: + cols = list(cols) + self.obj = self.obj.loc[:, cols] + + # update columns to include possible multiplicity of dupes + # and make sure sure cols is just a list of labels + cols = self.obj.columns + if isinstance(cols, Index): + cols = cols.to_native_types(na_rep=na_rep, + float_format=float_format, + date_format=date_format, + quoting=self.quoting) + else: + cols = list(cols) + + # save it + self.cols = cols + + # preallocate data 2d list + self.blocks = self.obj._data.blocks + ncols = sum(b.shape[0] for b in self.blocks) + self.data = [None] * ncols + + if chunksize is None: + chunksize = (100000 // (len(self.cols) or 1)) or 1 + self.chunksize = int(chunksize) + + self.data_index = obj.index + if (isinstance(self.data_index, (DatetimeIndex, PeriodIndex)) and + date_format is not None): + self.data_index = Index([x.strftime(date_format) if notna(x) else + '' for x in self.data_index]) + + self.nlevels = getattr(self.data_index, 'nlevels', 1) + if not index: + self.nlevels = 0 + + def save(self): + # create the writer & save + if self.encoding is None: + if compat.PY2: + encoding = 'ascii' + else: + encoding = 'utf-8' + else: + encoding = self.encoding + + if hasattr(self.path_or_buf, 'write'): + f = self.path_or_buf + close = False + else: + f, handles = _get_handle(self.path_or_buf, self.mode, + encoding=encoding, + compression=self.compression) + close = True + + try: + writer_kwargs = dict(lineterminator=self.line_terminator, + delimiter=self.sep, quoting=self.quoting, + doublequote=self.doublequote, + escapechar=self.escapechar, + quotechar=self.quotechar) + if encoding == 'ascii': + self.writer = csvlib.writer(f, **writer_kwargs) + else: + writer_kwargs['encoding'] = encoding + self.writer = UnicodeWriter(f, **writer_kwargs) + + self._save() + + finally: + if close: + f.close() + + def _save_header(self): + + writer = self.writer + obj = self.obj + index_label = self.index_label + cols = self.cols + has_mi_columns = self.has_mi_columns + header = self.header + encoded_labels = [] + + has_aliases = isinstance(header, (tuple, list, np.ndarray, Index)) + if not (has_aliases or self.header): + return + if has_aliases: + if len(header) != len(cols): + raise ValueError(('Writing {ncols} cols but got {nalias} ' + 'aliases'.format(ncols=len(cols), + nalias=len(header)))) + else: + write_cols = header + else: + write_cols = cols + + if self.index: + # should write something for index label + if index_label is not False: + if index_label is None: + if isinstance(obj.index, MultiIndex): + index_label = [] + for i, name in enumerate(obj.index.names): + if name is None: + name = '' + index_label.append(name) + else: + index_label = obj.index.name + if index_label is None: + index_label = [''] + else: + index_label = [index_label] + elif not isinstance(index_label, + (list, tuple, np.ndarray, Index)): + # given a string for a DF with Index + index_label = [index_label] + + encoded_labels = list(index_label) + else: + encoded_labels = [] + + if not has_mi_columns or has_aliases: + encoded_labels += list(write_cols) + writer.writerow(encoded_labels) + else: + # write out the mi + columns = obj.columns + + # write out the names for each level, then ALL of the values for + # each level + for i in range(columns.nlevels): + + # we need at least 1 index column to write our col names + col_line = [] + if self.index: + + # name is the first column + col_line.append(columns.names[i]) + + if isinstance(index_label, list) and len(index_label) > 1: + col_line.extend([''] * (len(index_label) - 1)) + + col_line.extend(columns._get_level_values(i)) + + writer.writerow(col_line) + + # Write out the index line if it's not empty. + # Otherwise, we will print out an extraneous + # blank line between the mi and the data rows. + if encoded_labels and set(encoded_labels) != set(['']): + encoded_labels.extend([''] * len(columns)) + writer.writerow(encoded_labels) + + def _save(self): + + self._save_header() + + nrows = len(self.data_index) + + # write in chunksize bites + chunksize = self.chunksize + chunks = int(nrows / chunksize) + 1 + + for i in range(chunks): + start_i = i * chunksize + end_i = min((i + 1) * chunksize, nrows) + if start_i >= end_i: + break + + self._save_chunk(start_i, end_i) + + def _save_chunk(self, start_i, end_i): + + data_index = self.data_index + + # create the data for a chunk + slicer = slice(start_i, end_i) + for i in range(len(self.blocks)): + b = self.blocks[i] + d = b.to_native_types(slicer=slicer, na_rep=self.na_rep, + float_format=self.float_format, + decimal=self.decimal, + date_format=self.date_format, + quoting=self.quoting) + + for col_loc, col in zip(b.mgr_locs, d): + # self.data is a preallocated list + self.data[col_loc] = col + + ix = data_index.to_native_types(slicer=slicer, na_rep=self.na_rep, + float_format=self.float_format, + decimal=self.decimal, + date_format=self.date_format, + quoting=self.quoting) + + libwriters.write_csv_rows(self.data, ix, self.nlevels, + self.cols, self.writer) diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 81e8881f3f06b..76ffd41f93090 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -14,7 +14,7 @@ from pandas.core.dtypes.common import is_float, is_scalar from pandas.core.dtypes import missing from pandas import Index, MultiIndex, PeriodIndex -from pandas.io.formats.common import get_level_lengths +from pandas.io.formats.format import get_level_lengths class ExcelCell(object): diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 50b4f11634b78..1731dbb3ac68d 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -5,11 +5,8 @@ """ from __future__ import print_function -from distutils.version import LooseVersion # pylint: disable=W0141 -from textwrap import dedent - from pandas.core.dtypes.missing import isna, notna from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -30,15 +27,14 @@ import pandas.core.common as com from pandas.core.index import Index, MultiIndex, _ensure_index from pandas import compat -from pandas.compat import (StringIO, lzip, range, map, zip, u, - OrderedDict, unichr) +from pandas.compat import (StringIO, lzip, map, zip, u) + from pandas.io.formats.terminal import get_terminal_size from pandas.core.config import get_option, set_option -from pandas.io.common import (_get_handle, UnicodeWriter, _expand_user, - _stringify_path) +from pandas.io.common import (_expand_user, _stringify_path) from pandas.io.formats.printing import adjoin, justify, pprint_thing -from pandas.io.formats.common import get_level_lengths -from pandas._libs import lib, writers as libwriters +from pandas._libs import lib + from pandas._libs.tslib import (iNaT, Timestamp, Timedelta, format_array_from_datetime) from pandas.core.indexes.datetimes import DatetimeIndex @@ -46,7 +42,6 @@ import pandas as pd import numpy as np -import csv from functools import partial common_docstring = """ @@ -354,6 +349,7 @@ def _get_adjustment(): class TableFormatter(object): + is_truncated = False show_dimensions = None @@ -698,6 +694,7 @@ def to_latex(self, column_format=None, longtable=False, encoding=None, Render a DataFrame to a LaTeX tabular/longtable environment output. """ + from pandas.io.formats.latex import LatexFormatter latex_renderer = LatexFormatter(self, column_format=column_format, longtable=longtable, multicolumn=multicolumn, @@ -742,6 +739,7 @@ def to_html(self, classes=None, notebook=False, border=None): .. versionadded:: 0.19.0 """ + from pandas.io.formats.html import HTMLFormatter html_renderer = HTMLFormatter(self, classes=classes, max_rows=self.max_rows, max_cols=self.max_cols, @@ -851,964 +849,6 @@ def _get_column_name_list(self): names.append('' if columns.name is None else columns.name) return names - -class LatexFormatter(TableFormatter): - """ Used to render a DataFrame to a LaTeX tabular/longtable environment - output. - - Parameters - ---------- - formatter : `DataFrameFormatter` - column_format : str, default None - The columns format as specified in `LaTeX table format - <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl' for 3 columns - longtable : boolean, default False - Use a longtable environment instead of tabular. - - See also - -------- - HTMLFormatter - """ - - def __init__(self, formatter, column_format=None, longtable=False, - multicolumn=False, multicolumn_format=None, multirow=False): - self.fmt = formatter - self.frame = self.fmt.frame - self.bold_rows = self.fmt.kwds.get('bold_rows', False) - self.column_format = column_format - self.longtable = longtable - self.multicolumn = multicolumn - self.multicolumn_format = multicolumn_format - self.multirow = multirow - - def write_result(self, buf): - """ - Render a DataFrame to a LaTeX tabular/longtable environment output. - """ - - # string representation of the columns - if len(self.frame.columns) == 0 or len(self.frame.index) == 0: - info_line = (u('Empty {name}\nColumns: {col}\nIndex: {idx}') - .format(name=type(self.frame).__name__, - col=self.frame.columns, - idx=self.frame.index)) - strcols = [[info_line]] - else: - strcols = self.fmt._to_str_columns() - - def get_col_type(dtype): - if issubclass(dtype.type, np.number): - return 'r' - else: - return 'l' - - # reestablish the MultiIndex that has been joined by _to_str_column - if self.fmt.index and isinstance(self.frame.index, MultiIndex): - clevels = self.frame.columns.nlevels - strcols.pop(0) - name = any(self.frame.index.names) - cname = any(self.frame.columns.names) - lastcol = self.frame.index.nlevels - 1 - previous_lev3 = None - for i, lev in enumerate(self.frame.index.levels): - lev2 = lev.format() - blank = ' ' * len(lev2[0]) - # display column names in last index-column - if cname and i == lastcol: - lev3 = [x if x else '{}' for x in self.frame.columns.names] - else: - lev3 = [blank] * clevels - if name: - lev3.append(lev.name) - current_idx_val = None - for level_idx in self.frame.index.labels[i]: - if ((previous_lev3 is None or - previous_lev3[len(lev3)].isspace()) and - lev2[level_idx] == current_idx_val): - # same index as above row and left index was the same - lev3.append(blank) - else: - # different value than above or left index different - lev3.append(lev2[level_idx]) - current_idx_val = lev2[level_idx] - strcols.insert(i, lev3) - previous_lev3 = lev3 - - column_format = self.column_format - if column_format is None: - dtypes = self.frame.dtypes._values - column_format = ''.join(map(get_col_type, dtypes)) - if self.fmt.index: - index_format = 'l' * self.frame.index.nlevels - column_format = index_format + column_format - elif not isinstance(column_format, - compat.string_types): # pragma: no cover - raise AssertionError('column_format must be str or unicode, ' - 'not {typ}'.format(typ=type(column_format))) - - if not self.longtable: - buf.write('\\begin{{tabular}}{{{fmt}}}\n' - .format(fmt=column_format)) - buf.write('\\toprule\n') - else: - buf.write('\\begin{{longtable}}{{{fmt}}}\n' - .format(fmt=column_format)) - buf.write('\\toprule\n') - - ilevels = self.frame.index.nlevels - clevels = self.frame.columns.nlevels - nlevels = clevels - if any(self.frame.index.names): - nlevels += 1 - strrows = list(zip(*strcols)) - self.clinebuf = [] - - for i, row in enumerate(strrows): - if i == nlevels and self.fmt.header: - buf.write('\\midrule\n') # End of header - if self.longtable: - buf.write('\\endhead\n') - buf.write('\\midrule\n') - buf.write('\\multicolumn{{{n}}}{{r}}{{{{Continued on next ' - 'page}}}} \\\\\n'.format(n=len(row))) - buf.write('\\midrule\n') - buf.write('\\endfoot\n\n') - buf.write('\\bottomrule\n') - buf.write('\\endlastfoot\n') - if self.fmt.kwds.get('escape', True): - # escape backslashes first - crow = [(x.replace('\\', '\\textbackslash').replace('_', '\\_') - .replace('%', '\\%').replace('$', '\\$') - .replace('#', '\\#').replace('{', '\\{') - .replace('}', '\\}').replace('~', '\\textasciitilde') - .replace('^', '\\textasciicircum').replace('&', '\\&') - if (x and x != '{}') else '{}') for x in row] - else: - crow = [x if x else '{}' for x in row] - if self.bold_rows and self.fmt.index: - # bold row labels - crow = ['\\textbf{{{x}}}'.format(x=x) - if j < ilevels and x.strip() not in ['', '{}'] else x - for j, x in enumerate(crow)] - if i < clevels and self.fmt.header and self.multicolumn: - # sum up columns to multicolumns - crow = self._format_multicolumn(crow, ilevels) - if (i >= nlevels and self.fmt.index and self.multirow and - ilevels > 1): - # sum up rows to multirows - crow = self._format_multirow(crow, ilevels, i, strrows) - buf.write(' & '.join(crow)) - buf.write(' \\\\\n') - if self.multirow and i < len(strrows) - 1: - self._print_cline(buf, i, len(strcols)) - - if not self.longtable: - buf.write('\\bottomrule\n') - buf.write('\\end{tabular}\n') - else: - buf.write('\\end{longtable}\n') - - def _format_multicolumn(self, row, ilevels): - r""" - Combine columns belonging to a group to a single multicolumn entry - according to self.multicolumn_format - - e.g.: - a & & & b & c & - will become - \multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c} - """ - row2 = list(row[:ilevels]) - ncol = 1 - coltext = '' - - def append_col(): - # write multicolumn if needed - if ncol > 1: - row2.append('\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}' - .format(ncol=ncol, fmt=self.multicolumn_format, - txt=coltext.strip())) - # don't modify where not needed - else: - row2.append(coltext) - for c in row[ilevels:]: - # if next col has text, write the previous - if c.strip(): - if coltext: - append_col() - coltext = c - ncol = 1 - # if not, add it to the previous multicolumn - else: - ncol += 1 - # write last column name - if coltext: - append_col() - return row2 - - def _format_multirow(self, row, ilevels, i, rows): - r""" - Check following rows, whether row should be a multirow - - e.g.: becomes: - a & 0 & \multirow{2}{*}{a} & 0 & - & 1 & & 1 & - b & 0 & \cline{1-2} - b & 0 & - """ - for j in range(ilevels): - if row[j].strip(): - nrow = 1 - for r in rows[i + 1:]: - if not r[j].strip(): - nrow += 1 - else: - break - if nrow > 1: - # overwrite non-multirow entry - row[j] = '\\multirow{{{nrow:d}}}{{*}}{{{row:s}}}'.format( - nrow=nrow, row=row[j].strip()) - # save when to end the current block with \cline - self.clinebuf.append([i + nrow - 1, j + 1]) - return row - - def _print_cline(self, buf, i, icol): - """ - Print clines after multirow-blocks are finished - """ - for cl in self.clinebuf: - if cl[0] == i: - buf.write('\\cline{{{cl:d}-{icol:d}}}\n' - .format(cl=cl[1], icol=icol)) - # remove entries that have been written to buffer - self.clinebuf = [x for x in self.clinebuf if x[0] != i] - - -class HTMLFormatter(TableFormatter): - - indent_delta = 2 - - def __init__(self, formatter, classes=None, max_rows=None, max_cols=None, - notebook=False, border=None, table_id=None): - self.fmt = formatter - self.classes = classes - - self.frame = self.fmt.frame - self.columns = self.fmt.tr_frame.columns - self.elements = [] - self.bold_rows = self.fmt.kwds.get('bold_rows', False) - self.escape = self.fmt.kwds.get('escape', True) - - self.max_rows = max_rows or len(self.fmt.frame) - self.max_cols = max_cols or len(self.fmt.columns) - self.show_dimensions = self.fmt.show_dimensions - self.is_truncated = (self.max_rows < len(self.fmt.frame) or - self.max_cols < len(self.fmt.columns)) - self.notebook = notebook - if border is None: - border = get_option('display.html.border') - self.border = border - self.table_id = table_id - - def write(self, s, indent=0): - rs = pprint_thing(s) - self.elements.append(' ' * indent + rs) - - def write_th(self, s, indent=0, tags=None): - if self.fmt.col_space is not None and self.fmt.col_space > 0: - tags = (tags or "") - tags += ('style="min-width: {colspace};"' - .format(colspace=self.fmt.col_space)) - - return self._write_cell(s, kind='th', indent=indent, tags=tags) - - def write_td(self, s, indent=0, tags=None): - return self._write_cell(s, kind='td', indent=indent, tags=tags) - - def _write_cell(self, s, kind='td', indent=0, tags=None): - if tags is not None: - start_tag = '<{kind} {tags}>'.format(kind=kind, tags=tags) - else: - start_tag = '<{kind}>'.format(kind=kind) - - if self.escape: - # escape & first to prevent double escaping of & - esc = OrderedDict([('&', r'&amp;'), ('<', r'&lt;'), - ('>', r'&gt;')]) - else: - esc = {} - rs = pprint_thing(s, escape_chars=esc).strip() - self.write(u'{start}{rs}</{kind}>' - .format(start=start_tag, rs=rs, kind=kind), indent) - - def write_tr(self, line, indent=0, indent_delta=4, header=False, - align=None, tags=None, nindex_levels=0): - if tags is None: - tags = {} - - if align is None: - self.write('<tr>', indent) - else: - self.write('<tr style="text-align: {align};">' - .format(align=align), indent) - indent += indent_delta - - for i, s in enumerate(line): - val_tag = tags.get(i, None) - if header or (self.bold_rows and i < nindex_levels): - self.write_th(s, indent, tags=val_tag) - else: - self.write_td(s, indent, tags=val_tag) - - indent -= indent_delta - self.write('</tr>', indent) - - def write_style(self): - # We use the "scoped" attribute here so that the desired - # style properties for the data frame are not then applied - # throughout the entire notebook. - template_first = """\ - <style scoped>""" - template_last = """\ - </style>""" - template_select = """\ - .dataframe %s { - %s: %s; - }""" - element_props = [('tbody tr th:only-of-type', - 'vertical-align', - 'middle'), - ('tbody tr th', - 'vertical-align', - 'top')] - if isinstance(self.columns, MultiIndex): - element_props.append(('thead tr th', - 'text-align', - 'left')) - if all((self.fmt.has_index_names, - self.fmt.index, - self.fmt.show_index_names)): - element_props.append(('thead tr:last-of-type th', - 'text-align', - 'right')) - else: - element_props.append(('thead th', - 'text-align', - 'right')) - template_mid = '\n\n'.join(map(lambda t: template_select % t, - element_props)) - template = dedent('\n'.join((template_first, - template_mid, - template_last))) - if self.notebook: - self.write(template) - - def write_result(self, buf): - indent = 0 - id_section = "" - frame = self.frame - - _classes = ['dataframe'] # Default class. - use_mathjax = get_option("display.html.use_mathjax") - if not use_mathjax: - _classes.append('tex2jax_ignore') - if self.classes is not None: - if isinstance(self.classes, str): - self.classes = self.classes.split() - if not isinstance(self.classes, (list, tuple)): - raise AssertionError('classes must be list or tuple, not {typ}' - .format(typ=type(self.classes))) - _classes.extend(self.classes) - - if self.notebook: - div_style = '' - try: - import IPython - if IPython.__version__ < LooseVersion('3.0.0'): - div_style = ' style="max-width:1500px;overflow:auto;"' - except (ImportError, AttributeError): - pass - - self.write('<div{style}>'.format(style=div_style)) - - self.write_style() - - if self.table_id is not None: - id_section = ' id="{table_id}"'.format(table_id=self.table_id) - self.write('<table border="{border}" class="{cls}"{id_section}>' - .format(border=self.border, cls=' '.join(_classes), - id_section=id_section), indent) - - indent += self.indent_delta - indent = self._write_header(indent) - indent = self._write_body(indent) - - self.write('</table>', indent) - if self.should_show_dimensions: - by = chr(215) if compat.PY3 else unichr(215) # × - self.write(u('<p>{rows} rows {by} {cols} columns</p>') - .format(rows=len(frame), - by=by, - cols=len(frame.columns))) - - if self.notebook: - self.write('</div>') - - _put_lines(buf, self.elements) - - def _write_header(self, indent): - truncate_h = self.fmt.truncate_h - row_levels = self.frame.index.nlevels - if not self.fmt.header: - # write nothing - return indent - - def _column_header(): - if self.fmt.index: - row = [''] * (self.frame.index.nlevels - 1) - else: - row = [] - - if isinstance(self.columns, MultiIndex): - if self.fmt.has_column_names and self.fmt.index: - row.append(single_column_table(self.columns.names)) - else: - row.append('') - style = "text-align: {just};".format(just=self.fmt.justify) - row.extend([single_column_table(c, self.fmt.justify, style) - for c in self.columns]) - else: - if self.fmt.index: - row.append(self.columns.name or '') - row.extend(self.columns) - return row - - self.write('<thead>', indent) - row = [] - - indent += self.indent_delta - - if isinstance(self.columns, MultiIndex): - template = 'colspan="{span:d}" halign="left"' - - if self.fmt.sparsify: - # GH3547 - sentinel = com.sentinel_factory() - else: - sentinel = None - levels = self.columns.format(sparsify=sentinel, adjoin=False, - names=False) - level_lengths = get_level_lengths(levels, sentinel) - inner_lvl = len(level_lengths) - 1 - for lnum, (records, values) in enumerate(zip(level_lengths, - levels)): - if truncate_h: - # modify the header lines - ins_col = self.fmt.tr_col_num - if self.fmt.sparsify: - recs_new = {} - # Increment tags after ... col. - for tag, span in list(records.items()): - if tag >= ins_col: - recs_new[tag + 1] = span - elif tag + span > ins_col: - recs_new[tag] = span + 1 - if lnum == inner_lvl: - values = (values[:ins_col] + (u('...'),) + - values[ins_col:]) - else: - # sparse col headers do not receive a ... - values = (values[:ins_col] + - (values[ins_col - 1], ) + - values[ins_col:]) - else: - recs_new[tag] = span - # if ins_col lies between tags, all col headers - # get ... - if tag + span == ins_col: - recs_new[ins_col] = 1 - values = (values[:ins_col] + (u('...'),) + - values[ins_col:]) - records = recs_new - inner_lvl = len(level_lengths) - 1 - if lnum == inner_lvl: - records[ins_col] = 1 - else: - recs_new = {} - for tag, span in list(records.items()): - if tag >= ins_col: - recs_new[tag + 1] = span - else: - recs_new[tag] = span - recs_new[ins_col] = 1 - records = recs_new - values = (values[:ins_col] + [u('...')] + - values[ins_col:]) - - name = self.columns.names[lnum] - row = [''] * (row_levels - 1) + ['' if name is None else - pprint_thing(name)] - - if row == [""] and self.fmt.index is False: - row = [] - - tags = {} - j = len(row) - for i, v in enumerate(values): - if i in records: - if records[i] > 1: - tags[j] = template.format(span=records[i]) - else: - continue - j += 1 - row.append(v) - self.write_tr(row, indent, self.indent_delta, tags=tags, - header=True) - else: - col_row = _column_header() - align = self.fmt.justify - - if truncate_h: - ins_col = row_levels + self.fmt.tr_col_num - col_row.insert(ins_col, '...') - - self.write_tr(col_row, indent, self.indent_delta, header=True, - align=align) - - if all((self.fmt.has_index_names, - self.fmt.index, - self.fmt.show_index_names)): - row = ([x if x is not None else '' - for x in self.frame.index.names] + - [''] * min(len(self.columns), self.max_cols)) - if truncate_h: - ins_col = row_levels + self.fmt.tr_col_num - row.insert(ins_col, '') - self.write_tr(row, indent, self.indent_delta, header=True) - - indent -= self.indent_delta - self.write('</thead>', indent) - - return indent - - def _write_body(self, indent): - self.write('<tbody>', indent) - indent += self.indent_delta - - fmt_values = {} - for i in range(min(len(self.columns), self.max_cols)): - fmt_values[i] = self.fmt._format_col(i) - - # write values - if self.fmt.index: - if isinstance(self.frame.index, MultiIndex): - self._write_hierarchical_rows(fmt_values, indent) - else: - self._write_regular_rows(fmt_values, indent) - else: - for i in range(min(len(self.frame), self.max_rows)): - row = [fmt_values[j][i] for j in range(len(self.columns))] - self.write_tr(row, indent, self.indent_delta, tags=None) - - indent -= self.indent_delta - self.write('</tbody>', indent) - indent -= self.indent_delta - - return indent - - def _write_regular_rows(self, fmt_values, indent): - truncate_h = self.fmt.truncate_h - truncate_v = self.fmt.truncate_v - - ncols = len(self.fmt.tr_frame.columns) - nrows = len(self.fmt.tr_frame) - fmt = self.fmt._get_formatter('__index__') - if fmt is not None: - index_values = self.fmt.tr_frame.index.map(fmt) - else: - index_values = self.fmt.tr_frame.index.format() - - row = [] - for i in range(nrows): - - if truncate_v and i == (self.fmt.tr_row_num): - str_sep_row = ['...' for ele in row] - self.write_tr(str_sep_row, indent, self.indent_delta, - tags=None, nindex_levels=1) - - row = [] - row.append(index_values[i]) - row.extend(fmt_values[j][i] for j in range(ncols)) - - if truncate_h: - dot_col_ix = self.fmt.tr_col_num + 1 - row.insert(dot_col_ix, '...') - self.write_tr(row, indent, self.indent_delta, tags=None, - nindex_levels=1) - - def _write_hierarchical_rows(self, fmt_values, indent): - template = 'rowspan="{span}" valign="top"' - - truncate_h = self.fmt.truncate_h - truncate_v = self.fmt.truncate_v - frame = self.fmt.tr_frame - ncols = len(frame.columns) - nrows = len(frame) - row_levels = self.frame.index.nlevels - - idx_values = frame.index.format(sparsify=False, adjoin=False, - names=False) - idx_values = lzip(*idx_values) - - if self.fmt.sparsify: - # GH3547 - sentinel = com.sentinel_factory() - levels = frame.index.format(sparsify=sentinel, adjoin=False, - names=False) - - level_lengths = get_level_lengths(levels, sentinel) - inner_lvl = len(level_lengths) - 1 - if truncate_v: - # Insert ... row and adjust idx_values and - # level_lengths to take this into account. - ins_row = self.fmt.tr_row_num - inserted = False - for lnum, records in enumerate(level_lengths): - rec_new = {} - for tag, span in list(records.items()): - if tag >= ins_row: - rec_new[tag + 1] = span - elif tag + span > ins_row: - rec_new[tag] = span + 1 - - # GH 14882 - Make sure insertion done once - if not inserted: - dot_row = list(idx_values[ins_row - 1]) - dot_row[-1] = u('...') - idx_values.insert(ins_row, tuple(dot_row)) - inserted = True - else: - dot_row = list(idx_values[ins_row]) - dot_row[inner_lvl - lnum] = u('...') - idx_values[ins_row] = tuple(dot_row) - else: - rec_new[tag] = span - # If ins_row lies between tags, all cols idx cols - # receive ... - if tag + span == ins_row: - rec_new[ins_row] = 1 - if lnum == 0: - idx_values.insert(ins_row, tuple( - [u('...')] * len(level_lengths))) - - # GH 14882 - Place ... in correct level - elif inserted: - dot_row = list(idx_values[ins_row]) - dot_row[inner_lvl - lnum] = u('...') - idx_values[ins_row] = tuple(dot_row) - level_lengths[lnum] = rec_new - - level_lengths[inner_lvl][ins_row] = 1 - for ix_col in range(len(fmt_values)): - fmt_values[ix_col].insert(ins_row, '...') - nrows += 1 - - for i in range(nrows): - row = [] - tags = {} - - sparse_offset = 0 - j = 0 - for records, v in zip(level_lengths, idx_values[i]): - if i in records: - if records[i] > 1: - tags[j] = template.format(span=records[i]) - else: - sparse_offset += 1 - continue - - j += 1 - row.append(v) - - row.extend(fmt_values[j][i] for j in range(ncols)) - if truncate_h: - row.insert(row_levels - sparse_offset + - self.fmt.tr_col_num, '...') - self.write_tr(row, indent, self.indent_delta, tags=tags, - nindex_levels=len(levels) - sparse_offset) - else: - for i in range(len(frame)): - idx_values = list(zip(*frame.index.format( - sparsify=False, adjoin=False, names=False))) - row = [] - row.extend(idx_values[i]) - row.extend(fmt_values[j][i] for j in range(ncols)) - if truncate_h: - row.insert(row_levels + self.fmt.tr_col_num, '...') - self.write_tr(row, indent, self.indent_delta, tags=None, - nindex_levels=frame.index.nlevels) - - -class CSVFormatter(object): - - def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', - float_format=None, cols=None, header=True, index=True, - index_label=None, mode='w', nanRep=None, encoding=None, - compression=None, quoting=None, line_terminator='\n', - chunksize=None, tupleize_cols=False, quotechar='"', - date_format=None, doublequote=True, escapechar=None, - decimal='.'): - - self.obj = obj - - if path_or_buf is None: - path_or_buf = StringIO() - - self.path_or_buf = _expand_user(_stringify_path(path_or_buf)) - self.sep = sep - self.na_rep = na_rep - self.float_format = float_format - self.decimal = decimal - - self.header = header - self.index = index - self.index_label = index_label - self.mode = mode - self.encoding = encoding - self.compression = compression - - if quoting is None: - quoting = csv.QUOTE_MINIMAL - self.quoting = quoting - - if quoting == csv.QUOTE_NONE: - # prevents crash in _csv - quotechar = None - self.quotechar = quotechar - - self.doublequote = doublequote - self.escapechar = escapechar - - self.line_terminator = line_terminator - - self.date_format = date_format - - self.tupleize_cols = tupleize_cols - self.has_mi_columns = (isinstance(obj.columns, MultiIndex) and - not self.tupleize_cols) - - # validate mi options - if self.has_mi_columns: - if cols is not None: - raise TypeError("cannot specify cols with a MultiIndex on the " - "columns") - - if cols is not None: - if isinstance(cols, Index): - cols = cols.to_native_types(na_rep=na_rep, - float_format=float_format, - date_format=date_format, - quoting=self.quoting) - else: - cols = list(cols) - self.obj = self.obj.loc[:, cols] - - # update columns to include possible multiplicity of dupes - # and make sure sure cols is just a list of labels - cols = self.obj.columns - if isinstance(cols, Index): - cols = cols.to_native_types(na_rep=na_rep, - float_format=float_format, - date_format=date_format, - quoting=self.quoting) - else: - cols = list(cols) - - # save it - self.cols = cols - - # preallocate data 2d list - self.blocks = self.obj._data.blocks - ncols = sum(b.shape[0] for b in self.blocks) - self.data = [None] * ncols - - if chunksize is None: - chunksize = (100000 // (len(self.cols) or 1)) or 1 - self.chunksize = int(chunksize) - - self.data_index = obj.index - if (isinstance(self.data_index, (DatetimeIndex, PeriodIndex)) and - date_format is not None): - self.data_index = Index([x.strftime(date_format) if notna(x) else - '' for x in self.data_index]) - - self.nlevels = getattr(self.data_index, 'nlevels', 1) - if not index: - self.nlevels = 0 - - def save(self): - # create the writer & save - if self.encoding is None: - if compat.PY2: - encoding = 'ascii' - else: - encoding = 'utf-8' - else: - encoding = self.encoding - - if hasattr(self.path_or_buf, 'write'): - f = self.path_or_buf - close = False - else: - f, handles = _get_handle(self.path_or_buf, self.mode, - encoding=encoding, - compression=self.compression) - close = True - - try: - writer_kwargs = dict(lineterminator=self.line_terminator, - delimiter=self.sep, quoting=self.quoting, - doublequote=self.doublequote, - escapechar=self.escapechar, - quotechar=self.quotechar) - if encoding == 'ascii': - self.writer = csv.writer(f, **writer_kwargs) - else: - writer_kwargs['encoding'] = encoding - self.writer = UnicodeWriter(f, **writer_kwargs) - - self._save() - - finally: - if close: - f.close() - - def _save_header(self): - - writer = self.writer - obj = self.obj - index_label = self.index_label - cols = self.cols - has_mi_columns = self.has_mi_columns - header = self.header - encoded_labels = [] - - has_aliases = isinstance(header, (tuple, list, np.ndarray, Index)) - if not (has_aliases or self.header): - return - if has_aliases: - if len(header) != len(cols): - raise ValueError(('Writing {ncols} cols but got {nalias} ' - 'aliases'.format(ncols=len(cols), - nalias=len(header)))) - else: - write_cols = header - else: - write_cols = cols - - if self.index: - # should write something for index label - if index_label is not False: - if index_label is None: - if isinstance(obj.index, MultiIndex): - index_label = [] - for i, name in enumerate(obj.index.names): - if name is None: - name = '' - index_label.append(name) - else: - index_label = obj.index.name - if index_label is None: - index_label = [''] - else: - index_label = [index_label] - elif not isinstance(index_label, - (list, tuple, np.ndarray, Index)): - # given a string for a DF with Index - index_label = [index_label] - - encoded_labels = list(index_label) - else: - encoded_labels = [] - - if not has_mi_columns or has_aliases: - encoded_labels += list(write_cols) - writer.writerow(encoded_labels) - else: - # write out the mi - columns = obj.columns - - # write out the names for each level, then ALL of the values for - # each level - for i in range(columns.nlevels): - - # we need at least 1 index column to write our col names - col_line = [] - if self.index: - - # name is the first column - col_line.append(columns.names[i]) - - if isinstance(index_label, list) and len(index_label) > 1: - col_line.extend([''] * (len(index_label) - 1)) - - col_line.extend(columns._get_level_values(i)) - - writer.writerow(col_line) - - # Write out the index line if it's not empty. - # Otherwise, we will print out an extraneous - # blank line between the mi and the data rows. - if encoded_labels and set(encoded_labels) != set(['']): - encoded_labels.extend([''] * len(columns)) - writer.writerow(encoded_labels) - - def _save(self): - - self._save_header() - - nrows = len(self.data_index) - - # write in chunksize bites - chunksize = self.chunksize - chunks = int(nrows / chunksize) + 1 - - for i in range(chunks): - start_i = i * chunksize - end_i = min((i + 1) * chunksize, nrows) - if start_i >= end_i: - break - - self._save_chunk(start_i, end_i) - - def _save_chunk(self, start_i, end_i): - - data_index = self.data_index - - # create the data for a chunk - slicer = slice(start_i, end_i) - for i in range(len(self.blocks)): - b = self.blocks[i] - d = b.to_native_types(slicer=slicer, na_rep=self.na_rep, - float_format=self.float_format, - decimal=self.decimal, - date_format=self.date_format, - quoting=self.quoting) - - for col_loc, col in zip(b.mgr_locs, d): - # self.data is a preallocated list - self.data[col_loc] = col - - ix = data_index.to_native_types(slicer=slicer, na_rep=self.na_rep, - float_format=self.float_format, - decimal=self.decimal, - date_format=self.date_format, - quoting=self.quoting) - - libwriters.write_csv_rows(self.data, ix, self.nlevels, - self.cols, self.writer) - - # ---------------------------------------------------------------------- # Array formatters @@ -2366,27 +1406,6 @@ def _cond(values): return [x + "0" if x.endswith('.') and x != na_rep else x for x in trimmed] -def single_column_table(column, align=None, style=None): - table = '<table' - if align is not None: - table += (' align="{align}"'.format(align=align)) - if style is not None: - table += (' style="{style}"'.format(style=style)) - table += '><tbody>' - for i in column: - table += ('<tr><td>{i!s}</td></tr>'.format(i=i)) - table += '</tbody></table>' - return table - - -def single_row_table(row): # pragma: no cover - table = '<table><tbody><tr>' - for i in row: - table += ('<td>{i!s}</td>'.format(i=i)) - table += '</tr></tbody></table>' - return table - - def _has_names(index): if isinstance(index, MultiIndex): return com._any_not_none(*index.names) @@ -2506,12 +1525,6 @@ def set_eng_float_format(accuracy=3, use_eng_prefix=False): set_option("display.column_space", max(12, accuracy + 9)) -def _put_lines(buf, lines): - if any(isinstance(x, compat.text_type) for x in lines): - lines = [compat.text_type(x) for x in lines] - buf.write('\n'.join(lines)) - - def _binify(cols, line_width): adjoin_width = 1 bins = [] @@ -2530,3 +1543,59 @@ def _binify(cols, line_width): bins.append(len(cols)) return bins + + +def get_level_lengths(levels, sentinel=''): + """For each index in each level the function returns lengths of indexes. + + Parameters + ---------- + levels : list of lists + List of values on for level. + sentinel : string, optional + Value which states that no new index starts on there. + + Returns + ---------- + Returns list of maps. For each level returns map of indexes (key is index + in row and value is length of index). + """ + if len(levels) == 0: + return [] + + control = [True for x in levels[0]] + + result = [] + for level in levels: + last_index = 0 + + lengths = {} + for i, key in enumerate(level): + if control[i] and key == sentinel: + pass + else: + control[i] = False + lengths[last_index] = i - last_index + last_index = i + + lengths[last_index] = len(level) - last_index + + result.append(lengths) + + return result + + +def buffer_put_lines(buf, lines): + """ + Appends lines to a buffer. + + Parameters + ---------- + buf + The buffer to write to + lines + The lines to append. + """ + if any(isinstance(x, compat.text_type) for x in lines): + lines = [compat.text_type(x) for x in lines] + buf.write('\n'.join(lines)) diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py new file mode 100644 index 0000000000000..a43c55a220292 --- /dev/null +++ b/pandas/io/formats/html.py @@ -0,0 +1,506 @@ +# -*- coding: utf-8 -*- +""" +Module for formatting output data in HTML. +""" + +from __future__ import print_function +from distutils.version import LooseVersion + +from textwrap import dedent + +import pandas.core.common as com +from pandas.core.index import MultiIndex +from pandas import compat +from pandas.compat import (lzip, range, map, zip, u, + OrderedDict, unichr) +from pandas.core.config import get_option +from pandas.io.formats.printing import pprint_thing +from pandas.io.formats.format import (get_level_lengths, + buffer_put_lines) +from pandas.io.formats.format import TableFormatter + + +class HTMLFormatter(TableFormatter): + + indent_delta = 2 + + def __init__(self, formatter, classes=None, max_rows=None, max_cols=None, + notebook=False, border=None, table_id=None): + self.fmt = formatter + self.classes = classes + + self.frame = self.fmt.frame + self.columns = self.fmt.tr_frame.columns + self.elements = [] + self.bold_rows = self.fmt.kwds.get('bold_rows', False) + self.escape = self.fmt.kwds.get('escape', True) + + self.max_rows = max_rows or len(self.fmt.frame) + self.max_cols = max_cols or len(self.fmt.columns) + self.show_dimensions = self.fmt.show_dimensions + self.is_truncated = (self.max_rows < len(self.fmt.frame) or + self.max_cols < len(self.fmt.columns)) + self.notebook = notebook + if border is None: + border = get_option('display.html.border') + self.border = border + self.table_id = table_id + + def write(self, s, indent=0): + rs = pprint_thing(s) + self.elements.append(' ' * indent + rs) + + def write_th(self, s, indent=0, tags=None): + if self.fmt.col_space is not None and self.fmt.col_space > 0: + tags = (tags or "") + tags += ('style="min-width: {colspace};"' + .format(colspace=self.fmt.col_space)) + + return self._write_cell(s, kind='th', indent=indent, tags=tags) + + def write_td(self, s, indent=0, tags=None): + return self._write_cell(s, kind='td', indent=indent, tags=tags) + + def _write_cell(self, s, kind='td', indent=0, tags=None): + if tags is not None: + start_tag = '<{kind} {tags}>'.format(kind=kind, tags=tags) + else: + start_tag = '<{kind}>'.format(kind=kind) + + if self.escape: + # escape & first to prevent double escaping of & + esc = OrderedDict([('&', r'&amp;'), ('<', r'&lt;'), + ('>', r'&gt;')]) + else: + esc = {} + rs = pprint_thing(s, escape_chars=esc).strip() + self.write(u'{start}{rs}</{kind}>' + .format(start=start_tag, rs=rs, kind=kind), indent) + + def write_tr(self, line, indent=0, indent_delta=4, header=False, + align=None, tags=None, nindex_levels=0): + if tags is None: + tags = {} + + if align is None: + self.write('<tr>', indent) + else: + self.write('<tr style="text-align: {align};">' + .format(align=align), indent) + indent += indent_delta + + for i, s in enumerate(line): + val_tag = tags.get(i, None) + if header or (self.bold_rows and i < nindex_levels): + self.write_th(s, indent, tags=val_tag) + else: + self.write_td(s, indent, tags=val_tag) + + indent -= indent_delta + self.write('</tr>', indent) + + def write_style(self): + # We use the "scoped" attribute here so that the desired + # style properties for the data frame are not then applied + # throughout the entire notebook. + template_first = """\ + <style scoped>""" + template_last = """\ + </style>""" + template_select = """\ + .dataframe %s { + %s: %s; + }""" + element_props = [('tbody tr th:only-of-type', + 'vertical-align', + 'middle'), + ('tbody tr th', + 'vertical-align', + 'top')] + if isinstance(self.columns, MultiIndex): + element_props.append(('thead tr th', + 'text-align', + 'left')) + if all((self.fmt.has_index_names, + self.fmt.index, + self.fmt.show_index_names)): + element_props.append(('thead tr:last-of-type th', + 'text-align', + 'right')) + else: + element_props.append(('thead th', + 'text-align', + 'right')) + template_mid = '\n\n'.join(map(lambda t: template_select % t, + element_props)) + template = dedent('\n'.join((template_first, + template_mid, + template_last))) + if self.notebook: + self.write(template) + + def write_result(self, buf): + indent = 0 + id_section = "" + frame = self.frame + + _classes = ['dataframe'] # Default class. + use_mathjax = get_option("display.html.use_mathjax") + if not use_mathjax: + _classes.append('tex2jax_ignore') + if self.classes is not None: + if isinstance(self.classes, str): + self.classes = self.classes.split() + if not isinstance(self.classes, (list, tuple)): + raise AssertionError('classes must be list or tuple, not {typ}' + .format(typ=type(self.classes))) + _classes.extend(self.classes) + + if self.notebook: + div_style = '' + try: + import IPython + if IPython.__version__ < LooseVersion('3.0.0'): + div_style = ' style="max-width:1500px;overflow:auto;"' + except (ImportError, AttributeError): + pass + + self.write('<div{style}>'.format(style=div_style)) + + self.write_style() + + if self.table_id is not None: + id_section = ' id="{table_id}"'.format(table_id=self.table_id) + self.write('<table border="{border}" class="{cls}"{id_section}>' + .format(border=self.border, cls=' '.join(_classes), + id_section=id_section), indent) + + indent += self.indent_delta + indent = self._write_header(indent) + indent = self._write_body(indent) + + self.write('</table>', indent) + if self.should_show_dimensions: + by = chr(215) if compat.PY3 else unichr(215) # × + self.write(u('<p>{rows} rows {by} {cols} columns</p>') + .format(rows=len(frame), + by=by, + cols=len(frame.columns))) + + if self.notebook: + self.write('</div>') + + buffer_put_lines(buf, self.elements) + + def _write_header(self, indent): + truncate_h = self.fmt.truncate_h + row_levels = self.frame.index.nlevels + if not self.fmt.header: + # write nothing + return indent + + def _column_header(): + if self.fmt.index: + row = [''] * (self.frame.index.nlevels - 1) + else: + row = [] + + if isinstance(self.columns, MultiIndex): + if self.fmt.has_column_names and self.fmt.index: + row.append(single_column_table(self.columns.names)) + else: + row.append('') + style = "text-align: {just};".format(just=self.fmt.justify) + row.extend([single_column_table(c, self.fmt.justify, style) + for c in self.columns]) + else: + if self.fmt.index: + row.append(self.columns.name or '') + row.extend(self.columns) + return row + + self.write('<thead>', indent) + row = [] + + indent += self.indent_delta + + if isinstance(self.columns, MultiIndex): + template = 'colspan="{span:d}" halign="left"' + + if self.fmt.sparsify: + # GH3547 + sentinel = com.sentinel_factory() + else: + sentinel = None + levels = self.columns.format(sparsify=sentinel, adjoin=False, + names=False) + level_lengths = get_level_lengths(levels, sentinel) + inner_lvl = len(level_lengths) - 1 + for lnum, (records, values) in enumerate(zip(level_lengths, + levels)): + if truncate_h: + # modify the header lines + ins_col = self.fmt.tr_col_num + if self.fmt.sparsify: + recs_new = {} + # Increment tags after ... col. + for tag, span in list(records.items()): + if tag >= ins_col: + recs_new[tag + 1] = span + elif tag + span > ins_col: + recs_new[tag] = span + 1 + if lnum == inner_lvl: + values = (values[:ins_col] + (u('...'),) + + values[ins_col:]) + else: + # sparse col headers do not receive a ... + values = (values[:ins_col] + + (values[ins_col - 1], ) + + values[ins_col:]) + else: + recs_new[tag] = span + # if ins_col lies between tags, all col headers + # get ... + if tag + span == ins_col: + recs_new[ins_col] = 1 + values = (values[:ins_col] + (u('...'),) + + values[ins_col:]) + records = recs_new + inner_lvl = len(level_lengths) - 1 + if lnum == inner_lvl: + records[ins_col] = 1 + else: + recs_new = {} + for tag, span in list(records.items()): + if tag >= ins_col: + recs_new[tag + 1] = span + else: + recs_new[tag] = span + recs_new[ins_col] = 1 + records = recs_new + values = (values[:ins_col] + [u('...')] + + values[ins_col:]) + + name = self.columns.names[lnum] + row = [''] * (row_levels - 1) + ['' if name is None else + pprint_thing(name)] + + if row == [""] and self.fmt.index is False: + row = [] + + tags = {} + j = len(row) + for i, v in enumerate(values): + if i in records: + if records[i] > 1: + tags[j] = template.format(span=records[i]) + else: + continue + j += 1 + row.append(v) + self.write_tr(row, indent, self.indent_delta, tags=tags, + header=True) + else: + col_row = _column_header() + align = self.fmt.justify + + if truncate_h: + ins_col = row_levels + self.fmt.tr_col_num + col_row.insert(ins_col, '...') + + self.write_tr(col_row, indent, self.indent_delta, header=True, + align=align) + + if all((self.fmt.has_index_names, + self.fmt.index, + self.fmt.show_index_names)): + row = ([x if x is not None else '' + for x in self.frame.index.names] + + [''] * min(len(self.columns), self.max_cols)) + if truncate_h: + ins_col = row_levels + self.fmt.tr_col_num + row.insert(ins_col, '') + self.write_tr(row, indent, self.indent_delta, header=True) + + indent -= self.indent_delta + self.write('</thead>', indent) + + return indent + + def _write_body(self, indent): + self.write('<tbody>', indent) + indent += self.indent_delta + + fmt_values = {} + for i in range(min(len(self.columns), self.max_cols)): + fmt_values[i] = self.fmt._format_col(i) + + # write values + if self.fmt.index: + if isinstance(self.frame.index, MultiIndex): + self._write_hierarchical_rows(fmt_values, indent) + else: + self._write_regular_rows(fmt_values, indent) + else: + for i in range(min(len(self.frame), self.max_rows)): + row = [fmt_values[j][i] for j in range(len(self.columns))] + self.write_tr(row, indent, self.indent_delta, tags=None) + + indent -= self.indent_delta + self.write('</tbody>', indent) + indent -= self.indent_delta + + return indent + + def _write_regular_rows(self, fmt_values, indent): + truncate_h = self.fmt.truncate_h + truncate_v = self.fmt.truncate_v + + ncols = len(self.fmt.tr_frame.columns) + nrows = len(self.fmt.tr_frame) + fmt = self.fmt._get_formatter('__index__') + if fmt is not None: + index_values = self.fmt.tr_frame.index.map(fmt) + else: + index_values = self.fmt.tr_frame.index.format() + + row = [] + for i in range(nrows): + + if truncate_v and i == (self.fmt.tr_row_num): + str_sep_row = ['...' for ele in row] + self.write_tr(str_sep_row, indent, self.indent_delta, + tags=None, nindex_levels=1) + + row = [] + row.append(index_values[i]) + row.extend(fmt_values[j][i] for j in range(ncols)) + + if truncate_h: + dot_col_ix = self.fmt.tr_col_num + 1 + row.insert(dot_col_ix, '...') + self.write_tr(row, indent, self.indent_delta, tags=None, + nindex_levels=1) + + def _write_hierarchical_rows(self, fmt_values, indent): + template = 'rowspan="{span}" valign="top"' + + truncate_h = self.fmt.truncate_h + truncate_v = self.fmt.truncate_v + frame = self.fmt.tr_frame + ncols = len(frame.columns) + nrows = len(frame) + row_levels = self.frame.index.nlevels + + idx_values = frame.index.format(sparsify=False, adjoin=False, + names=False) + idx_values = lzip(*idx_values) + + if self.fmt.sparsify: + # GH3547 + sentinel = com.sentinel_factory() + levels = frame.index.format(sparsify=sentinel, adjoin=False, + names=False) + + level_lengths = get_level_lengths(levels, sentinel) + inner_lvl = len(level_lengths) - 1 + if truncate_v: + # Insert ... row and adjust idx_values and + # level_lengths to take this into account. + ins_row = self.fmt.tr_row_num + inserted = False + for lnum, records in enumerate(level_lengths): + rec_new = {} + for tag, span in list(records.items()): + if tag >= ins_row: + rec_new[tag + 1] = span + elif tag + span > ins_row: + rec_new[tag] = span + 1 + + # GH 14882 - Make sure insertion done once + if not inserted: + dot_row = list(idx_values[ins_row - 1]) + dot_row[-1] = u('...') + idx_values.insert(ins_row, tuple(dot_row)) + inserted = True + else: + dot_row = list(idx_values[ins_row]) + dot_row[inner_lvl - lnum] = u('...') + idx_values[ins_row] = tuple(dot_row) + else: + rec_new[tag] = span + # If ins_row lies between tags, all cols idx cols + # receive ... + if tag + span == ins_row: + rec_new[ins_row] = 1 + if lnum == 0: + idx_values.insert(ins_row, tuple( + [u('...')] * len(level_lengths))) + + # GH 14882 - Place ... in correct level + elif inserted: + dot_row = list(idx_values[ins_row]) + dot_row[inner_lvl - lnum] = u('...') + idx_values[ins_row] = tuple(dot_row) + level_lengths[lnum] = rec_new + + level_lengths[inner_lvl][ins_row] = 1 + for ix_col in range(len(fmt_values)): + fmt_values[ix_col].insert(ins_row, '...') + nrows += 1 + + for i in range(nrows): + row = [] + tags = {} + + sparse_offset = 0 + j = 0 + for records, v in zip(level_lengths, idx_values[i]): + if i in records: + if records[i] > 1: + tags[j] = template.format(span=records[i]) + else: + sparse_offset += 1 + continue + + j += 1 + row.append(v) + + row.extend(fmt_values[j][i] for j in range(ncols)) + if truncate_h: + row.insert(row_levels - sparse_offset + + self.fmt.tr_col_num, '...') + self.write_tr(row, indent, self.indent_delta, tags=tags, + nindex_levels=len(levels) - sparse_offset) + else: + for i in range(len(frame)): + idx_values = list(zip(*frame.index.format( + sparsify=False, adjoin=False, names=False))) + row = [] + row.extend(idx_values[i]) + row.extend(fmt_values[j][i] for j in range(ncols)) + if truncate_h: + row.insert(row_levels + self.fmt.tr_col_num, '...') + self.write_tr(row, indent, self.indent_delta, tags=None, + nindex_levels=frame.index.nlevels) + + +def single_column_table(column, align=None, style=None): + table = '<table' + if align is not None: + table += (' align="{align}"'.format(align=align)) + if style is not None: + table += (' style="{style}"'.format(style=style)) + table += '><tbody>' + for i in column: + table += ('<tr><td>{i!s}</td></tr>'.format(i=i)) + table += '</tbody></table>' + return table + + +def single_row_table(row): # pragma: no cover + table = '<table><tbody><tr>' + for i in row: + table += ('<td>{i!s}</td>'.format(i=i)) + table += '</tr></tbody></table>' + return table diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py new file mode 100644 index 0000000000000..67b0a4f0e034e --- /dev/null +++ b/pandas/io/formats/latex.py @@ -0,0 +1,244 @@ +# -*- coding: utf-8 -*- +""" +Module for formatting output data in Latex. +""" + +from __future__ import print_function + +from pandas.core.index import MultiIndex +from pandas import compat +from pandas.compat import range, map, zip, u +from pandas.io.formats.format import TableFormatter +import numpy as np + + +class LatexFormatter(TableFormatter): + """ Used to render a DataFrame to a LaTeX tabular/longtable environment + output. + + Parameters + ---------- + formatter : `DataFrameFormatter` + column_format : str, default None + The columns format as specified in `LaTeX table format + <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl' for 3 columns + longtable : boolean, default False + Use a longtable environment instead of tabular. + + See Also + -------- + HTMLFormatter + """ + + def __init__(self, formatter, column_format=None, longtable=False, + multicolumn=False, multicolumn_format=None, multirow=False): + self.fmt = formatter + self.frame = self.fmt.frame + self.bold_rows = self.fmt.kwds.get('bold_rows', False) + self.column_format = column_format + self.longtable = longtable + self.multicolumn = multicolumn + self.multicolumn_format = multicolumn_format + self.multirow = multirow + + def write_result(self, buf): + """ + Render a DataFrame to a LaTeX tabular/longtable environment output. + """ + + # string representation of the columns + if len(self.frame.columns) == 0 or len(self.frame.index) == 0: + info_line = (u('Empty {name}\nColumns: {col}\nIndex: {idx}') + .format(name=type(self.frame).__name__, + col=self.frame.columns, + idx=self.frame.index)) + strcols = [[info_line]] + else: + strcols = self.fmt._to_str_columns() + + def get_col_type(dtype): + if issubclass(dtype.type, np.number): + return 'r' + else: + return 'l' + + # reestablish the MultiIndex that has been joined by _to_str_column + if self.fmt.index and isinstance(self.frame.index, MultiIndex): + clevels = self.frame.columns.nlevels + strcols.pop(0) + name = any(self.frame.index.names) + cname = any(self.frame.columns.names) + lastcol = self.frame.index.nlevels - 1 + previous_lev3 = None + for i, lev in enumerate(self.frame.index.levels): + lev2 = lev.format() + blank = ' ' * len(lev2[0]) + # display column names in last index-column + if cname and i == lastcol: + lev3 = [x if x else '{}' for x in self.frame.columns.names] + else: + lev3 = [blank] * clevels + if name: + lev3.append(lev.name) + current_idx_val = None + for level_idx in self.frame.index.labels[i]: + if ((previous_lev3 is None or + previous_lev3[len(lev3)].isspace()) and + lev2[level_idx] == current_idx_val): + # same index as above row and left index was the same + lev3.append(blank) + else: + # different value than above or left index different + lev3.append(lev2[level_idx]) + current_idx_val = lev2[level_idx] + strcols.insert(i, lev3) + previous_lev3 = lev3 + + column_format = self.column_format + if column_format is None: + dtypes = self.frame.dtypes._values + column_format = ''.join(map(get_col_type, dtypes)) + if self.fmt.index: + index_format = 'l' * self.frame.index.nlevels + column_format = index_format + column_format + elif not isinstance(column_format, + compat.string_types): # pragma: no cover + raise AssertionError('column_format must be str or unicode, ' + 'not {typ}'.format(typ=type(column_format))) + + if not self.longtable: + buf.write('\\begin{{tabular}}{{{fmt}}}\n' + .format(fmt=column_format)) + buf.write('\\toprule\n') + else: + buf.write('\\begin{{longtable}}{{{fmt}}}\n' + .format(fmt=column_format)) + buf.write('\\toprule\n') + + ilevels = self.frame.index.nlevels + clevels = self.frame.columns.nlevels + nlevels = clevels + if any(self.frame.index.names): + nlevels += 1 + strrows = list(zip(*strcols)) + self.clinebuf = [] + + for i, row in enumerate(strrows): + if i == nlevels and self.fmt.header: + buf.write('\\midrule\n') # End of header + if self.longtable: + buf.write('\\endhead\n') + buf.write('\\midrule\n') + buf.write('\\multicolumn{{{n}}}{{r}}{{{{Continued on next ' + 'page}}}} \\\\\n'.format(n=len(row))) + buf.write('\\midrule\n') + buf.write('\\endfoot\n\n') + buf.write('\\bottomrule\n') + buf.write('\\endlastfoot\n') + if self.fmt.kwds.get('escape', True): + # escape backslashes first + crow = [(x.replace('\\', '\\textbackslash').replace('_', '\\_') + .replace('%', '\\%').replace('$', '\\$') + .replace('#', '\\#').replace('{', '\\{') + .replace('}', '\\}').replace('~', '\\textasciitilde') + .replace('^', '\\textasciicircum').replace('&', '\\&') + if (x and x != '{}') else '{}') for x in row] + else: + crow = [x if x else '{}' for x in row] + if self.bold_rows and self.fmt.index: + # bold row labels + crow = ['\\textbf{{{x}}}'.format(x=x) + if j < ilevels and x.strip() not in ['', '{}'] else x + for j, x in enumerate(crow)] + if i < clevels and self.fmt.header and self.multicolumn: + # sum up columns to multicolumns + crow = self._format_multicolumn(crow, ilevels) + if (i >= nlevels and self.fmt.index and self.multirow and + ilevels > 1): + # sum up rows to multirows + crow = self._format_multirow(crow, ilevels, i, strrows) + buf.write(' & '.join(crow)) + buf.write(' \\\\\n') + if self.multirow and i < len(strrows) - 1: + self._print_cline(buf, i, len(strcols)) + + if not self.longtable: + buf.write('\\bottomrule\n') + buf.write('\\end{tabular}\n') + else: + buf.write('\\end{longtable}\n') + + def _format_multicolumn(self, row, ilevels): + r""" + Combine columns belonging to a group to a single multicolumn entry + according to self.multicolumn_format + + e.g.: + a & & & b & c & + will become + \multicolumn{3}{l}{a} & b & \multicolumn{2}{l}{c} + """ + row2 = list(row[:ilevels]) + ncol = 1 + coltext = '' + + def append_col(): + # write multicolumn if needed + if ncol > 1: + row2.append('\\multicolumn{{{ncol:d}}}{{{fmt:s}}}{{{txt:s}}}' + .format(ncol=ncol, fmt=self.multicolumn_format, + txt=coltext.strip())) + # don't modify where not needed + else: + row2.append(coltext) + for c in row[ilevels:]: + # if next col has text, write the previous + if c.strip(): + if coltext: + append_col() + coltext = c + ncol = 1 + # if not, add it to the previous multicolumn + else: + ncol += 1 + # write last column name + if coltext: + append_col() + return row2 + + def _format_multirow(self, row, ilevels, i, rows): + r""" + Check following rows, whether row should be a multirow + + e.g.: becomes: + a & 0 & \multirow{2}{*}{a} & 0 & + & 1 & & 1 & + b & 0 & \cline{1-2} + b & 0 & + """ + for j in range(ilevels): + if row[j].strip(): + nrow = 1 + for r in rows[i + 1:]: + if not r[j].strip(): + nrow += 1 + else: + break + if nrow > 1: + # overwrite non-multirow entry + row[j] = '\\multirow{{{nrow:d}}}{{*}}{{{row:s}}}'.format( + nrow=nrow, row=row[j].strip()) + # save when to end the current block with \cline + self.clinebuf.append([i + nrow - 1, j + 1]) + return row + + def _print_cline(self, buf, i, icol): + """ + Print clines after multirow-blocks are finished + """ + for cl in self.clinebuf: + if cl[0] == i: + buf.write('\\cline{{{cl:d}-{icol:d}}}\n' + .format(cl=cl[1], icol=icol)) + # remove entries that have been written to buffer + self.clinebuf = [x for x in self.clinebuf if x[0] != i]
The branch for the other PR was messed up, so I created a new one. - [x] based on discussion here: https://github.com/pandas-dev/pandas/pull/20032#pullrequestreview-101917292 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This PR splits the various formatters into different files so that it's easier to refactor a specific formatter.
https://api.github.com/repos/pandas-dev/pandas/pulls/20341
2018-03-14T09:08:04Z
2018-03-14T11:02:11Z
2018-03-14T11:02:11Z
2018-03-14T11:02:16Z
TST: Parametrize dtypes tests - test_common.py and test_concat.py
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index bfec229d32b22..2960a12b133d2 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -16,44 +16,46 @@ class TestPandasDtype(object): # Passing invalid dtype, both as a string or object, must raise TypeError # Per issue GH15520 - def test_invalid_dtype_error(self): - msg = 'not understood' - invalid_list = [pd.Timestamp, 'pd.Timestamp', list] - for dtype in invalid_list: - with tm.assert_raises_regex(TypeError, msg): - com.pandas_dtype(dtype) - - valid_list = [object, 'float64', np.object_, np.dtype('object'), 'O', - np.float64, float, np.dtype('float64')] - for dtype in valid_list: - com.pandas_dtype(dtype) - - def test_numpy_dtype(self): - for dtype in ['M8[ns]', 'm8[ns]', 'object', 'float64', 'int64']: - assert com.pandas_dtype(dtype) == np.dtype(dtype) + @pytest.mark.parametrize('box', [pd.Timestamp, 'pd.Timestamp', list]) + def test_invalid_dtype_error(self, box): + with tm.assert_raises_regex(TypeError, 'not understood'): + com.pandas_dtype(box) + + @pytest.mark.parametrize('dtype', [ + object, 'float64', np.object_, np.dtype('object'), 'O', + np.float64, float, np.dtype('float64')]) + def test_pandas_dtype_valid(self, dtype): + assert com.pandas_dtype(dtype) == dtype + + @pytest.mark.parametrize('dtype', [ + 'M8[ns]', 'm8[ns]', 'object', 'float64', 'int64']) + def test_numpy_dtype(self, dtype): + assert com.pandas_dtype(dtype) == np.dtype(dtype) def test_numpy_string_dtype(self): # do not parse freq-like string as period dtype assert com.pandas_dtype('U') == np.dtype('U') assert com.pandas_dtype('S') == np.dtype('S') - def test_datetimetz_dtype(self): - for dtype in ['datetime64[ns, US/Eastern]', - 'datetime64[ns, Asia/Tokyo]', - 'datetime64[ns, UTC]']: - assert com.pandas_dtype(dtype) is DatetimeTZDtype(dtype) - assert com.pandas_dtype(dtype) == DatetimeTZDtype(dtype) - assert com.pandas_dtype(dtype) == dtype + @pytest.mark.parametrize('dtype', [ + 'datetime64[ns, US/Eastern]', + 'datetime64[ns, Asia/Tokyo]', + 'datetime64[ns, UTC]']) + def test_datetimetz_dtype(self, dtype): + assert com.pandas_dtype(dtype) is DatetimeTZDtype(dtype) + assert com.pandas_dtype(dtype) == DatetimeTZDtype(dtype) + assert com.pandas_dtype(dtype) == dtype def test_categorical_dtype(self): assert com.pandas_dtype('category') == CategoricalDtype() - def test_period_dtype(self): - for dtype in ['period[D]', 'period[3M]', 'period[U]', - 'Period[D]', 'Period[3M]', 'Period[U]']: - assert com.pandas_dtype(dtype) is PeriodDtype(dtype) - assert com.pandas_dtype(dtype) == PeriodDtype(dtype) - assert com.pandas_dtype(dtype) == dtype + @pytest.mark.parametrize('dtype', [ + 'period[D]', 'period[3M]', 'period[U]', + 'Period[D]', 'Period[3M]', 'Period[U]']) + def test_period_dtype(self, dtype): + assert com.pandas_dtype(dtype) is PeriodDtype(dtype) + assert com.pandas_dtype(dtype) == PeriodDtype(dtype) + assert com.pandas_dtype(dtype) == dtype dtypes = dict(datetime_tz=com.pandas_dtype('datetime64[ns, US/Eastern]'), diff --git a/pandas/tests/dtypes/test_concat.py b/pandas/tests/dtypes/test_concat.py index ca579e2dc9390..b6c5c119ffb6f 100644 --- a/pandas/tests/dtypes/test_concat.py +++ b/pandas/tests/dtypes/test_concat.py @@ -1,77 +1,53 @@ # -*- coding: utf-8 -*- -import pandas as pd +import pytest import pandas.core.dtypes.concat as _concat - - -class TestConcatCompat(object): - - def check_concat(self, to_concat, exp): - for klass in [pd.Index, pd.Series]: - to_concat_klass = [klass(c) for c in to_concat] - res = _concat.get_dtype_kinds(to_concat_klass) - assert res == set(exp) - - def test_get_dtype_kinds(self): - to_concat = [['a'], [1, 2]] - self.check_concat(to_concat, ['i', 'object']) - - to_concat = [[3, 4], [1, 2]] - self.check_concat(to_concat, ['i']) - - to_concat = [[3, 4], [1, 2.1]] - self.check_concat(to_concat, ['i', 'f']) - - def test_get_dtype_kinds_datetimelike(self): - to_concat = [pd.DatetimeIndex(['2011-01-01']), - pd.DatetimeIndex(['2011-01-02'])] - self.check_concat(to_concat, ['datetime']) - - to_concat = [pd.TimedeltaIndex(['1 days']), - pd.TimedeltaIndex(['2 days'])] - self.check_concat(to_concat, ['timedelta']) - - def test_get_dtype_kinds_datetimelike_object(self): - to_concat = [pd.DatetimeIndex(['2011-01-01']), - pd.DatetimeIndex(['2011-01-02'], tz='US/Eastern')] - self.check_concat(to_concat, - ['datetime', 'datetime64[ns, US/Eastern]']) - - to_concat = [pd.DatetimeIndex(['2011-01-01'], tz='Asia/Tokyo'), - pd.DatetimeIndex(['2011-01-02'], tz='US/Eastern')] - self.check_concat(to_concat, - ['datetime64[ns, Asia/Tokyo]', - 'datetime64[ns, US/Eastern]']) - - # timedelta has single type - to_concat = [pd.TimedeltaIndex(['1 days']), - pd.TimedeltaIndex(['2 hours'])] - self.check_concat(to_concat, ['timedelta']) - - to_concat = [pd.DatetimeIndex(['2011-01-01'], tz='Asia/Tokyo'), - pd.TimedeltaIndex(['1 days'])] - self.check_concat(to_concat, - ['datetime64[ns, Asia/Tokyo]', 'timedelta']) - - def test_get_dtype_kinds_period(self): - # because we don't have Period dtype (yet), - # Series results in object dtype - to_concat = [pd.PeriodIndex(['2011-01'], freq='M'), - pd.PeriodIndex(['2011-01'], freq='M')] - res = _concat.get_dtype_kinds(to_concat) - assert res == set(['period[M]']) - - to_concat = [pd.Series([pd.Period('2011-01', freq='M')]), - pd.Series([pd.Period('2011-02', freq='M')])] - res = _concat.get_dtype_kinds(to_concat) - assert res == set(['object']) - - to_concat = [pd.PeriodIndex(['2011-01'], freq='M'), - pd.PeriodIndex(['2011-01'], freq='D')] - res = _concat.get_dtype_kinds(to_concat) - assert res == set(['period[M]', 'period[D]']) - - to_concat = [pd.Series([pd.Period('2011-01', freq='M')]), - pd.Series([pd.Period('2011-02', freq='D')])] - res = _concat.get_dtype_kinds(to_concat) - assert res == set(['object']) +from pandas import ( + Index, DatetimeIndex, PeriodIndex, TimedeltaIndex, Series, Period) + + +@pytest.mark.parametrize('to_concat, expected', [ + # int/float/str + ([['a'], [1, 2]], ['i', 'object']), + ([[3, 4], [1, 2]], ['i']), + ([[3, 4], [1, 2.1]], ['i', 'f']), + + # datetimelike + ([DatetimeIndex(['2011-01-01']), DatetimeIndex(['2011-01-02'])], + ['datetime']), + ([TimedeltaIndex(['1 days']), TimedeltaIndex(['2 days'])], + ['timedelta']), + + # datetimelike object + ([DatetimeIndex(['2011-01-01']), + DatetimeIndex(['2011-01-02'], tz='US/Eastern')], + ['datetime', 'datetime64[ns, US/Eastern]']), + ([DatetimeIndex(['2011-01-01'], tz='Asia/Tokyo'), + DatetimeIndex(['2011-01-02'], tz='US/Eastern')], + ['datetime64[ns, Asia/Tokyo]', 'datetime64[ns, US/Eastern]']), + ([TimedeltaIndex(['1 days']), TimedeltaIndex(['2 hours'])], + ['timedelta']), + ([DatetimeIndex(['2011-01-01'], tz='Asia/Tokyo'), + TimedeltaIndex(['1 days'])], + ['datetime64[ns, Asia/Tokyo]', 'timedelta'])]) +@pytest.mark.parametrize('klass', [Index, Series]) +def test_get_dtype_kinds(klass, to_concat, expected): + to_concat_klass = [klass(c) for c in to_concat] + result = _concat.get_dtype_kinds(to_concat_klass) + assert result == set(expected) + + +@pytest.mark.parametrize('to_concat, expected', [ + # because we don't have Period dtype (yet), + # Series results in object dtype + ([PeriodIndex(['2011-01'], freq='M'), + PeriodIndex(['2011-01'], freq='M')], ['period[M]']), + ([Series([Period('2011-01', freq='M')]), + Series([Period('2011-02', freq='M')])], ['object']), + ([PeriodIndex(['2011-01'], freq='M'), + PeriodIndex(['2011-01'], freq='D')], ['period[M]', 'period[D]']), + ([Series([Period('2011-01', freq='M')]), + Series([Period('2011-02', freq='D')])], ['object'])]) +def test_get_dtype_kinds_period(to_concat, expected): + result = _concat.get_dtype_kinds(to_concat) + assert result == set(expected)
Parametrized some straightforward dtypes related tests. Relatively minor changes to `test_common.py`: - mostly just extracted `for` loops - split one test into two separate tests (see code comment) Made larger changes to `test_concat.py`: - removed the test class in favor of plain functions, since there was only one class in the file - combined a few different tests into a single test, since they were all using test procedure - removed the `check_concat` validation function since it's only called once now - further parametrized over a `for` loop previously in the `check_concat` validation function - removed the `import pandas as pd` in favor of directly importing the necessary classes
https://api.github.com/repos/pandas-dev/pandas/pulls/20340
2018-03-14T05:55:27Z
2018-03-15T10:26:21Z
2018-03-15T10:26:21Z
2018-03-15T16:55:34Z
TST: Parameterize some compression tests
diff --git a/pandas/tests/io/parser/compression.py b/pandas/tests/io/parser/compression.py index 4291d59123e8b..01c6620e50d37 100644 --- a/pandas/tests/io/parser/compression.py +++ b/pandas/tests/io/parser/compression.py @@ -12,6 +12,13 @@ import pandas.util.testing as tm import pandas.util._test_decorators as td +import gzip +import bz2 +try: + lzma = compat.import_lzma() +except ImportError: + lzma = None + class CompressionTests(object): @@ -64,83 +71,36 @@ def test_zip(self): pytest.raises(zipfile.BadZipfile, self.read_csv, f, compression='zip') - def test_gzip(self): - import gzip - - with open(self.csv1, 'rb') as data_file: - data = data_file.read() - expected = self.read_csv(self.csv1) - - with tm.ensure_clean() as path: - tmp = gzip.GzipFile(path, mode='wb') - tmp.write(data) - tmp.close() - - result = self.read_csv(path, compression='gzip') - tm.assert_frame_equal(result, expected) - - with open(path, 'rb') as f: - result = self.read_csv(f, compression='gzip') - tm.assert_frame_equal(result, expected) - - with tm.ensure_clean('test.gz') as path: - tmp = gzip.GzipFile(path, mode='wb') - tmp.write(data) - tmp.close() - result = self.read_csv(path, compression='infer') - tm.assert_frame_equal(result, expected) - - def test_bz2(self): - import bz2 + @pytest.mark.parametrize('compress_type, compress_method, ext', [ + ('gzip', gzip.GzipFile, 'gz'), + ('bz2', bz2.BZ2File, 'bz2'), + pytest.param('xz', getattr(lzma, 'LZMAFile', None), 'xz', + marks=td.skip_if_no_lzma) + ]) + def test_other_compression(self, compress_type, compress_method, ext): with open(self.csv1, 'rb') as data_file: data = data_file.read() expected = self.read_csv(self.csv1) with tm.ensure_clean() as path: - tmp = bz2.BZ2File(path, mode='wb') + tmp = compress_method(path, mode='wb') tmp.write(data) tmp.close() - result = self.read_csv(path, compression='bz2') + result = self.read_csv(path, compression=compress_type) tm.assert_frame_equal(result, expected) - pytest.raises(ValueError, self.read_csv, - path, compression='bz3') + if compress_type == 'bz2': + pytest.raises(ValueError, self.read_csv, + path, compression='bz3') with open(path, 'rb') as fin: - result = self.read_csv(fin, compression='bz2') - tm.assert_frame_equal(result, expected) - - with tm.ensure_clean('test.bz2') as path: - tmp = bz2.BZ2File(path, mode='wb') - tmp.write(data) - tmp.close() - result = self.read_csv(path, compression='infer') - tm.assert_frame_equal(result, expected) - - @td.skip_if_no_lzma - def test_xz(self): - lzma = compat.import_lzma() - - with open(self.csv1, 'rb') as data_file: - data = data_file.read() - expected = self.read_csv(self.csv1) - - with tm.ensure_clean() as path: - tmp = lzma.LZMAFile(path, mode='wb') - tmp.write(data) - tmp.close() - - result = self.read_csv(path, compression='xz') - tm.assert_frame_equal(result, expected) - - with open(path, 'rb') as f: - result = self.read_csv(f, compression='xz') + result = self.read_csv(fin, compression=compress_type) tm.assert_frame_equal(result, expected) - with tm.ensure_clean('test.xz') as path: - tmp = lzma.LZMAFile(path, mode='wb') + with tm.ensure_clean('test.{}'.format(ext)) as path: + tmp = compress_method(path, mode='wb') tmp.write(data) tmp.close() result = self.read_csv(path, compression='infer')
closes #19226 Parameterizing some tests in ``pandas/tests/io/parser/compression.py``. I left the zip test alone because it was quite different to the others and I couldn't see an easy way to incorporate it in the parameterizing.
https://api.github.com/repos/pandas-dev/pandas/pulls/20337
2018-03-13T21:53:56Z
2018-03-16T11:35:21Z
2018-03-16T11:35:20Z
2018-03-17T23:01:09Z
DOC: update the pandas.DataFrame.cummax docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5682ad411fd2f..2adc289f98d94 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8487,19 +8487,21 @@ def compound(self, axis=None, skipna=None, level=None): cls.compound = compound cls.cummin = _make_cum_function( - cls, 'cummin', name, name2, axis_descr, "cumulative minimum", + cls, 'cummin', name, name2, axis_descr, "minimum", lambda y, axis: np.minimum.accumulate(y, axis), "min", - np.inf, np.nan) + np.inf, np.nan, _cummin_examples) cls.cumsum = _make_cum_function( - cls, 'cumsum', name, name2, axis_descr, "cumulative sum", - lambda y, axis: y.cumsum(axis), "sum", 0., np.nan) + cls, 'cumsum', name, name2, axis_descr, "sum", + lambda y, axis: y.cumsum(axis), "sum", 0., + np.nan, _cumsum_examples) cls.cumprod = _make_cum_function( - cls, 'cumprod', name, name2, axis_descr, "cumulative product", - lambda y, axis: y.cumprod(axis), "prod", 1., np.nan) + cls, 'cumprod', name, name2, axis_descr, "product", + lambda y, axis: y.cumprod(axis), "prod", 1., + np.nan, _cumprod_examples) cls.cummax = _make_cum_function( - cls, 'cummax', name, name2, axis_descr, "cumulative max", + cls, 'cummax', name, name2, axis_descr, "maximum", lambda y, axis: np.maximum.accumulate(y, axis), "max", - -np.inf, np.nan) + -np.inf, np.nan, _cummax_examples) cls.sum = _make_min_count_stat_function( cls, 'sum', name, name2, axis_descr, @@ -8702,8 +8704,8 @@ def _doc_parms(cls): Include only boolean columns. If None, will attempt to use everything, then use only boolean data. Not implemented for Series. **kwargs : any, default None - Additional keywords have no affect but might be accepted for - compatibility with numpy. + Additional keywords have no effect but might be accepted for + compatibility with NumPy. Returns ------- @@ -8761,24 +8763,296 @@ def _doc_parms(cls): """ _cnum_doc = """ +Return cumulative %(desc)s over a DataFrame or Series axis. + +Returns a DataFrame or Series of the same size containing the cumulative +%(desc)s. Parameters ---------- -axis : %(axis_descr)s +axis : {0 or 'index', 1 or 'columns'}, default 0 + The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result - will be NA + will be NA. +*args, **kwargs : + Additional keywords have no effect but might be accepted for + compatibility with NumPy. Returns ------- -%(outname)s : %(name1)s\n - - +%(outname)s : %(name1)s or %(name2)s\n +%(examples)s See also -------- pandas.core.window.Expanding.%(accum_func_name)s : Similar functionality but ignores ``NaN`` values. +%(name2)s.%(accum_func_name)s : Return the %(desc)s over + %(name2)s axis. +%(name2)s.cummax : Return cumulative maximum over %(name2)s axis. +%(name2)s.cummin : Return cumulative minimum over %(name2)s axis. +%(name2)s.cumsum : Return cumulative sum over %(name2)s axis. +%(name2)s.cumprod : Return cumulative product over %(name2)s axis. +""" + +_cummin_examples = """\ +Examples +-------- +**Series** + +>>> s = pd.Series([2, np.nan, 5, -1, 0]) +>>> s +0 2.0 +1 NaN +2 5.0 +3 -1.0 +4 0.0 +dtype: float64 + +By default, NA values are ignored. + +>>> s.cummin() +0 2.0 +1 NaN +2 2.0 +3 -1.0 +4 -1.0 +dtype: float64 + +To include NA values in the operation, use ``skipna=False`` + +>>> s.cummin(skipna=False) +0 2.0 +1 NaN +2 NaN +3 NaN +4 NaN +dtype: float64 + +**DataFrame** + +>>> df = pd.DataFrame([[2.0, 1.0], +... [3.0, np.nan], +... [1.0, 0.0]], +... columns=list('AB')) +>>> df + A B +0 2.0 1.0 +1 3.0 NaN +2 1.0 0.0 + +By default, iterates over rows and finds the minimum +in each column. This is equivalent to ``axis=None`` or ``axis='index'``. + +>>> df.cummin() + A B +0 2.0 1.0 +1 2.0 NaN +2 1.0 0.0 + +To iterate over columns and find the minimum in each row, +use ``axis=1`` + +>>> df.cummin(axis=1) + A B +0 2.0 1.0 +1 3.0 NaN +2 1.0 0.0 +""" + +_cumsum_examples = """\ +Examples +-------- +**Series** + +>>> s = pd.Series([2, np.nan, 5, -1, 0]) +>>> s +0 2.0 +1 NaN +2 5.0 +3 -1.0 +4 0.0 +dtype: float64 + +By default, NA values are ignored. + +>>> s.cumsum() +0 2.0 +1 NaN +2 7.0 +3 6.0 +4 6.0 +dtype: float64 + +To include NA values in the operation, use ``skipna=False`` + +>>> s.cumsum(skipna=False) +0 2.0 +1 NaN +2 NaN +3 NaN +4 NaN +dtype: float64 + +**DataFrame** + +>>> df = pd.DataFrame([[2.0, 1.0], +... [3.0, np.nan], +... [1.0, 0.0]], +... columns=list('AB')) +>>> df + A B +0 2.0 1.0 +1 3.0 NaN +2 1.0 0.0 + +By default, iterates over rows and finds the sum +in each column. This is equivalent to ``axis=None`` or ``axis='index'``. + +>>> df.cumsum() + A B +0 2.0 1.0 +1 5.0 NaN +2 6.0 1.0 + +To iterate over columns and find the sum in each row, +use ``axis=1`` + +>>> df.cumsum(axis=1) + A B +0 2.0 3.0 +1 3.0 NaN +2 1.0 1.0 +""" + +_cumprod_examples = """\ +Examples +-------- +**Series** + +>>> s = pd.Series([2, np.nan, 5, -1, 0]) +>>> s +0 2.0 +1 NaN +2 5.0 +3 -1.0 +4 0.0 +dtype: float64 + +By default, NA values are ignored. + +>>> s.cumprod() +0 2.0 +1 NaN +2 10.0 +3 -10.0 +4 -0.0 +dtype: float64 + +To include NA values in the operation, use ``skipna=False`` + +>>> s.cumprod(skipna=False) +0 2.0 +1 NaN +2 NaN +3 NaN +4 NaN +dtype: float64 +**DataFrame** + +>>> df = pd.DataFrame([[2.0, 1.0], +... [3.0, np.nan], +... [1.0, 0.0]], +... columns=list('AB')) +>>> df + A B +0 2.0 1.0 +1 3.0 NaN +2 1.0 0.0 + +By default, iterates over rows and finds the product +in each column. This is equivalent to ``axis=None`` or ``axis='index'``. + +>>> df.cumprod() + A B +0 2.0 1.0 +1 6.0 NaN +2 6.0 0.0 + +To iterate over columns and find the product in each row, +use ``axis=1`` + +>>> df.cumprod(axis=1) + A B +0 2.0 2.0 +1 3.0 NaN +2 1.0 0.0 +""" + +_cummax_examples = """\ +Examples +-------- +**Series** + +>>> s = pd.Series([2, np.nan, 5, -1, 0]) +>>> s +0 2.0 +1 NaN +2 5.0 +3 -1.0 +4 0.0 +dtype: float64 + +By default, NA values are ignored. + +>>> s.cummax() +0 2.0 +1 NaN +2 5.0 +3 5.0 +4 5.0 +dtype: float64 + +To include NA values in the operation, use ``skipna=False`` + +>>> s.cummax(skipna=False) +0 2.0 +1 NaN +2 NaN +3 NaN +4 NaN +dtype: float64 + +**DataFrame** + +>>> df = pd.DataFrame([[2.0, 1.0], +... [3.0, np.nan], +... [1.0, 0.0]], +... columns=list('AB')) +>>> df + A B +0 2.0 1.0 +1 3.0 NaN +2 1.0 0.0 + +By default, iterates over rows and finds the maximum +in each column. This is equivalent to ``axis=None`` or ``axis='index'``. + +>>> df.cummax() + A B +0 2.0 1.0 +1 3.0 NaN +2 3.0 1.0 + +To iterate over columns and find the maximum in each row, +use ``axis=1`` + +>>> df.cummax(axis=1) + A B +0 2.0 2.0 +1 3.0 NaN +2 1.0 1.0 """ _any_see_also = """\ @@ -8975,11 +9249,11 @@ def stat_func(self, axis=None, skipna=None, level=None, ddof=1, def _make_cum_function(cls, name, name1, name2, axis_descr, desc, - accum_func, accum_func_name, mask_a, mask_b): + accum_func, accum_func_name, mask_a, mask_b, examples): @Substitution(outname=name, desc=desc, name1=name1, name2=name2, - axis_descr=axis_descr, accum_func_name=accum_func_name) - @Appender("Return {0} over requested axis.".format(desc) + - _cnum_doc) + axis_descr=axis_descr, accum_func_name=accum_func_name, + examples=examples) + @Appender(_cnum_doc) def cum_func(self, axis=None, skipna=True, *args, **kwargs): skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name) if axis is None:
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ##################### Docstring (pandas.DataFrame.cummax) ##################### ################################################################################ Return cumulative maximum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative maximum. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- cummax : Series or DataFrame Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cummax() 0 2.0 1 NaN 2 5.0 3 5.0 4 5.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cummax(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the maximum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cummax() A B 0 2.0 1.0 1 3.0 NaN 2 3.0 1.0 To iterate over columns and find the maximum in each row, use ``axis=1`` >>> df.cummax(axis=1) A B 0 2.0 2.0 1 3.0 NaN 2 1.0 1.0 See also -------- pandas.core.window.Expanding.max : Similar functionality but ignores ``NaN`` values. DataFrame.max : Return the maximum over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'kwargs', 'args'} not documented Unknown parameters {'*args, **kwargs :'} Parameter "*args, **kwargs :" has no type ################################################################################ ##################### Docstring (pandas.DataFrame.cummin) ##################### ################################################################################ Return cumulative minimum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative minimum. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- cummin : Series or DataFrame Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cummin() 0 2.0 1 NaN 2 2.0 3 -1.0 4 -1.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cummin(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the minimum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cummin() A B 0 2.0 1.0 1 2.0 NaN 2 1.0 0.0 To iterate over columns and find the minimum in each row, use ``axis=1`` >>> df.cummin(axis=1) A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 See also -------- pandas.core.window.Expanding.min : Similar functionality but ignores ``NaN`` values. DataFrame.min : Return the minimum over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'args', 'kwargs'} not documented Unknown parameters {'*args, **kwargs :'} Parameter "*args, **kwargs :" has no type ################################################################################ ##################### Docstring (pandas.DataFrame.cumsum) ##################### ################################################################################ Return cumulative sum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative sum. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- cumsum : Series or DataFrame Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cumsum() 0 2.0 1 NaN 2 7.0 3 6.0 4 6.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cumsum(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the sum in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cumsum() A B 0 2.0 1.0 1 5.0 NaN 2 6.0 1.0 To iterate over columns and find the sum in each row, use ``axis=1`` >>> df.cumsum(axis=1) A B 0 2.0 3.0 1 3.0 NaN 2 1.0 1.0 See also -------- pandas.core.window.Expanding.sum : Similar functionality but ignores ``NaN`` values. DataFrame.sum : Return the sum over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'args', 'kwargs'} not documented Unknown parameters {'*args, **kwargs :'} Parameter "*args, **kwargs :" has no type ################################################################################ ##################### Docstring (pandas.DataFrame.cumprod) ##################### ################################################################################ Return cumulative product over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative product. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- cumprod : Series or DataFrame Examples -------- **Series** >>> s = pd.Series([2, np.nan, 5, -1, 0]) >>> s 0 2.0 1 NaN 2 5.0 3 -1.0 4 0.0 dtype: float64 By default, NA values are ignored. >>> s.cumprod() 0 2.0 1 NaN 2 10.0 3 -10.0 4 -0.0 dtype: float64 To include NA values in the operation, use ``skipna=False`` >>> s.cumprod(skipna=False) 0 2.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 **DataFrame** >>> df = pd.DataFrame([[2.0, 1.0], ... [3.0, np.nan], ... [1.0, 0.0]], ... columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the product in each column. This is equivalent to ``axis=None`` or ``axis='index'``. >>> df.cumprod() A B 0 2.0 1.0 1 6.0 NaN 2 6.0 0.0 To iterate over columns and find the product in each row, use ``axis=1`` >>> df.cumprod(axis=1) A B 0 2.0 2.0 1 3.0 NaN 2 1.0 0.0 See also -------- pandas.core.window.Expanding.prod : Similar functionality but ignores ``NaN`` values. DataFrame.prod : Return the product over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'args', 'kwargs'} not documented Unknown parameters {'*args, **kwargs :'} Parameter "*args, **kwargs :" has no type ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. The *args/**kwargs error is a bug in the parameter evaluation
https://api.github.com/repos/pandas-dev/pandas/pulls/20336
2018-03-13T20:29:35Z
2018-03-17T18:04:34Z
2018-03-17T18:04:34Z
2018-03-17T19:17:10Z
DOC: update the Period.qyear docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index d89c06d43ccb9..5072d196709e6 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1463,6 +1463,45 @@ cdef class _Period(object): @property def qyear(self): + """ + Fiscal year the Period lies in according to its starting-quarter. + + The `year` and the `qyear` of the period will be the same if the fiscal + and calendar years are the same. When they are not, the fiscal year + can be different from the calendar year of the period. + + Returns + ------- + int + The fiscal year of the period. + + See Also + -------- + Period.year : Return the calendar year of the period. + + Examples + -------- + If the natural and fiscal year are the same, `qyear` and `year` will + be the same. + + >>> per = pd.Period('2018Q1', freq='Q') + >>> per.qyear + 2018 + >>> per.year + 2018 + + If the fiscal year starts in April (`Q-MAR`), the first quarter of + 2018 will start in April 2017. `year` will then be 2018, but `qyear` + will be the fiscal year, 2018. + + >>> per = pd.Period('2018Q1', freq='Q-MAR') + >>> per.start_time + Timestamp('2017-04-01 00:00:00') + >>> per.qyear + 2018 + >>> per.year + 2017 + """ base, mult = get_freq_code(self.freq) return pqyear(self.ordinal, base)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ ] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` (pandas_dev) ani@ani-Lenovo-G50-80:~/github/pandas/scripts$ python validate_docstrings.py - [ ] pandas.Period.qyear ################################################################################ ####################### Docstring (pandas.Period.qyear) ####################### ################################################################################ Return a year of the given date. This function simply find the year of the given date that period fallsin. Returns ------- int See Also -------- Period.qyear :Return the year of the date Examples -------- >>> p = pd.Period("2014-9-21", freq="A") >>> p.qyear 2014 ################################################################################ ################################## Validation ################################## ################################################################################ ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20333
2018-03-13T18:20:20Z
2018-07-08T19:42:56Z
2018-07-08T19:42:56Z
2018-07-08T19:47:32Z
DOC : Update the pandas.Period.week docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index eda0a8492ad24..9270b8baece08 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1305,6 +1305,32 @@ cdef class _Period(object): @property def week(self): + """ + Get the week of the year on the given Period. + + Returns + ------- + int + + See Also + -------- + Period.dayofweek : Get the day component of the Period. + Period.weekday : Get the day component of the Period. + + Examples + -------- + >>> p = pd.Period("2018-03-11", "H") + >>> p.week + 10 + + >>> p = pd.Period("2018-02-01", "D") + >>> p.week + 5 + + >>> p = pd.Period("2018-01-06", "D") + >>> p.week + 1 + """ return self.weekofyear @property
``` # Period.week ################################################################################ ######################## Docstring (pandas.Period.week) ######################## ################################################################################ Get the total weeks on the Period falls in. Returns ------- int See Also -------- Period.dayofweek : Get the day component of the Period. Period.weekday : Get the day component of the Period. Examples -------- >>> p = pd.Period("2018-03-11") >>> p.week 10 ################################################################################ ################################## Validation ################################## ################################################################################ ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20331
2018-03-13T16:33:06Z
2018-03-17T10:31:17Z
2018-03-17T10:31:17Z
2018-03-17T10:56:41Z
CI: Fix linting on master [ci skip]
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index ab7108fb60bd7..d7e66bf4c9320 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1300,7 +1300,7 @@ cdef class _Period(object): Returns ------- - int + int The second of the Period (ranges from 0 to 59). See Also
[ci skip] I broke master again. Sorry.
https://api.github.com/repos/pandas-dev/pandas/pulls/20330
2018-03-13T15:29:48Z
2018-03-13T15:30:04Z
2018-03-13T15:30:04Z
2018-03-13T15:30:07Z
DOC: Formatting for DtypeWarning Docstring [ci skip]
diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 16654f0227182..ff34df64c88d2 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -68,8 +68,7 @@ class DtypeWarning(Warning): ... 'b': ['b'] * 300000}) >>> df.to_csv('test.csv', index=False) >>> df2 = pd.read_csv('test.csv') - - DtypeWarning: Columns (0) have mixed types + ... # DtypeWarning: Columns (0) have mixed types Important to notice that ``df2`` will contain both `str` and `int` for the same input, '1'.
xref : https://github.com/pandas-dev/pandas/pull/20208 ![fireshot capture 002 - pandas errors dtypewarning pandas 0_ - file____users_taugspurger_sandbox_](https://user-images.githubusercontent.com/1312546/37349929-958f175e-26a5-11e8-8c1e-872c2261c64f.png) cc @jorisvandenbossche @hissashirocha
https://api.github.com/repos/pandas-dev/pandas/pulls/20329
2018-03-13T15:03:10Z
2018-03-13T15:08:00Z
2018-03-13T15:08:00Z
2018-03-13T15:08:03Z
CLN: Fixed line length
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ff3f377e07f98..79265e35ef6e6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4459,9 +4459,9 @@ def pivot(self, index=None, columns=None, values=None): Return reshaped DataFrame organized by given index / column values. Reshape data (produce a "pivot" table) based on column values. Uses - unique values from specified `index` / `columns` to form axes of the resulting - DataFrame. This function does not support data aggregation, multiple - values will result in a MultiIndex in the columns. See the + unique values from specified `index` / `columns` to form axes of the + resulting DataFrame. This function does not support data aggregation, + multiple values will result in a MultiIndex in the columns. See the :ref:`User Guide <reshaping>` for more on reshaping. Parameters
This is failing master right now.
https://api.github.com/repos/pandas-dev/pandas/pulls/20327
2018-03-13T11:36:29Z
2018-03-13T11:38:22Z
2018-03-13T11:38:22Z
2018-03-13T11:38:31Z
DOC: update the Period.start_time attribute docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index d7e66bf4c9320..2baf8c47ad7e3 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1164,6 +1164,32 @@ cdef class _Period(object): @property def start_time(self): + """ + Get the Timestamp for the start of the period. + + Returns + ------- + Timestamp + + See also + -------- + Period.end_time : Return the end Timestamp. + Period.dayofyear : Return the day of year. + Period.daysinmonth : Return the days in that month. + Period.dayofweek : Return the day of the week. + + Examples + -------- + >>> period = pd.Period('2012-1-1', freq='D') + >>> period + Period('2012-01-01', 'D') + + >>> period.start_time + Timestamp('2012-01-01 00:00:00') + + >>> period.end_time + Timestamp('2012-01-01 23:59:59.999999999') + """ return self.to_timestamp(how='S') @property
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ ] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` (pandas_dev) root@kalih:~/pythonpanda/pandas# python scripts/validate_docstrings.py pandas.Period.start_time ################################################################################ ##################### Docstring (pandas.Period.start_time) ##################### ################################################################################ Get the Timestamp for the start of the period. Returns ------- Timestamp See also -------- Period.dayofyear : Return the day of year. Period.daysinmonth : Return the days in that month. Period.dayofweek : Return the day of the week. Examples -------- >>> period = pd.Period('2012-1-1', freq='D') >>> period Period('2012-01-01', 'D') >>> period.start_time Timestamp('2012-01-01 00:00:00') >>> period.end_time Timestamp('2012-01-01 23:59:59.999999999') ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20325
2018-03-13T09:36:44Z
2018-03-14T14:38:18Z
2018-03-14T14:38:18Z
2018-03-14T14:38:18Z
DOC: update the Index.get duplicates docstring
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e40e084fe94d6..545324981c531 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1810,6 +1810,10 @@ def get_duplicates(self): [2.0, 3.0] >>> pd.Index(['a', 'b', 'b', 'c', 'c', 'c', 'd']).get_duplicates() ['b', 'c'] + + Note that for a DatetimeIndex, it does not return a list but a new + DatetimeIndex: + >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03', ... '2018-01-03', '2018-01-04', '2018-01-04'], ... format='%Y-%m-%d') @@ -1830,11 +1834,6 @@ def get_duplicates(self): ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() DatetimeIndex([], dtype='datetime64[ns]', freq=None) - - Notes - ----- - In case of datetime-like indexes, the function is overridden where the - result is converted to DatetimeIndex. """ from collections import defaultdict counter = defaultdict(lambda: 0)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################### Docstring (pandas.Index.get_duplicates) ################### ################################################################################ Extract duplicated index elements. Returns a sorted list of index elements which appear more than once in the index. Returns ------- array-like List of duplicated indexes. See Also -------- Index.duplicated : Return boolean array denoting duplicates. Index.drop_duplicates : Return Index with duplicates removed. Examples -------- Works on different Index of types. >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() [2, 3] >>> pd.Index([1., 2., 2., 3., 3., 3., 4.]).get_duplicates() [2.0, 3.0] >>> pd.Index(['a', 'b', 'b', 'c', 'c', 'c', 'd']).get_duplicates() ['b', 'c'] >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03', ... '2018-01-03', '2018-01-04', '2018-01-04'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() DatetimeIndex(['2018-01-03', '2018-01-04'], dtype='datetime64[ns]', freq=None) Sorts duplicated elements even when indexes are unordered. >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() [2, 3] Return empty array-like structure when all elements are unique. >>> pd.Index([1, 2, 3, 4]).get_duplicates() [] >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'], ... format='%Y-%m-%d') >>> pd.Index(dates).get_duplicates() DatetimeIndex([], dtype='datetime64[ns]', freq=None) ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Index.get_duplicates" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [ ] 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/20322
2018-03-13T08:31:25Z
2018-03-13T09:20:16Z
2018-03-13T09:20:16Z
2018-03-13T09:20:33Z
DOC : Update the Period.second docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index eda0a8492ad24..1c543eed41d83 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1295,6 +1295,25 @@ cdef class _Period(object): @property def second(self): + """ + Get the second component of the Period. + + Returns + ------- + int + The second of the Period (ranges from 0 to 59). + + See Also + -------- + Period.hour : Get the hour component of the Period. + Period.minute : Get the minute component of the Period. + + Examples + -------- + >>> p = pd.Period("2018-03-11 13:03:12.050000") + >>> p.second + 12 + """ base, mult = get_freq_code(self.freq) return psecond(self.ordinal, base)
``` # Period.second ############################################################################ ####################### Docstring (pandas.Period.second) ####################### ################################################################################ Get second of the minute component of the Period. Returns ------- int The second as an integer, between 0 and 59. See Also -------- Period.hour : Get the hour component of the Period. Period.minute : Get the minute component of the Period. Examples -------- >>> p = pd.Period("2018-03-11 13:03:12.050000") >>> p.second 12 ################################################################################ ################################## Validation ################################## ################################################################################ ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20319
2018-03-13T02:58:20Z
2018-03-13T11:41:20Z
2018-03-13T11:41:20Z
2018-03-17T11:02:10Z
DOC: update the pandas.Series.add_suffix docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ca54b744f02a4..6a68fccb46eac 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2951,7 +2951,8 @@ def add_prefix(self, prefix): See Also -------- - Series.add_suffix: Suffix labels with string `suffix`. + Series.add_suffix: Suffix row labels with string `suffix`. + DataFrame.add_suffix: Suffix column labels with string `suffix`. Examples -------- @@ -2990,15 +2991,57 @@ def add_prefix(self, prefix): def add_suffix(self, suffix): """ - Concatenate suffix string with panel items names. + Suffix labels with string `suffix`. + + For Series, the row labels are suffixed. + For DataFrame, the column labels are suffixed. Parameters ---------- - suffix : string + suffix : str + The string to add after each label. Returns ------- - with_suffix : type of caller + Series or DataFrame + New Series or DataFrame with updated labels. + + See Also + -------- + Series.add_prefix: Prefix row labels with string `prefix`. + DataFrame.add_prefix: Prefix column labels with string `prefix`. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4]) + >>> s + 0 1 + 1 2 + 2 3 + 3 4 + dtype: int64 + + >>> s.add_suffix('_item') + 0_item 1 + 1_item 2 + 2_item 3 + 3_item 4 + dtype: int64 + + >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) + >>> df + A B + 0 1 3 + 1 2 4 + 2 3 5 + 3 4 6 + + >>> df.add_suffix('_col') + A_col B_col + 0 1 3 + 1 2 4 + 2 3 5 + 3 4 6 """ new_data = self._data.add_suffix(suffix) return self._constructor(new_data).__finalize__(self)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ##################### Docstring (pandas.Series.add_suffix) ##################### ################################################################################ Add a suffix string to panel items names. Parameters ---------- suffix : str The string to add after each item name. Returns ------- Series Original Series with updated item names. See Also -------- pandas.Series.add_prefix: Concatenate prefix string with panel items names. Examples -------- >>> s = pd.Series([1,2,3,4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_suffix('_item') 0_item 1 1_item 2 2_item 3 3_item 4 dtype: int64 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20315
2018-03-12T20:36:37Z
2018-03-13T17:54:33Z
2018-03-13T17:54:33Z
2018-03-13T17:54:40Z
Doc : update the pandas.Period.minute docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 7763fe7b9008d..e82a149f5745b 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1246,6 +1246,25 @@ cdef class _Period(object): @property def minute(self): + """ + Get minute of the hour component of the Period. + + Returns + ------- + int + The minute as an integer, between 0 and 59. + + See Also + -------- + Period.hour : Get the hour component of the Period. + Period.second : Get the second component of the Period. + + Examples + -------- + >>> p = pd.Period("2018-03-11 13:03:12.050000") + >>> p.minute + 3 + """ base, mult = get_freq_code(self.freq) return pminute(self.ordinal, base)
# Period.minute ################################################################################ ####################### Docstring (pandas.Period.minute) ####################### ################################################################################ Get minute of the hour component of the Period. Returns ------- int The minute as an integer, between 0 and 59. See Also -------- Period.hour : Get the hour of the Period. Period.second : Get the second of the Period. Examples -------- >>> p = pd.Period("2018-03-11 13:03:12.050000") >>> p.minute 3 ################################################################################ ################################## Validation ################################## ################################################################################
https://api.github.com/repos/pandas-dev/pandas/pulls/20314
2018-03-12T20:31:31Z
2018-03-12T21:16:30Z
2018-03-12T21:16:30Z
2018-03-13T02:18:14Z
DOC: update docstring of pandas.Series.add_prefix docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 23654613104ec..64787869ef46c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2963,15 +2963,56 @@ def _update_inplace(self, result, verify_is_copy=True): def add_prefix(self, prefix): """ - Concatenate prefix string with panel items names. + Prefix labels with string `prefix`. + + For Series, the row labels are prefixed. + For DataFrame, the column labels are prefixed. Parameters ---------- - prefix : string + prefix : str + The string to add before each label. Returns ------- - with_prefix : type of caller + Series or DataFrame + New Series or DataFrame with updated labels. + + See Also + -------- + Series.add_suffix: Suffix labels with string `suffix`. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4]) + >>> s + 0 1 + 1 2 + 2 3 + 3 4 + dtype: int64 + + >>> s.add_prefix('item_') + item_0 1 + item_1 2 + item_2 3 + item_3 4 + dtype: int64 + + >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) + >>> df + A B + 0 1 3 + 1 2 4 + 2 3 5 + 3 4 6 + + >>> df.add_prefix('col_') + col_A col_B + 0 1 3 + 1 2 4 + 2 3 5 + 3 4 6 """ new_data = self._data.add_prefix(prefix) return self._constructor(new_data).__finalize__(self)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ##################### Docstring (pandas.Series.add_prefix) ##################### ################################################################################ Concatenate prefix string with panel items names. Parameters ---------- prefix : str The string to add before each item name. Returns ------- Series Original Series with updated item names. See Also -------- pandas.Series.add_suffix: Add a suffix string to panel items names. Examples -------- >>> s = pd.Series([1,2,3,4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_prefix('item_') item_0 1 item_1 2 item_2 3 item_3 4 dtype: int64 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20313
2018-03-12T20:17:40Z
2018-03-13T17:50:47Z
2018-03-13T17:50:47Z
2018-03-13T17:51:06Z
DOC : Update the pandas.Period.hour docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 7763fe7b9008d..d5241e5a706f5 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1241,6 +1241,31 @@ cdef class _Period(object): @property def hour(self): + """ + Get the hour of the day component of the Period. + + Returns + ------- + int + The hour as an integer, between 0 and 23. + + See Also + -------- + Period.second : Get the second component of the Period. + Period.minute : Get the minute component of the Period. + + Examples + -------- + >>> p = pd.Period("2018-03-11 13:03:12.050000") + >>> p.hour + 13 + + Period longer than a day + + >>> p = pd.Period("2018-03-11", freq="M") + >>> p.hour + 0 + """ base, mult = get_freq_code(self.freq) return phour(self.ordinal, base)
``` # Period.hour ################################################################################ ######################## Docstring (pandas.Period.hour) ######################## ################################################################################ Get hours of a day that a Period falls on. Returns ------- int See Also -------- Period.minute : Get the minute of hour Period.second : Get the second of hour Examples -------- >>> p = pd.Period("2018-03-11 13:03:12.050000") >>> p.hour 13 ################################################################################ ################################## Validation ################################## ################################################################################ ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20312
2018-03-12T19:30:49Z
2018-03-12T21:04:41Z
2018-03-12T21:04:41Z
2018-03-13T02:19:24Z
COMPAT: Ascii example
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index f3f5c80c66e2f..a57d48f1b9ce4 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1534,10 +1534,10 @@ def is_categorical(self): >>> idx.is_categorical() False - >>> s = pd.Series(["Peter", "Víctor", "Elisabeth", "Mar"]) + >>> s = pd.Series(["Peter", "Victor", "Elisabeth", "Mar"]) >>> s 0 Peter - 1 Víctor + 1 Victor 2 Elisabeth 3 Mar dtype: object
Py2 issues: ``` pytest -m single -r xX --junitxml=/tmp/single.xml --strict --only-slow --skip-network pandas Traceback (most recent call last): File "/home/travis/miniconda3/envs/pandas/lib/python2.7/site-packages/_pytest/config.py", line 366, in _importconftest mod = conftestpath.pyimport() File "/home/travis/miniconda3/envs/pandas/lib/python2.7/site-packages/py/_path/local.py", line 668, in pyimport __import__(modname) File "/home/travis/build/pandas-dev/pandas/pandas/__init__.py", line 45, in <module> from pandas.core.api import * File "/home/travis/build/pandas-dev/pandas/pandas/core/api.py", line 10, in <module> from pandas.core.groupby import Grouper File "/home/travis/build/pandas-dev/pandas/pandas/core/groupby.py", line 45, in <module> from pandas.core.index import (Index, MultiIndex, File "/home/travis/build/pandas-dev/pandas/pandas/core/index.py", line 2, in <module> from pandas.core.indexes.api import * File "/home/travis/build/pandas-dev/pandas/pandas/core/indexes/api.py", line 1, in <module> from pandas.core.indexes.base import (Index, File "/home/travis/build/pandas-dev/pandas/pandas/core/indexes/base.py", line 1537 SyntaxError: Non-ASCII character '\xc3' in file /home/travis/build/pandas-dev/pandas/pandas/core/indexes/base.py on line 1538, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details ERROR: could not load /home/travis/build/pandas-dev/pandas/pandas/conftest.py ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20311
2018-03-12T18:50:09Z
2018-03-12T19:06:32Z
2018-03-12T19:06:32Z
2018-03-12T19:06:35Z
DOC: update the pandas.DataFrame.pct_change docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d5bdeb7fe1a4d..b1326b84cefcd 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7515,29 +7515,118 @@ def _check_percentile(self, q): return q _shared_docs['pct_change'] = """ - Percent change over given number of periods. + Percentage change between the current and a prior element. + + Computes the percentage change from the immediately previous row by + default. This is useful in comparing the percentage of change in a time + series of elements. Parameters ---------- periods : int, default 1 - Periods to shift for forming percent change + Periods to shift for forming percent change. fill_method : str, default 'pad' - How to handle NAs before computing percent changes + How to handle NAs before computing percent changes. limit : int, default None - The number of consecutive NAs to fill before stopping + The number of consecutive NAs to fill before stopping. freq : DateOffset, timedelta, or offset alias string, optional - Increment to use from time series API (e.g. 'M' or BDay()) + Increment to use from time series API (e.g. 'M' or BDay()). + **kwargs + Additional keyword arguments are passed into + `DataFrame.shift` or `Series.shift`. Returns ------- - chg : %(klass)s + chg : Series or DataFrame + The same type as the calling object. - Notes - ----- + See Also + -------- + Series.diff : Compute the difference of two elements in a Series. + DataFrame.diff : Compute the difference of two elements in a DataFrame. + Series.shift : Shift the index by some number of periods. + DataFrame.shift : Shift the index by some number of periods. + + Examples + -------- + **Series** + + >>> s = pd.Series([90, 91, 85]) + >>> s + 0 90 + 1 91 + 2 85 + dtype: int64 + + >>> s.pct_change() + 0 NaN + 1 0.011111 + 2 -0.065934 + dtype: float64 + + >>> s.pct_change(periods=2) + 0 NaN + 1 NaN + 2 -0.055556 + dtype: float64 - By default, the percentage change is calculated along the stat - axis: 0, or ``Index``, for ``DataFrame`` and 1, or ``minor`` for - ``Panel``. You can change this with the ``axis`` keyword argument. + See the percentage change in a Series where filling NAs with last + valid observation forward to next valid. + + >>> s = pd.Series([90, 91, None, 85]) + >>> s + 0 90.0 + 1 91.0 + 2 NaN + 3 85.0 + dtype: float64 + + >>> s.pct_change(fill_method='ffill') + 0 NaN + 1 0.011111 + 2 0.000000 + 3 -0.065934 + dtype: float64 + + **DataFrame** + + Percentage change in French franc, Deutsche Mark, and Italian lira from + 1980-01-01 to 1980-03-01. + + >>> df = pd.DataFrame({ + ... 'FR': [4.0405, 4.0963, 4.3149], + ... 'GR': [1.7246, 1.7482, 1.8519], + ... 'IT': [804.74, 810.01, 860.13]}, + ... index=['1980-01-01', '1980-02-01', '1980-03-01']) + >>> df + FR GR IT + 1980-01-01 4.0405 1.7246 804.74 + 1980-02-01 4.0963 1.7482 810.01 + 1980-03-01 4.3149 1.8519 860.13 + + >>> df.pct_change() + FR GR IT + 1980-01-01 NaN NaN NaN + 1980-02-01 0.013810 0.013684 0.006549 + 1980-03-01 0.053365 0.059318 0.061876 + + Percentage of change in GOOG and APPL stock volume. Shows computing + the percentage change between columns. + + >>> df = pd.DataFrame({ + ... '2016': [1769950, 30586265], + ... '2015': [1500923, 40912316], + ... '2014': [1371819, 41403351]}, + ... index=['GOOG', 'APPL']) + >>> df + 2016 2015 2014 + GOOG 1769950 1500923 1371819 + APPL 30586265 40912316 41403351 + + >>> df.pct_change(axis='columns') + 2016 2015 2014 + GOOG NaN -0.151997 -0.086016 + APPL NaN 0.337604 0.012002 """ @Appender(_shared_docs['pct_change'] % _shared_doc_kwargs)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ ] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################### Docstring (pandas.DataFrame.pct_change) ################### ################################################################################ Percentage change between the current and previous element. This is useful in comparing the percentage of change in a time series of elements. Parameters ---------- periods : int, default 1 Periods to shift for forming percent change. fill_method : str, default 'pad' How to handle NAs before computing percent changes. limit : int, default None The number of consecutive NAs to fill before stopping. freq : DateOffset, timedelta, or offset alias string, optional Increment to use from time series API (e.g. 'M' or BDay()). **kwargs : mapping, optional Additional keyword arguments are passed into `DataFrame.shift` or `Series.shift`. Returns ------- chg : Series or DataFrame The same type as the calling object. Examples -------- See the percentage change in a Series. >>> s = pd.Series([90, 91, 85]) >>> s 0 90 1 91 2 85 dtype: int64 >>> s.pct_change() 0 NaN 1 0.011111 2 -0.065934 dtype: float64 See the percentage change in a Series where filling NAs with last valid observation forward to next valid. >>> s = pd.Series([90, 91, None, 85]) >>> s 0 90.0 1 91.0 2 NaN 3 85.0 dtype: float64 >>> s.pct_change(fill_method='ffill') 0 NaN 1 0.011111 2 0.000000 3 -0.065934 dtype: float64 Percentage change in French franc, Deutsche Mark, and Italian lira from 1 January 1980 to 1 March 1980. >>> df = pd.DataFrame({ ... 'FR': [4.0405, 4.0963, 4.3149], ... 'GR': [1.7246, 1.7482, 1.8519], ... 'IT': [804.74, 810.01, 860.13]}, ... index=['1980-01-01', '1980-02-01', '1980-03-01']) >>> df FR GR IT 1980-01-01 4.0405 1.7246 804.74 1980-02-01 4.0963 1.7482 810.01 1980-03-01 4.3149 1.8519 860.13 >>> df.pct_change() FR GR IT 1980-01-01 NaN NaN NaN 1980-02-01 0.013810 0.013684 0.006549 1980-03-01 0.053365 0.059318 0.061876 Percentage of change in GOOG and APPL stock volume. >>> df = pd.DataFrame({ ... '2016': [1769950, 30586265], ... '2015': [1500923, 40912316], ... '2014': [1371819, 41403351]}, ... index=['GOOG', 'APPL']) >>> df 2016 2015 2014 GOOG 1769950 1500923 1371819 APPL 30586265 40912316 41403351 >>> df.pct_change(axis='columns') 2016 2015 2014 GOOG NaN -0.151997 -0.086016 APPL NaN 0.337604 0.012002 See Also -------- DataFrame.diff : see the difference of two columns Series.diff : see the difference of two columns ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'kwargs'} not documented Unknown parameters {'**kwargs'} ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20310
2018-03-12T18:04:05Z
2018-03-12T20:19:14Z
2018-03-12T20:19:14Z
2018-03-12T20:53:13Z
DOC: update the pandas.Series.str.split docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 11081535cf63f..cb55108e9d05a 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1116,9 +1116,8 @@ def str_split(arr, pat=None, n=None): Returns ------- - split : Series/Index or DataFrame/MultiIndex of objects - Type matches caller unless ``expand=True`` (return type is DataFrame or - MultiIndex) + Series, Index, DataFrame or MultiIndex + Type matches caller unless ``expand=True`` (see Notes). Notes ----- @@ -1129,6 +1128,16 @@ def str_split(arr, pat=None, n=None): - If for a certain row the number of found splits < `n`, append `None` for padding up to `n` if ``expand=True`` + If using ``expand=True``, Series and Index callers return DataFrame and + MultiIndex objects, respectively. + + See Also + -------- + str.split : Standard library version of this method. + Series.str.get_dummies : Split each string into dummy variables. + Series.str.partition : Split string on a separator, returning + the before, separator, and after components. + Examples -------- >>> s = pd.Series(["this is good text", "but this is even better"]) @@ -1145,8 +1154,10 @@ def str_split(arr, pat=None, n=None): 1 [but this is even better] dtype: object - When using ``expand=True``, the split elements will - expand out into separate columns. + When using ``expand=True``, the split elements will expand out into + separate columns. + + For Series object, output return type is DataFrame. >>> s.str.split(expand=True) 0 1 2 3 4 @@ -1157,6 +1168,13 @@ def str_split(arr, pat=None, n=None): 0 this good text 1 but this even better + For Index object, output return type is MultiIndex. + + >>> i = pd.Index(["ba 100 001", "ba 101 002", "ba 102 003"]) + >>> i.str.split(expand=True) + MultiIndex(levels=[['ba'], ['100', '101', '102'], ['001', '002', '003']], + labels=[[0, 0, 0], [0, 1, 2], [0, 1, 2]]) + Parameter `n` can be used to limit the number of splits in the output. >>> s.str.split("is", n=1)
Following up from discussion on #20282 - [x] PR title is "DOC: update the pandas.Series.str.split docstring" - [x] The validation script passes: `scripts/validate_docstrings.py pandas.Series.str.split docstring` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single pandas.Series.str.split docstring` ``` ################################################################################ ##################### Docstring (pandas.Series.str.split) ##################### ################################################################################ Split strings around given separator/delimiter. Split each string in the caller's values by given pattern, propagating NaN values. Equivalent to :meth:`str.split`. Parameters ---------- pat : str, optional String or regular expression to split on. If not specified, split on whitespace. n : int, default -1 (all) Limit number of splits in output. ``None``, 0 and -1 will be interpreted as return all splits. expand : bool, default False Expand the splitted strings into separate columns. * If ``True``, return DataFrame/MultiIndex expanding dimensionality. * If ``False``, return Series/Index, containing lists of strings. Returns ------- split : Series/Index or DataFrame/MultiIndex of objects Type matches caller unless ``expand=True`` (return type is DataFrame or MultiIndex) Notes ----- The handling of the `n` keyword depends on the number of found splits: - If found splits > `n`, make first `n` splits only - If found splits <= `n`, make all splits - If for a certain row the number of found splits < `n`, append `None` for padding up to `n` if ``expand=True`` Examples -------- >>> s = pd.Series(["this is good text", "but this is even better"]) By default, split will return an object of the same size having lists containing the split elements >>> s.str.split() 0 [this, is, good, text] 1 [but, this, is, even, better] dtype: object >>> s.str.split("random") 0 [this is good text] 1 [but this is even better] dtype: object When using ``expand=True``, the split elements will expand out into separate columns. For Series object, output return type is DataFrame. >>> s.str.split(expand=True) 0 1 2 3 4 0 this is good text None 1 but this is even better >>> s.str.split(" is ", expand=True) 0 1 0 this good text 1 but this even better For Index object, output return type is MultiIndex. >>> i = pd.Index(["ba 100 001", "ba 101 002", "ba 102 003"]) >>> i.str.split(expand=True) MultiIndex(levels=[['ba'], ['100', '101', '102'], ['001', '002', '003']], labels=[[0, 0, 0], [0, 1, 2], [0, 1, 2]]) Parameter `n` can be used to limit the number of splits in the output. >>> s.str.split("is", n=1) 0 [th, is good text] 1 [but th, is even better] dtype: object >>> s.str.split("is", n=1, expand=True) 0 1 0 th is good text 1 but th is even better If NaN is present, it is propagated throughout the columns during the split. >>> s = pd.Series(["this is good text", "but this is even better", np.nan]) >>> s.str.split(n=3, expand=True) 0 1 2 3 0 this is good text 1 but this is even better 2 NaN NaN NaN NaN ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: See Also section not found ``` @jorisvandenbossche @WillAyd
https://api.github.com/repos/pandas-dev/pandas/pulls/20307
2018-03-12T16:34:14Z
2018-03-13T11:58:03Z
2018-03-13T11:58:03Z
2018-03-13T11:58:03Z
DOC: update the Index.sort_values docstring
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e82b641db98fd..6233fea2c52d0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2311,7 +2311,46 @@ def asof_locs(self, where, mask): def sort_values(self, return_indexer=False, ascending=True): """ - Return sorted copy of Index + Return a sorted copy of the index. + + Return a sorted copy of the index, and optionally return the indices + that sorted the index itself. + + Parameters + ---------- + return_indexer : bool, default False + Should the indices that would sort the index be returned. + ascending : bool, default True + Should the index values be sorted in an ascending order. + + Returns + ------- + sorted_index : pandas.Index + Sorted copy of the index. + indexer : numpy.ndarray, optional + The indices that the index itself was sorted by. + + See Also + -------- + pandas.Series.sort_values : Sort values of a Series. + pandas.DataFrame.sort_values : Sort values in a DataFrame. + + Examples + -------- + >>> idx = pd.Index([10, 100, 1, 1000]) + >>> idx + Int64Index([10, 100, 1, 1000], dtype='int64') + + Sort values in ascending order (default behavior). + + >>> idx.sort_values() + Int64Index([1, 10, 100, 1000], dtype='int64') + + Sort values in descending order, and also get the indices `idx` was + sorted by. + + >>> idx.sort_values(ascending=False, return_indexer=True) + (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2])) """ _as = self.argsort() if not ascending:
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ##################### Docstring (pandas.Index.sort_values) ##################### ################################################################################ Return a sorted copy of the index. Return a sorted copy of the index, and optionally return the indices that sorted the index itself. Parameters ---------- return_indexer : bool, default False Should the indices that would sort the index be returned. ascending : bool, default True Should the index values be sorted in an ascending order. Returns ------- sorted_index : pandas.Index Sorted copy of the index. _as : numpy.ndarray, optional The indices that the index itself was sorted by. See Also -------- pandas.Series.sort_values : Sort values of a Series. pandas.DataFrame.sort_values : Sort values in a DataFrame. Examples -------- >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Int64Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Int64Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices `idx` was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2])) ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Index.sort_values" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20299
2018-03-12T12:21:22Z
2018-03-12T20:21:16Z
2018-03-12T20:21:16Z
2018-03-12T20:29:39Z
DOC: update the Period.days_in_month docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 89f38724cde1a..adf4f0569965f 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1270,6 +1270,35 @@ cdef class _Period(object): @property def days_in_month(self): + """ + Get the total number of days in the month that this period falls on. + + Returns + ------- + int + + See Also + -------- + Period.daysinmonth : Gets the number of days in the month. + DatetimeIndex.daysinmonth : Gets the number of days in the month. + calendar.monthrange : Returns a tuple containing weekday + (0-6 ~ Mon-Sun) and number of days (28-31). + + Examples + -------- + >>> p = pd.Period('2018-2-17') + >>> p.days_in_month + 28 + + >>> pd.Period('2018-03-01').days_in_month + 31 + + Handles the leap year case as well: + + >>> p = pd.Period('2016-2-17') + >>> p.days_in_month + 29 + """ base, mult = get_freq_code(self.freq) return pdays_in_month(self.ordinal, base)
- [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ ] It has been proofread on language by another sprint participant ``` ################################################################################ ################### Docstring (pandas.Period.days_in_month) ################### ################################################################################ Get the total number of days in the month that this period falls on. Returns ------- int See Also -------- Period.daysinmonth : Returns the number of days in the month. DatetimeIndex.daysinmonth : Return the number of days in the month. calendar.monthrange : Return a tuple containing weekday (0-6 ~ Mon-Sun) and number of days (28-31). Examples -------- >>> p= pd.Period('2018-2-17') >>> p.days_in_month 28 >>> import datetime >>> pd.Period(datetime.datetime.today(), freq= 'B').days_in_month 31 Handles the leap year case as well: >>> p= pd.Period('2016-2-17') >>> p.days_in_month 29 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found ``` * Short summary summarises pretty much all the characteristics of this attribute.
https://api.github.com/repos/pandas-dev/pandas/pulls/20297
2018-03-12T11:38:30Z
2018-03-12T16:37:52Z
2018-03-12T16:37:52Z
2018-03-12T21:18:06Z
DOC: update the Period.daysinmonth docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 89f38724cde1a..c5829d1846f0a 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1275,6 +1275,24 @@ cdef class _Period(object): @property def daysinmonth(self): + """ + Get the total number of days of the month that the Period falls in. + + Returns + ------- + int + + See Also + -------- + Period.days_in_month : Return the days of the month + Period.dayofyear : Return the day of the year + + Examples + -------- + >>> p = pd.Period("2018-03-11", freq='H') + >>> p.daysinmonth + 31 + """ return self.days_in_month @property
# Period.daysinmonth ################################################################################ #################### Docstring (pandas.Period.daysinmonth) #################### ################################################################################ Return total number of days of the month in given Period. This attribute returns the total number of days of given month Returns ------- Int Number of days with in month See also -------- Period.dayofweek Return the day of the week Period.dayofyear Return the day of the year Examples -------- >>> import pandas as pd >>> p = pd.Period("2018-03-11", freq='H') >>> p.daysinmonth 31 ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Period.daysinmonth" correct. :)
https://api.github.com/repos/pandas-dev/pandas/pulls/20295
2018-03-12T07:10:55Z
2018-03-12T15:02:07Z
2018-03-12T15:02:07Z
2018-03-12T15:13:08Z
DOC: Update the Period.day docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 89f38724cde1a..af4ec4e8a9a66 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1217,6 +1217,25 @@ cdef class _Period(object): @property def day(self): + """ + Get day of the month that a Period falls on. + + Returns + ------- + int + + See Also + -------- + Period.dayofweek : Get the day of the week + + Period.dayofyear : Get the day of the year + + Examples + -------- + >>> p = pd.Period("2018-03-11", freq='H') + >>> p.day + 11 + """ base, mult = get_freq_code(self.freq) return pday(self.ordinal, base)
# Period.day Docstring ################################################################################ ######################## Docstring (pandas.Period.day) ######################## ################################################################################ Return the number of days of particular month of a given Period. This attribute returns the total number of days of given month on which the particular date occurs. Returns ------- Int Number of days till particular date See also -------- Period.dayofweek Return the day of the week Period.dayofyear Return the day of the year Examples -------- >>> import pandas as pd >>> p = pd.Period("2018-03-11", freq='H') >>> p.day 11 ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Period.day" correct. :)
https://api.github.com/repos/pandas-dev/pandas/pulls/20294
2018-03-12T05:26:55Z
2018-03-12T10:26:24Z
2018-03-12T10:26:24Z
2018-03-12T10:32:37Z
Clean / Consolidate pandas/tests/io/test_html.py
diff --git a/ci/requirements-2.7_COMPAT.pip b/ci/requirements-2.7_COMPAT.pip index 13cd35a923124..0e154dbc07525 100644 --- a/ci/requirements-2.7_COMPAT.pip +++ b/ci/requirements-2.7_COMPAT.pip @@ -1,4 +1,4 @@ html5lib==1.0b2 -beautifulsoup4==4.2.0 +beautifulsoup4==4.2.1 openpyxl argparse diff --git a/ci/requirements-optional-conda.txt b/ci/requirements-optional-conda.txt index 6edb8d17337e4..65357ce2018d2 100644 --- a/ci/requirements-optional-conda.txt +++ b/ci/requirements-optional-conda.txt @@ -1,4 +1,4 @@ -beautifulsoup4 +beautifulsoup4>=4.2.1 blosc bottleneck fastparquet diff --git a/ci/requirements-optional-pip.txt b/ci/requirements-optional-pip.txt index 8d4421ba2b681..43c7d47892095 100644 --- a/ci/requirements-optional-pip.txt +++ b/ci/requirements-optional-pip.txt @@ -1,6 +1,6 @@ # This file was autogenerated by scripts/convert_deps.py # Do not modify directly -beautifulsoup4 +beautifulsoup4>=4.2.1 blosc bottleneck fastparquet diff --git a/doc/source/install.rst b/doc/source/install.rst index 07f57dbd65709..7d741c6c2c75a 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -266,6 +266,12 @@ Optional Dependencies * One of the following combinations of libraries is needed to use the top-level :func:`~pandas.read_html` function: + .. versionchanged:: 0.23.0 + + .. note:: + + If using BeautifulSoup4 a minimum version of 4.2.1 is required + * `BeautifulSoup4`_ and `html5lib`_ (Any recent version of `html5lib`_ is okay.) * `BeautifulSoup4`_ and `lxml`_ @@ -282,9 +288,6 @@ Optional Dependencies * You are highly encouraged to read :ref:`HTML Table Parsing gotchas <io.html.gotchas>`. It explains issues surrounding the installation and usage of the above three libraries. - * You may need to install an older version of `BeautifulSoup4`_: - Versions 4.2.1, 4.1.3 and 4.0.2 have been confirmed for 64 and 32-bit - Ubuntu/Debian .. note:: diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 791365295c268..c08e22af295f4 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -358,13 +358,15 @@ Dependencies have increased minimum versions We have updated our minimum supported versions of dependencies (:issue:`15184`). If installed, we now require: -+-----------------+-----------------+----------+ -| Package | Minimum Version | Required | -+=================+=================+==========+ -| python-dateutil | 2.5.0 | X | -+-----------------+-----------------+----------+ -| openpyxl | 2.4.0 | | -+-----------------+-----------------+----------+ ++-----------------+-----------------+----------+---------------+ +| Package | Minimum Version | Required | Issue | ++=================+=================+==========+===============+ +| python-dateutil | 2.5.0 | X | :issue:`15184`| ++-----------------+-----------------+----------+---------------+ +| openpyxl | 2.4.0 | | :issue:`15184`| ++-----------------+-----------------+----------+---------------+ +| beautifulsoup4 | 4.2.1 | | :issue:`20082`| ++-----------------+-----------------+----------+---------------+ .. _whatsnew_0230.api_breaking.dict_insertion_order: diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 78aaf4596c8b7..aefa1ddd6cf0b 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -131,6 +131,9 @@ def lmap(*args, **kwargs): def lfilter(*args, **kwargs): return list(filter(*args, **kwargs)) + from importlib import reload + reload = reload + else: # Python 2 import re @@ -184,6 +187,7 @@ def get_range_parameters(data): lmap = builtins.map lfilter = builtins.filter + reload = builtins.reload if PY2: def iteritems(obj, **kw): diff --git a/pandas/io/html.py b/pandas/io/html.py index 300a5a151f5d2..ba5da1b4e3a76 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -14,8 +14,7 @@ from pandas.core.dtypes.common import is_list_like from pandas.errors import EmptyDataError -from pandas.io.common import (_is_url, urlopen, - parse_url, _validate_header_arg) +from pandas.io.common import _is_url, urlopen, _validate_header_arg from pandas.io.parsers import TextParser from pandas.compat import (lrange, lmap, u, string_types, iteritems, raise_with_traceback, binary_type) @@ -554,8 +553,7 @@ def _parse_td(self, row): return row.xpath('.//td|.//th') def _parse_tr(self, table): - expr = './/tr[normalize-space()]' - return table.xpath(expr) + return table.xpath('.//tr') def _parse_tables(self, doc, match, kwargs): pattern = match.pattern @@ -606,18 +604,20 @@ def _build_doc(self): """ from lxml.html import parse, fromstring, HTMLParser from lxml.etree import XMLSyntaxError - - parser = HTMLParser(recover=False, encoding=self.encoding) + parser = HTMLParser(recover=True, encoding=self.encoding) try: - # try to parse the input in the simplest way - r = parse(self.io, parser=parser) - + if _is_url(self.io): + with urlopen(self.io) as f: + r = parse(f, parser=parser) + else: + # try to parse the input in the simplest way + r = parse(self.io, parser=parser) try: r = r.getroot() except AttributeError: pass - except (UnicodeDecodeError, IOError): + except (UnicodeDecodeError, IOError) as e: # if the input is a blob of html goop if not _is_url(self.io): r = fromstring(self.io, parser=parser) @@ -627,17 +627,7 @@ def _build_doc(self): except AttributeError: pass else: - # not a url - scheme = parse_url(self.io).scheme - if scheme not in _valid_schemes: - # lxml can't parse it - msg = (('{invalid!r} is not a valid url scheme, valid ' - 'schemes are {valid}') - .format(invalid=scheme, valid=_valid_schemes)) - raise ValueError(msg) - else: - # something else happened: maybe a faulty connection - raise + raise e else: if not hasattr(r, 'text_content'): raise XMLSyntaxError("no text parsed from document", 0, 0, 0) @@ -657,12 +647,21 @@ def _parse_raw_thead(self, table): thead = table.xpath(expr) res = [] if thead: - trs = self._parse_tr(thead[0]) - for tr in trs: - cols = [_remove_whitespace(x.text_content()) for x in - self._parse_td(tr)] + # Grab any directly descending table headers first + ths = thead[0].xpath('./th') + if ths: + cols = [_remove_whitespace(x.text_content()) for x in ths] if any(col != '' for col in cols): res.append(cols) + else: + trs = self._parse_tr(thead[0]) + + for tr in trs: + cols = [_remove_whitespace(x.text_content()) for x in + self._parse_td(tr)] + + if any(col != '' for col in cols): + res.append(cols) return res def _parse_raw_tfoot(self, table): @@ -739,14 +738,10 @@ def _parser_dispatch(flavor): raise ImportError( "BeautifulSoup4 (bs4) not found, please install it") import bs4 - if LooseVersion(bs4.__version__) == LooseVersion('4.2.0'): - raise ValueError("You're using a version" - " of BeautifulSoup4 (4.2.0) that has been" - " known to cause problems on certain" - " operating systems such as Debian. " - "Please install a version of" - " BeautifulSoup4 != 4.2.0, both earlier" - " and later releases will work.") + if LooseVersion(bs4.__version__) <= LooseVersion('4.2.0'): + raise ValueError("A minimum version of BeautifulSoup 4.2.1 " + "is required") + else: if not _HAS_LXML: raise ImportError("lxml not found, please install it") diff --git a/pandas/tests/io/data/banklist.html b/pandas/tests/io/data/banklist.html index cbcce5a2d49ff..c6f0e47c2a3ef 100644 --- a/pandas/tests/io/data/banklist.html +++ b/pandas/tests/io/data/banklist.html @@ -340,6 +340,7 @@ <h1 class="page_title">Failed Bank List</h1> <td class="closing">April 19, 2013</td> <td class="updated">April 23, 2013</td> </tr> + <tr> <td class="institution"><a href="goldcanyon.html">Gold Canyon Bank</a></td> <td class="city">Gold Canyon</td> <td class="state">AZ</td> diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index b18104e951504..79b9a3715efd2 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -4,17 +4,8 @@ import os import re import threading -import warnings - -# imports needed for Python 3.x but will fail under Python 2.x -try: - from importlib import import_module, reload -except ImportError: - import_module = __import__ - - -from distutils.version import LooseVersion +from functools import partial import pytest @@ -23,48 +14,18 @@ from pandas import (DataFrame, MultiIndex, read_csv, Timestamp, Index, date_range, Series) -from pandas.compat import (map, zip, StringIO, string_types, BytesIO, - is_platform_windows, PY3) -from pandas.io.common import URLError, urlopen, file_path_to_url +from pandas.compat import (map, zip, StringIO, BytesIO, + is_platform_windows, PY3, reload) +from pandas.io.common import URLError, file_path_to_url import pandas.io.html from pandas.io.html import read_html from pandas._libs.parsers import ParserError import pandas.util.testing as tm +import pandas.util._test_decorators as td from pandas.util.testing import makeCustomDataframe as mkdf, network -def _have_module(module_name): - try: - import_module(module_name) - return True - except ImportError: - return False - - -def _skip_if_no(module_name): - if not _have_module(module_name): - pytest.skip("{0!r} not found".format(module_name)) - - -def _skip_if_none_of(module_names): - if isinstance(module_names, string_types): - _skip_if_no(module_names) - if module_names == 'bs4': - import bs4 - if LooseVersion(bs4.__version__) == LooseVersion('4.2.0'): - pytest.skip("Bad version of bs4: 4.2.0") - else: - not_found = [module_name for module_name in module_names if not - _have_module(module_name)] - if set(not_found) & set(module_names): - pytest.skip("{0!r} not found".format(not_found)) - if 'bs4' in module_names: - import bs4 - if LooseVersion(bs4.__version__) == LooseVersion('4.2.0'): - pytest.skip("Bad version of bs4: 4.2.0") - - DATA_PATH = tm.get_data_path() @@ -82,33 +43,45 @@ def assert_framelist_equal(list1, list2, *args, **kwargs): assert not frame_i.empty, 'frames are both empty' -def test_bs4_version_fails(): - _skip_if_none_of(('bs4', 'html5lib')) +@td.skip_if_no('bs4') +def test_bs4_version_fails(monkeypatch): import bs4 - if LooseVersion(bs4.__version__) == LooseVersion('4.2.0'): - tm.assert_raises(AssertionError, read_html, os.path.join(DATA_PATH, - "spam.html"), - flavor='bs4') + monkeypatch.setattr(bs4, '__version__', '4.2') + with tm.assert_raises_regex(ValueError, "minimum version"): + read_html(os.path.join(DATA_PATH, "spam.html"), flavor='bs4') -class ReadHtmlMixin(object): +def test_invalid_flavor(): + url = 'google.com' + with pytest.raises(ValueError): + read_html(url, 'google', flavor='not a* valid**++ flaver') - def read_html(self, *args, **kwargs): - kwargs.setdefault('flavor', self.flavor) - return read_html(*args, **kwargs) + +@td.skip_if_no('bs4') +@td.skip_if_no('lxml') +def test_same_ordering(): + filename = os.path.join(DATA_PATH, 'valid_markup.html') + dfs_lxml = read_html(filename, index_col=0, flavor=['lxml']) + dfs_bs4 = read_html(filename, index_col=0, flavor=['bs4']) + assert_framelist_equal(dfs_lxml, dfs_bs4) -class TestReadHtml(ReadHtmlMixin): - flavor = 'bs4' +@pytest.mark.parametrize("flavor", [ + pytest.param('bs4', marks=pytest.mark.skipif( + not td.safe_import('lxml'), reason='No bs4')), + pytest.param('lxml', marks=pytest.mark.skipif( + not td.safe_import('lxml'), reason='No lxml'))], scope="class") +class TestReadHtml(object): spam_data = os.path.join(DATA_PATH, 'spam.html') spam_data_kwargs = {} if PY3: spam_data_kwargs['encoding'] = 'UTF-8' banklist_data = os.path.join(DATA_PATH, 'banklist.html') - @classmethod - def setup_class(cls): - _skip_if_none_of(('bs4', 'html5lib')) + @pytest.fixture(autouse=True, scope="function") + def set_defaults(self, flavor, request): + self.read_html = partial(read_html, flavor=flavor) + yield def test_to_html_compat(self): df = mkdf(4, 3, data_gen_f=lambda *args: rand(), c_idx_names=False, @@ -150,7 +123,6 @@ def test_spam_no_types(self): df1 = self.read_html(self.spam_data, '.*Water.*') df2 = self.read_html(self.spam_data, 'Unit') assert_framelist_equal(df1, df2) - assert df1[0].iloc[0, 0] == 'Proximates' assert df1[0].columns[0] == 'Nutrient' @@ -667,6 +639,9 @@ def test_computer_sales_page(self): r"multi_index of columns"): self.read_html(data, header=[0, 1]) + data = os.path.join(DATA_PATH, 'computer_sales_page.html') + assert self.read_html(data, header=[1, 2]) + def test_wikipedia_states_table(self): data = os.path.join(DATA_PATH, 'wikipedia_states.html') assert os.path.isfile(data), '%r is not a file' % data @@ -674,39 +649,6 @@ def test_wikipedia_states_table(self): result = self.read_html(data, 'Arizona', header=1)[0] assert result['sq mi'].dtype == np.dtype('float64') - @pytest.mark.parametrize("displayed_only,exp0,exp1", [ - (True, DataFrame(["foo"]), None), - (False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"]))]) - def test_displayed_only(self, displayed_only, exp0, exp1): - # GH 20027 - data = StringIO("""<html> - <body> - <table> - <tr> - <td> - foo - <span style="display:none;text-align:center">bar</span> - <span style="display:none">baz</span> - <span style="display: none">qux</span> - </td> - </tr> - </table> - <table style="display: none"> - <tr> - <td>foo</td> - </tr> - </table> - </body> - </html>""") - - dfs = self.read_html(data, displayed_only=displayed_only) - tm.assert_frame_equal(dfs[0], exp0) - - if exp1 is not None: - tm.assert_frame_equal(dfs[1], exp1) - else: - assert len(dfs) == 1 # Should not parse hidden table - def test_decimal_rows(self): # GH 12907 @@ -815,80 +757,6 @@ def test_multiple_header_rows(self): html_df = read_html(html, )[0] tm.assert_frame_equal(expected_df, html_df) - -def _lang_enc(filename): - return os.path.splitext(os.path.basename(filename))[0].split('_') - - -class TestReadHtmlEncoding(object): - files = glob.glob(os.path.join(DATA_PATH, 'html_encoding', '*.html')) - flavor = 'bs4' - - @classmethod - def setup_class(cls): - _skip_if_none_of((cls.flavor, 'html5lib')) - - def read_html(self, *args, **kwargs): - kwargs['flavor'] = self.flavor - return read_html(*args, **kwargs) - - def read_filename(self, f, encoding): - return self.read_html(f, encoding=encoding, index_col=0) - - def read_file_like(self, f, encoding): - with open(f, 'rb') as fobj: - return self.read_html(BytesIO(fobj.read()), encoding=encoding, - index_col=0) - - def read_string(self, f, encoding): - with open(f, 'rb') as fobj: - return self.read_html(fobj.read(), encoding=encoding, index_col=0) - - def test_encode(self): - assert self.files, 'no files read from the data folder' - for f in self.files: - _, encoding = _lang_enc(f) - try: - from_string = self.read_string(f, encoding).pop() - from_file_like = self.read_file_like(f, encoding).pop() - from_filename = self.read_filename(f, encoding).pop() - tm.assert_frame_equal(from_string, from_file_like) - tm.assert_frame_equal(from_string, from_filename) - except Exception: - # seems utf-16/32 fail on windows - if is_platform_windows(): - if '16' in encoding or '32' in encoding: - continue - raise - - -class TestReadHtmlEncodingLxml(TestReadHtmlEncoding): - flavor = 'lxml' - - @classmethod - def setup_class(cls): - super(TestReadHtmlEncodingLxml, cls).setup_class() - _skip_if_no(cls.flavor) - - -class TestReadHtmlLxml(ReadHtmlMixin): - flavor = 'lxml' - - @classmethod - def setup_class(cls): - _skip_if_no('lxml') - - def test_data_fail(self): - from lxml.etree import XMLSyntaxError - spam_data = os.path.join(DATA_PATH, 'spam.html') - banklist_data = os.path.join(DATA_PATH, 'banklist.html') - - with pytest.raises(XMLSyntaxError): - self.read_html(spam_data) - - with pytest.raises(XMLSyntaxError): - self.read_html(banklist_data) - def test_works_on_valid_markup(self): filename = os.path.join(DATA_PATH, 'valid_markup.html') dfs = self.read_html(filename, index_col=0) @@ -897,7 +765,6 @@ def test_works_on_valid_markup(self): @pytest.mark.slow def test_fallback_success(self): - _skip_if_none_of(('bs4', 'html5lib')) banklist_data = os.path.join(DATA_PATH, 'banklist.html') self.read_html(banklist_data, '.*Water.*', flavor=['lxml', 'html5lib']) @@ -908,27 +775,6 @@ def test_to_html_timestamp(self): result = df.to_html() assert '2000-01-01' in result - def test_parse_dates_list(self): - df = DataFrame({'date': date_range('1/1/2001', periods=10)}) - expected = df.to_html() - res = self.read_html(expected, parse_dates=[1], index_col=0) - tm.assert_frame_equal(df, res[0]) - res = self.read_html(expected, parse_dates=['date'], index_col=0) - tm.assert_frame_equal(df, res[0]) - - def test_parse_dates_combine(self): - raw_dates = Series(date_range('1/1/2001', periods=10)) - df = DataFrame({'date': raw_dates.map(lambda x: str(x.date())), - 'time': raw_dates.map(lambda x: str(x.time()))}) - res = self.read_html(df.to_html(), parse_dates={'datetime': [1, 2]}, - index_col=1) - newdf = DataFrame({'datetime': raw_dates}) - tm.assert_frame_equal(newdf, res[0]) - - def test_computer_sales_page(self): - data = os.path.join(DATA_PATH, 'computer_sales_page.html') - self.read_html(data, header=[0, 1]) - @pytest.mark.parametrize("displayed_only,exp0,exp1", [ (True, DataFrame(["foo"]), None), (False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"]))]) @@ -962,134 +808,99 @@ def test_displayed_only(self, displayed_only, exp0, exp1): else: assert len(dfs) == 1 # Should not parse hidden table + @pytest.mark.parametrize("f", glob.glob( + os.path.join(DATA_PATH, 'html_encoding', '*.html'))) + def test_encode(self, f): + _, encoding = os.path.splitext(os.path.basename(f))[0].split('_') -def test_invalid_flavor(): - url = 'google.com' - with pytest.raises(ValueError): - read_html(url, 'google', flavor='not a* valid**++ flaver') - - -def get_elements_from_file(url, element='table'): - _skip_if_none_of(('bs4', 'html5lib')) - url = file_path_to_url(url) - from bs4 import BeautifulSoup - with urlopen(url) as f: - soup = BeautifulSoup(f, features='html5lib') - return soup.find_all(element) - - -@pytest.mark.slow -def test_bs4_finds_tables(): - filepath = os.path.join(DATA_PATH, "spam.html") - with warnings.catch_warnings(): - warnings.filterwarnings('ignore') - assert get_elements_from_file(filepath, 'table') - - -def get_lxml_elements(url, element): - _skip_if_no('lxml') - from lxml.html import parse - doc = parse(url) - return doc.xpath('.//{0}'.format(element)) - - -@pytest.mark.slow -def test_lxml_finds_tables(): - filepath = os.path.join(DATA_PATH, "spam.html") - assert get_lxml_elements(filepath, 'table') - - -@pytest.mark.slow -def test_lxml_finds_tbody(): - filepath = os.path.join(DATA_PATH, "spam.html") - assert get_lxml_elements(filepath, 'tbody') - - -def test_same_ordering(): - _skip_if_none_of(['bs4', 'lxml', 'html5lib']) - filename = os.path.join(DATA_PATH, 'valid_markup.html') - dfs_lxml = read_html(filename, index_col=0, flavor=['lxml']) - dfs_bs4 = read_html(filename, index_col=0, flavor=['bs4']) - assert_framelist_equal(dfs_lxml, dfs_bs4) - - -class ErrorThread(threading.Thread): - def run(self): try: - super(ErrorThread, self).run() - except Exception as e: - self.err = e - else: - self.err = None + with open(f, 'rb') as fobj: + from_string = self.read_html(fobj.read(), encoding=encoding, + index_col=0).pop() + with open(f, 'rb') as fobj: + from_file_like = self.read_html(BytesIO(fobj.read()), + encoding=encoding, + index_col=0).pop() -@pytest.mark.slow -def test_importcheck_thread_safety(): - # see gh-16928 + from_filename = self.read_html(f, encoding=encoding, + index_col=0).pop() + tm.assert_frame_equal(from_string, from_file_like) + tm.assert_frame_equal(from_string, from_filename) + except Exception: + # seems utf-16/32 fail on windows + if is_platform_windows(): + if '16' in encoding or '32' in encoding: + pytest.skip() + raise - # force import check by reinitalising global vars in html.py - pytest.importorskip('lxml') - reload(pandas.io.html) + def test_parse_failure_unseekable(self): + # Issue #17975 - filename = os.path.join(DATA_PATH, 'valid_markup.html') - helper_thread1 = ErrorThread(target=read_html, args=(filename,)) - helper_thread2 = ErrorThread(target=read_html, args=(filename,)) + if self.read_html.keywords.get('flavor') == 'lxml': + pytest.skip("Not applicable for lxml") - helper_thread1.start() - helper_thread2.start() + class UnseekableStringIO(StringIO): + def seekable(self): + return False - while helper_thread1.is_alive() or helper_thread2.is_alive(): - pass - assert None is helper_thread1.err is helper_thread2.err + bad = UnseekableStringIO(''' + <table><tr><td>spam<foobr />eggs</td></tr></table>''') + assert self.read_html(bad) -def test_parse_failure_unseekable(): - # Issue #17975 - _skip_if_no('lxml') - _skip_if_no('bs4') + with pytest.raises(ValueError, + match='passed a non-rewindable file object'): + self.read_html(bad) - class UnseekableStringIO(StringIO): - def seekable(self): - return False + def test_parse_failure_rewinds(self): + # Issue #17975 - good = UnseekableStringIO(''' - <table><tr><td>spam<br />eggs</td></tr></table>''') - bad = UnseekableStringIO(''' - <table><tr><td>spam<foobr />eggs</td></tr></table>''') + class MockFile(object): + def __init__(self, data): + self.data = data + self.at_end = False - assert read_html(good) - assert read_html(bad, flavor='bs4') + def read(self, size=None): + data = '' if self.at_end else self.data + self.at_end = True + return data - bad.seek(0) + def seek(self, offset): + self.at_end = False - with pytest.raises(ValueError, - match='passed a non-rewindable file object'): - read_html(bad) + def seekable(self): + return True + good = MockFile('<table><tr><td>spam<br />eggs</td></tr></table>') + bad = MockFile('<table><tr><td>spam<foobr />eggs</td></tr></table>') -def test_parse_failure_rewinds(): - # Issue #17975 - _skip_if_no('lxml') - _skip_if_no('bs4') + assert self.read_html(good) + assert self.read_html(bad) - class MockFile(object): - def __init__(self, data): - self.data = data - self.at_end = False + @pytest.mark.slow + def test_importcheck_thread_safety(self): + # see gh-16928 - def read(self, size=None): - data = '' if self.at_end else self.data - self.at_end = True - return data + class ErrorThread(threading.Thread): + def run(self): + try: + super(ErrorThread, self).run() + except Exception as e: + self.err = e + else: + self.err = None - def seek(self, offset): - self.at_end = False + # force import check by reinitalising global vars in html.py + reload(pandas.io.html) - def seekable(self): - return True + filename = os.path.join(DATA_PATH, 'valid_markup.html') + helper_thread1 = ErrorThread(target=self.read_html, args=(filename,)) + helper_thread2 = ErrorThread(target=self.read_html, args=(filename,)) - good = MockFile('<table><tr><td>spam<br />eggs</td></tr></table>') - bad = MockFile('<table><tr><td>spam<foobr />eggs</td></tr></table>') + helper_thread1.start() + helper_thread2.start() - assert read_html(good) - assert read_html(bad) + while helper_thread1.is_alive() or helper_thread2.is_alive(): + pass + assert None is helper_thread1.err is helper_thread2.err
This is an **extremely** aggressive change to get all of the test cases unified between the LXML and BS4 parsers. On the plus side both parsers can share the same set of tests and functionality, but on the downside it gives lxml a little more power than it had previously, where it would quickly fall back to bs4 for malformed sites. Review / criticism appreciated
https://api.github.com/repos/pandas-dev/pandas/pulls/20293
2018-03-12T04:12:28Z
2018-03-14T10:47:48Z
2018-03-14T10:47:48Z
2018-03-14T15:50:38Z
BUG: Retain tz-aware dtypes with melt (#15785)
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index f686a042c1a74..791365295c268 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -896,6 +896,7 @@ Timezones - Bug in :func:`Timestamp.tz_localize` where localizing a timestamp near the minimum or maximum valid values could overflow and return a timestamp with an incorrect nanosecond value (:issue:`12677`) - Bug when iterating over :class:`DatetimeIndex` that was localized with fixed timezone offset that rounded nanosecond precision to microseconds (:issue:`19603`) - Bug in :func:`DataFrame.diff` that raised an ``IndexError`` with tz-aware values (:issue:`18578`) +- Bug in :func:`melt` that converted tz-aware dtypes to tz-naive (:issue:`15785`) Offsets ^^^^^^^ diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 01445eb30a9e5..ce99d2f8c9a63 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -13,7 +13,9 @@ import re from pandas.core.dtypes.missing import notna +from pandas.core.dtypes.common import is_extension_type from pandas.core.tools.numeric import to_numeric +from pandas.core.reshape.concat import concat @Appender(_shared_docs['melt'] % @@ -70,7 +72,12 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None, mdata = {} for col in id_vars: - mdata[col] = np.tile(frame.pop(col).values, K) + id_data = frame.pop(col) + if is_extension_type(id_data): + id_data = concat([id_data] * K, ignore_index=True) + else: + id_data = np.tile(id_data.values, K) + mdata[col] = id_data mcolumns = id_vars + var_name + [value_name] diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index 000b22d4fdd36..81570de7586de 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -212,6 +212,27 @@ def test_multiindex(self): res = self.df1.melt() assert res.columns.tolist() == ['CAP', 'low', 'value'] + @pytest.mark.parametrize("col", [ + pd.Series(pd.date_range('2010', periods=5, tz='US/Pacific')), + pd.Series(["a", "b", "c", "a", "d"], dtype="category"), + pd.Series([0, 1, 0, 0, 0])]) + def test_pandas_dtypes(self, col): + # GH 15785 + df = DataFrame({'klass': range(5), + 'col': col, + 'attr1': [1, 0, 0, 0, 0], + 'attr2': col}) + expected_value = pd.concat([pd.Series([1, 0, 0, 0, 0]), col], + ignore_index=True) + result = melt(df, id_vars=['klass', 'col'], var_name='attribute', + value_name='value') + expected = DataFrame({0: list(range(5)) * 2, + 1: pd.concat([col] * 2, ignore_index=True), + 2: ['attr1'] * 5 + ['attr2'] * 5, + 3: expected_value}) + expected.columns = ['klass', 'col', 'attribute', 'value'] + tm.assert_frame_equal(result, expected) + class TestLreshape(object):
- [x] closes #15785 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry `.values` call was converting tz aware data to tz naive data (by casting to a numpy array). Added an additional test for Categorical data as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/20292
2018-03-12T02:00:24Z
2018-03-13T10:31:10Z
2018-03-13T10:31:10Z
2018-03-13T15:01:34Z
DOC: update the DataFrame.at[] docstring
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 560e7638b5510..fb3279840c7bf 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1888,11 +1888,50 @@ def __setitem__(self, key, value): class _AtIndexer(_ScalarAccessIndexer): - """Fast label-based scalar accessor + """ + Access a single value for a row/column label pair. + + Similar to ``loc``, in that both provide label-based lookups. Use + ``at`` if you only need to get or set a single value in a DataFrame + or Series. + + See Also + -------- + DataFrame.iat : Access a single value for a row/column pair by integer + position + DataFrame.loc : Access a group of rows and columns by label(s) + Series.at : Access a single value using a label + + Examples + -------- + >>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]], + ... index=[4, 5, 6], columns=['A', 'B', 'C']) + >>> df + A B C + 4 0 2 3 + 5 0 4 1 + 6 10 20 30 + + Get value at specified row/column pair + + >>> df.at[4, 'B'] + 2 + + Set value at specified row/column pair + + >>> df.at[4, 'B'] = 10 + >>> df.at[4, 'B'] + 10 - Similarly to ``loc``, ``at`` provides **label** based scalar lookups. - You can also set using these indexers. + Get value within a Series + >>> df.loc[5].at['B'] + 4 + + Raises + ------ + KeyError + When label does not exist in DataFrame """ _takeable = False
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` # paste output of "scripts/validate_docstrings.py <your-function-or-method>" here # between the "```" (remove this comment, but keep the "```") ################################################################################ ####################### Docstring (pandas.DataFrame.at) ####################### ################################################################################ Access a single value for a row/column label pair. Similar to ``loc``, in that both provide label-based lookups. Use ``at`` if you only need to get or set a single value in a DataFrame or Series. See Also -------- DataFrame.iat : Access a single value for a row/column pair by integer position DataFrame.loc : Access a group of rows and columns by label(s) Series.at : Access a single value using a label Examples -------- >>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], columns=['A', 'B', 'C']) >>> df A B C 4 0 2 3 5 0 4 1 6 10 20 30 Get value at specified row/column pair >>> df.at[4, 'B'] 2 Set value at specified row/column pair >>> df.at[4, 'B'] = 10 >>> df.at[4, 'B'] 10 Get value within a series >>> df.loc[5].at['B'] 4 Raises ------ KeyError When label does not exist in DataFrame ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No returns section found ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20290
2018-03-12T00:29:18Z
2018-03-12T14:25:34Z
2018-03-12T14:25:34Z
2018-03-12T14:25:47Z
DOC: update the pandas.DataFrame.clip_lower docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a75e3960cda16..920b0f5ae7b51 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6572,7 +6572,10 @@ def clip_upper(self, threshold, axis=None, inplace=False): def clip_lower(self, threshold, axis=None, inplace=False): """ - Return copy of the input with values below a threshold truncated. + Trim values below a given threshold. + + Elements below the `threshold` will be changed to match the + `threshold` value(s). Parameters ---------- @@ -6597,17 +6600,22 @@ def clip_lower(self, threshold, axis=None, inplace=False): See Also -------- - Series.clip : Return copy of input with values below and above - thresholds truncated. - Series.clip_upper : Return copy of input with values above - threshold truncated. + DataFrame.clip : General purpose method to trim `DataFrame` values to + given threshold(s) + DataFrame.clip_upper : Trim `DataFrame` values above given + threshold(s) + Series.clip : General purpose method to trim `Series` values to given + threshold(s) + Series.clip_upper : Trim `Series` values above given threshold(s) Returns ------- - clipped : same type as input + clipped + Original data with values trimmed. Examples -------- + Series single threshold clipping: >>> s = pd.Series([5, 6, 7, 8, 9]) @@ -6659,17 +6667,18 @@ def clip_lower(self, threshold, axis=None, inplace=False): `threshold` should be the same length as the axis specified by `axis`. - >>> df.clip_lower(np.array([3, 3, 5]), axis='index') + >>> df.clip_lower([3, 3, 5], axis='index') A B 0 3 3 1 3 4 2 5 6 - >>> df.clip_lower(np.array([4, 5]), axis='columns') + >>> df.clip_lower([4, 5], axis='columns') A B 0 4 5 1 4 5 2 5 6 + """ return self._clip_with_one_bound(threshold, method=self.ge, axis=axis, inplace=inplace)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.DataFrame.clip_lower" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20289
2018-03-11T23:03:51Z
2018-07-08T14:39:58Z
2018-07-08T14:39:58Z
2018-07-08T14:40:31Z
CI: use dateutil-master in testing
diff --git a/ci/requirements-3.6_NUMPY_DEV.build.sh b/ci/requirements-3.6_NUMPY_DEV.build.sh index 9145bf1d3481c..fd79142c5cebb 100644 --- a/ci/requirements-3.6_NUMPY_DEV.build.sh +++ b/ci/requirements-3.6_NUMPY_DEV.build.sh @@ -12,8 +12,7 @@ PRE_WHEELS="https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf pip install --pre --upgrade --timeout=60 -f $PRE_WHEELS numpy scipy # install dateutil from master -# pip install -U git+git://github.com/dateutil/dateutil.git -pip install dateutil +pip install -U git+git://github.com/dateutil/dateutil.git # cython via pip pip install cython diff --git a/pandas/conftest.py b/pandas/conftest.py index 37f0a2f818a3b..5eca467746157 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1,9 +1,7 @@ import pytest -from distutils.version import LooseVersion import numpy import pandas -import dateutil import pandas.util._test_decorators as td @@ -68,14 +66,6 @@ def ip(): return InteractiveShell() -is_dateutil_le_261 = pytest.mark.skipif( - LooseVersion(dateutil.__version__) > LooseVersion('2.6.1'), - reason="dateutil api change version") -is_dateutil_gt_261 = pytest.mark.skipif( - LooseVersion(dateutil.__version__) <= LooseVersion('2.6.1'), - reason="dateutil stable version") - - @pytest.fixture(params=[None, 'gzip', 'bz2', 'zip', pytest.param('xz', marks=td.skip_if_no_lzma)]) def compression(request): diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 0d42b6e9692fe..fb7677bb1449c 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -12,7 +12,6 @@ from distutils.version import LooseVersion import pandas as pd -from pandas.conftest import is_dateutil_le_261, is_dateutil_gt_261 from pandas._libs import tslib from pandas._libs.tslibs import parsing from pandas.core.tools import datetimes as tools @@ -1058,7 +1057,6 @@ def test_dayfirst(self, cache): class TestGuessDatetimeFormat(object): @td.skip_if_not_us_locale - @is_dateutil_le_261 def test_guess_datetime_format_for_array(self): expected_format = '%Y-%m-%d %H:%M:%S.%f' dt_string = datetime(2011, 12, 30, 0, 0, 0).strftime(expected_format) @@ -1078,27 +1076,6 @@ def test_guess_datetime_format_for_array(self): [np.nan, np.nan, np.nan], dtype='O')) assert format_for_string_of_nans is None - @td.skip_if_not_us_locale - @is_dateutil_gt_261 - def test_guess_datetime_format_for_array_gt_261(self): - expected_format = '%Y-%m-%d %H:%M:%S.%f' - dt_string = datetime(2011, 12, 30, 0, 0, 0).strftime(expected_format) - - test_arrays = [ - np.array([dt_string, dt_string, dt_string], dtype='O'), - np.array([np.nan, np.nan, dt_string], dtype='O'), - np.array([dt_string, 'random_string'], dtype='O'), - ] - - for test_array in test_arrays: - assert tools._guess_datetime_format_for_array( - test_array) is None - - format_for_string_of_nans = tools._guess_datetime_format_for_array( - np.array( - [np.nan, np.nan, np.nan], dtype='O')) - assert format_for_string_of_nans is None - class TestToDatetimeInferFormat(object): diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py index 34cce088a8b42..14c9ca1f6cc54 100644 --- a/pandas/tests/tslibs/test_parsing.py +++ b/pandas/tests/tslibs/test_parsing.py @@ -8,7 +8,6 @@ from dateutil.parser import parse import pandas.util._test_decorators as td -from pandas.conftest import is_dateutil_le_261, is_dateutil_gt_261 from pandas import compat from pandas.util import testing as tm from pandas._libs.tslibs import parsing @@ -96,7 +95,6 @@ def test_parsers_monthfreq(self): class TestGuessDatetimeFormat(object): @td.skip_if_not_us_locale - @is_dateutil_le_261 @pytest.mark.parametrize( "string, format", [ @@ -112,19 +110,6 @@ def test_guess_datetime_format_with_parseable_formats( result = parsing._guess_datetime_format(string) assert result == format - @td.skip_if_not_us_locale - @is_dateutil_gt_261 - @pytest.mark.parametrize( - "string", - ['20111230', '2011-12-30', '30-12-2011', - '2011-12-30 00:00:00', '2011-12-30T00:00:00', - '2011-12-30 00:00:00.000000']) - def test_guess_datetime_format_with_parseable_formats_gt_261( - self, string): - result = parsing._guess_datetime_format(string) - assert result is None - - @is_dateutil_le_261 @pytest.mark.parametrize( "dayfirst, expected", [ @@ -136,17 +121,7 @@ def test_guess_datetime_format_with_dayfirst(self, dayfirst, expected): ambiguous_string, dayfirst=dayfirst) assert result == expected - @is_dateutil_gt_261 - @pytest.mark.parametrize( - "dayfirst", [True, False]) - def test_guess_datetime_format_with_dayfirst_gt_261(self, dayfirst): - ambiguous_string = '01/01/2011' - result = parsing._guess_datetime_format( - ambiguous_string, dayfirst=dayfirst) - assert result is None - @td.skip_if_has_locale - @is_dateutil_le_261 @pytest.mark.parametrize( "string, format", [ @@ -158,19 +133,6 @@ def test_guess_datetime_format_with_locale_specific_formats( result = parsing._guess_datetime_format(string) assert result == format - @td.skip_if_has_locale - @is_dateutil_gt_261 - @pytest.mark.parametrize( - "string", - [ - '30/Dec/2011', - '30/December/2011', - '30/Dec/2011 00:00:00']) - def test_guess_datetime_format_with_locale_specific_formats_gt_261( - self, string): - result = parsing._guess_datetime_format(string) - assert result is None - def test_guess_datetime_format_invalid_inputs(self): # A datetime string must include a year, month and a day for it # to be guessable, in addition to being a string that looks like @@ -189,7 +151,6 @@ def test_guess_datetime_format_invalid_inputs(self): for invalid_dt in invalid_dts: assert parsing._guess_datetime_format(invalid_dt) is None - @is_dateutil_le_261 @pytest.mark.parametrize( "string, format", [ @@ -204,21 +165,6 @@ def test_guess_datetime_format_nopadding(self, string, format): result = parsing._guess_datetime_format(string) assert result == format - @is_dateutil_gt_261 - @pytest.mark.parametrize( - "string", - [ - '2011-1-1', - '30-1-2011', - '1/1/2011', - '2011-1-1 00:00:00', - '2011-1-1 0:0:0', - '2011-1-3T00:00:0']) - def test_guess_datetime_format_nopadding_gt_261(self, string): - # GH 11142 - result = parsing._guess_datetime_format(string) - assert result is None - class TestArrayToDatetime(object): def test_try_parse_dates(self):
closes #18332
https://api.github.com/repos/pandas-dev/pandas/pulls/20288
2018-03-11T22:20:04Z
2018-03-12T12:09:44Z
2018-03-12T12:09:44Z
2018-03-12T12:09:44Z
TST: adding join_types fixture
diff --git a/pandas/conftest.py b/pandas/conftest.py index 5eca467746157..7a4ef56d7d749 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -89,3 +89,11 @@ def compression_no_zip(request): def datetime_tz_utc(): from datetime import timezone return timezone.utc + + +@pytest.fixture(params=['inner', 'outer', 'left', 'right']) +def join_type(request): + """ + Fixture for trying all types of join operations + """ + return request.param diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 8f51dbabd5b71..758f3f0ef9ebc 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -978,11 +978,10 @@ def test_empty(self): assert not index.empty assert index[:0].empty - @pytest.mark.parametrize('how', ['outer', 'inner', 'left', 'right']) - def test_join_self_unique(self, how): + def test_join_self_unique(self, join_type): index = self.create_index() if index.is_unique: - joined = index.join(index, how=how) + joined = index.join(index, how=join_type) assert (index == joined).all() def test_searchsorted_monotonic(self, indices): diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index b685584a29fb9..51788b3e25507 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -250,10 +250,9 @@ def test_does_not_convert_mixed_integer(self): assert cols.dtype == joined.dtype tm.assert_numpy_array_equal(cols.values, joined.values) - @pytest.mark.parametrize('how', ['outer', 'inner', 'left', 'right']) - def test_join_self(self, how): + def test_join_self(self, join_type): index = date_range('1/1/2000', periods=10) - joined = index.join(index, how=how) + joined = index.join(index, how=join_type) assert index is joined def assert_index_parameters(self, index): @@ -274,8 +273,7 @@ def test_ns_index(self): freq=index.freq) self.assert_index_parameters(new_index) - @pytest.mark.parametrize('how', ['left', 'right', 'inner', 'outer']) - def test_join_with_period_index(self, how): + def test_join_with_period_index(self, join_type): df = tm.makeCustomDataframe( 10, 10, data_gen_f=lambda *args: np.random.randint(2), c_idx_type='p', r_idx_type='dt') @@ -284,7 +282,7 @@ def test_join_with_period_index(self, how): with tm.assert_raises_regex(ValueError, 'can only call with other ' 'PeriodIndex-ed objects'): - df.columns.join(s.index, how=how) + df.columns.join(s.index, how=join_type) def test_factorize(self): idx1 = DatetimeIndex(['2014-01', '2014-01', '2014-02', '2014-02', diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 217610b76cf0f..2913812db0dd4 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -700,18 +700,17 @@ def test_dti_tz_constructors(self, tzstr): # ------------------------------------------------------------- # Unsorted - @pytest.mark.parametrize('how', ['inner', 'outer', 'left', 'right']) - def test_join_utc_convert(self, how): + def test_join_utc_convert(self, join_type): rng = date_range('1/1/2011', periods=100, freq='H', tz='utc') left = rng.tz_convert('US/Eastern') right = rng.tz_convert('Europe/Berlin') - result = left.join(left[:-5], how=how) + result = left.join(left[:-5], how=join_type) assert isinstance(result, DatetimeIndex) assert result.tz == left.tz - result = left.join(right[:-5], how=how) + result = left.join(right[:-5], how=join_type) assert isinstance(result, DatetimeIndex) assert result.tz.zone == 'UTC' diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 4548d7fa1a468..923d826fe1a5e 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -532,10 +532,9 @@ def test_map(self): exp = Index([x.ordinal for x in index]) tm.assert_index_equal(result, exp) - @pytest.mark.parametrize('how', ['outer', 'inner', 'left', 'right']) - def test_join_self(self, how): + def test_join_self(self, join_type): index = period_range('1/1/2000', periods=10) - joined = index.join(index, how=how) + joined = index.join(index, how=join_type) assert index is joined def test_insert(self): diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index ec0836dfa174b..6598e0663fb9a 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -14,20 +14,18 @@ def _permute(obj): class TestPeriodIndex(object): - @pytest.mark.parametrize('kind', ['inner', 'outer', 'left', 'right']) - def test_joins(self, kind): + def test_joins(self, join_type): index = period_range('1/1/2000', '1/20/2000', freq='D') - joined = index.join(index[:-5], how=kind) + joined = index.join(index[:-5], how=join_type) assert isinstance(joined, PeriodIndex) assert joined.freq == index.freq - @pytest.mark.parametrize('kind', ['inner', 'outer', 'left', 'right']) - def test_join_self(self, kind): + def test_join_self(self, join_type): index = period_range('1/1/2000', '1/20/2000', freq='D') - res = index.join(index, how=kind) + res = index.join(index, how=join_type) assert index is res def test_join_does_not_recur(self): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index eb429f46a3355..e8f05cb928cad 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1599,16 +1599,15 @@ def test_slice_keep_name(self): idx = Index(['a', 'b'], name='asdf') assert idx.name == idx[1:].name - def test_join_self(self): - # instance attributes of the form self.<name>Index - indices = 'unicode', 'str', 'date', 'int', 'float' - kinds = 'outer', 'inner', 'left', 'right' - for index_kind in indices: - res = getattr(self, '{0}Index'.format(index_kind)) - - for kind in kinds: - joined = res.join(res, how=kind) - assert res is joined + # instance attributes of the form self.<name>Index + @pytest.mark.parametrize('index_kind', + ['unicode', 'str', 'date', 'int', 'float']) + def test_join_self(self, join_type, index_kind): + + res = getattr(self, '{0}Index'.format(index_kind)) + + joined = res.join(res, how=join_type) + assert res is joined def test_str_attribute(self): # GH9068 diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index cd6a5c761d0c2..34abf7052da8c 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -450,11 +450,11 @@ def test_inplace_mutation_resets_values(self): # Make sure label setting works too labels2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] - exp_values = np.empty((6, ), dtype=object) + exp_values = np.empty((6,), dtype=object) exp_values[:] = [(long(1), 'a')] * 6 # Must be 1d array of tuples - assert exp_values.shape == (6, ) + assert exp_values.shape == (6,) new_values = mi2.set_labels(labels2).values # Not inplace shouldn't change @@ -583,7 +583,7 @@ def test_constructor_single_level(self): def test_constructor_no_levels(self): tm.assert_raises_regex(ValueError, "non-zero number " - "of levels/labels", + "of levels/labels", MultiIndex, levels=[], labels=[]) both_re = re.compile('Must pass both levels and labels') with tm.assert_raises_regex(TypeError, both_re): @@ -595,7 +595,7 @@ def test_constructor_mismatched_label_levels(self): labels = [np.array([1]), np.array([2]), np.array([3])] levels = ["a"] tm.assert_raises_regex(ValueError, "Length of levels and labels " - "must be the same", MultiIndex, + "must be the same", MultiIndex, levels=levels, labels=labels) length_error = re.compile('>= length of level') label_error = re.compile(r'Unequal label lengths: \[4, 2\]') @@ -844,19 +844,19 @@ def test_from_arrays_different_lengths(self): idx1 = [1, 2, 3] idx2 = ['a', 'b'] tm.assert_raises_regex(ValueError, '^all arrays must ' - 'be same length$', + 'be same length$', MultiIndex.from_arrays, [idx1, idx2]) idx1 = [] idx2 = ['a', 'b'] tm.assert_raises_regex(ValueError, '^all arrays must ' - 'be same length$', + 'be same length$', MultiIndex.from_arrays, [idx1, idx2]) idx1 = [1, 2, 3] idx2 = [] tm.assert_raises_regex(ValueError, '^all arrays must ' - 'be same length$', + 'be same length$', MultiIndex.from_arrays, [idx1, idx2]) def test_from_product(self): @@ -964,7 +964,7 @@ def test_values_boxed(self): def test_values_multiindex_datetimeindex(self): # Test to ensure we hit the boxing / nobox part of MI.values - ints = np.arange(10**18, 10**18 + 5) + ints = np.arange(10 ** 18, 10 ** 18 + 5) naive = pd.DatetimeIndex(ints) aware = pd.DatetimeIndex(ints, tz='US/Central') @@ -1023,7 +1023,7 @@ def test_append(self): def test_append_mixed_dtypes(self): # GH 13660 - dti = date_range('2011-01-01', freq='M', periods=3,) + dti = date_range('2011-01-01', freq='M', periods=3, ) dti_tz = date_range('2011-01-01', freq='M', periods=3, tz='US/Eastern') pi = period_range('2011-01', freq='M', periods=3) @@ -1067,9 +1067,12 @@ def test_get_level_values(self): tm.assert_index_equal(result, expected) # GH 10460 - index = MultiIndex(levels=[CategoricalIndex( - ['A', 'B']), CategoricalIndex([1, 2, 3])], labels=[np.array( - [0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])]) + index = MultiIndex( + levels=[CategoricalIndex(['A', 'B']), + CategoricalIndex([1, 2, 3])], + labels=[np.array([0, 0, 0, 1, 1, 1]), + np.array([0, 1, 2, 0, 1, 2])]) + exp = CategoricalIndex(['A', 'A', 'A', 'B', 'B', 'B']) tm.assert_index_equal(index.get_level_values(0), exp) exp = CategoricalIndex([1, 2, 3, 1, 2, 3]) @@ -1397,7 +1400,7 @@ def test_slice_locs_not_sorted(self): [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) tm.assert_raises_regex(KeyError, "[Kk]ey length.*greater than " - "MultiIndex lexsort depth", + "MultiIndex lexsort depth", index.slice_locs, (1, 0, 1), (2, 1, 0)) # works @@ -1887,12 +1890,12 @@ def test_difference(self): expected.names = first.names assert first.names == result.names tm.assert_raises_regex(TypeError, "other must be a MultiIndex " - "or a list of tuples", + "or a list of tuples", first.difference, [1, 2, 3, 4, 5]) def test_from_tuples(self): tm.assert_raises_regex(TypeError, 'Cannot infer number of levels ' - 'from empty list', + 'from empty list', MultiIndex.from_tuples, []) expected = MultiIndex(levels=[[1, 3], [2, 4]], @@ -2039,8 +2042,9 @@ def test_droplevel_with_names(self): dropped = index.droplevel(0) assert dropped.name == 'second' - index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( - lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( + index = MultiIndex( + levels=[Index(lrange(4)), Index(lrange(4)), Index(lrange(4))], + labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])], names=['one', 'two', 'three']) dropped = index.droplevel(0) @@ -2051,8 +2055,9 @@ def test_droplevel_with_names(self): assert dropped.equals(expected) def test_droplevel_multiple(self): - index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index( - lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( + index = MultiIndex( + levels=[Index(lrange(4)), Index(lrange(4)), Index(lrange(4))], + labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])], names=['one', 'two', 'three']) @@ -2101,7 +2106,7 @@ def test_insert(self): # key wrong length msg = "Item must have length equal to number of levels" with tm.assert_raises_regex(ValueError, msg): - self.index.insert(0, ('foo2', )) + self.index.insert(0, ('foo2',)) left = pd.DataFrame([['a', 'b', 0], ['b', 'd', 1]], columns=['1st', '2nd', '3rd']) @@ -2134,8 +2139,8 @@ def test_insert(self): # GH9250 idx = [('test1', i) for i in range(5)] + \ - [('test2', i) for i in range(6)] + \ - [('test', 17), ('test', 18)] + [('test2', i) for i in range(6)] + \ + [('test', 17), ('test', 18)] left = pd.Series(np.linspace(0, 10, 11), pd.MultiIndex.from_tuples(idx[:-2])) @@ -2210,42 +2215,36 @@ def take_invalid_kwargs(self): tm.assert_raises_regex(ValueError, msg, idx.take, indices, mode='clip') - def test_join_level(self): - def _check_how(other, how): - join_index, lidx, ridx = other.join(self.index, how=how, - level='second', - return_indexers=True) - - exp_level = other.join(self.index.levels[1], how=how) - assert join_index.levels[0].equals(self.index.levels[0]) - assert join_index.levels[1].equals(exp_level) - - # pare down levels - mask = np.array( - [x[1] in exp_level for x in self.index], dtype=bool) - exp_values = self.index.values[mask] - tm.assert_numpy_array_equal(join_index.values, exp_values) - - if how in ('outer', 'inner'): - join_index2, ridx2, lidx2 = \ - self.index.join(other, how=how, level='second', - return_indexers=True) - - assert join_index.equals(join_index2) - tm.assert_numpy_array_equal(lidx, lidx2) - tm.assert_numpy_array_equal(ridx, ridx2) - tm.assert_numpy_array_equal(join_index2.values, exp_values) - - def _check_all(other): - _check_how(other, 'outer') - _check_how(other, 'inner') - _check_how(other, 'left') - _check_how(other, 'right') - - _check_all(Index(['three', 'one', 'two'])) - _check_all(Index(['one'])) - _check_all(Index(['one', 'three'])) - + @pytest.mark.parametrize('other', + [Index(['three', 'one', 'two']), + Index(['one']), + Index(['one', 'three'])]) + def test_join_level(self, other, join_type): + join_index, lidx, ridx = other.join(self.index, how=join_type, + level='second', + return_indexers=True) + + exp_level = other.join(self.index.levels[1], how=join_type) + assert join_index.levels[0].equals(self.index.levels[0]) + assert join_index.levels[1].equals(exp_level) + + # pare down levels + mask = np.array( + [x[1] in exp_level for x in self.index], dtype=bool) + exp_values = self.index.values[mask] + tm.assert_numpy_array_equal(join_index.values, exp_values) + + if join_type in ('outer', 'inner'): + join_index2, ridx2, lidx2 = \ + self.index.join(other, how=join_type, level='second', + return_indexers=True) + + assert join_index.equals(join_index2) + tm.assert_numpy_array_equal(lidx, lidx2) + tm.assert_numpy_array_equal(ridx, ridx2) + tm.assert_numpy_array_equal(join_index2.values, exp_values) + + def test_join_level_corner_case(self): # some corner cases idx = Index(['three', 'one', 'two']) result = idx.join(self.index, level='second') @@ -2254,12 +2253,10 @@ def _check_all(other): tm.assert_raises_regex(TypeError, "Join.*MultiIndex.*ambiguous", self.index.join, self.index, level=1) - def test_join_self(self): - kinds = 'outer', 'inner', 'left', 'right' - for kind in kinds: - res = self.index - joined = res.join(res, how=kind) - assert res is joined + def test_join_self(self, join_type): + res = self.index + joined = res.join(res, how=join_type) + assert res is joined def test_join_multi(self): # GH 10665 @@ -2335,7 +2332,7 @@ def test_duplicates(self): assert self.index.append(self.index).has_duplicates index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[ - [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]) + [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]) assert index.has_duplicates # GH 9075 @@ -2434,8 +2431,11 @@ def check(nlevels, with_nulls): def test_duplicate_meta_data(self): # GH 10115 - index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[ - [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]) + index = MultiIndex( + levels=[[0, 1], [0, 1, 2]], + labels=[[0, 0, 0, 0, 1, 1, 1], + [0, 1, 2, 0, 0, 1, 2]]) + for idx in [index, index.set_names([None, None]), index.set_names([None, 'Num']), diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 37db9d704aa1f..4692b6d675e6b 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -102,10 +102,9 @@ def test_factorize(self): tm.assert_numpy_array_equal(arr, exp_arr) tm.assert_index_equal(idx, idx3) - @pytest.mark.parametrize('kind', ['outer', 'inner', 'left', 'right']) - def test_join_self(self, kind): + def test_join_self(self, join_type): index = timedelta_range('1 day', periods=10) - joined = index.join(index, how=kind) + joined = index.join(index, how=join_type) tm.assert_index_equal(index, joined) def test_does_not_convert_mixed_integer(self): diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index a64069fa700b8..1b8f3632d381c 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -297,7 +297,25 @@ def test_join_on_series_buglet(self): 'b': [2, 2]}, index=df.index) tm.assert_frame_equal(result, expected) - def test_join_index_mixed(self): + def test_join_index_mixed(self, join_type): + # no overlapping blocks + df1 = DataFrame(index=np.arange(10)) + df1['bool'] = True + df1['string'] = 'foo' + + df2 = DataFrame(index=np.arange(5, 15)) + df2['int'] = 1 + df2['float'] = 1. + + joined = df1.join(df2, how=join_type) + expected = _join_by_hand(df1, df2, how=join_type) + assert_frame_equal(joined, expected) + + joined = df2.join(df1, how=join_type) + expected = _join_by_hand(df2, df1, how=join_type) + assert_frame_equal(joined, expected) + + def test_join_index_mixed_overlap(self): df1 = DataFrame({'A': 1., 'B': 2, 'C': 'foo', 'D': True}, index=np.arange(10), columns=['A', 'B', 'C', 'D']) @@ -317,25 +335,6 @@ def test_join_index_mixed(self): expected = _join_by_hand(df1, df2) assert_frame_equal(joined, expected) - # no overlapping blocks - df1 = DataFrame(index=np.arange(10)) - df1['bool'] = True - df1['string'] = 'foo' - - df2 = DataFrame(index=np.arange(5, 15)) - df2['int'] = 1 - df2['float'] = 1. - - for kind in ['inner', 'outer', 'left', 'right']: - - joined = df1.join(df2, how=kind) - expected = _join_by_hand(df1, df2, how=kind) - assert_frame_equal(joined, expected) - - joined = df2.join(df1, how=kind) - expected = _join_by_hand(df2, df1, how=kind) - assert_frame_equal(joined, expected) - def test_join_empty_bug(self): # generated an exception in 0.4.3 x = DataFrame() diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 5dca45c8dd8bb..dbf7c7f100b0e 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -22,7 +22,6 @@ import pandas.util.testing as tm from pandas.api.types import CategoricalDtype as CDT - N = 50 NGROUPS = 8 @@ -319,7 +318,12 @@ def test_left_merge_empty_dataframe(self): result = merge(right, left, on='key', how='right') assert_frame_equal(result, left) - def test_merge_left_empty_right_empty(self): + @pytest.mark.parametrize('kwarg', + [dict(left_index=True, right_index=True), + dict(left_index=True, right_on='x'), + dict(left_on='a', right_index=True), + dict(left_on='a', right_on='x')]) + def test_merge_left_empty_right_empty(self, join_type, kwarg): # GH 10824 left = pd.DataFrame([], columns=['a', 'b', 'c']) right = pd.DataFrame([], columns=['x', 'y', 'z']) @@ -328,19 +332,8 @@ def test_merge_left_empty_right_empty(self): index=pd.Index([], dtype=object), dtype=object) - for kwarg in [dict(left_index=True, right_index=True), - dict(left_index=True, right_on='x'), - dict(left_on='a', right_index=True), - dict(left_on='a', right_on='x')]: - - result = pd.merge(left, right, how='inner', **kwarg) - tm.assert_frame_equal(result, exp_in) - result = pd.merge(left, right, how='left', **kwarg) - tm.assert_frame_equal(result, exp_in) - result = pd.merge(left, right, how='right', **kwarg) - tm.assert_frame_equal(result, exp_in) - result = pd.merge(left, right, how='outer', **kwarg) - tm.assert_frame_equal(result, exp_in) + result = pd.merge(left, right, how=join_type, **kwarg) + tm.assert_frame_equal(result, exp_in) def test_merge_left_empty_right_notempty(self): # GH 10824 @@ -429,14 +422,16 @@ def test_merge_nosort(self): d = {"var1": np.random.randint(0, 10, size=10), "var2": np.random.randint(0, 10, size=10), - "var3": [datetime(2012, 1, 12), datetime(2011, 2, 4), - datetime( - 2010, 2, 3), datetime(2012, 1, 12), - datetime( - 2011, 2, 4), datetime(2012, 4, 3), - datetime( - 2012, 3, 4), datetime(2008, 5, 1), - datetime(2010, 2, 3), datetime(2012, 2, 3)]} + "var3": [datetime(2012, 1, 12), + datetime(2011, 2, 4), + datetime(2010, 2, 3), + datetime(2012, 1, 12), + datetime(2011, 2, 4), + datetime(2012, 4, 3), + datetime(2012, 3, 4), + datetime(2008, 5, 1), + datetime(2010, 2, 3), + datetime(2012, 2, 3)]} df = DataFrame.from_dict(d) var3 = df.var3.unique() var3.sort() @@ -1299,6 +1294,7 @@ def test_join_multi_levels(self): def f(): household.join(portfolio, how='inner') + pytest.raises(ValueError, f) portfolio2 = portfolio.copy() @@ -1306,6 +1302,7 @@ def f(): def f(): portfolio2.join(portfolio, how='inner') + pytest.raises(ValueError, f) def test_join_multi_levels2(self): @@ -1347,6 +1344,7 @@ def test_join_multi_levels2(self): def f(): household.join(log_return, how='inner') + pytest.raises(NotImplementedError, f) # this is the equivalency @@ -1375,6 +1373,7 @@ def f(): def f(): household.join(log_return, how='outer') + pytest.raises(NotImplementedError, f) @pytest.mark.parametrize("klass", [None, np.asarray, Series, Index]) @@ -1413,8 +1412,7 @@ class TestMergeDtypes(object): [1.0, 2.0], Series([1, 2], dtype='uint64'), Series([1, 2], dtype='int32') - ] - ) + ]) def test_different(self, right_vals): left = DataFrame({'A': ['foo', 'bar'], @@ -1683,8 +1681,7 @@ def test_other_columns(self, left, right): 'change', [lambda x: x, lambda x: x.astype(CDT(['foo', 'bar', 'bah'])), lambda x: x.astype(CDT(ordered=True))]) - @pytest.mark.parametrize('how', ['inner', 'outer', 'left', 'right']) - def test_dtype_on_merged_different(self, change, how, left, right): + def test_dtype_on_merged_different(self, change, join_type, left, right): # our merging columns, X now has 2 different dtypes # so we must be object as a result @@ -1693,7 +1690,7 @@ def test_dtype_on_merged_different(self, change, how, left, right): assert is_categorical_dtype(left.X.values) # assert not left.X.values.is_dtype_equal(right.X.values) - merged = pd.merge(left, right, on='X', how=how) + merged = pd.merge(left, right, on='X', how=join_type) result = merged.dtypes.sort_index() expected = Series([np.dtype('O'), @@ -1823,7 +1820,6 @@ class TestMergeOnIndexes(object): 'b': [np.nan, 100, 200, 300]}, index=[0, 1, 2, 3]))]) def test_merge_on_indexes(self, left_df, right_df, how, sort, expected): - result = pd.merge(left_df, right_df, left_index=True, right_index=True, diff --git a/pandas/tests/reshape/merge/test_merge_index_as_string.py b/pandas/tests/reshape/merge/test_merge_index_as_string.py index 09109e2692a24..a27fcf41681e6 100644 --- a/pandas/tests/reshape/merge/test_merge_index_as_string.py +++ b/pandas/tests/reshape/merge/test_merge_index_as_string.py @@ -157,9 +157,7 @@ def test_merge_indexes_and_columns_lefton_righton( @pytest.mark.parametrize('left_index', ['inner', ['inner', 'outer']]) -@pytest.mark.parametrize('how', - ['inner', 'left', 'right', 'outer']) -def test_join_indexes_and_columns_on(df1, df2, left_index, how): +def test_join_indexes_and_columns_on(df1, df2, left_index, join_type): # Construct left_df left_df = df1.set_index(left_index) @@ -169,12 +167,12 @@ def test_join_indexes_and_columns_on(df1, df2, left_index, how): # Result expected = (left_df.reset_index() - .join(right_df, on=['outer', 'inner'], how=how, + .join(right_df, on=['outer', 'inner'], how=join_type, lsuffix='_x', rsuffix='_y') .set_index(left_index)) # Perform join - result = left_df.join(right_df, on=['outer', 'inner'], how=how, + result = left_df.join(right_df, on=['outer', 'inner'], how=join_type, lsuffix='_x', rsuffix='_y') assert_frame_equal(result, expected, check_like=True) diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index c1b6d0a452232..999ed5f26daee 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -18,8 +18,6 @@ from pandas.util.testing import (assert_series_equal) import pandas.util.testing as tm -JOIN_TYPES = ['inner', 'outer', 'left', 'right'] - @pytest.mark.parametrize( 'first_slice,second_slice', [ @@ -28,7 +26,6 @@ [[None, -5], [None, 0]], [[None, 0], [None, 0]] ]) -@pytest.mark.parametrize('join_type', JOIN_TYPES) @pytest.mark.parametrize('fill', [None, -1]) def test_align(test_data, first_slice, second_slice, join_type, fill): a = test_data.ts[slice(*first_slice)] @@ -67,7 +64,6 @@ def test_align(test_data, first_slice, second_slice, join_type, fill): [[None, -5], [None, 0]], [[None, 0], [None, 0]] ]) -@pytest.mark.parametrize('join_type', JOIN_TYPES) @pytest.mark.parametrize('method', ['pad', 'bfill']) @pytest.mark.parametrize('limit', [None, 1]) def test_align_fill_method(test_data, diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index f1f4a5a05697d..2aef0df5349cb 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -16,8 +16,6 @@ from pandas.util.testing import (assert_series_equal) import pandas.util.testing as tm -JOIN_TYPES = ['inner', 'outer', 'left', 'right'] - def test_getitem_boolean(test_data): s = test_data.series diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index f484cdea2e09f..bcea47f42056b 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -20,7 +20,6 @@ import pandas._libs.index as _index from pandas._libs import tslib -JOIN_TYPES = ['inner', 'outer', 'left', 'right'] """ Also test support for datetime64[ns] in Series / DataFrame diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index 8ff2071e351d0..63726f27914f3 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -117,7 +117,7 @@ def test_intercept_astype_object(self): result = df.values.squeeze() assert (result[:, 0] == expected.values).all() - def test_align_series(self): + def test_add_series(self): rng = period_range('1/1/2000', '1/1/2010', freq='A') ts = Series(np.random.randn(len(rng)), index=rng) @@ -129,13 +129,16 @@ def test_align_series(self): result = ts + _permute(ts[::2]) tm.assert_series_equal(result, expected) - # it works! - for kind in ['inner', 'outer', 'left', 'right']: - ts.align(ts[::2], join=kind) msg = "Input has different freq=D from PeriodIndex\\(freq=A-DEC\\)" with tm.assert_raises_regex(period.IncompatibleFrequency, msg): ts + ts.asfreq('D', how="end") + def test_align_series(self, join_type): + rng = period_range('1/1/2000', '1/1/2010', freq='A') + ts = Series(np.random.randn(len(rng)), index=rng) + + ts.align(ts[::2], join=join_type) + def test_truncate(self): # GH 17717 idx1 = pd.PeriodIndex([
follow up for PR #20059 Extracting join types to a fixture - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/20287
2018-03-11T22:13:20Z
2018-03-13T10:32:17Z
2018-03-13T10:32:17Z
2018-03-13T10:50:44Z
DOC: Improve the docstrings of CategoricalIndex.map
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index e7d414f9de544..afbf4baf0d002 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1080,20 +1080,73 @@ def remove_unused_categories(self, inplace=False): return cat def map(self, mapper): - """Apply mapper function to its categories (not codes). + """ + Map categories using input correspondence (dict, Series, or function). + + Maps the categories to new categories. If the mapping correspondence is + one-to-one the result is a :class:`~pandas.Categorical` which has the + same order property as the original, otherwise a :class:`~pandas.Index` + is returned. + + If a `dict` or :class:`~pandas.Series` is used any unmapped category is + mapped to `NaN`. Note that if this happens an :class:`~pandas.Index` + will be returned. Parameters ---------- - mapper : callable - Function to be applied. When all categories are mapped - to different categories, the result will be Categorical which has - the same order property as the original. Otherwise, the result will - be np.ndarray. + mapper : function, dict, or Series + Mapping correspondence. Returns ------- - applied : Categorical or Index. + pandas.Categorical or pandas.Index + Mapped categorical. + + See Also + -------- + CategoricalIndex.map : Apply a mapping correspondence on a + :class:`~pandas.CategoricalIndex`. + Index.map : Apply a mapping correspondence on an + :class:`~pandas.Index`. + Series.map : Apply a mapping correspondence on a + :class:`~pandas.Series`. + Series.apply : Apply more complex functions on a + :class:`~pandas.Series`. + + Examples + -------- + >>> cat = pd.Categorical(['a', 'b', 'c']) + >>> cat + [a, b, c] + Categories (3, object): [a, b, c] + >>> cat.map(lambda x: x.upper()) + [A, B, C] + Categories (3, object): [A, B, C] + >>> cat.map({'a': 'first', 'b': 'second', 'c': 'third'}) + [first, second, third] + Categories (3, object): [first, second, third] + + If the mapping is one-to-one the ordering of the categories is + preserved: + + >>> cat = pd.Categorical(['a', 'b', 'c'], ordered=True) + >>> cat + [a, b, c] + Categories (3, object): [a < b < c] + >>> cat.map({'a': 3, 'b': 2, 'c': 1}) + [3, 2, 1] + Categories (3, int64): [3 < 2 < 1] + + If the mapping is not one-to-one an :class:`~pandas.Index` is returned: + + >>> cat.map({'a': 'first', 'b': 'second', 'c': 'first'}) + Index(['first', 'second', 'first'], dtype='object') + + If a `dict` is used, all unmapped categories are mapped to `NaN` and + the result is an :class:`~pandas.Index`: + >>> cat.map({'a': 'first', 'b': 'second'}) + Index(['first', 'second', nan], dtype='object') """ new_categories = self.categories.map(mapper) try: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 446b1b02706e3..95bfc8bfcb5c5 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3352,14 +3352,16 @@ def groupby(self, values): return result def map(self, mapper, na_action=None): - """Map values of Series using input correspondence + """ + Map values using input correspondence (a dict, Series, or function). Parameters ---------- mapper : function, dict, or Series + Mapping correspondence. na_action : {None, 'ignore'} If 'ignore', propagate NA values, without passing them to the - mapping function + mapping correspondence. Returns ------- @@ -3367,7 +3369,6 @@ def map(self, mapper, na_action=None): The output of the mapping function applied to the index. If the function returns a tuple with more than one element a MultiIndex will be returned. - """ from .multi import MultiIndex diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 7b902b92d44a4..71caa098c7a28 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -660,20 +660,71 @@ def is_dtype_equal(self, other): take_nd = take def map(self, mapper): - """Apply mapper function to its categories (not codes). + """ + Map values using input correspondence (a dict, Series, or function). + + Maps the values (their categories, not the codes) of the index to new + categories. If the mapping correspondence is one-to-one the result is a + :class:`~pandas.CategoricalIndex` which has the same order property as + the original, otherwise an :class:`~pandas.Index` is returned. + + If a `dict` or :class:`~pandas.Series` is used any unmapped category is + mapped to `NaN`. Note that if this happens an :class:`~pandas.Index` + will be returned. Parameters ---------- - mapper : callable - Function to be applied. When all categories are mapped - to different categories, the result will be a CategoricalIndex - which has the same order property as the original. Otherwise, - the result will be a Index. + mapper : function, dict, or Series + Mapping correspondence. Returns ------- - applied : CategoricalIndex or Index + pandas.CategoricalIndex or pandas.Index + Mapped index. + + See Also + -------- + Index.map : Apply a mapping correspondence on an + :class:`~pandas.Index`. + Series.map : Apply a mapping correspondence on a + :class:`~pandas.Series`. + Series.apply : Apply more complex functions on a + :class:`~pandas.Series`. + Examples + -------- + >>> idx = pd.CategoricalIndex(['a', 'b', 'c']) + >>> idx + CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'], + ordered=False, dtype='category') + >>> idx.map(lambda x: x.upper()) + CategoricalIndex(['A', 'B', 'C'], categories=['A', 'B', 'C'], + ordered=False, dtype='category') + >>> idx.map({'a': 'first', 'b': 'second', 'c': 'third'}) + CategoricalIndex(['first', 'second', 'third'], categories=['first', + 'second', 'third'], ordered=False, dtype='category') + + If the mapping is one-to-one the ordering of the categories is + preserved: + + >>> idx = pd.CategoricalIndex(['a', 'b', 'c'], ordered=True) + >>> idx + CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'], + ordered=True, dtype='category') + >>> idx.map({'a': 3, 'b': 2, 'c': 1}) + CategoricalIndex([3, 2, 1], categories=[3, 2, 1], ordered=True, + dtype='category') + + If the mapping is not one-to-one an :class:`~pandas.Index` is returned: + + >>> idx.map({'a': 'first', 'b': 'second', 'c': 'first'}) + Index(['first', 'second', 'first'], dtype='object') + + If a `dict` is used, all unmapped categories are mapped to `NaN` and + the result is an :class:`~pandas.Index`: + + >>> idx.map({'a': 'first', 'b': 'second'}) + Index(['first', 'second', nan], dtype='object') """ return self._shallow_copy_with_infer(self.values.map(mapper)) diff --git a/pandas/core/series.py b/pandas/core/series.py index e4801242073a2..f0ba369e1731a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2831,25 +2831,26 @@ def unstack(self, level=-1, fill_value=None): def map(self, arg, na_action=None): """ - Map values of Series using input correspondence (which can be - a dict, Series, or function) + Map values of Series using input correspondence (a dict, Series, or + function). Parameters ---------- arg : function, dict, or Series + Mapping correspondence. na_action : {None, 'ignore'} If 'ignore', propagate NA values, without passing them to the - mapping function + mapping correspondence. Returns ------- y : Series - same index as caller + Same index as caller. Examples -------- - Map inputs to outputs (both of type `Series`) + Map inputs to outputs (both of type `Series`): >>> x = pd.Series([1,2,3], index=['one', 'two', 'three']) >>> x @@ -2900,9 +2901,9 @@ def map(self, arg, na_action=None): See Also -------- - Series.apply: For applying more complex functions on a Series - DataFrame.apply: Apply a function row-/column-wise - DataFrame.applymap: Apply a function elementwise on a whole DataFrame + Series.apply : For applying more complex functions on a Series. + DataFrame.apply : Apply a function row-/column-wise. + DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Notes -----
Hi core devs, I worked on the CategoricalIndex.map docstring during the sprint in Paris. Although we concentrated on this function, while doing that we couldn't help improving (marginally!) also the docstrings for Categorical.map, Index.map and Series.map. We probably should have refrained from doing it, knowing that other cities were working on those, but it was difficult to change one and leaving the style of the others incoherent with the first. As a result I'm proposing here a pull request that combines all the changes. The validation script passes for CategoricalIndex.map but not for the other cases. If that is not acceptable I can change that, but I will probably need some help with the git part. Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################### Docstring (pandas.CategoricalIndex.map) ################### ################################################################################ Map index values using input correspondence (a dict, Series, or function). Maps the values (their categories, not the codes) of the index to new categories. If the mapping correspondence maps each original category to a different new category the result is a CategoricalIndex which has the same order property as the original, otherwise an Index is returned. If a dictionary or Series is used any unmapped category is mapped to NA. Note that if this happens an Index will be returned. Parameters ---------- mapper : function, dict, or Series Mapping correspondence. Returns ------- CategoricalIndex or Index Mapped index. See Also -------- Index.map : Apply a mapping correspondence on an Index. Series.map : Apply a mapping correspondence on a Series. Series.apply : Apply more complex functions on a Series. Examples -------- >>> idx = pd.CategoricalIndex(['a', 'b', 'c']) >>> idx CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'], ordered=False, dtype='category') >>> idx.map(lambda x: x.upper()) CategoricalIndex(['A', 'B', 'C'], categories=['A', 'B', 'C'], ordered=False, dtype='category') >>> idx.map({'a': 'first', 'b': 'second', 'c': 'third'}) CategoricalIndex(['first', 'second', 'third'], categories=['first', 'second', 'third'], ordered=False, dtype='category') If the mapping is not bijective an Index is returned: >>> idx.map({'a': 'first', 'b': 'second', 'c': 'first'}) Index(['first', 'second', 'first'], dtype='object') If a dictionary is used, all unmapped categories are mapped to NA and the result is an Index: >>> idx.map({'a': 'first', 'b': 'second'}) Index(['first', 'second', nan], dtype='object') ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.CategoricalIndex.map" correct. :) ################################################################################ ###################### Docstring (pandas.Categorical.map) ###################### ################################################################################ Map categories (not codes) using input correspondence (a dict, Series, or function). Maps the categories to new categories. If the mapping correspondence maps each original category to a different new category the result is a Categorical which has the same order property as the original, otherwise an np.ndarray is returned. If a dictionary or Series is used any unmapped category is mapped to NA. Note that if this happens an np.ndarray will be returned. Parameters ---------- mapper : callable Function to be applied. Returns ------- applied : Categorical or Index. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: See Also section not found No examples section found ################################################################################ ######################### Docstring (pandas.Index.map) ######################### ################################################################################ Map values using input correspondence (a dict, Series, or function). Parameters ---------- mapper : function, dict, or Series Mapping correspondence. na_action : {None, 'ignore'} If 'ignore', propagate NA values, without passing them to the mapping correspondence. Returns ------- applied : Union[Index, MultiIndex], inferred The output of the mapping function applied to the index. If the function returns a tuple with more than one element a MultiIndex will be returned. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found See Also section not found No examples section found ################################################################################ ######################## Docstring (pandas.Series.map) ######################## ################################################################################ Map values of Series using input correspondence (a dict, Series, or function). Parameters ---------- arg : function, dict, or Series Mapping correspondence. na_action : {None, 'ignore'} If 'ignore', propagate NA values, without passing them to the mapping correspondence. Returns ------- y : Series Same index as caller. Examples -------- Map inputs to outputs (both of type `Series`): >>> x = pd.Series([1,2,3], index=['one', 'two', 'three']) >>> x one 1 two 2 three 3 dtype: int64 >>> y = pd.Series(['foo', 'bar', 'baz'], index=[1,2,3]) >>> y 1 foo 2 bar 3 baz >>> x.map(y) one foo two bar three baz If `arg` is a dictionary, return a new Series with values converted according to the dictionary's mapping: >>> z = {1: 'A', 2: 'B', 3: 'C'} >>> x.map(z) one A two B three C Use na_action to control whether NA values are affected by the mapping function. >>> s = pd.Series([1, 2, 3, np.nan]) >>> s2 = s.map('this is a string {}'.format, na_action=None) 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 this is a string nan dtype: object >>> s3 = s.map('this is a string {}'.format, na_action='ignore') 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 NaN dtype: object See Also -------- Series.apply : For applying more complex functions on a Series. DataFrame.apply : Apply a function row-/column-wise. DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Notes ----- When `arg` is a dictionary, values in Series that are not in the dictionary (as keys) are converted to ``NaN``. However, if the dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e. provides a method for default values), then this default is used rather than ``NaN``: >>> from collections import Counter >>> counter = Counter() >>> counter['bar'] += 1 >>> y.map(counter) 1 0 2 1 3 0 dtype: int64 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No summary found (a short summary in a single line should be present at the beginning of the docstring) Examples do not pass tests ################################################################################ ################################### Doctests ################################### ################################################################################ ********************************************************************** Line 31, in pandas.Series.map Failed example: y Expected: 1 foo 2 bar 3 baz Got: 1 foo 2 bar 3 baz dtype: object ********************************************************************** Line 36, in pandas.Series.map Failed example: x.map(y) Expected: one foo two bar three baz Got: one foo two bar three baz dtype: object ********************************************************************** Line 46, in pandas.Series.map Failed example: x.map(z) Expected: one A two B three C Got: one A two B three C dtype: object ********************************************************************** Line 56, in pandas.Series.map Failed example: s2 = s.map('this is a string {}'.format, na_action=None) Expected: 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 this is a string nan dtype: object Got nothing ********************************************************************** Line 63, in pandas.Series.map Failed example: s3 = s.map('this is a string {}'.format, na_action='ignore') Expected: 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 NaN dtype: object Got nothing ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20286
2018-03-11T17:16:41Z
2018-03-22T08:39:01Z
2018-03-22T08:39:01Z
2018-03-29T11:55:58Z
DOC/TST: Added NORMALIZE_WHITESPACE flag
diff --git a/setup.cfg b/setup.cfg index 942b2b0a1a0bf..6d9657737a8bd 100644 --- a/setup.cfg +++ b/setup.cfg @@ -32,3 +32,4 @@ 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
I think we want this to be always on. You can disable it with ``` doctest: -NORMALIZE_WHITESPACE ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20284
2018-03-11T15:24:40Z
2018-03-12T14:38:30Z
2018-03-12T14:38:30Z
2018-03-12T14:38:33Z
DOC: update the pandas.Series.str.split docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index fac607f4621a8..11081535cf63f 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1095,24 +1095,88 @@ def str_pad(arr, width, side='left', fillchar=' '): def str_split(arr, pat=None, n=None): """ - Split each string (a la re.split) in the Series/Index by given - pattern, propagating NA values. Equivalent to :meth:`str.split`. + Split strings around given separator/delimiter. + + Split each string in the caller's values by given + pattern, propagating NaN values. Equivalent to :meth:`str.split`. Parameters ---------- - pat : string, default None - String or regular expression to split on. If None, splits on whitespace + pat : str, optional + String or regular expression to split on. + If not specified, split on whitespace. n : int, default -1 (all) - None, 0 and -1 will be interpreted as return all splits + Limit number of splits in output. + ``None``, 0 and -1 will be interpreted as return all splits. expand : bool, default False - * If True, return DataFrame/MultiIndex expanding dimensionality. - * If False, return Series/Index. + Expand the splitted strings into separate columns. - return_type : deprecated, use `expand` + * If ``True``, return DataFrame/MultiIndex expanding dimensionality. + * If ``False``, return Series/Index, containing lists of strings. Returns ------- split : Series/Index or DataFrame/MultiIndex of objects + Type matches caller unless ``expand=True`` (return type is DataFrame or + MultiIndex) + + Notes + ----- + The handling of the `n` keyword depends on the number of found splits: + + - If found splits > `n`, make first `n` splits only + - If found splits <= `n`, make all splits + - If for a certain row the number of found splits < `n`, + append `None` for padding up to `n` if ``expand=True`` + + Examples + -------- + >>> s = pd.Series(["this is good text", "but this is even better"]) + + By default, split will return an object of the same size + having lists containing the split elements + + >>> s.str.split() + 0 [this, is, good, text] + 1 [but, this, is, even, better] + dtype: object + >>> s.str.split("random") + 0 [this is good text] + 1 [but this is even better] + dtype: object + + When using ``expand=True``, the split elements will + expand out into separate columns. + + >>> s.str.split(expand=True) + 0 1 2 3 4 + 0 this is good text None + 1 but this is even better + >>> s.str.split(" is ", expand=True) + 0 1 + 0 this good text + 1 but this even better + + Parameter `n` can be used to limit the number of splits in the output. + + >>> s.str.split("is", n=1) + 0 [th, is good text] + 1 [but th, is even better] + dtype: object + >>> s.str.split("is", n=1, expand=True) + 0 1 + 0 th is good text + 1 but th is even better + + If NaN is present, it is propagated throughout the columns + during the split. + + >>> s = pd.Series(["this is good text", "but this is even better", np.nan]) + >>> s.str.split(n=3, expand=True) + 0 1 2 3 + 0 this is good text + 1 but this is even better + 2 NaN NaN NaN NaN """ if pat is None: if n is None or n == 0:
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant ``` ################################################################################ ##################### Docstring (pandas.Series.str.split) ##################### ################################################################################ Split strings around given separator/delimiter. Split each str in the caller's values by given pattern, propagating NaN values. Equivalent to :meth:`str.split`. Parameters ---------- pat : string, default None String or regular expression to split on. If `None`, split on whitespace. n : int, default -1 (all) Vary dimensionality of output. * `None`, 0 and -1 will be interpreted as return all splits expand : bool, default False Expand the split strings into separate columns. * If `True`, return DataFrame/MultiIndex expanding dimensionality. * If `False`, return Series/Index. Returns ------- Type matches caller unless `expand=True` (return type is `DataFrame`) split : Series/Index or DataFrame/MultiIndex of objects Notes ----- If `expand` parameter is `True` and: - If n >= default splits, makes all splits - If n < default splits, makes first n splits only - Appends `None` for padding. Examples -------- >>> s = pd.Series(["this is good text", "but this is even better"]) By default, split will return an object of the same size having lists containing the split elements >>> s.str.split() 0 [this, is, good, text] 1 [but, this, is, even, better] dtype: object >>> s.str.split("random") 0 [this is good text] 1 [but this is even better] dtype: object When using `expand=True`, the split elements will expand out into separate columns. >>> s.str.split(expand=True) 0 1 2 3 4 0 this is good text None 1 but this is even better >>> s.str.split(" is ", expand=True) 0 1 0 this good text 1 but this even better Parameter `n` can be used to limit the number of columns in expansion of output. >>> s.str.split("is", n=1, expand=True) 0 1 0 th is good text 1 but th is even better If NaN is present, it is propagated throughout the columns during the split. >>> s = pd.Series(["this is good text", "but this is even better", np.nan]) >>> s.str.split(n=3, expand=True) 0 1 2 3 0 this is good text 1 but this is even better 2 NaN NaN NaN NaN ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameter "n" description should finish with "." See Also section not found ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20282
2018-03-11T15:08:00Z
2018-03-12T15:30:27Z
2018-03-12T15:30:27Z
2018-03-12T15:52:28Z
DOC: update the Period.dayofweek attribute docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 89f38724cde1a..e84642b4a8f2c 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1246,6 +1246,37 @@ cdef class _Period(object): @property def dayofweek(self): + """ + Return the day of the week. + + This attribute returns the day of the week on which the particular + date for the given period occurs depending on the frequency with + Monday=0, Sunday=6. + + Returns + ------- + Int + Range from 0 to 6 (included). + + See also + -------- + Period.dayofyear : Return the day of the year. + Period.daysinmonth : Return the number of days in that month. + + Examples + -------- + >>> period1 = pd.Period('2012-1-1 19:00', freq='H') + >>> period1 + Period('2012-01-01 19:00', 'H') + >>> period1.dayofweek + 6 + + >>> period2 = pd.Period('2013-1-9 11:00', freq='H') + >>> period2 + Period('2013-01-09 11:00', 'H') + >>> period2.dayofweek + 2 + """ base, mult = get_freq_code(self.freq) return pweekday(self.ordinal, base)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` (pandas_dev) root@kalih:~/pythonpanda/pandas# python scripts/validate_docstrings.py pandas.Period.dayofweek ################################################################################ ##################### Docstring (pandas.Period.dayofweek) ##################### ################################################################################ Return the day of the week. This attribute returns the day of the week on which the particular starting date for the given period occurs with Monday=0, Sunday=6. Returns ------- Int Range of 0 to 6 See also -------- Period.dayofyear Return the day of year. Period.daysinmonth Return the days in that month. Examples -------- >>> period1 = pd.Period('2012-1-1 19:00', freq='H') >>> period1 Period('2012-01-01 19:00', 'H') >>> period1.dayofweek 6 >>> period2 = pd.Period('2013-1-9 11:00', freq='H') >>> period2 Period('2013-01-09 11:00', 'H') >>> period2.dayofweek 2 ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Period.dayofweek" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20280
2018-03-11T11:17:23Z
2018-03-13T10:05:03Z
2018-03-13T10:05:03Z
2018-03-13T10:11:54Z
DOC: update the pandas.Series.dt.is_quarter_end docstring
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e5e9bba269fd4..4c81eafabf24a 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1739,7 +1739,44 @@ def freq(self, value): is_quarter_end = _field_accessor( 'is_quarter_end', 'is_quarter_end', - "Logical indicating if last day of quarter (defined by frequency)") + """ + Indicator for whether the date is the last day of a quarter. + + Returns + ------- + is_quarter_end : Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + quarter : Return the quarter of the date. + is_quarter_start : Similar method indicating the quarter start. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", + ... periods=4)}) + >>> df.assign(quarter=df.dates.dt.quarter, + ... is_quarter_end=df.dates.dt.is_quarter_end) + dates quarter is_quarter_end + 0 2017-03-30 1 False + 1 2017-03-31 1 True + 2 2017-04-01 2 False + 3 2017-04-02 2 False + + >>> idx = pd.date_range('2017-03-30', periods=4) + >>> idx + DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_quarter_end + array([False, True, False, False]) + """) is_year_start = _field_accessor( 'is_year_start', 'is_year_start',
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################# Docstring (pandas.Series.dt.is_quarter_end) ################# ################################################################################ Return a boolean indicating whether the date is the last day of a quarter. Returns ------- is_quarter_end : Series of boolean. See Also -------- quarter : Return the quarter of the date. is_quarter_start : Return a boolean indicating whether the date is the first day of the quarter. Examples -------- >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", ... periods=4)}) >>> df.assign(quarter = df.dates.dt.quarter, ... is_quarter_end = df.dates.dt.is_quarter_end) dates quarter is_quarter_end 0 2017-03-30 1 False 1 2017-03-31 1 True 2 2017-04-01 2 False 3 2017-04-02 2 False ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No summary found (a short summary in a single line should be present at the beginning of the docstring) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. * No extended summary required. * Short summary exceeds one line by one word, hope that is ok
https://api.github.com/repos/pandas-dev/pandas/pulls/20279
2018-03-11T11:08:40Z
2018-03-14T18:41:30Z
2018-03-14T18:41:30Z
2018-03-14T18:47:55Z
DOC: update the pandas.Series.dt.is_quarter_start docstring
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e5e9bba269fd4..6f8fb766f5dfa 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1735,7 +1735,44 @@ def freq(self, value): is_quarter_start = _field_accessor( 'is_quarter_start', 'is_quarter_start', - "Logical indicating if first day of quarter (defined by frequency)") + """ + Indicator for whether the date is the first day of a quarter. + + Returns + ------- + is_quarter_start : Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + quarter : Return the quarter of the date. + is_quarter_end : Similar method for indicating the start of a quarter. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", + ... periods=4)}) + >>> df.assign(quarter=df.dates.dt.quarter, + ... is_quarter_start=df.dates.dt.is_quarter_start) + dates quarter is_quarter_start + 0 2017-03-30 1 False + 1 2017-03-31 1 False + 2 2017-04-01 2 True + 3 2017-04-02 2 False + + >>> idx = pd.date_range('2017-03-30', periods=4) + >>> idx + DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_quarter_start + array([False, False, True, False]) + """) is_quarter_end = _field_accessor( 'is_quarter_end', 'is_quarter_end',
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################ Docstring (pandas.Series.dt.is_quarter_start) ################ ################################################################################ Return a boolean indicating whether the date is the first day of a quarter. Returns ------- is_quarter_start : Series of boolean. See Also -------- quarter : Return the quarter of the date. is_quarter_end : Return a boolean indicating whether the date is the last day of the quarter. Examples -------- >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", periods=4)}) >>> df.assign(quarter = df.dates.dt.quarter, ... is_quarter_start = df.dates.dt.is_quarter_start) dates quarter is_quarter_start 0 2017-03-30 1 False 1 2017-03-31 1 False 2 2017-04-01 2 True 3 2017-04-02 2 False ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No summary found (a short summary in a single line should be present at the beginning of the docstring) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. * Short summary exceeds single line by one word, hope that is ok.
https://api.github.com/repos/pandas-dev/pandas/pulls/20278
2018-03-11T10:51:33Z
2018-03-14T18:47:45Z
2018-03-14T18:47:45Z
2018-03-14T18:47:48Z
DOC: update the Period.dayofyear docstring
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 89f38724cde1a..e14efaf04bd41 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1255,6 +1255,36 @@ cdef class _Period(object): @property def dayofyear(self): + """ + Return the day of the year. + + This attribute returns the day of the year on which the particular + date occurs. The return value ranges between 1 to 365 for regular + years and 1 to 366 for leap years. + + Returns + ------- + int + The day of year. + + See Also + -------- + Period.day : Return the day of the month. + Period.dayofweek : Return the day of week. + PeriodIndex.dayofyear : Return the day of year of all indexes. + + Examples + -------- + >>> period = pd.Period("2015-10-23", freq='H') + >>> period.dayofyear + 296 + >>> period = pd.Period("2012-12-31", freq='D') + >>> period.dayofyear + 366 + >>> period = pd.Period("2013-01-01", freq='D') + >>> period.dayofyear + 1 + """ base, mult = get_freq_code(self.freq) return pday_of_year(self.ordinal, base)
Signed-off-by: Tushar Mittal <chiragmittal.mittal@gmail.com> Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ##################### Docstring (pandas.Period.dayofyear) ##################### ################################################################################ Return the day of the year. This attribute returns the day of the year on which the particular date occurs. The return value ranges between 1 to 365 for regular years and 1 to 366 for leap years. Returns ------- int The day of year. See Also -------- Period.dayofweek : Return the day of week. Period.daysinmonth : Return the days in that month. PeriodIndex.dayofyear : Return the day of year of all indexes. Examples -------- >>> period = pd.Period("2015-10-23", freq='H') >>> period.dayofyear 296 >>> period = pd.Period("2012-12-31", freq='D') >>> period.dayofyear 366 >>> period = pd.Period("2013-01-01", freq='D') >>> period.dayofyear 1 ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Period.dayofyear" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20277
2018-03-11T10:46:41Z
2018-03-13T08:55:51Z
2018-03-13T08:55:51Z
2018-03-13T09:07:31Z
DOC: update the aggregate docstring
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 79265e35ef6e6..12a7141bdb0ee 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -107,6 +107,10 @@ _shared_doc_kwargs = dict( axes='index, columns', klass='DataFrame', axes_single_arg="{0 or 'index', 1 or 'columns'}", + axis=""" + axis : {0 or 'index', 1 or 'columns'}, default 0 + - 0 or 'index': apply function to each column. + - 1 or 'columns': apply function to each row.""", optional_by=""" by : str or list of str Name or list of names to sort by. @@ -4460,9 +4464,9 @@ def pivot(self, index=None, columns=None, values=None): Reshape data (produce a "pivot" table) based on column values. Uses unique values from specified `index` / `columns` to form axes of the - resulting DataFrame. This function does not support data aggregation, - multiple values will result in a MultiIndex in the columns. See the - :ref:`User Guide <reshaping>` for more on reshaping. + resulting DataFrame. This function does not support data + aggregation, multiple values will result in a MultiIndex in the + columns. See the :ref:`User Guide <reshaping>` for more on reshaping. Parameters ---------- @@ -4980,36 +4984,59 @@ def _gotitem(self, key, ndim, subset=None): return self[key] _agg_doc = dedent(""" + Notes + ----- + The aggregation operations are always performed over an axis, either the + index (default) or the column axis. This behavior is different from + `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`, + `var`), where the default is to compute the aggregation of the flattened + array, e.g., ``numpy.mean(arr_2d)`` as opposed to ``numpy.mean(arr_2d, + axis=0)``. + + `agg` is an alias for `aggregate`. Use the alias. + Examples -------- + >>> df = pd.DataFrame([[1, 2, 3], + ... [4, 5, 6], + ... [7, 8, 9], + ... [np.nan, np.nan, np.nan]], + ... columns=['A', 'B', 'C']) - >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'], - ... index=pd.date_range('1/1/2000', periods=10)) - >>> df.iloc[3:7] = np.nan - - Aggregate these functions across all columns + Aggregate these functions over the rows. >>> df.agg(['sum', 'min']) - A B C - sum -0.182253 -0.614014 -2.909534 - min -1.916563 -1.460076 -1.568297 + A B C + sum 12.0 15.0 18.0 + min 1.0 2.0 3.0 - Different aggregations per column + Different aggregations per column. >>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']}) - A B - max NaN 1.514318 - min -1.916563 -1.460076 - sum -0.182253 NaN + A B + max NaN 8.0 + min 1.0 2.0 + sum 12.0 NaN + + Aggregate over the columns. + + >>> df.agg("mean", axis="columns") + 0 2.0 + 1 5.0 + 2 8.0 + 3 NaN + dtype: float64 See also -------- - pandas.DataFrame.apply - pandas.DataFrame.transform - pandas.DataFrame.groupby.aggregate - pandas.DataFrame.resample.aggregate - pandas.DataFrame.rolling.aggregate - + DataFrame.apply : Perform any type of operations. + DataFrame.transform : Perform transformation type operations. + pandas.core.groupby.GroupBy : Perform operations over groups. + pandas.core.resample.Resampler : Perform operations over resampled bins. + pandas.core.window.Rolling : Perform operations over rolling window. + pandas.core.window.Expanding : Perform operations over expanding window. + pandas.core.window.EWM : Perform operation over exponential weighted + window. """) @Appender(_agg_doc) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index bfb251b0995ec..494351dd27ca5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3937,36 +3937,37 @@ def pipe(self, func, *args, **kwargs): return com._pipe(self, func, *args, **kwargs) _shared_docs['aggregate'] = (""" - Aggregate using callable, string, dict, or list of string/callables + Aggregate using one or more operations over the specified axis. %(versionadded)s Parameters ---------- - func : callable, string, dictionary, or list of string/callables + func : function, string, dictionary, or list of string/functions Function to use for aggregating the data. If a function, must either work when passed a %(klass)s or when passed to %(klass)s.apply. For a DataFrame, can pass a dict, if the keys are DataFrame column names. - Accepted Combinations are: + Accepted combinations are: - - string function name - - function - - list of functions - - dict of column names -> functions (or list of functions) + - string function name. + - function. + - list of functions. + - dict of column names -> functions (or list of functions). - Notes - ----- - Numpy functions mean/median/prod/sum/std/var are special cased so the - default behavior is applying the function along axis=0 - (e.g., np.mean(arr_2d, axis=0)) as opposed to - mimicking the default Numpy behavior (e.g., np.mean(arr_2d)). - - `agg` is an alias for `aggregate`. Use the alias. + %(axis)s + *args + Positional arguments to pass to `func`. + **kwargs + Keyword arguments to pass to `func`. Returns ------- aggregated : %(klass)s + + Notes + ----- + `agg` is an alias for `aggregate`. Use the alias. """) _shared_docs['transform'] = (""" @@ -4014,7 +4015,6 @@ def pipe(self, func, *args, **kwargs): -------- pandas.%(klass)s.aggregate pandas.%(klass)s.apply - """) # ---------------------------------------------------------------------- diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index a89b8714db6a0..4352a001aa989 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3432,7 +3432,8 @@ def apply(self, func, *args, **kwargs): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( klass='Series', - versionadded='')) + versionadded='', + axis='')) def aggregate(self, func_or_funcs, *args, **kwargs): _level = kwargs.pop('_level', None) if isinstance(func_or_funcs, compat.string_types): @@ -4611,7 +4612,8 @@ class DataFrameGroupBy(NDFrameGroupBy): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( klass='DataFrame', - versionadded='')) + versionadded='', + axis='')) def aggregate(self, arg, *args, **kwargs): return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 4f9c22ca98f1a..004d572375234 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -334,7 +334,8 @@ def plot(self, *args, **kwargs): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( klass='DataFrame', - versionadded='')) + versionadded='', + axis='')) def aggregate(self, arg, *args, **kwargs): self._set_binner() diff --git a/pandas/core/series.py b/pandas/core/series.py index 46d1f4468b4d0..4d6bbedc51922 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -77,6 +77,10 @@ _shared_doc_kwargs = dict( axes='index', klass='Series', axes_single_arg="{0 or 'index'}", + axis=""" + axis : {0 or 'index'} + Parameter needed for compatibility with DataFrame. + """, inplace="""inplace : boolean, default False If True, performs operation inplace and returns None.""", unique='np.ndarray', duplicated='Series', diff --git a/pandas/core/window.py b/pandas/core/window.py index 59cf9ad2920ca..e70a3cb5e911b 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -626,7 +626,8 @@ def f(arg, *args, **kwargs): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( versionadded='', - klass='Series/DataFrame')) + klass='Series/DataFrame', + axis='')) def aggregate(self, arg, *args, **kwargs): result, how = self._aggregate(arg, *args, **kwargs) if result is None: @@ -1300,7 +1301,8 @@ def _validate_freq(self): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( versionadded='', - klass='Series/DataFrame')) + klass='Series/DataFrame', + axis='')) def aggregate(self, arg, *args, **kwargs): return super(Rolling, self).aggregate(arg, *args, **kwargs) @@ -1566,7 +1568,8 @@ def _get_window(self, other=None): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( versionadded='', - klass='Series/DataFrame')) + klass='Series/DataFrame', + axis='')) def aggregate(self, arg, *args, **kwargs): return super(Expanding, self).aggregate(arg, *args, **kwargs) @@ -1869,7 +1872,8 @@ def _constructor(self): @Appender(_agg_doc) @Appender(_shared_docs['aggregate'] % dict( versionadded='', - klass='Series/DataFrame')) + klass='Series/DataFrame', + axis='')) def aggregate(self, arg, *args, **kwargs): return super(EWM, self).aggregate(arg, *args, **kwargs)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [ ] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ ] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ #################### Docstring (pandas.DataFrame.aggregate) #################### ################################################################################ Aggregate using one or multiple operations along the specified axis. .. versionadded:: 0.20.0 Parameters ---------- func : function, string, dictionary, or list of string/functions Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. For a DataFrame, can pass a dict, if the keys are DataFrame column names. Accepted combinations are: - string function name. - function. - list of functions. - dict of column names -> functions (or list of functions). axis : {0 or 'index', 1 or 'columns'}, default 0 - 0 or 'index': apply function to each column. - 1 or 'columns': apply function to each row. args Optional positional arguments to pass to the function. kwargs Optional keyword arguments to pass to the function. Returns ------- aggregated : DataFrame Notes ----- `agg` is an alias for `aggregate`. Use the alias. Notes ----- The default behavior of aggregating over the axis 0 is different from `numpy` functions `mean`/`median`/`prod`/`sum`/`std`/`var`, where the default is to compute the aggregation of the flattened array (e.g., `numpy.mean(arr_2d)` as opposed to `numpy.mean(arr_2d, axis=0)`). `agg` is an alias for `aggregate`. Use the alias. Examples -------- >>> df = df = pd.DataFrame([[1,2,3], ... [4,5,6], ... [7,8,9], ... [np.nan, np.nan, np.nan]], ... columns=['A', 'B', 'C']) Aggregate these functions across all columns >>> df.aggregate(['sum', 'min']) A B C sum 12.0 15.0 18.0 min 1.0 2.0 3.0 Different aggregations per column >>> df.aggregate({'A' : ['sum', 'min'], 'B' : ['min', 'max']}) A B max NaN 8.0 min 1.0 2.0 sum 12.0 NaN See also -------- pandas.DataFrame.apply : Perform any type of operations. pandas.DataFrame.transform : Perform transformation type operations. pandas.DataFrame.groupby.aggregate : Perform aggregation type operations over groups. pandas.DataFrame.resample.aggregate : Perform aggregation type operations over resampled bins. pandas.DataFrame.rolling.aggregate : Perform aggregation type operations over rolling window. ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameter "axis" description should start with capital letter Parameter "args" has no type Parameter "kwargs" has no type ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. - args and kwargs have no type - axis : {0 or 'index', 1 or 'columns'}, default 0 This PR has been made in collaboration with @rochamatcomp Question to reviewers: we have added to the docstring the parameter `axis` because this is appropriate for DataFrame. However this dosctring is generic (shared with Series, groupby, window and resample) and the parameter `axis` is wrong for them (for Series the parameter has only one possible value). What should be the right way to fix this?
https://api.github.com/repos/pandas-dev/pandas/pulls/20276
2018-03-11T10:40:36Z
2018-03-13T14:11:25Z
2018-03-13T14:11:25Z
2018-03-13T14:56:41Z
DOC: update the pandas.Series.dt.is_year_start docstring
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e5e9bba269fd4..4e299f4045fbb 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1743,7 +1743,46 @@ def freq(self, value): is_year_start = _field_accessor( 'is_year_start', 'is_year_start', - "Logical indicating if first day of year (defined by frequency)") + """ + Indicate whether the date is the first day of a year. + + Returns + ------- + Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + is_year_end : Similar method indicating the last day of the year. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) + >>> dates + 0 2017-12-30 + 1 2017-12-31 + 2 2018-01-01 + dtype: datetime64[ns] + + >>> dates.dt.is_year_start + 0 False + 1 False + 2 True + dtype: bool + + >>> idx = pd.date_range("2017-12-30", periods=3) + >>> idx + DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_year_start + array([False, False, True]) + """) is_year_end = _field_accessor( 'is_year_end', 'is_year_end',
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################## Docstring (pandas.Series.dt.is_year_start) ################## ################################################################################ Return a boolean indicating whether the date is the first day of the year. Returns ------- is_year_start : Series of boolean. See Also -------- is_year_end : Return a boolean indicating whether the date is the last day of the year. Examples -------- >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) >>> dates 0 2017-12-30 1 2017-12-31 2 2018-01-01 dtype: datetime64[ns] >>> dates.dt.is_year_start 0 False 1 False 2 True dtype: bool ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No summary found (a short summary in a single line should be present at the beginning of the docstring) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. * short summary exceeds one line by one word, hope that is ok
https://api.github.com/repos/pandas-dev/pandas/pulls/20275
2018-03-11T10:04:43Z
2018-03-14T18:51:24Z
2018-03-14T18:51:24Z
2018-03-14T18:51:26Z
DOC: update the pandas.Series.dt.is_year_end docstring
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 7496334b0a86f..b82cc3980bae8 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1790,7 +1790,7 @@ def freq(self, value): See Also -------- quarter : Return the quarter of the date. - is_quarter_end : Similar method for indicating the start of a quarter. + is_quarter_end : Similar property for indicating the start of a quarter. Examples -------- @@ -1831,7 +1831,7 @@ def freq(self, value): See Also -------- quarter : Return the quarter of the date. - is_quarter_start : Similar method indicating the quarter start. + is_quarter_start : Similar property indicating the quarter start. Examples -------- @@ -1871,7 +1871,7 @@ def freq(self, value): See Also -------- - is_year_end : Similar method indicating the last day of the year. + is_year_end : Similar property indicating the last day of the year. Examples -------- @@ -1902,7 +1902,46 @@ def freq(self, value): is_year_end = _field_accessor( 'is_year_end', 'is_year_end', - "Logical indicating if last day of year (defined by frequency)") + """ + Indicate whether the date is the last day of the year. + + Returns + ------- + Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + is_year_start : Similar property indicating the start of the year. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) + >>> dates + 0 2017-12-30 + 1 2017-12-31 + 2 2018-01-01 + dtype: datetime64[ns] + + >>> dates.dt.is_year_end + 0 False + 1 True + 2 False + dtype: bool + + >>> idx = pd.date_range("2017-12-30", periods=3) + >>> idx + DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_year_end + array([False, True, False]) + """) is_leap_year = _field_accessor( 'is_leap_year', 'is_leap_year',
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################### Docstring (pandas.Series.dt.is_year_end) ################### ################################################################################ Return a boolean indicating whether the date is the last day of the year. Returns ------- is_year_end : Series of boolean. See Also -------- is_year_start : Return a boolean indicating whether the date is the first day of the year. Examples -------- >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) >>> dates 0 2017-12-30 1 2017-12-31 2 2018-01-01 dtype: datetime64[ns] >>> dates.dt.is_year_end 0 False 1 True 2 False dtype: bool ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. * No extended summary required
https://api.github.com/repos/pandas-dev/pandas/pulls/20274
2018-03-11T09:52:54Z
2018-03-14T18:56:52Z
2018-03-14T18:56:52Z
2018-03-14T18:56:52Z
DOC: update the pandas.Series.str.slice_replace docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 08a1cc29b8367..2eb2d284d8518 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1322,19 +1322,75 @@ def str_slice(arr, start=None, stop=None, step=None): def str_slice_replace(arr, start=None, stop=None, repl=None): """ - Replace a slice of each string in the Series/Index with another - string. + Replace a positional slice of a string with another value. Parameters ---------- - start : int or None - stop : int or None - repl : str or None - String for replacement + start : int, optional + Left index position to use for the slice. If not specified (None), + the slice is unbounded on the left, i.e. slice from the start + of the string. + stop : int, optional + Right index position to use for the slice. If not specified (None), + the slice is unbounded on the right, i.e. slice until the + end of the string. + repl : str, optional + String for replacement. If not specified (None), the sliced region + is replaced with an empty string. Returns ------- - replaced : Series/Index of objects + replaced : Series or Index + Same type as the original object. + + See Also + -------- + Series.str.slice : Just slicing without replacement. + + Examples + -------- + >>> s = pd.Series(['a', 'ab', 'abc', 'abdc', 'abcde']) + >>> s + 0 a + 1 ab + 2 abc + 3 abdc + 4 abcde + dtype: object + + Specify just `start`, meaning replace `start` until the end of the + string with `repl`. + + >>> s.str.slice_replace(1, repl='X') + 0 aX + 1 aX + 2 aX + 3 aX + 4 aX + dtype: object + + Specify just `stop`, meaning the start of the string to `stop` is replaced + with `repl`, and the rest of the string is included. + + >>> s.str.slice_replace(stop=2, repl='X') + 0 X + 1 X + 2 Xc + 3 Xdc + 4 Xcde + dtype: object + + Specify `start` and `stop`, meaning the slice from `start` to `stop` is + replaced with `repl`. Everything before or after `start` and `stop` is + included as is. + + >>> s.str.slice_replace(start=1, stop=3, repl='X') + 0 aX + 1 aX + 2 aX + 3 aXc + 4 aXde + dtype: object """ if repl is None: repl = ''
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################# Docstring (pandas.Series.str.slice_replace) ################# ################################################################################ Replace a sliced string. Replace a slice of each string in the Series/Index with another string. Parameters ---------- start : int or None Left edge index. stop : int or None Right edge index. repl : str or None String for replacement. Returns ------- replaced : Series/Index of objects Examples -------- >>> s = pd.Series(['This is a Test 1', 'This is a Test 2']) >>> s 0 This is a Test 1 1 This is a Test 2 dtype: object >>> s = s.str.slice_replace(8, 14, 'an Example') >>> s 0 This is an Example 1 1 This is an Example 2 dtype: object ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: See Also section not found ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20273
2018-03-11T07:50:32Z
2018-03-16T11:47:50Z
2018-03-16T11:47:50Z
2018-04-07T10:38:09Z
DOC: Update the pandas.core.window.x.sum docstring
diff --git a/pandas/core/window.py b/pandas/core/window.py index e70a3cb5e911b..358ef98e1c072 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -320,7 +320,79 @@ def aggregate(self, arg, *args, **kwargs): agg = aggregate _shared_docs['sum'] = dedent(""" - %(name)s sum""") + Calculate %(name)s sum of given DataFrame or Series. + + Parameters + ---------- + *args, **kwargs + For compatibility with other %(name)s methods. Has no effect + on the computed value. + + Returns + ------- + Series or DataFrame + Same type as the input, with the same index, containing the + %(name)s sum. + + See Also + -------- + Series.sum : Reducing sum for Series. + DataFrame.sum : Reducing sum for DataFrame. + + Examples + -------- + >>> s = pd.Series([1, 2, 3, 4, 5]) + >>> s + 0 1 + 1 2 + 2 3 + 3 4 + 4 5 + dtype: int64 + + >>> s.rolling(3).sum() + 0 NaN + 1 NaN + 2 6.0 + 3 9.0 + 4 12.0 + dtype: float64 + + >>> s.expanding(3).sum() + 0 NaN + 1 NaN + 2 6.0 + 3 10.0 + 4 15.0 + dtype: float64 + + >>> s.rolling(3, center=True).sum() + 0 NaN + 1 6.0 + 2 9.0 + 3 12.0 + 4 NaN + dtype: float64 + + For DataFrame, each %(name)s sum is computed column-wise. + + >>> df = pd.DataFrame({"A": s, "B": s ** 2}) + >>> df + A B + 0 1 1 + 1 2 4 + 2 3 9 + 3 4 16 + 4 5 25 + + >>> df.rolling(3).sum() + A B + 0 NaN NaN + 1 NaN NaN + 2 6.0 14.0 + 3 9.0 29.0 + 4 12.0 50.0 + """) _shared_docs['mean'] = dedent(""" %(name)s mean""") @@ -640,7 +712,6 @@ def aggregate(self, arg, *args, **kwargs): agg = aggregate @Substitution(name='window') - @Appender(_doc_template) @Appender(_shared_docs['sum']) def sum(self, *args, **kwargs): nv.validate_window_func('sum', args, kwargs) @@ -1326,7 +1397,6 @@ def apply(self, func, args=(), kwargs={}): return super(Rolling, self).apply(func, args=args, kwargs=kwargs) @Substitution(name='rolling') - @Appender(_doc_template) @Appender(_shared_docs['sum']) def sum(self, *args, **kwargs): nv.validate_rolling_func('sum', args, kwargs) @@ -1588,7 +1658,6 @@ def apply(self, func, args=(), kwargs={}): return super(Expanding, self).apply(func, args=args, kwargs=kwargs) @Substitution(name='expanding') - @Appender(_doc_template) @Appender(_shared_docs['sum']) def sum(self, *args, **kwargs): nv.validate_expanding_func('sum', args, kwargs)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x ] PR title is "DOC: update the <your-function-or-method> docstring" - [x ] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x ] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x ] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` # paste output of "scripts/validate_docstrings.py <your-function-or-method>" here # between the "```" (pandas-dev) D:\GitHub\pandas>python scripts/validate_docstrings.py pandas.core.window.Rolling.sum ################################################################################ ################## Docstring (pandas.core.window.Rolling.sum) ################## ################################################################################ Calculate rolling sum of given DataFrame or Series. Parameters ---------- *args Under Review. **kwargs Under Review. Returns ------- Series or DataFrame Like-indexed object containing the result of function application See Also -------- Series.rolling : Calling object with Series data DataFrame.rolling : Calling object with DataFrame data Series.sum : Equivalent method for Series DataFrame.sum : Equivalent method for DataFrame Examples -------- >>> s = pd.Series([1, 2, 3, 4, 5]) >>> s.rolling(3).sum() 0 NaN 1 NaN 2 6.0 3 9.0 4 12.0 dtype: float64 >>> s.expanding(3).sum() 0 NaN 1 NaN 2 6.0 3 10.0 4 15.0 dtype: float64 >>> s.rolling(3, center=True).sum() 0 NaN 1 6.0 2 9.0 3 12.0 4 NaN dtype: float64 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found Errors in parameters section Parameters {'kwargs', 'args'} not documented Unknown parameters {'**kwargs', '*args'} Parameter "*args" has no type Parameter "**kwargs" has no type (pandas-dev) D:\GitHub\pandas>python scripts/validate_docstrings.py pandas.core.window.Expanding.sum ################################################################################ ################# Docstring (pandas.core.window.Expanding.sum) ################# ################################################################################ Calculate expanding sum of given DataFrame or Series. Parameters ---------- *args Under Review. **kwargs Under Review. Returns ------- Series or DataFrame Like-indexed object containing the result of function application See Also -------- Series.expanding : Calling object with Series data DataFrame.expanding : Calling object with DataFrame data Series.sum : Equivalent method for Series DataFrame.sum : Equivalent method for DataFrame Examples -------- >>> s = pd.Series([1, 2, 3, 4, 5]) >>> s.rolling(3).sum() 0 NaN 1 NaN 2 6.0 3 9.0 4 12.0 dtype: float64 >>> s.expanding(3).sum() 0 NaN 1 NaN 2 6.0 3 10.0 4 15.0 dtype: float64 >>> s.rolling(3, center=True).sum() 0 NaN 1 6.0 2 9.0 3 12.0 4 NaN dtype: float64 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found Errors in parameters section Parameters {'kwargs', 'args'} not documented Unknown parameters {'**kwargs', '*args'} Parameter "*args" has no type Parameter "**kwargs" has no type (pandas-dev) D:\GitHub\pandas>python scripts/validate_docstrings.py pandas.core.window.Window.sum ################################################################################ ################## Docstring (pandas.core.window.Window.sum) ################## ################################################################################ Calculate window sum of given DataFrame or Series. Parameters ---------- *args Under Review. **kwargs Under Review. Returns ------- Series or DataFrame Like-indexed object containing the result of function application See Also -------- Series.window : Calling object with Series data DataFrame.window : Calling object with DataFrame data Series.sum : Equivalent method for Series DataFrame.sum : Equivalent method for DataFrame Examples -------- >>> s = pd.Series([1, 2, 3, 4, 5]) >>> s.rolling(3).sum() 0 NaN 1 NaN 2 6.0 3 9.0 4 12.0 dtype: float64 >>> s.expanding(3).sum() 0 NaN 1 NaN 2 6.0 3 10.0 4 15.0 dtype: float64 >>> s.rolling(3, center=True).sum() 0 NaN 1 6.0 2 9.0 3 12.0 4 NaN dtype: float64 ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: No extended summary found Errors in parameters section Parameters {'args', 'kwargs'} not documented Unknown parameters {'*args', '**kwargs'} Parameter "*args" has no type Parameter "**kwargs" has no type ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20272
2018-03-11T03:55:19Z
2018-03-14T19:30:05Z
2018-03-14T19:30:05Z
2018-03-14T19:30:09Z
DOC: update the pandas.DataFrame.replace docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 397726181d2fb..5534d21b43ff7 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4867,28 +4867,33 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): limit=limit, downcast=downcast) _shared_docs['replace'] = (""" - Replace values given in 'to_replace' with 'value'. + Replace values given in `to_replace` with `value`. + + Values of the %(klass)s are replaced with other values dynamically. + This differs from updating with ``.loc`` or ``.iloc``, which require + you to specify a location to update with some value. Parameters ---------- - to_replace : str, regex, list, dict, Series, numeric, or None + to_replace : str, regex, list, dict, Series, int, float, or None + How to find the values that will be replaced. * numeric, str or regex: - - numeric: numeric values equal to ``to_replace`` will be - replaced with ``value`` - - str: string exactly matching ``to_replace`` will be replaced - with ``value`` - - regex: regexs matching ``to_replace`` will be replaced with - ``value`` + - numeric: numeric values equal to `to_replace` will be + replaced with `value` + - str: string exactly matching `to_replace` will be replaced + with `value` + - regex: regexs matching `to_replace` will be replaced with + `value` * list of str, regex, or numeric: - - First, if ``to_replace`` and ``value`` are both lists, they + - First, if `to_replace` and `value` are both lists, they **must** be the same length. - Second, if ``regex=True`` then all of the strings in **both** lists will be interpreted as regexs otherwise they will match - directly. This doesn't matter much for ``value`` since there + directly. This doesn't matter much for `value` since there are only a few possible substitution regexes you can use. - str, regex and numeric rules apply as above. @@ -4896,20 +4901,20 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): - Dicts can be used to specify different replacement values for different existing values. For example, - {'a': 'b', 'y': 'z'} replaces the value 'a' with 'b' and - 'y' with 'z'. To use a dict in this way the ``value`` - parameter should be ``None``. + ``{'a': 'b', 'y': 'z'}`` replaces the value 'a' with 'b' and + 'y' with 'z'. To use a dict in this way the `value` + parameter should be `None`. - For a DataFrame a dict can specify that different values should be replaced in different columns. For example, - {'a': 1, 'b': 'z'} looks for the value 1 in column 'a' and - the value 'z' in column 'b' and replaces these values with - whatever is specified in ``value``. The ``value`` parameter + ``{'a': 1, 'b': 'z'}`` looks for the value 1 in column 'a' + and the value 'z' in column 'b' and replaces these values + with whatever is specified in `value`. The `value` parameter should not be ``None`` in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in. - For a DataFrame nested dictionaries, e.g., - {'a': {'b': np.nan}}, are read as follows: look in column 'a' - for the value 'b' and replace it with NaN. The ``value`` + ``{'a': {'b': np.nan}}``, are read as follows: look in column + 'a' for the value 'b' and replace it with NaN. The `value` parameter should be ``None`` to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested @@ -4917,14 +4922,14 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): * None: - - This means that the ``regex`` argument must be a string, - compiled regular expression, or list, dict, ndarray or Series - of such elements. If ``value`` is also ``None`` then this - **must** be a nested dictionary or ``Series``. + - This means that the `regex` argument must be a string, + compiled regular expression, or list, dict, ndarray or + Series of such elements. If `value` is also ``None`` then + this **must** be a nested dictionary or Series. See the examples section for examples of each of these. value : scalar, dict, list, str, regex, default None - Value to replace any values matching ``to_replace`` with. + Value to replace any values matching `to_replace` with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such @@ -4934,45 +4939,50 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True. limit : int, default None - Maximum size gap to forward or backward fill - regex : bool or same types as ``to_replace``, default False - Whether to interpret ``to_replace`` and/or ``value`` as regular - expressions. If this is ``True`` then ``to_replace`` *must* be a + Maximum size gap to forward or backward fill. + regex : bool or same types as `to_replace`, default False + Whether to interpret `to_replace` and/or `value` as regular + expressions. If this is ``True`` then `to_replace` *must* be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case - ``to_replace`` must be ``None``. - method : string, optional, {'pad', 'ffill', 'bfill'} - The method to use when for replacement, when ``to_replace`` is a - scalar, list or tuple and ``value`` is None. + `to_replace` must be ``None``. + method : {'pad', 'ffill', 'bfill', `None`} + The method to use when for replacement, when `to_replace` is a + scalar, list or tuple and `value` is ``None``. - .. versionchanged:: 0.23.0 - Added to DataFrame + .. versionchanged:: 0.23.0 + Added to DataFrame. + axis : None + .. deprecated:: 0.13.0 + Has no effect and will be removed. See Also -------- - %(klass)s.fillna : Fill NA/NaN values + %(klass)s.fillna : Fill NA values %(klass)s.where : Replace values based on boolean condition + Series.str.replace : Simple string replacement. Returns ------- - filled : %(klass)s + %(klass)s + Object after replacement. Raises ------ AssertionError - * If ``regex`` is not a ``bool`` and ``to_replace`` is not + * If `regex` is not a ``bool`` and `to_replace` is not ``None``. TypeError - * If ``to_replace`` is a ``dict`` and ``value`` is not a ``list``, + * If `to_replace` is a ``dict`` and `value` is not a ``list``, ``dict``, ``ndarray``, or ``Series`` - * If ``to_replace`` is ``None`` and ``regex`` is not compilable + * If `to_replace` is ``None`` and `regex` is not compilable into a regular expression or is a list, dict, ndarray, or Series. * When replacing multiple ``bool`` or ``datetime64`` objects and - the arguments to ``to_replace`` does not match the type of the + the arguments to `to_replace` does not match the type of the value being replaced ValueError - * If a ``list`` or an ``ndarray`` is passed to ``to_replace`` and + * If a ``list`` or an ``ndarray`` is passed to `to_replace` and `value` but they are not the same length. Notes @@ -4986,10 +4996,15 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): numbers *are* strings, then you can do this. * This method has *a lot* of options. You are encouraged to experiment and play with this method to gain intuition about how it works. + * When dict is used as the `to_replace` value, it is like + key(s) in the dict are the to_replace part and + value(s) in the dict are the value parameter. Examples -------- + **Scalar `to_replace` and `value`** + >>> s = pd.Series([0, 1, 2, 3, 4]) >>> s.replace(0, 5) 0 5 @@ -4998,6 +5013,7 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 3 3 4 4 dtype: int64 + >>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4], ... 'B': [5, 6, 7, 8, 9], ... 'C': ['a', 'b', 'c', 'd', 'e']}) @@ -5009,6 +5025,8 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 3 3 8 d 4 4 9 e + **List-like `to_replace`** + >>> df.replace([0, 1, 2, 3], 4) A B C 0 4 5 a @@ -5016,6 +5034,7 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 2 4 7 c 3 4 8 d 4 4 9 e + >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1]) A B C 0 4 5 a @@ -5023,6 +5042,7 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 2 2 7 c 3 1 8 d 4 4 9 e + >>> s.replace([1, 2], method='bfill') 0 0 1 3 @@ -5031,6 +5051,8 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 4 4 dtype: int64 + **dict-like `to_replace`** + >>> df.replace({0: 10, 1: 100}) A B C 0 10 5 a @@ -5038,6 +5060,7 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 2 2 7 c 3 3 8 d 4 4 9 e + >>> df.replace({'A': 0, 'B': 5}, 100) A B C 0 100 100 a @@ -5045,6 +5068,7 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 2 2 7 c 3 3 8 d 4 4 9 e + >>> df.replace({'A': {0: 100, 4: 400}}) A B C 0 100 5 a @@ -5053,6 +5077,8 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 3 3 8 d 4 400 9 e + **Regular expression `to_replace`** + >>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'], ... 'B': ['abc', 'bar', 'xyz']}) >>> df.replace(to_replace=r'^ba.$', value='new', regex=True) @@ -5060,21 +5086,25 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 0 new abc 1 foo new 2 bait xyz + >>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True) A B 0 new abc 1 foo bar 2 bait xyz + >>> df.replace(regex=r'^ba.$', value='new') A B 0 new abc 1 foo new 2 bait xyz + >>> df.replace(regex={r'^ba.$':'new', 'foo':'xyz'}) A B 0 new abc 1 xyz new 2 bait xyz + >>> df.replace(regex=[r'^ba.$', 'foo'], value='new') A B 0 new abc @@ -5082,16 +5112,52 @@ def bfill(self, axis=None, inplace=False, limit=None, downcast=None): 2 bait xyz Note that when replacing multiple ``bool`` or ``datetime64`` objects, - the data types in the ``to_replace`` parameter must match the data + the data types in the `to_replace` parameter must match the data type of the value being replaced: >>> df = pd.DataFrame({'A': [True, False, True], ... 'B': [False, True, False]}) >>> df.replace({'a string': 'new value', True: False}) # raises + Traceback (most recent call last): + ... TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' This raises a ``TypeError`` because one of the ``dict`` keys is not of the correct type for replacement. + + Compare the behavior of ``s.replace({'a': None})`` and + ``s.replace('a', None)`` to understand the pecularities + of the `to_replace` parameter: + + >>> s = pd.Series([10, 'a', 'a', 'b', 'a']) + + When one uses a dict as the `to_replace` value, it is like the + value(s) in the dict are equal to the `value` parameter. + ``s.replace({'a': None})`` is equivalent to + ``s.replace(to_replace={'a': None}, value=None, method=None)``: + + >>> s.replace({'a': None}) + 0 10 + 1 None + 2 None + 3 b + 4 None + dtype: object + + When ``value=None`` and `to_replace` is a scalar, list or + tuple, `replace` uses the method parameter (default 'pad') to do the + replacement. So this is why the 'a' values are being replaced by 10 + in rows 1 and 2 and 'b' in row 4 in this case. + The command ``s.replace('a', None)`` is actually equivalent to + ``s.replace(to_replace='a', value=None, method='pad')``: + + >>> s.replace('a', None) + 0 10 + 1 10 + 2 10 + 3 b + 4 b + dtype: object """) @Appender(_shared_docs['replace'] % _shared_doc_kwargs)
- [x] PR title is "DOC: update the <your-function-or-method> docstring" - [ ] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ ] It has been proofread on language by another sprint participant **Note:** Just did a minor improvement, not a full change! Still a few verification errors: - Errors in parameters section - Parameter "to_replace" description should start with capital letter - Parameter "axis" description should finish with "." - Examples do not pass tests ``` ################################################################################ ##################### Docstring (pandas.DataFrame.replace) ##################### ################################################################################ Replace values given in 'to_replace' with 'value'. Values of the DataFrame or a Series are being replaced with other values. One or several values can be replaced with one or several values. Parameters ---------- to_replace : str, regex, list, dict, Series, numeric, or None * numeric, str or regex: - numeric: numeric values equal to ``to_replace`` will be replaced with ``value`` - str: string exactly matching ``to_replace`` will be replaced with ``value`` - regex: regexs matching ``to_replace`` will be replaced with ``value`` * list of str, regex, or numeric: - First, if ``to_replace`` and ``value`` are both lists, they **must** be the same length. - Second, if ``regex=True`` then all of the strings in **both** lists will be interpreted as regexs otherwise they will match directly. This doesn't matter much for ``value`` since there are only a few possible substitution regexes you can use. - str, regex and numeric rules apply as above. * dict: - Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value 'a' with 'b' and 'y' with 'z'. To use a dict in this way the ``value`` parameter should be ``None``. - For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column 'a' and the value 'z' in column 'b' and replaces these values with whatever is specified in ``value``. The ``value`` parameter should not be ``None`` in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in. - For a DataFrame nested dictionaries, e.g., {'a': {'b': np.nan}}, are read as follows: look in column 'a' for the value 'b' and replace it with NaN. The ``value`` parameter should be ``None`` to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) **cannot** be regular expressions. * None: - This means that the ``regex`` argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If ``value`` is also ``None`` then this **must** be a nested dictionary or ``Series``. See the examples section for examples of each of these. value : scalar, dict, list, str, regex, default None Value to replace any values matching ``to_replace`` with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. inplace : boolean, default False If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True. limit : int, default None Maximum size gap to forward or backward fill. regex : bool or same types as ``to_replace``, default False Whether to interpret ``to_replace`` and/or ``value`` as regular expressions. If this is ``True`` then ``to_replace`` *must* be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case ``to_replace`` must be ``None``. method : string, optional, {'pad', 'ffill', 'bfill'}, default is 'pad' The method to use when for replacement, when ``to_replace`` is a scalar, list or tuple and ``value`` is None. axis : None Deprecated. .. versionchanged:: 0.23.0 Added to DataFrame See Also -------- DataFrame.fillna : Fill NA/NaN values DataFrame.where : Replace values based on boolean condition Returns ------- DataFrame Some values have been substituted for new values. Raises ------ AssertionError * If ``regex`` is not a ``bool`` and ``to_replace`` is not ``None``. TypeError * If ``to_replace`` is a ``dict`` and ``value`` is not a ``list``, ``dict``, ``ndarray``, or ``Series`` * If ``to_replace`` is ``None`` and ``regex`` is not compilable into a regular expression or is a list, dict, ndarray, or Series. * When replacing multiple ``bool`` or ``datetime64`` objects and the arguments to ``to_replace`` does not match the type of the value being replaced ValueError * If a ``list`` or an ``ndarray`` is passed to ``to_replace`` and `value` but they are not the same length. Notes ----- * Regex substitution is performed under the hood with ``re.sub``. The rules for substitution for ``re.sub`` are the same. * Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched. However, if those floating point numbers *are* strings, then you can do this. * This method has *a lot* of options. You are encouraged to experiment and play with this method to gain intuition about how it works. Examples -------- >>> s = pd.Series([0, 1, 2, 3, 4]) >>> s.replace(0, 5) 0 5 1 1 2 2 3 3 4 4 dtype: int64 >>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4], ... 'B': [5, 6, 7, 8, 9], ... 'C': ['a', 'b', 'c', 'd', 'e']}) >>> df.replace(0, 5) A B C 0 5 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace([0, 1, 2, 3], 4) A B C 0 4 5 a 1 4 6 b 2 4 7 c 3 4 8 d 4 4 9 e >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1]) A B C 0 4 5 a 1 3 6 b 2 2 7 c 3 1 8 d 4 4 9 e >>> s.replace([1, 2], method='bfill') 0 0 1 3 2 3 3 3 4 4 dtype: int64 >>> df.replace({0: 10, 1: 100}) A B C 0 10 5 a 1 100 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace({'A': 0, 'B': 5}, 100) A B C 0 100 100 a 1 1 6 b 2 2 7 c 3 3 8 d 4 4 9 e >>> df.replace({'A': {0: 100, 4: 400}}) A B C 0 100 5 a 1 1 6 b 2 2 7 c 3 3 8 d 4 400 9 e >>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'], ... 'B': ['abc', 'bar', 'xyz']}) >>> df.replace(to_replace=r'^ba.$', value='new', regex=True) A B 0 new abc 1 foo new 2 bait xyz >>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True) A B 0 new abc 1 foo bar 2 bait xyz >>> df.replace(regex=r'^ba.$', value='new') A B 0 new abc 1 foo new 2 bait xyz >>> df.replace(regex={r'^ba.$':'new', 'foo':'xyz'}) A B 0 new abc 1 xyz new 2 bait xyz >>> df.replace(regex=[r'^ba.$', 'foo'], value='new') A B 0 new abc 1 new new 2 bait xyz Note that when replacing multiple ``bool`` or ``datetime64`` objects, the data types in the ``to_replace`` parameter must match the data type of the value being replaced: >>> df = pd.DataFrame({'A': [True, False, True], ... 'B': [False, True, False]}) >>> df.replace({'a string': 'new value', True: False}) # raises TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' This raises a ``TypeError`` because one of the ``dict`` keys is not of the correct type for replacement. Compare the behavior of ``s.replace('a', None)`` and ``s.replace({'a': None})`` to understand the pecularities of the ``to_replace`` parameter. ``s.replace('a', None)`` is actually equivalent to ``s.replace(to_replace='a', value=None, method='pad')``, because when ``value=None`` and ``to_replace`` is a scalar, list or tuple, ``replace`` uses the method parameter to do the replacement. So this is why the 'a' values are being replaced by 30 in rows 3 and 4 and 'b' in row 6 in this case. However, this behaviour does not occur when you use a dict as the ``to_replace`` value. In this case, it is like the value(s) in the dict are equal to the value parameter. >>> s = pd.Series([10, 20, 30, 'a', 'a', 'b', 'a']) >>> print(s) 0 10 1 20 2 30 3 a 4 a 5 b 6 a dtype: object >>> print(s.replace('a', None)) 0 10 1 20 2 30 3 30 4 30 5 b 6 b dtype: object >>> print(s.replace({'a': None})) 0 10 1 20 2 30 3 None 4 None 5 b 6 None dtype: object ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameter "to_replace" description should start with capital letter Parameter "axis" description should finish with "." Examples do not pass tests ################################################################################ ################################### Doctests ################################### ################################################################################ ********************************************************************** Line 229, in pandas.DataFrame.replace Failed example: df.replace({'a string': 'new value', True: False}) # raises Exception raised: Traceback (most recent call last): File "C:\Users\thisi\AppData\Local\conda\conda\envs\pandas_dev\lib\doctest.py", line 1330, in __run compileflags, 1), test.globs) File "<doctest pandas.DataFrame.replace[17]>", line 1, in <module> df.replace({'a string': 'new value', True: False}) # raises File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\frame.py", line 3136, in replace method=method, axis=axis) File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\generic.py", line 5208, in replace limit=limit, regex=regex) File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\frame.py", line 3136, in replace method=method, axis=axis) File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\generic.py", line 5257, in replace regex=regex) File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\internals.py", line 3696, in replace_list masks = [comp(s) for i, s in enumerate(src_list)] File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\internals.py", line 3696, in <listcomp> masks = [comp(s) for i, s in enumerate(src_list)] File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\internals.py", line 3694, in comp return _maybe_compare(values, getattr(s, 'asm8', s), operator.eq) File "C:\Users\thisi\Documents\GitHub\pandas\pandas\core\internals.py", line 5122, in _maybe_compare b=type_names[1])) TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20271
2018-03-11T03:15:21Z
2018-04-22T14:22:17Z
2018-04-22T14:22:17Z
2018-04-22T14:22:30Z
CI: Temporarily build pandas with N_JOBS=1 to avoid flakiness
diff --git a/.github/actions/build_pandas/action.yml b/.github/actions/build_pandas/action.yml index 5e5a3bdf0f024..39d5998b4ee74 100644 --- a/.github/actions/build_pandas/action.yml +++ b/.github/actions/build_pandas/action.yml @@ -17,4 +17,6 @@ runs: shell: bash -el {0} env: # Cannot use parallel compilation on Windows, see https://github.com/pandas-dev/pandas/issues/30873 - N_JOBS: ${{ runner.os == 'Windows' && 1 || 2 }} + # GH 47305: Parallel build causes flaky ImportError: /home/runner/work/pandas/pandas/pandas/_libs/tslibs/timestamps.cpython-38-x86_64-linux-gnu.so: undefined symbol: pandas_datetime_to_datetimestruct + N_JOBS: 1 + #N_JOBS: ${{ runner.os == 'Windows' && 1 || 2 }}
xref: #47305
https://api.github.com/repos/pandas-dev/pandas/pulls/47341
2022-06-13T23:12:16Z
2022-06-15T22:12:03Z
2022-06-15T22:12:03Z
2022-06-15T22:12:06Z
ENH: Timestamp pickle support non-nano tzaware
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 1d21f602fac05..349cb0d50c46e 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -157,14 +157,7 @@ cdef inline _Timestamp create_timestamp_from_ts( def _unpickle_timestamp(value, freq, tz, reso=NPY_FR_ns): # GH#41949 dont warn on unpickle if we have a freq - if reso == NPY_FR_ns: - ts = Timestamp(value, tz=tz) - else: - if tz is not None: - raise NotImplementedError - abbrev = npy_unit_to_abbrev(reso) - dt64 = np.datetime64(value, abbrev) - ts = Timestamp._from_dt64(dt64) + ts = Timestamp._from_value_and_reso(value, reso, tz) ts._set_freq(freq) return ts diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 79c8a300b34e3..2f9b030e5d627 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -22,6 +22,7 @@ from pandas._libs.tslibs.timezones import ( dateutil_gettz as gettz, get_timezone, + maybe_get_tz, tz_compare, ) from pandas.errors import OutOfBoundsDatetime @@ -836,7 +837,10 @@ def test_cmp_cross_reso_reversed_dt64(self): assert other.asm8 < ts - def test_pickle(self, ts): + def test_pickle(self, ts, tz_aware_fixture): + tz = tz_aware_fixture + tz = maybe_get_tz(tz) + ts = Timestamp._from_value_and_reso(ts.value, ts._reso, tz) rt = tm.round_trip_pickle(ts) assert rt._reso == ts._reso assert rt == ts
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47340
2022-06-13T22:37:28Z
2022-06-14T16:54:15Z
2022-06-14T16:54:15Z
2022-06-14T17:00:03Z
ENH: Move UndefinedVariableError to error/__init__.py per GH27656
diff --git a/doc/source/reference/testing.rst b/doc/source/reference/testing.rst index 68e0555afc916..9d9fb91821ab1 100644 --- a/doc/source/reference/testing.rst +++ b/doc/source/reference/testing.rst @@ -45,6 +45,7 @@ Exceptions and warnings errors.SettingWithCopyError errors.SettingWithCopyWarning errors.SpecificationError + errors.UndefinedVariableError errors.UnsortedIndexError errors.UnsupportedFunctionCall diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 55bfb044fb31d..f3c5d7e8d64c4 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -152,7 +152,7 @@ Other enhancements - A :class:`errors.PerformanceWarning` is now thrown when using ``string[pyarrow]`` dtype with methods that don't dispatch to ``pyarrow.compute`` methods (:issue:`42613`) - Added ``numeric_only`` argument to :meth:`Resampler.sum`, :meth:`Resampler.prod`, :meth:`Resampler.min`, :meth:`Resampler.max`, :meth:`Resampler.first`, and :meth:`Resampler.last` (:issue:`46442`) - ``times`` argument in :class:`.ExponentialMovingWindow` now accepts ``np.timedelta64`` (:issue:`47003`) -- :class:`DataError`, :class:`SpecificationError`, :class:`SettingWithCopyError`, :class:`SettingWithCopyWarning`, and :class:`NumExprClobberingError` are now exposed in ``pandas.errors`` (:issue:`27656`) +- :class:`DataError`, :class:`SpecificationError`, :class:`SettingWithCopyError`, :class:`SettingWithCopyWarning`, :class:`NumExprClobberingError`, :class:`UndefinedVariableError` are now exposed in ``pandas.errors`` (:issue:`27656`) - Added ``check_like`` argument to :func:`testing.assert_series_equal` (:issue:`47247`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index ae55e61ab01a6..4b037ab564a87 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -18,6 +18,7 @@ import numpy as np from pandas.compat import PY39 +from pandas.errors import UndefinedVariableError import pandas.core.common as com from pandas.core.computation.ops import ( @@ -35,7 +36,6 @@ Op, Term, UnaryOp, - UndefinedVariableError, is_term, ) from pandas.core.computation.parsing import ( diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 9c54065de0353..3a556b57ea5a5 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -65,20 +65,6 @@ LOCAL_TAG = "__pd_eval_local_" -class UndefinedVariableError(NameError): - """ - NameError subclass for local variables. - """ - - def __init__(self, name: str, is_local: bool | None = None) -> None: - base_msg = f"{repr(name)} is not defined" - if is_local: - msg = f"local variable {base_msg}" - else: - msg = f"name {base_msg}" - super().__init__(msg) - - class Term: def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 91a8505fad8c5..29af322ba0b42 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -13,6 +13,7 @@ ) from pandas._typing import npt from pandas.compat.chainmap import DeepChainMap +from pandas.errors import UndefinedVariableError from pandas.core.dtypes.common import is_list_like @@ -24,10 +25,7 @@ ) from pandas.core.computation.common import ensure_decoded from pandas.core.computation.expr import BaseExprVisitor -from pandas.core.computation.ops import ( - UndefinedVariableError, - is_term, -) +from pandas.core.computation.ops import is_term from pandas.core.construction import extract_array from pandas.core.indexes.base import Index diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 52169b034603d..5188b44618b4d 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -15,6 +15,7 @@ from pandas._libs.tslibs import Timestamp from pandas.compat.chainmap import DeepChainMap +from pandas.errors import UndefinedVariableError def ensure_scope( @@ -207,9 +208,6 @@ def resolve(self, key: str, is_local: bool): # e.g., df[df > 0] return self.temps[key] except KeyError as err: - # runtime import because ops imports from scope - from pandas.core.computation.ops import UndefinedVariableError - raise UndefinedVariableError(key, is_local) from err def swapkey(self, old_key: str, new_key: str, new_value=None) -> None: diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 1918065d855a5..e30e5019c3568 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -1,6 +1,7 @@ """ Expose public exceptions & warnings """ +from __future__ import annotations from pandas._config.config import OptionError # noqa:F401 @@ -326,3 +327,29 @@ class NumExprClobberingError(NameError): >>> pd.eval("sin + a", engine='numexpr') # doctest: +SKIP ... # NumExprClobberingError: Variables in expression "(sin) + (a)" overlap... """ + + +class UndefinedVariableError(NameError): + """ + Exception is raised when trying to use an undefined variable name in a method + like query or eval. It will also specific whether the undefined variable is + local or not. + + Examples + -------- + >>> df = pd.DataFrame({'A': [1, 1, 1]}) + >>> df.query("A > x") # doctest: +SKIP + ... # UndefinedVariableError: name 'x' is not defined + >>> df.query("A > @y") # doctest: +SKIP + ... # UndefinedVariableError: local variable 'y' is not defined + >>> pd.eval('x + 1') # doctest: +SKIP + ... # UndefinedVariableError: name 'x' is not defined + """ + + def __init__(self, name: str, is_local: bool | None = None) -> None: + base_msg = f"{repr(name)} is not defined" + if is_local: + msg = f"local variable {base_msg}" + else: + msg = f"name {base_msg}" + super().__init__(msg) diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index e70d493d23515..b0ad2f69a75b9 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -12,6 +12,7 @@ from pandas.errors import ( NumExprClobberingError, PerformanceWarning, + UndefinedVariableError, ) import pandas.util._test_decorators as td @@ -44,7 +45,6 @@ from pandas.core.computation.ops import ( ARITH_OPS_SYMS, SPECIAL_CASE_ARITH_OPS_SYMS, - UndefinedVariableError, _binary_math_ops, _binary_ops_dict, _unary_math_ops, diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index fe3b04e8e27e6..3d703b54ca301 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -495,7 +495,7 @@ def test_query_syntax_error(self): df.query("i - +", engine=engine, parser=parser) def test_query_scope(self): - from pandas.core.computation.ops import UndefinedVariableError + from pandas.errors import UndefinedVariableError engine, parser = self.engine, self.parser skip_if_no_pandas_parser(parser) @@ -522,7 +522,7 @@ def test_query_scope(self): df.query("@a > b > c", engine=engine, parser=parser) def test_query_doesnt_pickup_local(self): - from pandas.core.computation.ops import UndefinedVariableError + from pandas.errors import UndefinedVariableError engine, parser = self.engine, self.parser n = m = 10 @@ -618,7 +618,7 @@ def test_nested_scope(self): tm.assert_frame_equal(result, expected) def test_nested_raises_on_local_self_reference(self): - from pandas.core.computation.ops import UndefinedVariableError + from pandas.errors import UndefinedVariableError df = DataFrame(np.random.randn(5, 3)) @@ -678,7 +678,7 @@ def test_at_inside_string(self): tm.assert_frame_equal(result, expected) def test_query_undefined_local(self): - from pandas.core.computation.ops import UndefinedVariableError + from pandas.errors import UndefinedVariableError engine, parser = self.engine, self.parser skip_if_no_pandas_parser(parser) @@ -838,7 +838,7 @@ def test_date_index_query_with_NaT_duplicates(self): df.query("index < 20130101 < dates3", engine=engine, parser=parser) def test_nested_scope(self): - from pandas.core.computation.ops import UndefinedVariableError + from pandas.errors import UndefinedVariableError engine = self.engine parser = self.parser diff --git a/pandas/tests/test_errors.py b/pandas/tests/test_errors.py index 827c5767c514f..d4e3fff5c2f86 100644 --- a/pandas/tests/test_errors.py +++ b/pandas/tests/test_errors.py @@ -1,6 +1,9 @@ import pytest -from pandas.errors import AbstractMethodError +from pandas.errors import ( + AbstractMethodError, + UndefinedVariableError, +) import pandas as pd @@ -48,6 +51,24 @@ def test_catch_oob(): pd.Timestamp("15000101") +@pytest.mark.parametrize( + "is_local", + [ + True, + False, + ], +) +def test_catch_undefined_variable_error(is_local): + variable_name = "x" + if is_local: + msg = f"local variable '{variable_name}' is not defined" + else: + msg = f"name '{variable_name}' is not defined" + + with pytest.raises(UndefinedVariableError, match=msg): + raise UndefinedVariableError(variable_name, is_local) + + class Foo: @classmethod def classmethod(cls): diff --git a/scripts/pandas_errors_documented.py b/scripts/pandas_errors_documented.py index 3e5bf34db4fe8..18db5fa10a8f9 100644 --- a/scripts/pandas_errors_documented.py +++ b/scripts/pandas_errors_documented.py @@ -22,7 +22,7 @@ def get_defined_errors(content: str) -> set[str]: for node in ast.walk(ast.parse(content)): if isinstance(node, ast.ClassDef): errors.add(node.name) - elif isinstance(node, ast.ImportFrom): + elif isinstance(node, ast.ImportFrom) and node.module != "__future__": for alias in node.names: errors.add(alias.name) return errors @@ -41,7 +41,7 @@ def main(argv: Sequence[str] | None = None) -> None: missing = file_errors.difference(doc_errors) if missing: sys.stdout.write( - f"The follow exceptions and/or warnings are not documented " + f"The following exceptions and/or warnings are not documented " f"in {API_PATH}: {missing}" ) sys.exit(1)
- [x] xref #27656. this GitHub issue is being done in multiple parts - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v1.5.0.rst` file if fixing a bug or adding a new feature. I made a tweak to scripts/pandas_errors_documented.py because it was flagging the `annotations` import not being in the testing.rst. I excluded __future__ module from the documentation check because the script's intent seems to be ensuring the custom pandas errors are documented. I also fixed a typo.
https://api.github.com/repos/pandas-dev/pandas/pulls/47338
2022-06-13T20:48:27Z
2022-06-13T23:32:47Z
2022-06-13T23:32:47Z
2022-06-13T23:32:56Z
BLD: add optional dependencies as extras_require in setup.py
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 54da61a5c074a..5f258973b3db9 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -242,8 +242,11 @@ Package Minimum support .. _install.recommended_dependencies: -Recommended dependencies -~~~~~~~~~~~~~~~~~~~~~~~~ +Performance dependencies (recommended) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +pandas recommends the following optional dependencies for performance gains. These dependencies can be specifically +installed with ``pandas[performance]`` (i.e. add as optional_extra to the pandas requirement) * `numexpr <https://github.com/pydata/numexpr>`__: for accelerating certain numerical operations. ``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups. @@ -253,6 +256,10 @@ Recommended dependencies evaluations. ``bottleneck`` uses specialized cython routines to achieve large speedups. If installed, must be Version 1.3.2 or higher. +* `numba <https://github.com/numba/numba>`__: alternative execution engine for operations that accept `engine="numba" + argument (eg. apply). ``numba`` is a JIT compiler that translates Python functions to optimized machine code using + the LLVM compiler library. If installed, must be Version 0.53.1 or higher. + .. note:: You are highly encouraged to install these libraries, as they provide speed improvements, especially @@ -270,69 +277,83 @@ For example, :func:`pandas.read_hdf` requires the ``pytables`` package, while optional dependency is not installed, pandas will raise an ``ImportError`` when the method requiring that dependency is called. +Optional pandas dependencies can be managed as optional extras (e.g.,``pandas[performance, aws]>=1.5.0``) +in a requirements.txt, setup, or pyproject.toml file. +Available optional dependencies are ``[all, performance, computation, aws, +gcp, excel, parquet, feather, hdf5, spss, postgresql, mysql, sql-other, html, xml, +plot, output_formatting, compression, test]`` + Timezones ^^^^^^^^^ -========================= ========================= ============================================================= -Dependency Minimum Version Notes -========================= ========================= ============================================================= -tzdata 2022.1(pypi)/ Allows the use of ``zoneinfo`` timezones with pandas. - 2022a(for system tzdata) **Note**: You only need to install the pypi package if your - system does not already provide the IANA tz database. - However, the minimum tzdata version still applies, even if it - is not enforced through an error. +Can be managed as optional_extra with ``pandas[timezone]``. + +========================= ========================= =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ========================= =============== ============================================================= +tzdata 2022.1(pypi)/ timezone Allows the use of ``zoneinfo`` timezones with pandas. + 2022a(for system tzdata) **Note**: You only need to install the pypi package if your + system does not already provide the IANA tz database. + However, the minimum tzdata version still applies, even if it + is not enforced through an error. - If you would like to keep your system tzdata version updated, - it is recommended to use the ``tzdata`` package from - conda-forge. -========================= ========================= ============================================================= + If you would like to keep your system tzdata version updated, + it is recommended to use the ``tzdata`` package from + conda-forge. +========================= ========================= =============== ============================================================= Visualization ^^^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -matplotlib 3.3.2 Plotting library -Jinja2 3.0.0 Conditional formatting with DataFrame.style -tabulate 0.8.9 Printing in Markdown-friendly format (see `tabulate`_) -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[plot, output_formatting]``, depending on the required functionality. + +========================= ================== ================== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== ================== ============================================================= +matplotlib 3.3.2 plot Plotting library +Jinja2 3.0.0 output_formatting Conditional formatting with DataFrame.style +tabulate 0.8.9 output_formatting Printing in Markdown-friendly format (see `tabulate`_) +========================= ================== ================== ============================================================= Computation ^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -SciPy 1.7.1 Miscellaneous statistical functions -numba 0.53.1 Alternative execution engine for rolling operations - (see :ref:`Enhancing Performance <enhancingperf.numba>`) -xarray 0.19.0 pandas-like API for N-dimensional data -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[computation]``. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +SciPy 1.7.1 computation Miscellaneous statistical functions +xarray 0.19.0 computation pandas-like API for N-dimensional data +========================= ================== =============== ============================================================= Excel files ^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -xlrd 2.0.1 Reading Excel -xlwt 1.3.0 Writing Excel -xlsxwriter 1.4.3 Writing Excel -openpyxl 3.0.7 Reading / writing for xlsx files -pyxlsb 1.0.8 Reading for xlsb files -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[excel]``. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +xlrd 2.0.1 excel Reading Excel +xlwt 1.3.0 excel Writing Excel +xlsxwriter 1.4.3 excel Writing Excel +openpyxl 3.0.7 excel Reading / writing for xlsx files +pyxlsb 1.0.8 excel Reading for xlsb files +========================= ================== =============== ============================================================= HTML ^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -BeautifulSoup4 4.9.3 HTML parser for read_html -html5lib 1.1 HTML parser for read_html -lxml 4.6.3 HTML parser for read_html -========================= ================== ============================================================= +These dependencies can be specifically installed with ``pandas[html]``. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +BeautifulSoup4 4.9.3 html HTML parser for read_html +html5lib 1.1 html HTML parser for read_html +lxml 4.6.3 html HTML parser for read_html +========================= ================== =============== ============================================================= One of the following combinations of libraries is needed to use the top-level :func:`~pandas.read_html` function: @@ -361,36 +382,47 @@ top-level :func:`~pandas.read_html` function: XML ^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -lxml 4.5.0 XML parser for read_xml and tree builder for to_xml -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[xml]``. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +lxml 4.6.3 xml XML parser for read_xml and tree builder for to_xml +========================= ================== =============== ============================================================= SQL databases ^^^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -SQLAlchemy 1.4.16 SQL support for databases other than sqlite -psycopg2 2.8.6 PostgreSQL engine for sqlalchemy -pymysql 1.0.2 MySQL engine for sqlalchemy -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[postgresql, mysql, sql-other]``, +depending on required sql compatibility. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +SQLAlchemy 1.4.16 postgresql, SQL support for databases other than sqlite + mysql, + sql-other +psycopg2 2.8.6 postgresql PostgreSQL engine for sqlalchemy +pymysql 1.0.2 mysql MySQL engine for sqlalchemy +========================= ================== =============== ============================================================= Other data sources ^^^^^^^^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -PyTables 3.6.1 HDF5-based reading / writing -blosc 1.21.0 Compression for HDF5 -zlib Compression for HDF5 -fastparquet 0.4.0 Parquet reading / writing -pyarrow 6.0.0 Parquet, ORC, and feather reading / writing -pyreadstat 1.1.2 SPSS files (.sav) reading -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[hdf5, parquet, feather, spss, excel]``, +depending on required compatibility. + +========================= ================== ================ ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== ================ ============================================================= +PyTables 3.6.1 hdf5 HDF5-based reading / writing +blosc 1.21.0 hdf5 Compression for HDF5 +zlib hdf5 Compression for HDF5 +fastparquet 0.4.0 - Parquet reading / writing (pyarrow is default) +pyarrow 6.0.0 parquet, feather Parquet, ORC, and feather reading / writing +pyreadstat 1.1.2 spss SPSS files (.sav) reading +odfpy 1.4.1 excel Open document format (.odf, .ods, .odt) reading / writing +========================= ================== ================ ============================================================= .. _install.warn_orc: @@ -410,35 +442,46 @@ pyreadstat 1.1.2 SPSS files (.sav) reading Access data in the cloud ^^^^^^^^^^^^^^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -fsspec 2021.7.0 Handling files aside from simple local and HTTP -gcsfs 2021.7.0 Google Cloud Storage access -pandas-gbq 0.15.0 Google Big Query access -s3fs 2021.08.0 Amazon S3 access -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[fss, aws, gcp]``, depending on required compatibility. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +fsspec 2021.7.0 fss, gcp, aws Handling files aside from simple local and HTTP (required + dependency of s3fs, gcsfs). +gcsfs 2021.7.0 gcp Google Cloud Storage access +pandas-gbq 0.15.0 gcp Google Big Query access +s3fs 2021.08.0 aws Amazon S3 access +========================= ================== =============== ============================================================= Clipboard ^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -PyQt4/PyQt5 Clipboard I/O -qtpy Clipboard I/O -xclip Clipboard I/O on linux -xsel Clipboard I/O on linux -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[clipboard]``. However, depending on operating system, system-level +packages may need to installed. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +PyQt4/PyQt5 5.15.1 Clipboard I/O +qtpy 2.2.0 Clipboard I/O +========================= ================== =============== ============================================================= + +.. note:: + + For clipboard to operate on Linux one of the CLI tools ``xclip`` or ``xsel`` must be installed on your system. Compression ^^^^^^^^^^^ -========================= ================== ============================================================= -Dependency Minimum Version Notes -========================= ================== ============================================================= -brotli 0.7.0 Brotli compression -python-snappy 0.6.0 Snappy compression -Zstandard 0.15.2 Zstandard compression -========================= ================== ============================================================= +Can be managed as optional_extra with ``pandas[compression]``. +If only one specific compression lib is required, please request it as an independent requirement. + +========================= ================== =============== ============================================================= +Dependency Minimum Version optional_extra Notes +========================= ================== =============== ============================================================= +brotli 0.7.0 compression Brotli compression +python-snappy 0.6.0 compression Snappy compression +Zstandard 0.15.2 compression Zstandard compression +========================= ================== =============== ============================================================= diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 81fdb4b7338f1..bbb5cece5aa28 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -14,10 +14,19 @@ including other versions of pandas. Enhancements ~~~~~~~~~~~~ -.. _whatsnew_200.enhancements.enhancement1: +.. _whatsnew_200.enhancements.optional_dependency_management: -enhancement1 -^^^^^^^^^^^^ +Optional dependencies version management +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Optional pandas dependencies can be managed as extras in a requirements/setup file, for example: + +.. code-block:: python + + pandas[performance, aws]>=2.0.0 + +Available optional dependencies (listed in order of appearance at `install guide <https://pandas.pydata.org/docs/getting_started/install>`_) are +``[all, performance, computation, timezone, fss, aws, gcp, excel, parquet, feather, hdf5, spss, postgresql, mysql, +sql-other, html, xml, plot, output_formatting, clipboard, compression, test]`` (:issue:`39164`). .. _whatsnew_200.enhancements.enhancement2: @@ -36,6 +45,7 @@ Other enhancements - Added ``index`` parameter to :meth:`DataFrame.to_dict` (:issue:`46398`) - Added metadata propagation for binary operators on :class:`DataFrame` (:issue:`28283`) - :class:`.CategoricalConversionWarning`, :class:`.InvalidComparison`, :class:`.InvalidVersion`, :class:`.LossySetitemError`, and :class:`.NoBufferPresent` are now exposed in ``pandas.errors`` (:issue:`27656`) +- Fix ``test`` optional_extra by adding missing test package ``pytest-asyncio`` (:issue:`48361`) - :func:`DataFrame.astype` exception message thrown improved to include column name when type conversion is not possible. (:issue:`47571`) .. --------------------------------------------------------------------------- diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index b644339a79de9..34e3234390ba5 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -9,7 +9,7 @@ from pandas.util.version import Version -# Update install.rst when updating versions! +# Update install.rst & setup.cfg when updating versions! VERSIONS = { "bs4": "4.9.3", diff --git a/setup.cfg b/setup.cfg index 9c88731f74ac8..eede4a66d598d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -53,6 +53,113 @@ test = hypothesis>=5.5.3 pytest>=6.0 pytest-xdist>=1.31 + pytest-asyncio>=0.17.0 +# optional extras for recommended dependencies +# see: doc/source/getting_started/install.rst +performance = + bottleneck>=1.3.2 + numba>=0.53.0 + numexpr>=2.7.1 +timezone = + tzdata>=2022.1 +computation = + scipy>=1.7.1 + xarray>=0.19.0 +fss = + fsspec>=2021.7.0 +aws = + boto3>=1.22.7 + s3fs>=0.4.0 +gcp = + gcsfs>=2021.05.0 + pandas-gbq>=0.15.0 +excel = + odfpy>=1.4.1 + openpyxl>=3.0.7 + pyxlsb>=1.0.8 + xlrd>=2.0.1 + xlwt>=1.3.0 + xlsxwriter>=1.4.3 +parquet = + pyarrow>=6.0.0 +feather = + pyarrow>=6.0.0 +hdf5 = + blosc>=1.20.1 + tables>=3.6.1 +spss = + pyreadstat>=1.1.2 +postgresql = + SQLAlchemy>=1.4.16 + psycopg2>=2.8.6 +mysql = + SQLAlchemy>=1.4.16 + pymysql>=1.0.2 +sql-other = + SQLAlchemy>=1.4.16 +html = + beautifulsoup4>=4.9.3 + html5lib>=1.1 + lxml>=4.6.3 +xml = + lxml>=4.6.3 +plot = + matplotlib>=3.3.2 +output_formatting = + jinja2>=3.0.0 + tabulate>=0.8.9 +clipboard= + PyQt5>=5.15.1 + qtpy>=2.2.0 +compression = + brotlipy>=0.7.0 + python-snappy>=0.6.0 + zstandard>=0.15.2 +# `all` supersets all the above options. +# Also adds the following redundant, superseded packages that are listed as supported: +# fastparquet (by pyarrow https://github.com/pandas-dev/pandas/issues/39164) +# `all ` should be kept as the complete set of pandas optional dependencies for general use. +all = + beautifulsoup4>=4.9.3 + blosc>=1.21.0 + bottleneck>=1.3.1 + boto3>=1.22.7 + brotlipy>=0.7.0 + fastparquet>=0.4.0 + fsspec>=2021.7.0 + gcsfs>=2021.05.0 + html5lib>=1.1 + hypothesis>=5.5.3 + jinja2>=3.0.0 + lxml>=4.6.3 + matplotlib>=3.3.2 + numba>=0.53.0 + numexpr>=2.7.1 + odfpy>=1.4.1 + openpyxl>=3.0.7 + pandas-gbq>=0.15.0 + psycopg2>=2.8.6 + pyarrow>=6.0.0 + pymysql>=1.0.2 + PyQt5>=5.15.1 + pyreadstat>=1.1.2 + pytest>=6.0 + pytest-xdist>=1.31 + pytest-asyncio>=0.17.0 + python-snappy>=0.6.0 + pyxlsb>=1.0.8 + qtpy>=2.2.0 + scipy>=1.7.1 + s3fs>=0.4.0 + SQLAlchemy>=1.4.16 + tables>=3.6.1 + tabulate>=0.8.9 + tzdata>=2022.1 + xarray>=0.19.0 + xlrd>=2.0.1 + xlsxwriter>=1.4.3 + xlwt>=1.3.0 + zstandard>=0.15.2 [build_ext] inplace = True
EDIT: This was originally a limited scope PR to bring recommended dependencies into pandas extras_require, but discussion evolved into 'solve packaging for all optional dependencies' rather than just solve for the `recommended` optional dependencies. The logic behind this is the same as originally argued for `recommended` dependencies but I updated the text of the post to keep it aligned with the PR contents --------- Closes #47335. Closes #39164 . Closes #48361 . Hoping to make this part of the 1.5 milestone. Optional dependencies should have package mgmt facilitated through pandas. This will make mgmt of pandas in production docker environments a significantly simpler and allow pandas explicit control over the versions of optional packages it should operate with. ## Actions Use setup.cfg options as [documented here](https://setuptools.pypa.io/en/latest/userguide/declarative_config.html?highlight=options.extras_require#configuring-setup-using-setup-cfg-files) to make optional extras for a pandas install. Once this is done, a user will be able to ensure version alignment by ``` # in requirements.txt or setup.py pandas[recommended, s3] == 1.22.4 # install pd 1.22.4 and compatible numexpr, bottleneck, s3fs versions ``` The proposed solution is simple to do, simple to maintain, and already done by major libraries in similar situations ([moto](https://github.com/spulec/moto/blob/master/setup.py), [aiobotocore](https://github.com/aio-libs/aiobotocore/blob/master/setup.py#L19)). Not having this solution wastes user time by forcing them to manually maintain versions of pandas dependencies that are not clearly linked to pandas, save in the brains of users and by manually referring to an install docs page. ## checklist - [x] closes #47335 , closes #39164 - [NA] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [NA] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. (no new functions) - [x] Added an entry in the latest `doc/source/whatsnew/v1.4.3.rst` file if fixing a bug or adding a new feature. (in `Other` section)
https://api.github.com/repos/pandas-dev/pandas/pulls/47336
2022-06-13T20:17:02Z
2022-10-21T16:47:17Z
2022-10-21T16:47:17Z
2022-10-27T16:15:45Z
BUG: DateOffset addition preserve non-nano
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index d37c287be4cfd..f1ebe9dd6348f 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -70,6 +70,7 @@ from pandas._libs.tslibs.np_datetime cimport ( from .dtypes cimport PeriodDtypeCode from .timedeltas cimport ( + _Timedelta, delta_to_nanoseconds, is_any_td_scalar, ) @@ -1140,7 +1141,9 @@ cdef class RelativeDeltaOffset(BaseOffset): weeks = kwds.get("weeks", 0) * self.n if weeks: - dt64other = dt64other + Timedelta(days=7 * weeks) + delta = Timedelta(days=7 * weeks) + td = (<_Timedelta>delta)._as_reso(reso) + dt64other = dt64other + td timedelta_kwds = { k: v @@ -1149,13 +1152,14 @@ cdef class RelativeDeltaOffset(BaseOffset): } if timedelta_kwds: delta = Timedelta(**timedelta_kwds) - dt64other = dt64other + (self.n * delta) - # FIXME: fails to preserve non-nano + td = (<_Timedelta>delta)._as_reso(reso) + dt64other = dt64other + (self.n * td) return dt64other elif not self._use_relativedelta and hasattr(self, "_offset"): # timedelta - # FIXME: fails to preserve non-nano - return dt64other + Timedelta(self._offset * self.n) + delta = Timedelta(self._offset * self.n) + td = (<_Timedelta>delta)._as_reso(reso) + return dt64other + td else: # relativedelta with other keywords kwd = set(kwds) - relativedelta_fast diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index cf5cbe6e2af66..49661fe1ec8ce 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -556,10 +556,6 @@ def test_add_dt64_ndarray_non_nano(self, offset_types, unit, request): # check that the result with non-nano matches nano off = self._get_offset(offset_types) - if type(off) is DateOffset: - mark = pytest.mark.xfail(reason="non-nano not implemented") - request.node.add_marker(mark) - dti = date_range("2016-01-01", periods=35, freq="D") arr = dti._data._ndarray.astype(f"M8[{unit}]")
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47334
2022-06-13T17:29:22Z
2022-06-13T19:29:01Z
2022-06-13T19:29:01Z
2022-06-13T19:30:27Z
ENH: implement Timestamp _as_reso, _as_unit
diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd index bde7cf9328712..69a1dd436dec0 100644 --- a/pandas/_libs/tslibs/timestamps.pxd +++ b/pandas/_libs/tslibs/timestamps.pxd @@ -37,3 +37,4 @@ cdef class _Timestamp(ABCTimestamp): cpdef void _set_freq(self, freq) cdef _warn_on_field_deprecation(_Timestamp self, freq, str field) cdef bint _compare_mismatched_resos(_Timestamp self, _Timestamp other, int op) + cdef _Timestamp _as_reso(_Timestamp self, NPY_DATETIMEUNIT reso, bint round_ok=*) diff --git a/pandas/_libs/tslibs/timestamps.pyi b/pandas/_libs/tslibs/timestamps.pyi index fd593ae453ef7..4de51d4dc7dd8 100644 --- a/pandas/_libs/tslibs/timestamps.pyi +++ b/pandas/_libs/tslibs/timestamps.pyi @@ -222,3 +222,4 @@ class Timestamp(datetime): def days_in_month(self) -> int: ... @property def daysinmonth(self) -> int: ... + def _as_unit(self, unit: str, round_ok: bool = ...) -> Timestamp: ... diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index c6bae70d04a98..ec8478f3fc82a 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -54,6 +54,7 @@ from pandas._libs.tslibs.conversion cimport ( maybe_localize_tso, ) from pandas._libs.tslibs.dtypes cimport ( + get_conversion_factor, npy_unit_to_abbrev, periods_per_day, periods_per_second, @@ -86,6 +87,7 @@ from pandas._libs.tslibs.np_datetime cimport ( dt64_to_dtstruct, get_datetime64_unit, get_datetime64_value, + get_unit_from_dtype, npy_datetimestruct, pandas_datetime_to_datetimestruct, pydatetime_to_dt64, @@ -1000,6 +1002,42 @@ cdef class _Timestamp(ABCTimestamp): # ----------------------------------------------------------------- # Conversion Methods + # TODO: share with _Timedelta? + @cython.cdivision(False) + cdef _Timestamp _as_reso(self, NPY_DATETIMEUNIT reso, bint round_ok=True): + cdef: + int64_t value, mult, div, mod + + if reso == self._reso: + return self + + if reso < self._reso: + # e.g. ns -> us + mult = get_conversion_factor(reso, self._reso) + div, mod = divmod(self.value, mult) + if mod > 0 and not round_ok: + raise ValueError("Cannot losslessly convert units") + + # Note that when mod > 0, we follow np.datetime64 in always + # rounding down. + value = div + else: + mult = get_conversion_factor(self._reso, reso) + with cython.overflowcheck(True): + # Note: caller is responsible for re-raising as OutOfBoundsDatetime + value = self.value * mult + return type(self)._from_value_and_reso(value, reso=reso, tz=self.tzinfo) + + def _as_unit(self, str unit, bint round_ok=True): + dtype = np.dtype(f"M8[{unit}]") + reso = get_unit_from_dtype(dtype) + try: + return self._as_reso(reso, round_ok=round_ok) + except OverflowError as err: + raise OutOfBoundsDatetime( + f"Cannot cast {self} to unit='{unit}' without overflow." + ) from err + @property def asm8(self) -> np.datetime64: """ diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 90c090d816c9d..5ae6ed9f13ece 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -13,6 +13,7 @@ NaT, iNaT, ) +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit from pandas.errors import OutOfBoundsTimedelta import pandas as pd @@ -33,7 +34,7 @@ def test_as_unit(self): res = td._as_unit("us") assert res.value == td.value // 1000 - assert res._reso == td._reso - 1 + assert res._reso == NpyDatetimeUnit.NPY_FR_us.value rt = res._as_unit("ns") assert rt.value == td.value @@ -41,7 +42,7 @@ def test_as_unit(self): res = td._as_unit("ms") assert res.value == td.value // 1_000_000 - assert res._reso == td._reso - 2 + assert res._reso == NpyDatetimeUnit.NPY_FR_ms.value rt = res._as_unit("ns") assert rt.value == td.value @@ -49,7 +50,7 @@ def test_as_unit(self): res = td._as_unit("s") assert res.value == td.value // 1_000_000_000 - assert res._reso == td._reso - 3 + assert res._reso == NpyDatetimeUnit.NPY_FR_s.value rt = res._as_unit("ns") assert rt.value == td.value @@ -58,7 +59,7 @@ def test_as_unit(self): def test_as_unit_overflows(self): # microsecond that would be just out of bounds for nano us = 9223372800000000 - td = Timedelta._from_value_and_reso(us, 9) + td = Timedelta._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value) msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow" with pytest.raises(OutOfBoundsTimedelta, match=msg): @@ -66,7 +67,7 @@ def test_as_unit_overflows(self): res = td._as_unit("ms") assert res.value == us // 1000 - assert res._reso == 8 + assert res._reso == NpyDatetimeUnit.NPY_FR_ms.value def test_as_unit_rounding(self): td = Timedelta(microseconds=1500) @@ -75,7 +76,7 @@ def test_as_unit_rounding(self): expected = Timedelta(milliseconds=1) assert res == expected - assert res._reso == 8 + assert res._reso == NpyDatetimeUnit.NPY_FR_ms.value assert res.value == 1 with pytest.raises(ValueError, match="Cannot losslessly convert units"): diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 89e5ce2241e42..292c8f95ec2e6 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -18,10 +18,12 @@ utc, ) +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit from pandas._libs.tslibs.timezones import ( dateutil_gettz as gettz, get_timezone, ) +from pandas.errors import OutOfBoundsDatetime import pandas.util._test_decorators as td from pandas import ( @@ -850,3 +852,82 @@ def test_timestamp(self, dt64, ts): def test_to_period(self, dt64, ts): alt = Timestamp(dt64) assert ts.to_period("D") == alt.to_period("D") + + +class TestAsUnit: + def test_as_unit(self): + ts = Timestamp("1970-01-01") + + assert ts._as_unit("ns") is ts + + res = ts._as_unit("us") + assert res.value == ts.value // 1000 + assert res._reso == NpyDatetimeUnit.NPY_FR_us.value + + rt = res._as_unit("ns") + assert rt.value == ts.value + assert rt._reso == ts._reso + + res = ts._as_unit("ms") + assert res.value == ts.value // 1_000_000 + assert res._reso == NpyDatetimeUnit.NPY_FR_ms.value + + rt = res._as_unit("ns") + assert rt.value == ts.value + assert rt._reso == ts._reso + + res = ts._as_unit("s") + assert res.value == ts.value // 1_000_000_000 + assert res._reso == NpyDatetimeUnit.NPY_FR_s.value + + rt = res._as_unit("ns") + assert rt.value == ts.value + assert rt._reso == ts._reso + + def test_as_unit_overflows(self): + # microsecond that would be just out of bounds for nano + us = 9223372800000000 + ts = Timestamp._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value, None) + + msg = "Cannot cast 2262-04-12 00:00:00 to unit='ns' without overflow" + with pytest.raises(OutOfBoundsDatetime, match=msg): + ts._as_unit("ns") + + res = ts._as_unit("ms") + assert res.value == us // 1000 + assert res._reso == NpyDatetimeUnit.NPY_FR_ms.value + + def test_as_unit_rounding(self): + ts = Timestamp(1_500_000) # i.e. 1500 microseconds + res = ts._as_unit("ms") + + expected = Timestamp(1_000_000) # i.e. 1 millisecond + assert res == expected + + assert res._reso == NpyDatetimeUnit.NPY_FR_ms.value + assert res.value == 1 + + with pytest.raises(ValueError, match="Cannot losslessly convert units"): + ts._as_unit("ms", round_ok=False) + + def test_as_unit_non_nano(self): + # case where we are going neither to nor from nano + ts = Timestamp("1970-01-02")._as_unit("ms") + assert ts.year == 1970 + assert ts.month == 1 + assert ts.day == 2 + assert ts.hour == ts.minute == ts.second == ts.microsecond == ts.nanosecond == 0 + + res = ts._as_unit("s") + assert res.value == 24 * 3600 + assert res.year == 1970 + assert res.month == 1 + assert res.day == 2 + assert ( + res.hour + == res.minute + == res.second + == res.microsecond + == res.nanosecond + == 0 + )
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47333
2022-06-13T15:13:43Z
2022-06-13T17:17:20Z
2022-06-13T17:17:20Z
2022-06-13T17:32:47Z
BUG: concat not sorting mixed column names when None is included
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 55bfb044fb31d..48b12338b8d03 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -902,6 +902,7 @@ Reshaping - Bug in :func:`get_dummies` that selected object and categorical dtypes but not string (:issue:`44965`) - Bug in :meth:`DataFrame.align` when aligning a :class:`MultiIndex` to a :class:`Series` with another :class:`MultiIndex` (:issue:`46001`) - Bug in concanenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`) +- Bug in :func:`concat` not sorting the column names when ``None`` is included (:issue:`47331`) - Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`) - Bug in :meth:`DataFrame.join` with a list when using suffixes to join DataFrames with duplicate column names (:issue:`46396`) - Bug in :meth:`DataFrame.pivot_table` with ``sort=False`` results in sorted index (:issue:`17041`) diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 888e943488953..cf73fd7c8929e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1771,9 +1771,12 @@ def safe_sort( def _sort_mixed(values) -> np.ndarray: """order ints before strings in 1d arrays, safe in py3""" str_pos = np.array([isinstance(x, str) for x in values], dtype=bool) - nums = np.sort(values[~str_pos]) + none_pos = np.array([x is None for x in values], dtype=bool) + nums = np.sort(values[~str_pos & ~none_pos]) strs = np.sort(values[str_pos]) - return np.concatenate([nums, np.asarray(strs, dtype=object)]) + return np.concatenate( + [nums, np.asarray(strs, dtype=object), np.array(values[none_pos])] + ) def _sort_tuples(values: np.ndarray) -> np.ndarray: diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index eb44b4889afb8..17c797fc36159 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -469,12 +469,12 @@ def __iter__(self): tm.assert_frame_equal(concat(CustomIterator2(), ignore_index=True), expected) def test_concat_order(self): - # GH 17344 + # GH 17344, GH#47331 dfs = [DataFrame(index=range(3), columns=["a", 1, None])] - dfs += [DataFrame(index=range(3), columns=[None, 1, "a"]) for i in range(100)] + dfs += [DataFrame(index=range(3), columns=[None, 1, "a"]) for _ in range(100)] result = concat(dfs, sort=True).columns - expected = dfs[0].columns + expected = Index([1, "a", None]) tm.assert_index_equal(result, expected) def test_concat_different_extension_dtypes_upcasts(self):
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. I think this is more sensible than the previous version, where an error was raised when None was included.
https://api.github.com/repos/pandas-dev/pandas/pulls/47331
2022-06-13T10:39:34Z
2022-06-14T16:32:20Z
2022-06-14T16:32:20Z
2022-06-14T16:51:25Z
BUG: assert_index_equal ignoring names when check_order is false
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index a5cb716317689..d8b8f620a1d62 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -963,7 +963,7 @@ Other .. ***DO NOT USE THIS SECTION*** -- +- Bug in :func:`.assert_index_equal` with ``names=True`` and ``check_order=False`` not checking names (:issue:`47328`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 2029a7665d57a..90ee600c1967d 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -45,10 +45,7 @@ Series, TimedeltaIndex, ) -from pandas.core.algorithms import ( - safe_sort, - take_nd, -) +from pandas.core.algorithms import take_nd from pandas.core.arrays import ( DatetimeArray, ExtensionArray, @@ -58,6 +55,7 @@ ) from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.arrays.string_ import StringDtype +from pandas.core.indexes.api import safe_sort_index from pandas.io.formats.printing import pprint_thing @@ -367,8 +365,8 @@ def _get_ilevel_values(index, level): # If order doesn't matter then sort the index entries if not check_order: - left = Index(safe_sort(left), dtype=left.dtype) - right = Index(safe_sort(right), dtype=right.dtype) + left = safe_sort_index(left) + right = safe_sort_index(right) # MultiIndex special comparison for little-friendly error messages if left.nlevels > 1: diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 1e740132e3464..634187a317baf 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -70,6 +70,7 @@ "get_unanimous_names", "all_indexes_same", "default_index", + "safe_sort_index", ] @@ -157,16 +158,7 @@ def _get_combined_index( index = ensure_index(index) if sort: - try: - array_sorted = safe_sort(index) - array_sorted = cast(np.ndarray, array_sorted) - if isinstance(index, MultiIndex): - index = MultiIndex.from_tuples(array_sorted, names=index.names) - else: - index = Index(array_sorted, name=index.name) - except TypeError: - pass - + index = safe_sort_index(index) # GH 29879 if copy: index = index.copy() @@ -174,6 +166,34 @@ def _get_combined_index( return index +def safe_sort_index(index: Index) -> Index: + """ + Returns the sorted index + + We keep the dtypes and the name attributes. + + Parameters + ---------- + index : an Index + + Returns + ------- + Index + """ + try: + array_sorted = safe_sort(index) + except TypeError: + pass + else: + array_sorted = cast(np.ndarray, array_sorted) + if isinstance(index, MultiIndex): + index = MultiIndex.from_tuples(array_sorted, names=index.names) + else: + index = Index(array_sorted, name=index.name, dtype=index.dtype) + + return index + + def union_indexes(indexes, sort: bool | None = True) -> Index: """ Return the union of indexes. diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index e3461e62b4eda..1fa7b979070a7 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -238,6 +238,14 @@ def test_index_equal_range_categories(check_categorical, exact): ) +def test_assert_index_equal_different_names_check_order_false(): + # GH#47328 + idx1 = Index([1, 3], name="a") + idx2 = Index([3, 1], name="b") + with pytest.raises(AssertionError, match='"names" are different'): + tm.assert_index_equal(idx1, idx2, check_order=False, check_names=True) + + def test_assert_index_equal_mixed_dtype(): # GH#39168 idx = Index(["foo", "bar", 42])
- [x] closes #47328 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This should get merged after #47325 (will probably have a conflict then)
https://api.github.com/repos/pandas-dev/pandas/pulls/47330
2022-06-13T09:48:39Z
2022-06-23T21:50:34Z
2022-06-23T21:50:33Z
2022-06-24T10:22:51Z
REGR: Fix fillna making a copy when dict was given as fill value and inplace is set
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index a4d81533df23d..d031426a2abbf 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -18,6 +18,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.to_csv` raising error when :class:`DataFrame` contains extension dtype categorical column (:issue:`46297`, :issue:`46812`) - Fixed regression in representation of ``dtypes`` attribute of :class:`MultiIndex` (:issue:`46900`) - Fixed regression when setting values with :meth:`DataFrame.loc` updating :class:`RangeIndex` when index was set as new column and column was updated afterwards (:issue:`47128`) +- Fixed regression in :meth:`DataFrame.fillna` and :meth:`DataFrame.update` creating a copy when updating inplace (:issue:`47188`) - Fixed regression in :meth:`DataFrame.nsmallest` led to wrong results when ``np.nan`` in the sorting column (:issue:`46589`) - Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`) - Fixed regression in :func:`concat` not sorting columns for mixed column names (:issue:`47127`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 39a940169e1f3..8711d53353185 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8000,7 +8000,7 @@ def update( if mask.all(): continue - self[col] = expressions.where(mask, this, that) + self.loc[:, col] = expressions.where(mask, this, that) # ---------------------------------------------------------------------- # Data reshaping diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f32b347de32c3..413429ea94d2c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6522,7 +6522,9 @@ def fillna( if k not in result: continue downcast_k = downcast if not is_dict else downcast.get(k) - result[k] = result[k].fillna(v, limit=limit, downcast=downcast_k) + result.loc[:, k] = result[k].fillna( + v, limit=limit, downcast=downcast_k + ) return result if not inplace else None elif not is_list_like(value): diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 5008e64dd0e99..f5c9dd65e4760 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -284,6 +284,7 @@ def test_fillna_downcast_noop(self, frame_or_series): res3 = obj2.fillna("foo", downcast=np.dtype(np.int32)) tm.assert_equal(res3, expected) + @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) def test_fillna_dictlike_value_duplicate_colnames(self, columns): # GH#43476 @@ -673,6 +674,17 @@ def test_fillna_inplace_with_columns_limit_and_value(self): df.fillna(axis=1, value=100, limit=1, inplace=True) tm.assert_frame_equal(df, expected) + @td.skip_array_manager_invalid_test + @pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}]) + def test_inplace_dict_update_view(self, val): + # GH#47188 + df = DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]}) + result_view = df[:] + df.fillna(val, inplace=True) + expected = DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]}) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(result_view, expected) + def test_fillna_nonconsolidated_frame(): # https://github.com/pandas-dev/pandas/issues/36495 diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index 408113e9bc417..d3257ac09a0ab 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import ( DataFrame, @@ -146,3 +148,14 @@ def test_update_with_different_dtype(self): expected = DataFrame({"a": [1, 3], "b": [np.nan, 2], "c": ["foo", np.nan]}) tm.assert_frame_equal(df, expected) + + @td.skip_array_manager_invalid_test + def test_update_modify_view(self): + # GH#47188 + df = DataFrame({"A": ["1", np.nan], "B": ["100", np.nan]}) + df2 = DataFrame({"A": ["a", "x"], "B": ["100", "200"]}) + result_view = df2[:] + df2.update(df) + expected = DataFrame({"A": ["1", "x"], "B": ["100", "200"]}) + tm.assert_frame_equal(df2, expected) + tm.assert_frame_equal(result_view, expected)
- [x] closes #47188 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. I think updating inplace is sensible here? This is a subtle change so I think we should backport, because the fact that we are using setitem under th hood should not leak into the interface. If we want to change this, we should deprecate, but only makes sens if we don't get Copy on Write in for 2.0
https://api.github.com/repos/pandas-dev/pandas/pulls/47327
2022-06-13T08:58:08Z
2022-06-21T18:09:33Z
2022-06-21T18:09:33Z
2022-06-21T19:42:22Z
REGR: Fix nan comparison for same Index object
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index ca8b8ca15ec47..bfc9422711690 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -20,6 +20,7 @@ Fixed regressions - Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`) - Fixed regression in :func:`concat` not sorting columns for mixed column names (:issue:`47127`) - Fixed regression in :meth:`.Groupby.transform` and :meth:`.Groupby.agg` failing with ``engine="numba"`` when the index was a :class:`MultiIndex` (:issue:`46867`) +- Fixed regression in ``NaN`` comparison for :class:`Index` operations where the same object was compared (:issue:`47105`) - Fixed regression is :meth:`.Styler.to_latex` and :meth:`.Styler.to_html` where ``buf`` failed in combination with ``encoding`` (:issue:`47053`) - Fixed regression in :func:`read_csv` with ``index_col=False`` identifying first row as index names when ``header=None`` (:issue:`46955`) - Fixed regression in :meth:`.DataFrameGroupBy.agg` when used with list-likes or dict-likes and ``axis=1`` that would give incorrect results; now raises ``NotImplementedError`` (:issue:`46995`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index cb01cfc981739..01bbc424c3764 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6955,7 +6955,7 @@ def _cmp_method(self, other, op): # TODO: should set MultiIndex._can_hold_na = False? arr[self.isna()] = False return arr - elif op in {operator.ne, operator.lt, operator.gt}: + elif op is operator.ne: arr = np.zeros(len(self), dtype=bool) if self._can_hold_na and not isinstance(self, ABCMultiIndex): arr[self.isna()] = True diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 943cc945995a1..5d7fc23feb5a8 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2,6 +2,7 @@ from datetime import datetime from io import StringIO import math +import operator import re import numpy as np @@ -1604,3 +1605,16 @@ def test_get_attributes_dict_deprecated(): with tm.assert_produces_warning(DeprecationWarning): attrs = idx._get_attributes_dict() assert attrs == {"name": None} + + +@pytest.mark.parametrize("op", [operator.lt, operator.gt]) +def test_nan_comparison_same_object(op): + # GH#47105 + idx = Index([np.nan]) + expected = np.array([False]) + + result = op(idx, idx) + tm.assert_numpy_array_equal(result, expected) + + result = op(idx, idx.copy()) + tm.assert_numpy_array_equal(result, expected)
- [x] closes #47105 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47326
2022-06-13T08:35:26Z
2022-06-15T11:41:16Z
2022-06-15T11:41:16Z
2022-06-15T11:43:25Z
REGR: Avoid regression warning with ea dtype and assert_index_equal order False
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index ca8b8ca15ec47..ce53d2b1dd04c 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :func:`read_csv` with ``index_col=False`` identifying first row as index names when ``header=None`` (:issue:`46955`) - Fixed regression in :meth:`.DataFrameGroupBy.agg` when used with list-likes or dict-likes and ``axis=1`` that would give incorrect results; now raises ``NotImplementedError`` (:issue:`46995`) - Fixed regression in :meth:`DataFrame.resample` and :meth:`DataFrame.rolling` when used with list-likes or dict-likes and ``axis=1`` that would raise an unintuitive error message; now raises ``NotImplementedError`` (:issue:`46904`) +- Fixed regression in :func:`assert_index_equal` when ``check_order=False`` and :class:`Index` has extension or object dtype (:issue:`47207`) - Fixed regression in :func:`read_excel` returning ints as floats on certain input sheets (:issue:`46988`) - Fixed regression in :meth:`DataFrame.shift` when ``axis`` is ``columns`` and ``fill_value`` is absent, ``freq`` is ignored (:issue:`47039`) diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 7170089581f69..2029a7665d57a 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -367,8 +367,8 @@ def _get_ilevel_values(index, level): # If order doesn't matter then sort the index entries if not check_order: - left = Index(safe_sort(left)) - right = Index(safe_sort(right)) + left = Index(safe_sort(left), dtype=left.dtype) + right = Index(safe_sort(right), dtype=right.dtype) # MultiIndex special comparison for little-friendly error messages if left.nlevels > 1: diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index 8211b52fed650..e3461e62b4eda 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -242,3 +242,17 @@ def test_assert_index_equal_mixed_dtype(): # GH#39168 idx = Index(["foo", "bar", 42]) tm.assert_index_equal(idx, idx, check_order=False) + + +def test_assert_index_equal_ea_dtype_order_false(any_numeric_ea_dtype): + # GH#47207 + idx1 = Index([1, 3], dtype=any_numeric_ea_dtype) + idx2 = Index([3, 1], dtype=any_numeric_ea_dtype) + tm.assert_index_equal(idx1, idx2, check_order=False) + + +def test_assert_index_equal_object_ints_order_false(): + # GH#47207 + idx1 = Index([1, 3], dtype="object") + idx2 = Index([3, 1], dtype="object") + tm.assert_index_equal(idx1, idx2, check_order=False)
- [x] closes #47207 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47325
2022-06-13T07:43:16Z
2022-06-15T11:48:10Z
2022-06-15T11:48:10Z
2022-06-15T15:55:33Z
ENH: DTA.to_period support non-nano
diff --git a/pandas/_libs/tslibs/vectorized.pyi b/pandas/_libs/tslibs/vectorized.pyi index 8820a17ce5996..72a87095e847c 100644 --- a/pandas/_libs/tslibs/vectorized.pyi +++ b/pandas/_libs/tslibs/vectorized.pyi @@ -14,6 +14,7 @@ def dt64arr_to_periodarr( stamps: npt.NDArray[np.int64], freq: int, tz: tzinfo | None, + reso: int = ..., # NPY_DATETIMEUNIT ) -> npt.NDArray[np.int64]: ... def is_date_array_normalized( stamps: npt.NDArray[np.int64], diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx index 2cab55e607f15..3686b330fb6c2 100644 --- a/pandas/_libs/tslibs/vectorized.pyx +++ b/pandas/_libs/tslibs/vectorized.pyx @@ -33,6 +33,7 @@ from .np_datetime cimport ( NPY_FR_ns, dt64_to_dtstruct, npy_datetimestruct, + pandas_datetime_to_datetimestruct, ) from .offsets cimport BaseOffset from .period cimport get_period_ordinal @@ -354,10 +355,12 @@ def is_date_array_normalized(ndarray stamps, tzinfo tz, NPY_DATETIMEUNIT reso) - @cython.wraparound(False) @cython.boundscheck(False) -def dt64arr_to_periodarr(ndarray stamps, int freq, tzinfo tz): +def dt64arr_to_periodarr( + ndarray stamps, int freq, tzinfo tz, NPY_DATETIMEUNIT reso=NPY_FR_ns +): # stamps is int64_t, arbitrary ndim cdef: - Localizer info = Localizer(tz, reso=NPY_FR_ns) + Localizer info = Localizer(tz, reso=reso) Py_ssize_t i, n = stamps.size Py_ssize_t pos = -1 # unused, avoid not-initialized warning int64_t utc_val, local_val, res_val @@ -374,7 +377,7 @@ def dt64arr_to_periodarr(ndarray stamps, int freq, tzinfo tz): res_val = NPY_NAT else: local_val = info.utc_val_to_local_val(utc_val, &pos) - dt64_to_dtstruct(local_val, &dts) + pandas_datetime_to_datetimestruct(local_val, reso, &dts) res_val = get_period_ordinal(&dts, freq) # Analogous to: result[i] = res_val diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index b6d21cd9dac54..c40e9428bab25 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -22,6 +22,7 @@ astype_overflowsafe, delta_to_nanoseconds, dt64arr_to_periodarr as c_dt64arr_to_periodarr, + get_unit_from_dtype, iNaT, parsing, period as libperiod, @@ -1024,7 +1025,7 @@ def dt64arr_to_periodarr(data, freq, tz=None): used. """ - if data.dtype != np.dtype("M8[ns]"): + if not isinstance(data.dtype, np.dtype) or data.dtype.kind != "M": raise ValueError(f"Wrong dtype: {data.dtype}") if freq is None: @@ -1036,9 +1037,10 @@ def dt64arr_to_periodarr(data, freq, tz=None): elif isinstance(data, (ABCIndex, ABCSeries)): data = data._values + reso = get_unit_from_dtype(data.dtype) freq = Period._maybe_convert_freq(freq) base = freq._period_dtype_code - return c_dt64arr_to_periodarr(data.view("i8"), base, tz), freq + return c_dt64arr_to_periodarr(data.view("i8"), base, tz, reso=reso), freq def _get_ordinal_range(start, end, periods, freq, mult=1): diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index f3d471ca96614..d4f8e5b76a7c5 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -37,6 +37,26 @@ def dtype(self, unit, tz_naive_fixture): else: return DatetimeTZDtype(unit=unit, tz=tz) + @pytest.fixture + def dta_dti(self, unit, dtype): + tz = getattr(dtype, "tz", None) + + dti = pd.date_range("2016-01-01", periods=55, freq="D", tz=tz) + if tz is None: + arr = np.asarray(dti).astype(f"M8[{unit}]") + else: + arr = np.asarray(dti.tz_convert("UTC").tz_localize(None)).astype( + f"M8[{unit}]" + ) + + dta = DatetimeArray._simple_new(arr, dtype=dtype) + return dta, dti + + @pytest.fixture + def dta(self, dta_dti): + dta, dti = dta_dti + return dta + def test_non_nano(self, unit, reso, dtype): arr = np.arange(5, dtype=np.int64).view(f"M8[{unit}]") dta = DatetimeArray._simple_new(arr, dtype=dtype) @@ -52,17 +72,8 @@ def test_non_nano(self, unit, reso, dtype): @pytest.mark.parametrize( "field", DatetimeArray._field_ops + DatetimeArray._bool_ops ) - def test_fields(self, unit, reso, field, dtype): - tz = getattr(dtype, "tz", None) - dti = pd.date_range("2016-01-01", periods=55, freq="D", tz=tz) - if tz is None: - arr = np.asarray(dti).astype(f"M8[{unit}]") - else: - arr = np.asarray(dti.tz_convert("UTC").tz_localize(None)).astype( - f"M8[{unit}]" - ) - - dta = DatetimeArray._simple_new(arr, dtype=dtype) + def test_fields(self, unit, reso, field, dtype, dta_dti): + dta, dti = dta_dti # FIXME: assert (dti == dta).all() @@ -107,6 +118,14 @@ def test_std_non_nano(self, unit): assert res._reso == dta._reso assert res == dti.std().floor(unit) + @pytest.mark.filterwarnings("ignore:Converting to PeriodArray.*:UserWarning") + def test_to_period(self, dta_dti): + dta, dti = dta_dti + result = dta.to_period("D") + expected = dti._data.to_period("D") + + tm.assert_extension_array_equal(result, expected) + class TestDatetimeArrayComparisons: # TODO: merge this into tests/arithmetic/test_datetime64 once it is diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index fdc286ef7ec1a..5dff5c2ad9c86 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -183,9 +183,10 @@ def test_constructor_datetime64arr(self): vals = np.arange(100000, 100000 + 10000, 100, dtype=np.int64) vals = vals.view(np.dtype("M8[us]")) - msg = r"Wrong dtype: datetime64\[us\]" - with pytest.raises(ValueError, match=msg): - PeriodIndex(vals, freq="D") + pi = PeriodIndex(vals, freq="D") + + expected = PeriodIndex(vals.astype("M8[ns]"), freq="D") + tm.assert_index_equal(pi, expected) @pytest.mark.parametrize("box", [None, "series", "index"]) def test_constructor_datetime64arr_ok(self, box): diff --git a/setup.py b/setup.py index cb713e6d74392..27e6d8cb10025 100755 --- a/setup.py +++ b/setup.py @@ -551,7 +551,11 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "depends": tseries_depends, "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], }, - "_libs.tslibs.vectorized": {"pyxfile": "_libs/tslibs/vectorized"}, + "_libs.tslibs.vectorized": { + "pyxfile": "_libs/tslibs/vectorized", + "depends": tseries_depends, + "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], + }, "_libs.testing": {"pyxfile": "_libs/testing"}, "_libs.window.aggregations": { "pyxfile": "_libs/window/aggregations",
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47324
2022-06-12T20:24:07Z
2022-06-13T17:25:51Z
2022-06-13T17:25:51Z
2022-06-13T17:33:21Z
Add test for multi-column dtype assignment
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index aef61045179ef..e127fe27b6209 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -1140,3 +1140,15 @@ def test_compare_complex_dtypes(): with pytest.raises(TypeError, match=msg): df.lt(df.astype(object)) + + +def test_multi_column_dtype_assignment(): + # GH #27583 + df = pd.DataFrame({"a": [0.0], "b": 0.0}) + expected = pd.DataFrame({"a": [0], "b": 0}) + + df[["a", "b"]] = 0 + tm.assert_frame_equal(df, expected) + + df["b"] = 0 + tm.assert_frame_equal(df, expected)
- [x] closes #27583 - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/47323
2022-06-12T19:34:17Z
2022-06-13T17:27:54Z
2022-06-13T17:27:54Z
2022-06-13T23:51:07Z
ENH: get_resolution support non-nano
diff --git a/pandas/_libs/tslibs/vectorized.pyi b/pandas/_libs/tslibs/vectorized.pyi index 8820a17ce5996..f303d51367ce7 100644 --- a/pandas/_libs/tslibs/vectorized.pyi +++ b/pandas/_libs/tslibs/vectorized.pyi @@ -28,6 +28,7 @@ def normalize_i8_timestamps( def get_resolution( stamps: npt.NDArray[np.int64], tz: tzinfo | None = ..., + reso: int = ..., # NPY_DATETIMEUNIT ) -> Resolution: ... def ints_to_pydatetime( arr: npt.NDArray[np.int64], diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx index 2cab55e607f15..4a957e24ccdfd 100644 --- a/pandas/_libs/tslibs/vectorized.pyx +++ b/pandas/_libs/tslibs/vectorized.pyx @@ -33,6 +33,7 @@ from .np_datetime cimport ( NPY_FR_ns, dt64_to_dtstruct, npy_datetimestruct, + pandas_datetime_to_datetimestruct, ) from .offsets cimport BaseOffset from .period cimport get_period_ordinal @@ -226,17 +227,19 @@ cdef inline c_Resolution _reso_stamp(npy_datetimestruct *dts): @cython.wraparound(False) @cython.boundscheck(False) -def get_resolution(ndarray stamps, tzinfo tz=None) -> Resolution: +def get_resolution( + ndarray stamps, tzinfo tz=None, NPY_DATETIMEUNIT reso=NPY_FR_ns +) -> Resolution: # stamps is int64_t, any ndim cdef: - Localizer info = Localizer(tz, reso=NPY_FR_ns) + Localizer info = Localizer(tz, reso=reso) int64_t utc_val, local_val Py_ssize_t i, n = stamps.size Py_ssize_t pos = -1 # unused, avoid not-initialized warning cnp.flatiter it = cnp.PyArray_IterNew(stamps) npy_datetimestruct dts - c_Resolution reso = c_Resolution.RESO_DAY, curr_reso + c_Resolution pd_reso = c_Resolution.RESO_DAY, curr_reso for i in range(n): # Analogous to: utc_val = stamps[i] @@ -247,14 +250,14 @@ def get_resolution(ndarray stamps, tzinfo tz=None) -> Resolution: else: local_val = info.utc_val_to_local_val(utc_val, &pos) - dt64_to_dtstruct(local_val, &dts) + pandas_datetime_to_datetimestruct(local_val, reso, &dts) curr_reso = _reso_stamp(&dts) - if curr_reso < reso: - reso = curr_reso + if curr_reso < pd_reso: + pd_reso = curr_reso cnp.PyArray_ITER_NEXT(it) - return Resolution(reso) + return Resolution(pd_reso) # ------------------------------------------------------------------------- diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index db55c165c9974..d297d3e9f8e4e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -619,7 +619,7 @@ def is_normalized(self) -> bool: @property # NB: override with cache_readonly in immutable subclasses def _resolution_obj(self) -> Resolution: - return get_resolution(self.asi8, self.tz) + return get_resolution(self.asi8, self.tz, reso=self._reso) # ---------------------------------------------------------------- # Array-Like / EA-Interface Methods diff --git a/pandas/tests/tslibs/test_resolution.py b/pandas/tests/tslibs/test_resolution.py index 15f4a9d032e5c..7b2268f16a85f 100644 --- a/pandas/tests/tslibs/test_resolution.py +++ b/pandas/tests/tslibs/test_resolution.py @@ -1,9 +1,11 @@ import numpy as np +import pytz from pandas._libs.tslibs import ( Resolution, get_resolution, ) +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit def test_get_resolution_nano(): @@ -11,3 +13,12 @@ def test_get_resolution_nano(): arr = np.array([1], dtype=np.int64) res = get_resolution(arr) assert res == Resolution.RESO_NS + + +def test_get_resolution_non_nano_data(): + arr = np.array([1], dtype=np.int64) + res = get_resolution(arr, None, NpyDatetimeUnit.NPY_FR_us.value) + assert res == Resolution.RESO_US + + res = get_resolution(arr, pytz.UTC, NpyDatetimeUnit.NPY_FR_us.value) + assert res == Resolution.RESO_US diff --git a/setup.py b/setup.py index cb713e6d74392..27e6d8cb10025 100755 --- a/setup.py +++ b/setup.py @@ -551,7 +551,11 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "depends": tseries_depends, "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], }, - "_libs.tslibs.vectorized": {"pyxfile": "_libs/tslibs/vectorized"}, + "_libs.tslibs.vectorized": { + "pyxfile": "_libs/tslibs/vectorized", + "depends": tseries_depends, + "sources": ["pandas/_libs/tslibs/src/datetime/np_datetime.c"], + }, "_libs.testing": {"pyxfile": "_libs/testing"}, "_libs.window.aggregations": { "pyxfile": "_libs/window/aggregations",
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47322
2022-06-12T19:32:37Z
2022-06-13T23:43:27Z
2022-06-13T23:43:27Z
2022-06-14T01:24:11Z
improve period constructor docs
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 0c05037097839..8fccd3541fde1 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2483,9 +2483,11 @@ class Period(_Period): Parameters ---------- value : Period or str, default None - The time period represented (e.g., '4Q2005'). + The time period represented (e.g., '4Q2005'). This represents neither + the start or the end of the period, but rather the entire period itself. freq : str, default None - One of pandas period strings or corresponding objects. + One of pandas period strings or corresponding objects. Accepted + strings are listed in the :ref:`offset alias section <timeseries.offset_aliases>` in the user docs. ordinal : int, default None The period offset from the proleptic Gregorian epoch. year : int, default None @@ -2502,6 +2504,12 @@ class Period(_Period): Minute value of the period. second : int, default 0 Second value of the period. + + Examples + -------- + >>> period = pd.Period('2012-1-1', freq='D') + >>> period + Period('2012-01-01', 'D') """ def __new__(cls, value=None, freq=None, ordinal=None,
- [x] closes #4591 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/47321
2022-06-12T18:53:48Z
2022-06-15T19:07:46Z
2022-06-15T19:07:46Z
2022-06-16T01:20:01Z
ENH: Timestamp.tz_convert support non-nano
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ec8478f3fc82a..3d43e5c91e604 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -2112,8 +2112,6 @@ default 'raise' >>> pd.NaT.tz_convert(tz='Asia/Tokyo') NaT """ - if self._reso != NPY_FR_ns: - raise NotImplementedError(self._reso) if self.tzinfo is None: # tz naive, use tz_localize @@ -2122,7 +2120,8 @@ default 'raise' ) else: # Same UTC timestamp, different time zone - out = Timestamp(self.value, tz=tz) + tz = maybe_get_tz(tz) + out = type(self)._from_value_and_reso(self.value, reso=self._reso, tz=tz) if out is not NaT: out._set_freq(self._freq) # avoid warning in constructor return out diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 292c8f95ec2e6..d7c157885c77e 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -22,6 +22,7 @@ from pandas._libs.tslibs.timezones import ( dateutil_gettz as gettz, get_timezone, + tz_compare, ) from pandas.errors import OutOfBoundsDatetime import pandas.util._test_decorators as td @@ -763,6 +764,16 @@ def test_month_name(self, dt64, ts): alt = Timestamp(dt64) assert ts.month_name() == alt.month_name() + def test_tz_convert(self, ts): + ts = Timestamp._from_value_and_reso(ts.value, ts._reso, utc) + + tz = pytz.timezone("US/Pacific") + result = ts.tz_convert(tz) + + assert isinstance(result, Timestamp) + assert result._reso == ts._reso + assert tz_compare(result.tz, tz) + def test_repr(self, dt64, ts): alt = Timestamp(dt64)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47320
2022-06-12T18:34:57Z
2022-06-13T23:44:18Z
2022-06-13T23:44:18Z
2022-06-14T01:23:39Z
CI: Pin PYTEST_WORKERS=1 for Windows builds due to memory errors
diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml index 4c48d83b68947..7052b770e2586 100644 --- a/.github/workflows/macos-windows.yml +++ b/.github/workflows/macos-windows.yml @@ -15,7 +15,6 @@ on: env: PANDAS_CI: 1 PYTEST_TARGET: pandas - PYTEST_WORKERS: auto PATTERN: "not slow and not db and not network and not single_cpu" @@ -36,6 +35,9 @@ jobs: # https://github.community/t/concurrecy-not-work-for-push/183068/7 group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.env_file }}-${{ matrix.os }} cancel-in-progress: true + env: + # GH 47443: PYTEST_WORKERS > 1 crashes Windows builds with memory related errors + PYTEST_WORKERS: ${{ matrix.os == 'macos-latest' && 'auto' || '1' }} steps: - name: Checkout
1. Running tests without xdist is okay 2. It's not due to pyarrow v8 (I think) 3. Same error with `windows-2019` as `windows-latest`
https://api.github.com/repos/pandas-dev/pandas/pulls/47318
2022-06-12T18:01:24Z
2022-06-21T17:01:19Z
2022-06-21T17:01:19Z
2022-06-21T17:02:50Z
DOC: added example of valid input dict in dfgroupby.aggregate
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 38b93c6be60f8..b4aea4240e458 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -814,6 +814,14 @@ class DataFrameGroupBy(GroupBy[DataFrame]): 1 1 2 2 3 4 + User-defined function for aggregation + + >>> df.groupby('A').agg(lambda x: sum(x) + 2) + B C + A + 1 5 2.590715 + 2 9 2.704907 + Different aggregations per column >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'})
- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). This edit adds an example in [dfgroupby.aggregate](https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html), for the more complicated case where the input is a "dict of axis labels -> functions, function names or list of such". It also explicitly states that it is possible to use `list` as a "function" (where the output will be a list of values for each group in the target column, as seen below). ![image](https://user-images.githubusercontent.com/90637415/173214630-6bdc6072-3d00-496c-8d52-49390f7d7f4f.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/47317
2022-06-12T04:36:50Z
2022-06-13T23:46:18Z
2022-06-13T23:46:18Z
2022-06-13T23:51:13Z
ENH: Timestamp.normalize support non-nano
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ec8478f3fc82a..afa678a6751af 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -856,12 +856,11 @@ cdef class _Timestamp(ABCTimestamp): local_val = self._maybe_convert_value_to_local() int64_t normalized int64_t ppd = periods_per_day(self._reso) - - if self._reso != NPY_FR_ns: - raise NotImplementedError(self._reso) + _Timestamp ts normalized = normalize_i8_stamp(local_val, ppd) - return Timestamp(normalized).tz_localize(self.tzinfo) + ts = type(self)._from_value_and_reso(normalized, reso=self._reso, tz=None) + return ts.tz_localize(self.tzinfo) # ----------------------------------------------------------------- # Pickle Methods @@ -2035,6 +2034,8 @@ default 'raise' NaT """ if self._reso != NPY_FR_ns: + if tz is None and self.tz is None: + return self raise NotImplementedError(self._reso) if ambiguous == 'infer': diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 292c8f95ec2e6..36c3803ef41ff 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -715,11 +715,11 @@ def test_non_nano_construction(self, dt64, ts, reso): assert ts.value == dt64.view("i8") if reso == "s": - assert ts._reso == 7 + assert ts._reso == NpyDatetimeUnit.NPY_FR_s.value elif reso == "ms": - assert ts._reso == 8 + assert ts._reso == NpyDatetimeUnit.NPY_FR_ms.value elif reso == "us": - assert ts._reso == 9 + assert ts._reso == NpyDatetimeUnit.NPY_FR_us.value def test_non_nano_fields(self, dt64, ts): alt = Timestamp(dt64) @@ -830,6 +830,12 @@ def test_pickle(self, ts): assert rt._reso == ts._reso assert rt == ts + def test_normalize(self, dt64, ts): + alt = Timestamp(dt64) + result = ts.normalize() + assert result._reso == ts._reso + assert result == alt.normalize() + def test_asm8(self, dt64, ts): rt = ts.asm8 assert rt == dt64
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47316
2022-06-12T03:13:22Z
2022-06-13T18:54:12Z
2022-06-13T18:54:12Z
2022-06-13T19:25:56Z
ENH: Timestamp +- timedeltalike scalar support non-nano
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ec8478f3fc82a..ddf8813c9f971 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -370,9 +370,6 @@ cdef class _Timestamp(ABCTimestamp): cdef: int64_t nanos = 0 - if isinstance(self, _Timestamp) and self._reso != NPY_FR_ns: - raise NotImplementedError(self._reso) - if is_any_td_scalar(other): if is_timedelta64_object(other): other_reso = get_datetime64_unit(other) @@ -390,20 +387,31 @@ cdef class _Timestamp(ABCTimestamp): # TODO: no tests get here other = ensure_td64ns(other) + # TODO: what to do with mismatched resos? # TODO: disallow round_ok nanos = delta_to_nanoseconds( other, reso=self._reso, round_ok=True ) try: - result = type(self)(self.value + nanos, tz=self.tzinfo) + new_value = self.value + nanos except OverflowError: # Use Python ints # Hit in test_tdi_add_overflow - result = type(self)(int(self.value) + int(nanos), tz=self.tzinfo) + new_value = int(self.value) + int(nanos) + + try: + result = type(self)._from_value_and_reso(new_value, reso=self._reso, tz=self.tzinfo) + except OverflowError as err: + # TODO: don't hard-code nanosecond here + raise OutOfBoundsDatetime(f"Out of bounds nanosecond timestamp: {new_value}") from err + if result is not NaT: result._set_freq(self._freq) # avoid warning in constructor return result + elif isinstance(self, _Timestamp) and self._reso != NPY_FR_ns: + raise NotImplementedError(self._reso) + elif is_integer_object(other): raise integer_op_not_supported(self) @@ -431,13 +439,16 @@ cdef class _Timestamp(ABCTimestamp): return NotImplemented def __sub__(self, other): - if isinstance(self, _Timestamp) and self._reso != NPY_FR_ns: - raise NotImplementedError(self._reso) + if other is NaT: + return NaT - if is_any_td_scalar(other) or is_integer_object(other): + elif is_any_td_scalar(other) or is_integer_object(other): neg_other = -other return self + neg_other + elif isinstance(self, _Timestamp) and self._reso != NPY_FR_ns: + raise NotImplementedError(self._reso) + elif is_array(other): if other.dtype.kind in ['i', 'u']: raise integer_op_not_supported(self) @@ -450,9 +461,6 @@ cdef class _Timestamp(ABCTimestamp): ) return NotImplemented - if other is NaT: - return NaT - # coerce if necessary if we are a Timestamp-like if (PyDateTime_Check(self) and (PyDateTime_Check(other) or is_datetime64_object(other))): diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 292c8f95ec2e6..5214223c3a656 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -853,6 +853,29 @@ def test_to_period(self, dt64, ts): alt = Timestamp(dt64) assert ts.to_period("D") == alt.to_period("D") + @pytest.mark.parametrize( + "td", [timedelta(days=4), Timedelta(days=4), np.timedelta64(4, "D")] + ) + def test_addsub_timedeltalike_non_nano(self, dt64, ts, td): + + result = ts - td + expected = Timestamp(dt64) - td + assert isinstance(result, Timestamp) + assert result._reso == ts._reso + assert result == expected + + result = ts + td + expected = Timestamp(dt64) + td + assert isinstance(result, Timestamp) + assert result._reso == ts._reso + assert result == expected + + result = td + ts + expected = td + Timestamp(dt64) + assert isinstance(result, Timestamp) + assert result._reso == ts._reso + assert result == expected + class TestAsUnit: def test_as_unit(self):
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47313
2022-06-11T18:38:13Z
2022-06-13T19:30:12Z
2022-06-13T19:30:12Z
2022-06-13T19:59:34Z
ENH: Timestamp.replace support non-nano
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index fb0c7d71ad58f..637a84998751f 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -27,7 +27,8 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, int32_t nanos=*) cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, - int32_t nanos=*) + int32_t nanos=*, + NPY_DATETIMEUNIT reso=*) cdef int64_t get_datetime64_nanos(object val) except? -1 diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 4e1fcbbcdcc61..6cbc06830471e 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -31,6 +31,7 @@ from cpython.datetime cimport ( import_datetime() from pandas._libs.tslibs.base cimport ABCTimestamp +from pandas._libs.tslibs.dtypes cimport periods_per_second from pandas._libs.tslibs.np_datetime cimport ( NPY_DATETIMEUNIT, NPY_FR_ns, @@ -40,11 +41,14 @@ from pandas._libs.tslibs.np_datetime cimport ( dtstruct_to_dt64, get_datetime64_unit, get_datetime64_value, + get_implementation_bounds, get_unit_from_dtype, npy_datetime, npy_datetimestruct, + npy_datetimestruct_to_datetime, pandas_datetime_to_datetimestruct, pydatetime_to_dt64, + pydatetime_to_dtstruct, string_to_dts, ) @@ -307,11 +311,15 @@ cdef maybe_localize_tso(_TSObject obj, tzinfo tz, NPY_DATETIMEUNIT reso): if obj.value != NPY_NAT: # check_overflows needs to run after _localize_tso check_dts_bounds(&obj.dts, reso) - check_overflows(obj) + check_overflows(obj, reso) -cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, - int32_t nanos=0): +cdef _TSObject convert_datetime_to_tsobject( + datetime ts, + tzinfo tz, + int32_t nanos=0, + NPY_DATETIMEUNIT reso=NPY_FR_ns, +): """ Convert a datetime (or Timestamp) input `ts`, along with optional timezone object `tz` to a _TSObject. @@ -327,6 +335,7 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, timezone for the timezone-aware output nanos : int32_t, default is 0 nanoseconds supplement the precision of the datetime input ts + reso : NPY_DATETIMEUNIT, default NPY_FR_ns Returns ------- @@ -334,6 +343,7 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, """ cdef: _TSObject obj = _TSObject() + int64_t pps obj.fold = ts.fold if tz is not None: @@ -342,34 +352,35 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, if ts.tzinfo is not None: # Convert the current timezone to the passed timezone ts = ts.astimezone(tz) - obj.value = pydatetime_to_dt64(ts, &obj.dts) + pydatetime_to_dtstruct(ts, &obj.dts) obj.tzinfo = ts.tzinfo elif not is_utc(tz): ts = _localize_pydatetime(ts, tz) - obj.value = pydatetime_to_dt64(ts, &obj.dts) + pydatetime_to_dtstruct(ts, &obj.dts) obj.tzinfo = ts.tzinfo else: # UTC - obj.value = pydatetime_to_dt64(ts, &obj.dts) + pydatetime_to_dtstruct(ts, &obj.dts) obj.tzinfo = tz else: - obj.value = pydatetime_to_dt64(ts, &obj.dts) + pydatetime_to_dtstruct(ts, &obj.dts) obj.tzinfo = ts.tzinfo - if obj.tzinfo is not None and not is_utc(obj.tzinfo): - offset = get_utcoffset(obj.tzinfo, ts) - obj.value -= int(offset.total_seconds() * 1e9) - if isinstance(ts, ABCTimestamp): - obj.value += <int64_t>ts.nanosecond obj.dts.ps = ts.nanosecond * 1000 if nanos: - obj.value += nanos obj.dts.ps = nanos * 1000 - check_dts_bounds(&obj.dts) - check_overflows(obj) + obj.value = npy_datetimestruct_to_datetime(reso, &obj.dts) + + if obj.tzinfo is not None and not is_utc(obj.tzinfo): + offset = get_utcoffset(obj.tzinfo, ts) + pps = periods_per_second(reso) + obj.value -= int(offset.total_seconds() * pps) + + check_dts_bounds(&obj.dts, reso) + check_overflows(obj, reso) return obj @@ -401,7 +412,7 @@ cdef _TSObject _create_tsobject_tz_using_offset(npy_datetimestruct dts, obj.tzinfo = pytz.FixedOffset(tzoffset) obj.value = tz_localize_to_utc_single(value, obj.tzinfo) if tz is None: - check_overflows(obj) + check_overflows(obj, NPY_FR_ns) return obj cdef: @@ -515,13 +526,14 @@ cdef _TSObject _convert_str_to_tsobject(object ts, tzinfo tz, str unit, return convert_datetime_to_tsobject(dt, tz) -cdef inline check_overflows(_TSObject obj): +cdef inline check_overflows(_TSObject obj, NPY_DATETIMEUNIT reso=NPY_FR_ns): """ Check that we haven't silently overflowed in timezone conversion Parameters ---------- obj : _TSObject + reso : NPY_DATETIMEUNIT, default NPY_FR_ns Returns ------- @@ -532,7 +544,12 @@ cdef inline check_overflows(_TSObject obj): OutOfBoundsDatetime """ # GH#12677 - if obj.dts.year == 1677: + cdef: + npy_datetimestruct lb, ub + + get_implementation_bounds(reso, &lb, &ub) + + if obj.dts.year == lb.year: if not (obj.value < 0): from pandas._libs.tslibs.timestamps import Timestamp fmt = (f"{obj.dts.year}-{obj.dts.month:02d}-{obj.dts.day:02d} " @@ -540,7 +557,7 @@ cdef inline check_overflows(_TSObject obj): raise OutOfBoundsDatetime( f"Converting {fmt} underflows past {Timestamp.min}" ) - elif obj.dts.year == 2262: + elif obj.dts.year == ub.year: if not (obj.value > 0): from pandas._libs.tslibs.timestamps import Timestamp fmt = (f"{obj.dts.year}-{obj.dts.month:02d}-{obj.dts.day:02d} " diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index d4dbcbe2acd6e..2f775912da141 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -79,6 +79,7 @@ cdef int64_t dtstruct_to_dt64(npy_datetimestruct* dts) nogil cdef void dt64_to_dtstruct(int64_t dt64, npy_datetimestruct* out) nogil cdef int64_t pydatetime_to_dt64(datetime val, npy_datetimestruct *dts) +cdef void pydatetime_to_dtstruct(datetime dt, npy_datetimestruct *dts) cdef int64_t pydate_to_dt64(date val, npy_datetimestruct *dts) cdef void pydate_to_dtstruct(date val, npy_datetimestruct *dts) @@ -104,3 +105,6 @@ cpdef cnp.ndarray astype_overflowsafe( ) cdef bint cmp_dtstructs(npy_datetimestruct* left, npy_datetimestruct* right, int op) +cdef get_implementation_bounds( + NPY_DATETIMEUNIT reso, npy_datetimestruct *lower, npy_datetimestruct *upper +) diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index cf967509a84c0..24ba329120a51 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -167,6 +167,26 @@ class OutOfBoundsTimedelta(ValueError): pass +cdef get_implementation_bounds(NPY_DATETIMEUNIT reso, npy_datetimestruct *lower, npy_datetimestruct *upper): + if reso == NPY_FR_ns: + upper[0] = _NS_MAX_DTS + lower[0] = _NS_MIN_DTS + elif reso == NPY_FR_us: + upper[0] = _US_MAX_DTS + lower[0] = _US_MIN_DTS + elif reso == NPY_FR_ms: + upper[0] = _MS_MAX_DTS + lower[0] = _MS_MIN_DTS + elif reso == NPY_FR_s: + upper[0] = _S_MAX_DTS + lower[0] = _S_MIN_DTS + elif reso == NPY_FR_m: + upper[0] = _M_MAX_DTS + lower[0] = _M_MIN_DTS + else: + raise NotImplementedError(reso) + + cdef check_dts_bounds(npy_datetimestruct *dts, NPY_DATETIMEUNIT unit=NPY_FR_ns): """Raises OutOfBoundsDatetime if the given date is outside the range that can be represented by nanosecond-resolution 64-bit integers.""" @@ -174,23 +194,7 @@ cdef check_dts_bounds(npy_datetimestruct *dts, NPY_DATETIMEUNIT unit=NPY_FR_ns): bint error = False npy_datetimestruct cmp_upper, cmp_lower - if unit == NPY_FR_ns: - cmp_upper = _NS_MAX_DTS - cmp_lower = _NS_MIN_DTS - elif unit == NPY_FR_us: - cmp_upper = _US_MAX_DTS - cmp_lower = _US_MIN_DTS - elif unit == NPY_FR_ms: - cmp_upper = _MS_MAX_DTS - cmp_lower = _MS_MIN_DTS - elif unit == NPY_FR_s: - cmp_upper = _S_MAX_DTS - cmp_lower = _S_MIN_DTS - elif unit == NPY_FR_m: - cmp_upper = _M_MAX_DTS - cmp_lower = _M_MIN_DTS - else: - raise NotImplementedError(unit) + get_implementation_bounds(unit, &cmp_lower, &cmp_upper) if cmp_npy_datetimestruct(dts, &cmp_lower) == -1: error = True @@ -229,19 +233,23 @@ def py_td64_to_tdstruct(int64_t td64, NPY_DATETIMEUNIT unit): return tds # <- returned as a dict to python +cdef inline void pydatetime_to_dtstruct(datetime dt, npy_datetimestruct *dts): + dts.year = PyDateTime_GET_YEAR(dt) + dts.month = PyDateTime_GET_MONTH(dt) + dts.day = PyDateTime_GET_DAY(dt) + dts.hour = PyDateTime_DATE_GET_HOUR(dt) + dts.min = PyDateTime_DATE_GET_MINUTE(dt) + dts.sec = PyDateTime_DATE_GET_SECOND(dt) + dts.us = PyDateTime_DATE_GET_MICROSECOND(dt) + dts.ps = dts.as = 0 + + cdef inline int64_t pydatetime_to_dt64(datetime val, npy_datetimestruct *dts): """ Note we are assuming that the datetime object is timezone-naive. """ - dts.year = PyDateTime_GET_YEAR(val) - dts.month = PyDateTime_GET_MONTH(val) - dts.day = PyDateTime_GET_DAY(val) - dts.hour = PyDateTime_DATE_GET_HOUR(val) - dts.min = PyDateTime_DATE_GET_MINUTE(val) - dts.sec = PyDateTime_DATE_GET_SECOND(val) - dts.us = PyDateTime_DATE_GET_MICROSECOND(val) - dts.ps = dts.as = 0 + pydatetime_to_dtstruct(val, dts) return dtstruct_to_dt64(dts) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index c6bae70d04a98..afa97c32fec30 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -2156,9 +2156,6 @@ default 'raise' datetime ts_input tzinfo_type tzobj - if self._reso != NPY_FR_ns: - raise NotImplementedError(self._reso) - # set to naive if needed tzobj = self.tzinfo value = self.value @@ -2171,7 +2168,7 @@ default 'raise' value = tz_convert_from_utc_single(value, tzobj, reso=self._reso) # setup components - dt64_to_dtstruct(value, &dts) + pandas_datetime_to_datetimestruct(value, self._reso, &dts) dts.ps = self.nanosecond * 1000 # replace @@ -2218,12 +2215,16 @@ default 'raise' 'fold': fold} ts_input = datetime(**kwargs) - ts = convert_datetime_to_tsobject(ts_input, tzobj) + ts = convert_datetime_to_tsobject(ts_input, tzobj, nanos=0, reso=self._reso) + # TODO: passing nanos=dts.ps // 1000 causes a RecursionError in + # TestTimestampConstructors.test_constructor; not clear why value = ts.value + (dts.ps // 1000) if value != NPY_NAT: - check_dts_bounds(&dts) + check_dts_bounds(&dts, self._reso) - return create_timestamp_from_ts(value, dts, tzobj, self._freq, fold) + return create_timestamp_from_ts( + value, dts, tzobj, self._freq, fold, reso=self._reso + ) def to_julian_date(self) -> np.float64: """ diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index 5f07cabd51ca1..35065a3c9877c 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -19,6 +19,7 @@ iNaT, to_offset, ) +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG import pandas.util._test_decorators as td @@ -338,6 +339,16 @@ def checker(res, ts, nanos): # -------------------------------------------------------------- # Timestamp.replace + def test_replace_non_nano(self): + ts = Timestamp._from_value_and_reso( + 91514880000000000, NpyDatetimeUnit.NPY_FR_us.value, None + ) + assert ts.to_pydatetime() == datetime(4869, 12, 28) + + result = ts.replace(year=4900) + assert result._reso == ts._reso + assert result.to_pydatetime() == datetime(4900, 12, 28) + def test_replace_naive(self): # GH#14621, GH#7825 ts = Timestamp("2016-01-01 09:00:00")
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47312
2022-06-11T15:27:55Z
2022-06-13T20:04:43Z
2022-06-13T20:04:43Z
2022-06-13T20:05:57Z
TYP: plotting._matplotlib
diff --git a/pandas/_typing.py b/pandas/_typing.py index 85ed2a3b636de..a1bb119c32ba6 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -326,3 +326,6 @@ def closed(self) -> bool: # quantile interpolation QuantileInterpolation = Literal["linear", "lower", "higher", "midpoint", "nearest"] + +# plotting +PlottingOrientation = Literal["horizontal", "vertical"] diff --git a/pandas/core/generic.py b/pandas/core/generic.py index b3fb9635b4801..f32b347de32c3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5727,7 +5727,7 @@ def _check_inplace_setting(self, value) -> bool_t: return True @final - def _get_numeric_data(self): + def _get_numeric_data(self: NDFrameT) -> NDFrameT: return self._constructor(self._mgr.get_numeric_data()).__finalize__(self) @final @@ -10954,7 +10954,8 @@ def mad( data = self._get_numeric_data() if axis == 0: - demeaned = data - data.mean(axis=0) + # error: Unsupported operand types for - ("NDFrame" and "float") + demeaned = data - data.mean(axis=0) # type: ignore[operator] else: demeaned = data.sub(data.mean(axis=1), axis=0) return np.abs(demeaned).mean(axis=axis, skipna=skipna) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 929ddb52aea6d..bc39d1f619f49 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1879,11 +1879,11 @@ def _get_plot_backend(backend: str | None = None): ----- Modifies `_backends` with imported backend as a side effect. """ - backend = backend or get_option("plotting.backend") + backend_str: str = backend or get_option("plotting.backend") - if backend in _backends: - return _backends[backend] + if backend_str in _backends: + return _backends[backend_str] - module = _load_backend(backend) - _backends[backend] = module + module = _load_backend(backend_str) + _backends[backend_str] = module return module diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index f82889a304dd2..a49b035b1aaf1 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -2,6 +2,7 @@ from typing import ( TYPE_CHECKING, + Literal, NamedTuple, ) import warnings @@ -34,7 +35,10 @@ class BoxPlot(LinePlot): - _kind = "box" + @property + def _kind(self) -> Literal["box"]: + return "box" + _layout_type = "horizontal" _valid_return_types = (None, "axes", "dict", "both") diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 19f726009f646..31f014d25d67d 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -574,6 +574,8 @@ def _daily_finder(vmin, vmax, freq: BaseOffset): Period(ordinal=int(vmin), freq=freq), Period(ordinal=int(vmax), freq=freq), ) + assert isinstance(vmin, Period) + assert isinstance(vmax, Period) span = vmax.ordinal - vmin.ordinal + 1 dates_ = period_range(start=vmin, end=vmax, freq=freq) # Initialize the output @@ -1073,7 +1075,9 @@ def __call__(self, x, pos=0) -> str: fmt = self.formatdict.pop(x, "") if isinstance(fmt, np.bytes_): fmt = fmt.decode("utf-8") - return Period(ordinal=int(x), freq=self.freq).strftime(fmt) + period = Period(ordinal=int(x), freq=self.freq) + assert isinstance(period, Period) + return period.strftime(fmt) class TimeSeries_TimedeltaFormatter(Formatter): diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 5fceb14b9d1cc..3641cd7213fec 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1,9 +1,14 @@ from __future__ import annotations +from abc import ( + ABC, + abstractmethod, +) from typing import ( TYPE_CHECKING, Hashable, Iterable, + Literal, Sequence, ) import warnings @@ -11,7 +16,10 @@ from matplotlib.artist import Artist import numpy as np -from pandas._typing import IndexLabel +from pandas._typing import ( + IndexLabel, + PlottingOrientation, +) from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -78,7 +86,7 @@ def _color_in_style(style: str) -> bool: return not set(BASE_COLORS).isdisjoint(style) -class MPLPlot: +class MPLPlot(ABC): """ Base class for assembling a pandas plot using matplotlib @@ -89,13 +97,17 @@ class MPLPlot: """ @property - def _kind(self): + @abstractmethod + def _kind(self) -> str: """Specify kind str. Must be overridden in child class""" raise NotImplementedError _layout_type = "vertical" _default_rot = 0 - orientation: str | None = None + + @property + def orientation(self) -> str | None: + return None axes: np.ndarray # of Axes objects @@ -843,7 +855,9 @@ def _get_xticks(self, convert_period: bool = False): @classmethod @register_pandas_matplotlib_converters - def _plot(cls, ax: Axes, x, y, style=None, is_errorbar: bool = False, **kwds): + def _plot( + cls, ax: Axes, x, y: np.ndarray, style=None, is_errorbar: bool = False, **kwds + ): mask = isna(y) if mask.any(): y = np.ma.array(y) @@ -1101,7 +1115,7 @@ def _get_axes_layout(self) -> tuple[int, int]: return (len(y_set), len(x_set)) -class PlanePlot(MPLPlot): +class PlanePlot(MPLPlot, ABC): """ Abstract class for plotting on plane, currently scatter and hexbin. """ @@ -1159,7 +1173,9 @@ def _plot_colorbar(self, ax: Axes, **kwds): class ScatterPlot(PlanePlot): - _kind = "scatter" + @property + def _kind(self) -> Literal["scatter"]: + return "scatter" def __init__(self, data, x, y, s=None, c=None, **kwargs) -> None: if s is None: @@ -1247,7 +1263,9 @@ def _make_plot(self): class HexBinPlot(PlanePlot): - _kind = "hexbin" + @property + def _kind(self) -> Literal["hexbin"]: + return "hexbin" def __init__(self, data, x, y, C=None, **kwargs) -> None: super().__init__(data, x, y, **kwargs) @@ -1277,9 +1295,15 @@ def _make_legend(self): class LinePlot(MPLPlot): - _kind = "line" _default_rot = 0 - orientation = "vertical" + + @property + def orientation(self) -> PlottingOrientation: + return "vertical" + + @property + def _kind(self) -> Literal["line", "area", "hist", "kde", "box"]: + return "line" def __init__(self, data, **kwargs) -> None: from pandas.plotting import plot_params @@ -1363,8 +1387,7 @@ def _plot( # type: ignore[override] cls._update_stacker(ax, stacking_id, y) return lines - @classmethod - def _ts_plot(cls, ax: Axes, x, data, style=None, **kwds): + def _ts_plot(self, ax: Axes, x, data, style=None, **kwds): # accept x to be consistent with normal plot func, # x is not passed to tsplot as it uses data.index as x coordinate # column_num must be in kwds for stacking purpose @@ -1377,9 +1400,9 @@ def _ts_plot(cls, ax: Axes, x, data, style=None, **kwds): decorate_axes(ax.left_ax, freq, kwds) if hasattr(ax, "right_ax"): decorate_axes(ax.right_ax, freq, kwds) - ax._plot_data.append((data, cls._kind, kwds)) + ax._plot_data.append((data, self._kind, kwds)) - lines = cls._plot(ax, data.index, data.values, style=style, **kwds) + lines = self._plot(ax, data.index, data.values, style=style, **kwds) # set date formatter, locators and rescale limits format_dateaxis(ax, ax.freq, data.index) return lines @@ -1471,7 +1494,9 @@ def get_label(i): class AreaPlot(LinePlot): - _kind = "area" + @property + def _kind(self) -> Literal["area"]: + return "area" def __init__(self, data, **kwargs) -> None: kwargs.setdefault("stacked", True) @@ -1544,9 +1569,15 @@ def _post_plot_logic(self, ax: Axes, data): class BarPlot(MPLPlot): - _kind = "bar" + @property + def _kind(self) -> Literal["bar", "barh"]: + return "bar" + _default_rot = 90 - orientation = "vertical" + + @property + def orientation(self) -> PlottingOrientation: + return "vertical" def __init__(self, data, **kwargs) -> None: # we have to treat a series differently than a @@ -1698,9 +1729,15 @@ def _decorate_ticks(self, ax: Axes, name, ticklabels, start_edge, end_edge): class BarhPlot(BarPlot): - _kind = "barh" + @property + def _kind(self) -> Literal["barh"]: + return "barh" + _default_rot = 0 - orientation = "horizontal" + + @property + def orientation(self) -> Literal["horizontal"]: + return "horizontal" @property def _start_base(self): @@ -1727,7 +1764,10 @@ def _decorate_ticks(self, ax: Axes, name, ticklabels, start_edge, end_edge): class PiePlot(MPLPlot): - _kind = "pie" + @property + def _kind(self) -> Literal["pie"]: + return "pie" + _layout_type = "horizontal" def __init__(self, data, kind=None, **kwargs) -> None: diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index 3be168fe159cf..77496cf049f3d 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -1,9 +1,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, + Literal, +) import numpy as np +from pandas._typing import PlottingOrientation + from pandas.core.dtypes.common import ( is_integer, is_list_like, @@ -40,7 +45,9 @@ class HistPlot(LinePlot): - _kind = "hist" + @property + def _kind(self) -> Literal["hist", "kde"]: + return "hist" def __init__(self, data, bins=10, bottom=0, **kwargs) -> None: self.bins = bins # use mpl default @@ -64,8 +71,8 @@ def _args_adjust(self): def _calculate_bins(self, data: DataFrame) -> np.ndarray: """Calculate bins given data""" - values = data._convert(datetime=True)._get_numeric_data() - values = np.ravel(values) + nd_values = data._convert(datetime=True)._get_numeric_data() + values = np.ravel(nd_values) values = values[~isna(values)] hist, bins = np.histogram( @@ -159,7 +166,7 @@ def _post_plot_logic(self, ax: Axes, data): ax.set_ylabel("Frequency") @property - def orientation(self): + def orientation(self) -> PlottingOrientation: if self.kwds.get("orientation", None) == "horizontal": return "horizontal" else: @@ -167,8 +174,13 @@ def orientation(self): class KdePlot(HistPlot): - _kind = "kde" - orientation = "vertical" + @property + def _kind(self) -> Literal["kde"]: + return "kde" + + @property + def orientation(self) -> Literal["vertical"]: + return "vertical" def __init__(self, data, bw_method=None, ind=None, **kwargs) -> None: MPLPlot.__init__(self, data, **kwargs) diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 597c0dafa8cab..9e459b82fec97 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -143,8 +143,8 @@ def _get_colors_from_colormap( num_colors: int, ) -> list[Color]: """Get colors from colormap.""" - colormap = _get_cmap_instance(colormap) - return [colormap(num) for num in np.linspace(0, 1, num=num_colors)] + cmap = _get_cmap_instance(colormap) + return [cmap(num) for num in np.linspace(0, 1, num=num_colors)] def _get_cmap_instance(colormap: str | Colormap) -> Colormap: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 303266ae410de..ca6cccb0f98eb 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -2,6 +2,7 @@ from __future__ import annotations +from datetime import timedelta import functools from typing import ( TYPE_CHECKING, @@ -185,11 +186,10 @@ def _get_ax_freq(ax: Axes): return ax_freq -def _get_period_alias(freq) -> str | None: +def _get_period_alias(freq: timedelta | BaseOffset | str) -> str | None: freqstr = to_offset(freq).rule_code - freq = get_period_alias(freqstr) - return freq + return get_period_alias(freqstr) def _get_freq(ax: Axes, series: Series): @@ -235,7 +235,9 @@ def use_dynamic_x(ax: Axes, data: DataFrame | Series) -> bool: x = data.index if base <= FreqGroup.FR_DAY.value: return x[:1].is_normalized - return Period(x[0], freq_str).to_timestamp().tz_localize(x.tz) == x[0] + period = Period(x[0], freq_str) + assert isinstance(period, Period) + return period.to_timestamp().tz_localize(x.tz) == x[0] return True diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index bfbf77e85afd3..94357e5002ffd 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -83,7 +83,11 @@ def table( return table -def _get_layout(nplots: int, layout=None, layout_type: str = "box") -> tuple[int, int]: +def _get_layout( + nplots: int, + layout: tuple[int, int] | None = None, + layout_type: str = "box", +) -> tuple[int, int]: if layout is not None: if not isinstance(layout, (tuple, list)) or len(layout) != 2: raise ValueError("Layout must be a tuple of (rows, columns)") diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index b26376461b901..bcbaa5c90f845 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -112,14 +112,6 @@ "pandas/io/sql.py", "pandas/io/stata.py", "pandas/io/xml.py", - "pandas/plotting/_core.py", - "pandas/plotting/_matplotlib/converter.py", - "pandas/plotting/_matplotlib/core.py", - "pandas/plotting/_matplotlib/hist.py", - "pandas/plotting/_matplotlib/misc.py", - "pandas/plotting/_matplotlib/style.py", - "pandas/plotting/_matplotlib/timeseries.py", - "pandas/plotting/_matplotlib/tools.py", "pandas/tseries/frequencies.py", ], }
The two main changes are 1) consistently using `property` and 2) checking whether `Period()` returns `NaT`.
https://api.github.com/repos/pandas-dev/pandas/pulls/47311
2022-06-11T14:27:02Z
2022-06-14T02:07:26Z
2022-06-14T02:07:26Z
2022-09-21T15:29:53Z
CI: Fix code-checks.yml name
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml index 85d8bedb95708..96088547634c5 100644 --- a/.github/workflows/code-checks.yml +++ b/.github/workflows/code-checks.yml @@ -58,7 +58,7 @@ jobs: path: ~/conda_pkgs_dir key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }} - - Name: Set up Conda + - name: Set up Conda uses: ./.github/actions/setup-conda - name: Build Pandas diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 5f108c26d239a..4227d43c459d0 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -162,9 +162,7 @@ def _groupby_and_merge(by, left: DataFrame, right: DataFrame, merge_pieces): lcols = lhs.columns.tolist() cols = lcols + [r for r in right.columns if r not in set(lcols)] merged = lhs.reindex(columns=cols) - # error: Incompatible types in assignment (expression has type - # "range", variable has type "Index") - merged.index = range(len(merged)) # type: ignore[assignment] + merged.index = range(len(merged)) pieces.append(merged) continue
xref https://github.com/pandas-dev/pandas/pull/47293
https://api.github.com/repos/pandas-dev/pandas/pulls/47309
2022-06-11T02:54:26Z
2022-06-11T05:25:05Z
2022-06-11T05:25:04Z
2022-06-11T05:25:07Z
TYP: Expanding.__init__
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 7f9dfece959de..d1a8b70b34462 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -127,7 +127,7 @@ def __init__( self, obj: NDFrame, min_periods: int = 1, - center=None, + center: bool | None = None, axis: Axis = 0, method: str = "single", selection=None, diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 4d506fbf896b6..b45f43adbe952 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -122,7 +122,7 @@ def __init__( obj: NDFrame, window=None, min_periods: int | None = None, - center: bool = False, + center: bool | None = False, win_type: str | None = None, axis: Axis = 0, on: str | Index | None = None, diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index ab1782af51260..b43c6a109adbf 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -85,7 +85,6 @@ "pandas/core/util/hashing.py", "pandas/core/util/numba_.py", "pandas/core/window/ewm.py", - "pandas/core/window/expanding.py", "pandas/core/window/rolling.py", "pandas/io/common.py", "pandas/io/excel/_base.py",
null
https://api.github.com/repos/pandas-dev/pandas/pulls/47308
2022-06-11T00:58:17Z
2022-06-12T17:38:40Z
2022-06-12T17:38:40Z
2022-09-21T15:29:54Z
ENH: DTA to_pydatetime, time, timetz, date, iter support non-nano
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index f1ebe9dd6348f..f29e6a2d0d9ea 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -3115,7 +3115,7 @@ cdef class FY5253Quarter(FY5253Mixin): for qlen in qtr_lens: if qlen * 7 <= tdelta.days: num_qtrs += 1 - tdelta -= Timedelta(days=qlen * 7) + tdelta -= (<_Timedelta>Timedelta(days=qlen * 7))._as_reso(norm._reso) else: break else: diff --git a/pandas/_libs/tslibs/vectorized.pyi b/pandas/_libs/tslibs/vectorized.pyi index b0c7644e892d2..7eb4695b9ca2c 100644 --- a/pandas/_libs/tslibs/vectorized.pyi +++ b/pandas/_libs/tslibs/vectorized.pyi @@ -37,6 +37,7 @@ def ints_to_pydatetime( freq: BaseOffset | None = ..., fold: bool = ..., box: str = ..., + reso: int = ..., # NPY_DATETIMEUNIT ) -> npt.NDArray[np.object_]: ... def tz_convert_from_utc( stamps: npt.NDArray[np.int64], diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx index 75efe6d4113cf..e5b0ba3f4dd80 100644 --- a/pandas/_libs/tslibs/vectorized.pyx +++ b/pandas/_libs/tslibs/vectorized.pyx @@ -100,7 +100,8 @@ def ints_to_pydatetime( tzinfo tz=None, BaseOffset freq=None, bint fold=False, - str box="datetime" + str box="datetime", + NPY_DATETIMEUNIT reso=NPY_FR_ns, ) -> np.ndarray: # stamps is int64, arbitrary ndim """ @@ -126,12 +127,14 @@ def ints_to_pydatetime( * If time, convert to datetime.time * If Timestamp, convert to pandas.Timestamp + reso : NPY_DATETIMEUNIT, default NPY_FR_ns + Returns ------- ndarray[object] of type specified by box """ cdef: - Localizer info = Localizer(tz, reso=NPY_FR_ns) + Localizer info = Localizer(tz, reso=reso) int64_t utc_val, local_val Py_ssize_t i, n = stamps.size Py_ssize_t pos = -1 # unused, avoid not-initialized warning @@ -179,10 +182,12 @@ def ints_to_pydatetime( # find right representation of dst etc in pytz timezone new_tz = tz._tzinfos[tz._transition_info[pos]] - dt64_to_dtstruct(local_val, &dts) + pandas_datetime_to_datetimestruct(local_val, reso, &dts) if use_ts: - res_val = create_timestamp_from_ts(utc_val, dts, new_tz, freq, fold) + res_val = create_timestamp_from_ts( + utc_val, dts, new_tz, freq, fold, reso=reso + ) elif use_pydt: res_val = datetime( dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us, diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 1dfb070e29c30..b9388c8047df9 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -424,17 +424,18 @@ def astype(self, dtype, copy: bool = True): if is_object_dtype(dtype): if self.dtype.kind == "M": + self = cast("DatetimeArray", self) # *much* faster than self._box_values # for e.g. test_get_loc_tuple_monotonic_above_size_cutoff - i8data = self.asi8.ravel() + i8data = self.asi8 converted = ints_to_pydatetime( i8data, - # error: "DatetimeLikeArrayMixin" has no attribute "tz" - tz=self.tz, # type: ignore[attr-defined] + tz=self.tz, freq=self.freq, box="timestamp", + reso=self._reso, ) - return converted.reshape(self.shape) + return converted elif self.dtype.kind == "m": return ints_to_pytimedelta(self._ndarray, box=True) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index d297d3e9f8e4e..18133d7cf25ea 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -653,7 +653,11 @@ def __iter__(self): start_i = i * chunksize end_i = min((i + 1) * chunksize, length) converted = ints_to_pydatetime( - data[start_i:end_i], tz=self.tz, freq=self.freq, box="timestamp" + data[start_i:end_i], + tz=self.tz, + freq=self.freq, + box="timestamp", + reso=self._reso, ) yield from converted @@ -1044,7 +1048,7 @@ def to_pydatetime(self) -> npt.NDArray[np.object_]: ------- datetimes : ndarray[object] """ - return ints_to_pydatetime(self.asi8, tz=self.tz) + return ints_to_pydatetime(self.asi8, tz=self.tz, reso=self._reso) def normalize(self) -> DatetimeArray: """ @@ -1301,7 +1305,7 @@ def time(self) -> npt.NDArray[np.object_]: # keeping their timezone and not using UTC timestamps = self._local_timestamps() - return ints_to_pydatetime(timestamps, box="time") + return ints_to_pydatetime(timestamps, box="time", reso=self._reso) @property def timetz(self) -> npt.NDArray[np.object_]: @@ -1311,7 +1315,7 @@ def timetz(self) -> npt.NDArray[np.object_]: The time part of the Timestamps. """ - return ints_to_pydatetime(self.asi8, self.tz, box="time") + return ints_to_pydatetime(self.asi8, self.tz, box="time", reso=self._reso) @property def date(self) -> npt.NDArray[np.object_]: @@ -1326,7 +1330,7 @@ def date(self) -> npt.NDArray[np.object_]: # keeping their timezone and not using UTC timestamps = self._local_timestamps() - return ints_to_pydatetime(timestamps, box="date") + return ints_to_pydatetime(timestamps, box="date", reso=self._reso) def isocalendar(self) -> DataFrame: """ diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index d4f8e5b76a7c5..d82e865b069aa 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -126,6 +126,35 @@ def test_to_period(self, dta_dti): tm.assert_extension_array_equal(result, expected) + def test_iter(self, dta): + res = next(iter(dta)) + expected = dta[0] + + assert type(res) is pd.Timestamp + assert res.value == expected.value + assert res._reso == expected._reso + assert res == expected + + def test_astype_object(self, dta): + result = dta.astype(object) + assert all(x._reso == dta._reso for x in result) + assert all(x == y for x, y in zip(result, dta)) + + def test_to_pydatetime(self, dta_dti): + dta, dti = dta_dti + + result = dta.to_pydatetime() + expected = dti.to_pydatetime() + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("meth", ["time", "timetz", "date"]) + def test_time_date(self, dta_dti, meth): + dta, dti = dta_dti + + result = getattr(dta, meth) + expected = getattr(dti, meth) + tm.assert_numpy_array_equal(result, expected) + class TestDatetimeArrayComparisons: # TODO: merge this into tests/arithmetic/test_datetime64 once it is
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47307
2022-06-10T23:33:21Z
2022-06-15T18:47:38Z
2022-06-15T18:47:38Z
2022-06-15T21:22:49Z
TST: GH39126 Test barh plot with string and integer at the same column
diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 9c7996adfed38..ca82c37b8a8b0 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -461,6 +461,21 @@ def test_bar_plot(self): for a, b in zip(plot_bar.get_xticklabels(), expected) ) + def test_barh_plot_labels_mixed_integer_string(self): + # GH39126 + # Test barh plot with string and integer at the same column + from matplotlib.text import Text + + df = DataFrame([{"word": 1, "value": 0}, {"word": "knowledg", "value": 2}]) + plot_barh = df.plot.barh(x="word", legend=None) + expected_yticklabels = [Text(0, 0, "1"), Text(0, 1, "knowledg")] + assert all( + actual.get_text() == expected.get_text() + for actual, expected in zip( + plot_barh.get_yticklabels(), expected_yticklabels + ) + ) + def test_has_externally_shared_axis_x_axis(self): # GH33819 # Test _has_externally_shared_axis() works for x-axis
- [x] closes #39126 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/47306
2022-06-10T22:09:59Z
2022-06-10T23:43:36Z
2022-06-10T23:43:35Z
2022-06-10T23:43:48Z
TYP: Series.quantile
diff --git a/pandas/_typing.py b/pandas/_typing.py index a85820a403fde..85ed2a3b636de 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -323,3 +323,6 @@ def closed(self) -> bool: # sort_index SortKind = Literal["quicksort", "mergesort", "heapsort", "stable"] NaPosition = Literal["first", "last"] + +# quantile interpolation +QuantileInterpolation = Literal["linear", "lower", "higher", "midpoint", "nearest"] diff --git a/pandas/core/common.py b/pandas/core/common.py index 7225b26a910dd..707201153e44a 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -125,11 +125,11 @@ def is_bool_indexer(key: Any) -> bool: is_array_like(key) and is_extension_array_dtype(key.dtype) ): if key.dtype == np.object_: - key = np.asarray(key) + key_array = np.asarray(key) - if not lib.is_bool_array(key): + if not lib.is_bool_array(key_array): na_msg = "Cannot mask with non-boolean array containing NA / NaN values" - if lib.infer_dtype(key) == "boolean" and isna(key).any(): + if lib.infer_dtype(key_array) == "boolean" and isna(key_array).any(): # Don't raise on e.g. ["A", "B", np.nan], see # test_loc_getitem_list_of_labels_categoricalindex_with_na raise ValueError(na_msg) @@ -508,18 +508,14 @@ def get_rename_function(mapper): Returns a function that will map names/labels, dependent if mapper is a dict, Series or just a function. """ - if isinstance(mapper, (abc.Mapping, ABCSeries)): - def f(x): - if x in mapper: - return mapper[x] - else: - return x - - else: - f = mapper + def f(x): + if x in mapper: + return mapper[x] + else: + return x - return f + return f if isinstance(mapper, (abc.Mapping, ABCSeries)) else mapper def convert_to_list_like( diff --git a/pandas/core/series.py b/pandas/core/series.py index 6ef024f13fbb1..c2260afb2438e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -33,6 +33,7 @@ from pandas._libs.lib import no_default from pandas._typing import ( AggFuncType, + AnyArrayLike, ArrayLike, Axis, Dtype, @@ -42,6 +43,7 @@ IndexKeyFunc, Level, NaPosition, + QuantileInterpolation, Renamer, SingleManager, SortKind, @@ -2478,7 +2480,33 @@ def round(self, decimals=0, *args, **kwargs) -> Series: return result - def quantile(self, q=0.5, interpolation="linear"): + @overload + def quantile( + self, q: float = ..., interpolation: QuantileInterpolation = ... + ) -> float: + ... + + @overload + def quantile( + self, + q: Sequence[float] | AnyArrayLike, + interpolation: QuantileInterpolation = ..., + ) -> Series: + ... + + @overload + def quantile( + self, + q: float | Sequence[float] | AnyArrayLike = ..., + interpolation: QuantileInterpolation = ..., + ) -> float | Series: + ... + + def quantile( + self, + q: float | Sequence[float] | AnyArrayLike = 0.5, + interpolation: QuantileInterpolation = "linear", + ) -> float | Series: """ Return value at the given quantile. diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 24646da9162b0..24669e84443a6 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -25,6 +25,7 @@ FilePath, IndexLabel, Level, + QuantileInterpolation, Scalar, WriteBuffer, ) @@ -3467,7 +3468,7 @@ def highlight_quantile( axis: Axis | None = 0, q_left: float = 0.0, q_right: float = 1.0, - interpolation: str = "linear", + interpolation: QuantileInterpolation = "linear", inclusive: str = "both", props: str | None = None, ) -> Styler: @@ -3539,13 +3540,17 @@ def highlight_quantile( # after quantile is found along axis, e.g. along rows, # applying the calculated quantile to alternate axis, e.g. to each column - kwargs = {"q": [q_left, q_right], "interpolation": interpolation} + quantiles = [q_left, q_right] if axis is None: - q = Series(data.to_numpy().ravel()).quantile(**kwargs) + q = Series(data.to_numpy().ravel()).quantile( + q=quantiles, interpolation=interpolation + ) axis_apply: int | None = None else: axis = self.data._get_axis_number(axis) - q = data.quantile(axis=axis, numeric_only=False, **kwargs) + q = data.quantile( + axis=axis, numeric_only=False, q=quantiles, interpolation=interpolation + ) axis_apply = 1 - axis if props is None: diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index ab1782af51260..248e4d1c13f23 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -35,10 +35,8 @@ "pandas/core/arrays/string_.py", "pandas/core/arrays/string_arrow.py", "pandas/core/arrays/timedeltas.py", - "pandas/core/common.py", "pandas/core/computation/align.py", "pandas/core/construction.py", - "pandas/core/describe.py", "pandas/core/dtypes/cast.py", "pandas/core/dtypes/common.py", "pandas/core/dtypes/concat.py",
null
https://api.github.com/repos/pandas-dev/pandas/pulls/47304
2022-06-10T13:45:35Z
2022-06-13T23:58:15Z
2022-06-13T23:58:15Z
2022-09-21T15:29:54Z
ENH/TST: ArrowExtenstionArray.reshape raises NotImplementedError
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 66bb12db277fc..1f35013075751 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -264,6 +264,12 @@ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]: return indices.values, uniques + def reshape(self, *args, **kwargs): + raise NotImplementedError( + f"{type(self)} does not support reshape " + f"as backed by a 1D pyarrow.ChunkedArray." + ) + def take( self, indices: TakeIndexer, diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 4047c0db1fee4..03616267c3f86 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -99,6 +99,10 @@ def na_value(): return pd.NA +class TestBaseCasting(base.BaseCastingTests): + pass + + class TestConstructors(base.BaseConstructorsTests): @pytest.mark.xfail( reason=( @@ -111,6 +115,20 @@ def test_from_dtype(self, data): super().test_from_dtype(data) +@pytest.mark.xfail( + raises=NotImplementedError, reason="pyarrow.ChunkedArray backing is 1D." +) +class TestDim2Compat(base.Dim2CompatTests): + pass + + +@pytest.mark.xfail( + raises=NotImplementedError, reason="pyarrow.ChunkedArray backing is 1D." +) +class TestNDArrayBacked2D(base.NDArrayBacked2DTests): + pass + + class TestGetitemTests(base.BaseGetitemTests): @pytest.mark.xfail( reason=( @@ -179,6 +197,10 @@ def test_loc_iloc_frame_single_dtype(self, request, using_array_manager, data): super().test_loc_iloc_frame_single_dtype(data) +class TestBaseIndex(base.BaseIndexTests): + pass + + def test_arrowdtype_construct_from_string_type_with_parameters(): with pytest.raises(NotImplementedError, match="Passing pyarrow type"): ArrowDtype.construct_from_string("timestamp[s][pyarrow]")
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Since the backing chunked array is always 1D and not reshapable to 2D with native pyarrow methods, raising a `NotImplementedError` for now. Possible to roll our own reshape possibly in the future.
https://api.github.com/repos/pandas-dev/pandas/pulls/47302
2022-06-10T05:43:17Z
2022-06-10T23:10:15Z
2022-06-10T23:10:15Z
2022-06-10T23:38:40Z
TYP: StorageExtensionDtype.na_values
diff --git a/pandas/core/arrays/arrow/dtype.py b/pandas/core/arrays/arrow/dtype.py index 6c932f3b94e53..af5b51a39b9c3 100644 --- a/pandas/core/arrays/arrow/dtype.py +++ b/pandas/core/arrays/arrow/dtype.py @@ -5,7 +5,6 @@ import numpy as np import pyarrow as pa -from pandas._libs import missing as libmissing from pandas._typing import DtypeObj from pandas.util._decorators import cache_readonly @@ -22,7 +21,6 @@ class ArrowDtype(StorageExtensionDtype): Modeled after BaseMaskedDtype """ - na_value = libmissing.NA _metadata = ("storage", "pyarrow_dtype") # type: ignore[assignment] def __init__(self, pyarrow_dtype: pa.DataType) -> None: diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index cffac15ef6496..f96a9ab4cfb43 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -395,7 +395,6 @@ class StorageExtensionDtype(ExtensionDtype): """ExtensionDtype that may be backed by more than one implementation.""" name: str - na_value = libmissing.NA _metadata = ("storage",) def __init__(self, storage=None) -> None: @@ -416,6 +415,10 @@ def __hash__(self) -> int: # custom __eq__ so have to override __hash__ return super().__hash__() + @property + def na_value(self) -> libmissing.NAType: + return libmissing.NA + def register_extension_dtype(cls: type_t[ExtensionDtypeT]) -> type_t[ExtensionDtypeT]: """ diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index 22d607eb958e1..09c6a51e6dff1 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -37,7 +37,6 @@ "pandas/core/computation/align.py", "pandas/core/construction.py", "pandas/core/describe.py", - "pandas/core/dtypes/base.py", "pandas/core/dtypes/cast.py", "pandas/core/dtypes/common.py", "pandas/core/dtypes/concat.py",
`ExtensionDtype.na_value` is a property: sub-classes should also use `property` and not a variable (or `ExtensionDtype` should use a variable).
https://api.github.com/repos/pandas-dev/pandas/pulls/47300
2022-06-10T01:01:16Z
2022-06-10T16:35:41Z
2022-06-10T16:35:41Z
2022-09-21T15:29:54Z
ENH: support non-nano in DTA._box_func
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index ba03de6f0b81f..fb0c7d71ad58f 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -8,7 +8,10 @@ from numpy cimport ( ndarray, ) -from pandas._libs.tslibs.np_datetime cimport npy_datetimestruct +from pandas._libs.tslibs.np_datetime cimport ( + NPY_DATETIMEUNIT, + npy_datetimestruct, +) cdef class _TSObject: @@ -31,3 +34,5 @@ cdef int64_t get_datetime64_nanos(object val) except? -1 cpdef datetime localize_pydatetime(datetime dt, tzinfo tz) cdef int64_t cast_from_unit(object ts, str unit) except? -1 cpdef (int64_t, int) precision_from_unit(str unit) + +cdef maybe_localize_tso(_TSObject obj, tzinfo tz, NPY_DATETIMEUNIT reso) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 57bccd662e1a0..4e1fcbbcdcc61 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -296,14 +296,18 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, raise TypeError(f'Cannot convert input [{ts}] of type {type(ts)} to ' f'Timestamp') + maybe_localize_tso(obj, tz, NPY_FR_ns) + return obj + + +cdef maybe_localize_tso(_TSObject obj, tzinfo tz, NPY_DATETIMEUNIT reso): if tz is not None: - _localize_tso(obj, tz) + _localize_tso(obj, tz, reso) if obj.value != NPY_NAT: # check_overflows needs to run after _localize_tso - check_dts_bounds(&obj.dts) + check_dts_bounds(&obj.dts, reso) check_overflows(obj) - return obj cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, @@ -548,7 +552,7 @@ cdef inline check_overflows(_TSObject obj): # ---------------------------------------------------------------------- # Localization -cdef inline void _localize_tso(_TSObject obj, tzinfo tz): +cdef inline void _localize_tso(_TSObject obj, tzinfo tz, NPY_DATETIMEUNIT reso): """ Given the UTC nanosecond timestamp in obj.value, find the wall-clock representation of that timestamp in the given timezone. @@ -557,6 +561,7 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz): ---------- obj : _TSObject tz : tzinfo + reso : NPY_DATETIMEUNIT Returns ------- @@ -569,7 +574,7 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz): cdef: int64_t local_val Py_ssize_t outpos = -1 - Localizer info = Localizer(tz, NPY_FR_ns) + Localizer info = Localizer(tz, reso) assert obj.tzinfo is None @@ -584,7 +589,7 @@ cdef inline void _localize_tso(_TSObject obj, tzinfo tz): # infer we went through a pytz path, will have outpos!=-1 tz = tz._tzinfos[tz._transition_info[outpos]] - dt64_to_dtstruct(local_val, &obj.dts) + pandas_datetime_to_datetimestruct(local_val, reso, &obj.dts) obj.tzinfo = tz diff --git a/pandas/_libs/tslibs/timestamps.pyi b/pandas/_libs/tslibs/timestamps.pyi index 4be9621a594dc..fd593ae453ef7 100644 --- a/pandas/_libs/tslibs/timestamps.pyi +++ b/pandas/_libs/tslibs/timestamps.pyi @@ -59,6 +59,10 @@ class Timestamp(datetime): # While Timestamp can return pd.NaT, having the constructor return # a Union with NaTType makes things awkward for users of pandas def _set_freq(self, freq: BaseOffset | None) -> None: ... + @classmethod + def _from_value_and_reso( + cls, value: int, reso: int, tz: _tzinfo | None + ) -> Timestamp: ... @property def year(self) -> int: ... @property diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 251211ea61651..c6bae70d04a98 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -51,6 +51,7 @@ from pandas._libs.tslibs.conversion cimport ( _TSObject, convert_datetime_to_tsobject, convert_to_tsobject, + maybe_localize_tso, ) from pandas._libs.tslibs.dtypes cimport ( npy_unit_to_abbrev, @@ -210,6 +211,23 @@ cdef class _Timestamp(ABCTimestamp): # ----------------------------------------------------------------- # Constructors + @classmethod + def _from_value_and_reso(cls, int64_t value, NPY_DATETIMEUNIT reso, tzinfo tz): + cdef: + npy_datetimestruct dts + _TSObject obj = _TSObject() + + if value == NPY_NAT: + return NaT + + obj.value = value + pandas_datetime_to_datetimestruct(value, reso, &obj.dts) + maybe_localize_tso(obj, tz, reso) + + return create_timestamp_from_ts( + value, obj.dts, tz=obj.tzinfo, freq=None, fold=obj.fold, reso=reso + ) + @classmethod def _from_dt64(cls, dt64: np.datetime64): # construct a Timestamp from a np.datetime64 object, keeping the @@ -223,10 +241,7 @@ cdef class _Timestamp(ABCTimestamp): reso = get_datetime64_unit(dt64) value = get_datetime64_value(dt64) - pandas_datetime_to_datetimestruct(value, reso, &dts) - return create_timestamp_from_ts( - value, dts, tz=None, freq=None, fold=0, reso=reso - ) + return cls._from_value_and_reso(value, reso, None) # ----------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 86cda289c80e6..7657633c7215a 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -88,15 +88,16 @@ cdef class Localizer: # NB: using floordiv here is implicitly assuming we will # never see trans or deltas that are not an integer number # of seconds. + # TODO: avoid these np.array calls if reso == NPY_DATETIMEUNIT.NPY_FR_us: - trans = trans // 1_000 - deltas = deltas // 1_000 + trans = np.array(trans) // 1_000 + deltas = np.array(deltas) // 1_000 elif reso == NPY_DATETIMEUNIT.NPY_FR_ms: - trans = trans // 1_000_000 - deltas = deltas // 1_000_000 + trans = np.array(trans) // 1_000_000 + deltas = np.array(deltas) // 1_000_000 elif reso == NPY_DATETIMEUNIT.NPY_FR_s: - trans = trans // 1_000_000_000 - deltas = deltas // 1_000_000_000 + trans = np.array(trans) // 1_000_000_000 + deltas = np.array(deltas) // 1_000_000_000 else: raise NotImplementedError(reso) diff --git a/pandas/_libs/tslibs/vectorized.pyi b/pandas/_libs/tslibs/vectorized.pyi index 919457724606d..8820a17ce5996 100644 --- a/pandas/_libs/tslibs/vectorized.pyi +++ b/pandas/_libs/tslibs/vectorized.pyi @@ -37,5 +37,7 @@ def ints_to_pydatetime( box: str = ..., ) -> npt.NDArray[np.object_]: ... def tz_convert_from_utc( - stamps: npt.NDArray[np.int64], tz: tzinfo | None + stamps: npt.NDArray[np.int64], + tz: tzinfo | None, + reso: int = ..., ) -> npt.NDArray[np.int64]: ... diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx index a52823681def6..2cab55e607f15 100644 --- a/pandas/_libs/tslibs/vectorized.pyx +++ b/pandas/_libs/tslibs/vectorized.pyx @@ -43,7 +43,7 @@ from .tzconversion cimport Localizer @cython.boundscheck(False) @cython.wraparound(False) -def tz_convert_from_utc(ndarray stamps, tzinfo tz): +def tz_convert_from_utc(ndarray stamps, tzinfo tz, NPY_DATETIMEUNIT reso=NPY_FR_ns): # stamps is int64_t, arbitrary ndim """ Convert the values (in i8) from UTC to tz @@ -58,7 +58,7 @@ def tz_convert_from_utc(ndarray stamps, tzinfo tz): ndarray[int64] """ cdef: - Localizer info = Localizer(tz, reso=NPY_FR_ns) + Localizer info = Localizer(tz, reso=reso) int64_t utc_val, local_val Py_ssize_t pos, i, n = stamps.size diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index da5542feaea56..400958449d3ff 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -546,7 +546,7 @@ def _check_compatible_with(self, other, setitem: bool = False): def _box_func(self, x: np.datetime64) -> Timestamp | NaTType: # GH#42228 value = x.view("i8") - ts = Timestamp(value, tz=self.tz) + ts = Timestamp._from_value_and_reso(value, reso=self._reso, tz=self.tz) # Non-overlapping identity check (left operand type: "Timestamp", # right operand type: "NaTType") if ts is not NaT: # type: ignore[comparison-overlap] @@ -775,7 +775,7 @@ def _local_timestamps(self) -> npt.NDArray[np.int64]: if self.tz is None or timezones.is_utc(self.tz): # Avoid the copy that would be made in tzconversion return self.asi8 - return tz_convert_from_utc(self.asi8, self.tz) + return tz_convert_from_utc(self.asi8, self.tz, reso=self._reso) def tz_convert(self, tz) -> DatetimeArray: """ diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 14d33ee52aae2..03703dfd2eb28 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -4,6 +4,9 @@ import numpy as np import pytest +from pandas._libs.tslibs import tz_compare +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit + from pandas.core.dtypes.dtypes import DatetimeTZDtype import pandas as pd @@ -20,16 +23,28 @@ def unit(self, request): @pytest.fixture def reso(self, unit): """Fixture returning datetime resolution for a given time unit""" - # TODO: avoid hard-coding - return {"s": 7, "ms": 8, "us": 9}[unit] + return { + "s": NpyDatetimeUnit.NPY_FR_s.value, + "ms": NpyDatetimeUnit.NPY_FR_ms.value, + "us": NpyDatetimeUnit.NPY_FR_us.value, + }[unit] + + @pytest.fixture + def dtype(self, unit, tz_naive_fixture): + tz = tz_naive_fixture + if tz is None: + return np.dtype(f"datetime64[{unit}]") + else: + return DatetimeTZDtype(unit=unit, tz=tz) - @pytest.mark.xfail(reason="_box_func is not yet patched to get reso right") - def test_non_nano(self, unit, reso): + def test_non_nano(self, unit, reso, dtype): arr = np.arange(5, dtype=np.int64).view(f"M8[{unit}]") - dta = DatetimeArray._simple_new(arr, dtype=arr.dtype) + dta = DatetimeArray._simple_new(arr, dtype=dtype) - assert dta.dtype == arr.dtype + assert dta.dtype == dtype assert dta[0]._reso == reso + assert tz_compare(dta.tz, dta[0].tz) + assert (dta[0] == dta[:1]).all() @pytest.mark.filterwarnings( "ignore:weekofyear and week have been deprecated:FutureWarning" @@ -37,11 +52,19 @@ def test_non_nano(self, unit, reso): @pytest.mark.parametrize( "field", DatetimeArray._field_ops + DatetimeArray._bool_ops ) - def test_fields(self, unit, reso, field): - dti = pd.date_range("2016-01-01", periods=55, freq="D") - arr = np.asarray(dti).astype(f"M8[{unit}]") + def test_fields(self, unit, reso, field, dtype): + tz = getattr(dtype, "tz", None) + dti = pd.date_range("2016-01-01", periods=55, freq="D", tz=tz) + if tz is None: + arr = np.asarray(dti).astype(f"M8[{unit}]") + else: + arr = np.asarray(dti.tz_convert("UTC").tz_localize(None)).astype( + f"M8[{unit}]" + ) - dta = DatetimeArray._simple_new(arr, dtype=arr.dtype) + dta = DatetimeArray._simple_new(arr, dtype=dtype) + + # FIXME: assert (dti == dta).all() res = getattr(dta, field) expected = getattr(dti._data, field) diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 108d58bcc251d..89e5ce2241e42 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -802,10 +802,12 @@ def test_comparison(self, dt64, ts): def test_cmp_cross_reso(self): # numpy gets this wrong because of silent overflow - dt64 = np.datetime64(106752, "D") # won't fit in M8[ns] + dt64 = np.datetime64(9223372800, "s") # won't fit in M8[ns] ts = Timestamp._from_dt64(dt64) - other = Timestamp(dt64 - 1) + # subtracting 3600*24 gives a datetime64 that _can_ fit inside the + # nanosecond implementation bounds. + other = Timestamp(dt64 - 3600 * 24) assert other < ts assert other.asm8 > ts.asm8 # <- numpy gets this wrong assert ts > other
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47299
2022-06-09T23:36:47Z
2022-06-10T17:00:34Z
2022-06-10T17:00:34Z
2022-06-10T19:36:19Z
TYP: NumericDtype._standardize_dtype
diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index cdffd57df9a84..b32cbdcba1853 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -5,6 +5,7 @@ TYPE_CHECKING, Any, Callable, + Mapping, TypeVar, ) @@ -113,11 +114,11 @@ def __from_arrow__( return array_class._concat_same_type(results) @classmethod - def _str_to_dtype_mapping(cls): + def _str_to_dtype_mapping(cls) -> Mapping[str, NumericDtype]: raise AbstractMethodError(cls) @classmethod - def _standardize_dtype(cls, dtype) -> NumericDtype: + def _standardize_dtype(cls, dtype: NumericDtype | str | np.dtype) -> NumericDtype: """ Convert a string representation or a numpy dtype to NumericDtype. """ @@ -126,7 +127,7 @@ def _standardize_dtype(cls, dtype) -> NumericDtype: # https://github.com/numpy/numpy/pull/7476 dtype = dtype.lower() - if not issubclass(type(dtype), cls): + if not isinstance(dtype, NumericDtype): mapping = cls._str_to_dtype_mapping() try: dtype = mapping[str(np.dtype(dtype))] diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index f6f9bed1af065..d05de313d7f46 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -28,7 +28,6 @@ "pandas/core/arrays/datetimes.py", "pandas/core/arrays/interval.py", "pandas/core/arrays/masked.py", - "pandas/core/arrays/numeric.py", "pandas/core/arrays/period.py", "pandas/core/arrays/sparse/array.py", "pandas/core/arrays/sparse/dtype.py",
null
https://api.github.com/repos/pandas-dev/pandas/pulls/47298
2022-06-09T23:20:44Z
2022-06-23T21:54:28Z
2022-06-23T21:54:28Z
2022-09-21T15:29:50Z
BUG: StataWriterUTF8 removing some valid characters in column names (#47276)
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 1b079217f64ea..3348cab0325de 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -845,6 +845,7 @@ I/O - :meth:`to_html` now excludes the ``border`` attribute from ``<table>`` elements when ``border`` keyword is set to ``False``. - Bug in :func:`read_sas` returned ``None`` rather than an empty DataFrame for SAS7BDAT files with zero rows (:issue:`18198`) - Bug in :class:`StataWriter` where value labels were always written with default encoding (:issue:`46750`) +- Bug in :class:`StataWriterUTF8` where some valid characters were removed from variable names (:issue:`47276`) Period ^^^^^^ diff --git a/pandas/io/stata.py b/pandas/io/stata.py index b8d56172027e1..1a230f4ae4164 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -3646,12 +3646,16 @@ def _validate_variable_name(self, name: str) -> str: # High code points appear to be acceptable for c in name: if ( - ord(c) < 128 - and (c < "A" or c > "Z") - and (c < "a" or c > "z") - and (c < "0" or c > "9") - and c != "_" - ) or 128 <= ord(c) < 256: + ( + ord(c) < 128 + and (c < "A" or c > "Z") + and (c < "a" or c > "z") + and (c < "0" or c > "9") + and c != "_" + ) + or 128 <= ord(c) < 192 + or c in {"×", "÷"} + ): name = name.replace(c, "_") return name diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 377b8758c250e..f06bf0035c7dc 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -1786,11 +1786,11 @@ def test_utf8_writer(self, version): [2.0, 2, "ᴮ", ""], [3.0, 3, "ᴰ", None], ], - columns=["a", "β", "ĉ", "strls"], + columns=["Å", "β", "ĉ", "strls"], ) data["ᴐᴬᵀ"] = cat variable_labels = { - "a": "apple", + "Å": "apple", "β": "ᵈᵉᵊ", "ĉ": "ᴎტჄႲႳႴႶႺ", "strls": "Long Strings",
- [x] closes #47276 - [x] Tests added and passed - [x] All code checks passed - [x] Added an entry in `doc/source/whatsnew/v1.5.0.rst`
https://api.github.com/repos/pandas-dev/pandas/pulls/47297
2022-06-09T19:19:48Z
2022-06-10T23:12:43Z
2022-06-10T23:12:43Z
2022-06-10T23:12:50Z
BUG: respect freq=None in DTA constructor
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 1b079217f64ea..156fe0498a8b7 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -737,6 +737,7 @@ Datetimelike - Bug in :meth:`DatetimeIndex.tz_localize` localizing to UTC failing to make a copy of the underlying data (:issue:`46460`) - Bug in :meth:`DatetimeIndex.resolution` incorrectly returning "day" instead of "nanosecond" for nanosecond-resolution indexes (:issue:`46903`) - Bug in :class:`Timestamp` with an integer or float value and ``unit="Y"`` or ``unit="M"`` giving slightly-wrong results (:issue:`47266`) +- Bug in :class:`DatetimeArray` construction when passed another :class:`DatetimeArray` and ``freq=None`` incorrectly inferring the freq from the given array (:issue:`47296`) - Timedelta diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index da5542feaea56..799cd941a4e52 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -9,6 +9,7 @@ from typing import ( TYPE_CHECKING, Literal, + cast, ) import warnings @@ -256,15 +257,26 @@ class DatetimeArray(dtl.TimelikeOps, dtl.DatelikeOps): _freq = None def __init__( - self, values, dtype=DT64NS_DTYPE, freq=None, copy: bool = False + self, values, dtype=DT64NS_DTYPE, freq=lib.no_default, copy: bool = False ) -> None: values = extract_array(values, extract_numpy=True) if isinstance(values, IntegerArray): values = values.to_numpy("int64", na_value=iNaT) inferred_freq = getattr(values, "_freq", None) + explicit_none = freq is None + freq = freq if freq is not lib.no_default else None if isinstance(values, type(self)): + if explicit_none: + # don't inherit from values + pass + elif freq is None: + freq = values.freq + elif freq and values.freq: + freq = to_offset(freq) + freq, _ = dtl.validate_inferred_freq(freq, values.freq, False) + # validation dtz = getattr(dtype, "tz", None) if dtz and values.tz is None: @@ -279,14 +291,13 @@ def __init__( elif values.tz: dtype = values.dtype - if freq is None: - freq = values.freq values = values._ndarray if not isinstance(values, np.ndarray): raise ValueError( - f"Unexpected type '{type(values).__name__}'. 'values' must be " - "a DatetimeArray, ndarray, or Series or Index containing one of those." + f"Unexpected type '{type(values).__name__}'. 'values' must be a " + f"{type(self).__name__}, ndarray, or Series or Index " + "containing one of those." ) if values.ndim not in [1, 2]: raise ValueError("Only 1-dimensional input arrays are supported.") @@ -297,17 +308,12 @@ def __init__( # nanosecond UTC (or tz-naive) unix timestamps values = values.view(DT64NS_DTYPE) - if values.dtype != DT64NS_DTYPE: - raise ValueError( - "The dtype of 'values' is incorrect. Must be 'datetime64[ns]'. " - f"Got {values.dtype} instead." - ) - + _validate_dt64_dtype(values.dtype) dtype = _validate_dt64_dtype(dtype) if freq == "infer": raise ValueError( - "Frequency inference not allowed in DatetimeArray.__init__. " + f"Frequency inference not allowed in {type(self).__name__}.__init__. " "Use 'pd.array()' instead." ) @@ -315,13 +321,6 @@ def __init__( values = values.copy() if freq: freq = to_offset(freq) - if getattr(dtype, "tz", None): - # https://github.com/pandas-dev/pandas/issues/18595 - # Ensure that we have a standard timezone for pytz objects. - # Without this, things like adding an array of timedeltas and - # a tz-aware Timestamp (with a tz specific to its datetime) will - # be incorrect(ish?) for the array as a whole - dtype = DatetimeTZDtype(tz=timezones.tz_standardize(dtype.tz)) NDArrayBacked.__init__(self, values=values, dtype=dtype) self._freq = freq @@ -2394,6 +2393,16 @@ def _validate_dt64_dtype(dtype): f"Unexpected value for 'dtype': '{dtype}'. " "Must be 'datetime64[ns]' or DatetimeTZDtype'." ) + + if getattr(dtype, "tz", None): + # https://github.com/pandas-dev/pandas/issues/18595 + # Ensure that we have a standard timezone for pytz objects. + # Without this, things like adding an array of timedeltas and + # a tz-aware Timestamp (with a tz specific to its datetime) will + # be incorrect(ish?) for the array as a whole + dtype = cast(DatetimeTZDtype, dtype) + dtype = DatetimeTZDtype(tz=timezones.tz_standardize(dtype.tz)) + return dtype diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 3bbb03d88e38d..e08518a54fe6b 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -186,21 +186,22 @@ def __init__( if isinstance(values, type(self)): if explicit_none: - # dont inherit from values + # don't inherit from values pass elif freq is None: freq = values.freq elif freq and values.freq: freq = to_offset(freq) freq, _ = dtl.validate_inferred_freq(freq, values.freq, False) + values = values._ndarray if not isinstance(values, np.ndarray): - msg = ( + raise ValueError( f"Unexpected type '{type(values).__name__}'. 'values' must be a " - "TimedeltaArray, ndarray, or Series or Index containing one of those." + f"{type(self).__name__}, ndarray, or Series or Index " + "containing one of those." ) - raise ValueError(msg) if values.ndim not in [1, 2]: raise ValueError("Only 1-dimensional input arrays are supported.") @@ -214,11 +215,10 @@ def __init__( dtype = _validate_td64_dtype(dtype) if freq == "infer": - msg = ( - "Frequency inference not allowed in TimedeltaArray.__init__. " + raise ValueError( + f"Frequency inference not allowed in {type(self).__name__}.__init__. " "Use 'pd.array()' instead." ) - raise ValueError(msg) if copy: values = values.copy() diff --git a/pandas/tests/arrays/datetimes/test_constructors.py b/pandas/tests/arrays/datetimes/test_constructors.py index ed285f2389959..684b478d1de08 100644 --- a/pandas/tests/arrays/datetimes/test_constructors.py +++ b/pandas/tests/arrays/datetimes/test_constructors.py @@ -87,9 +87,8 @@ def test_non_array_raises(self): def test_bool_dtype_raises(self): arr = np.array([1, 2, 3], dtype="bool") - with pytest.raises( - ValueError, match="The dtype of 'values' is incorrect.*bool" - ): + msg = "Unexpected value for 'dtype': 'bool'. Must be" + with pytest.raises(ValueError, match=msg): DatetimeArray(arr) msg = r"dtype bool cannot be converted to datetime64\[ns\]" diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index ea34e636d890f..e971e311e7d20 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -925,6 +925,9 @@ def test_explicit_none_freq(self): result = DatetimeIndex(rng._data, freq=None) assert result.freq is None + dta = DatetimeArray(rng, freq=None) + assert dta.freq is None + def test_dti_constructor_years_only(self, tz_naive_fixture): tz = tz_naive_fixture # GH 6961 diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py index 25a0a66ada519..2a5b1be7bddbd 100644 --- a/pandas/tests/indexes/timedeltas/test_constructors.py +++ b/pandas/tests/indexes/timedeltas/test_constructors.py @@ -263,6 +263,9 @@ def test_explicit_none_freq(self): result = TimedeltaIndex(tdi._data, freq=None) assert result.freq is None + tda = TimedeltaArray(tdi, freq=None) + assert tda.freq is None + def test_from_categorical(self): tdi = timedelta_range(1, periods=5)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47296
2022-06-09T17:56:30Z
2022-06-09T22:25:17Z
2022-06-09T22:25:17Z
2022-06-09T22:29:40Z
TYP: generate_regular_range
diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py index 3909875e5660a..3bef3e59d5687 100644 --- a/pandas/core/arrays/_ranges.py +++ b/pandas/core/arrays/_ranges.py @@ -14,14 +14,15 @@ Timestamp, iNaT, ) +from pandas._typing import npt def generate_regular_range( - start: Timestamp | Timedelta, - end: Timestamp | Timedelta, - periods: int, + start: Timestamp | Timedelta | None, + end: Timestamp | Timedelta | None, + periods: int | None, freq: BaseOffset, -): +) -> npt.NDArray[np.intp]: """ Generate a range of dates or timestamps with the spans between dates described by the given `freq` DateOffset. @@ -32,7 +33,7 @@ def generate_regular_range( First point of produced date range. end : Timedelta, Timestamp or None Last point of produced date range. - periods : int + periods : int or None Number of periods in produced date range. freq : Tick Describes space between dates in produced date range. @@ -45,15 +46,15 @@ def generate_regular_range( iend = end.value if end is not None else None stride = freq.nanos - if periods is None: + if periods is None and istart is not None and iend is not None: b = istart # cannot just use e = Timestamp(end) + 1 because arange breaks when # stride is too large, see GH10887 e = b + (iend - b) // stride * stride + stride // 2 + 1 - elif istart is not None: + elif istart is not None and periods is not None: b = istart e = _generate_range_overflow_safe(b, periods, stride, side="start") - elif iend is not None: + elif iend is not None and periods is not None: e = iend + stride b = _generate_range_overflow_safe(e, periods, stride, side="end") else: diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index 22d607eb958e1..a6b5715723a24 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -11,13 +11,15 @@ [ # exclude tests "pandas/tests", + # exclude vendored files + "pandas/io/clipboard", + "pandas/util/version", # and all files that currently don't pass "pandas/_config/config.py", "pandas/core/algorithms.py", "pandas/core/apply.py", "pandas/core/array_algos/take.py", "pandas/core/arrays/_mixins.py", - "pandas/core/arrays/_ranges.py", "pandas/core/arrays/arrow/array.py", "pandas/core/arrays/base.py", "pandas/core/arrays/boolean.py",
`generate_regular_range` seems to be only called from un-annotated places: mypy doesn't know that start/end/periods can actually be None. edit: I'm not annotating the functions calling `generate_regular_range` in this PR as my aim with this PR is to simply make `pandas/core/arrays/_ranges.py` compatible with pyright.
https://api.github.com/repos/pandas-dev/pandas/pulls/47295
2022-06-09T16:01:19Z
2022-06-10T03:53:26Z
2022-06-10T03:53:26Z
2022-09-21T15:29:55Z
Use setup-conda action
diff --git a/.github/actions/setup-conda/action.yml b/.github/actions/setup-conda/action.yml index 7f5d864330db2..87a0bd2ed1715 100644 --- a/.github/actions/setup-conda/action.yml +++ b/.github/actions/setup-conda/action.yml @@ -3,6 +3,12 @@ inputs: environment-file: description: Conda environment file to use. default: environment.yml + environment-name: + description: Name to use for the Conda environment + default: test + python-version: + description: Python version to install + required: false pyarrow-version: description: If set, overrides the PyArrow version in the Conda environment to the given string. required: false @@ -21,8 +27,11 @@ runs: uses: conda-incubator/setup-miniconda@v2.1.1 with: environment-file: ${{ inputs.environment-file }} + activate-environment: ${{ inputs.environment-name }} + python-version: ${{ inputs.python-version }} channel-priority: ${{ runner.os == 'macOS' && 'flexible' || 'strict' }} channels: conda-forge - mamba-version: "0.23" + mamba-version: "0.24" use-mamba: true + use-only-tar-bz2: true condarc-file: ci/condarc.yml diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml index 50720c5ebf0e2..022c12cf6ff6c 100644 --- a/.github/workflows/asv-bot.yml +++ b/.github/workflows/asv-bot.yml @@ -41,13 +41,8 @@ jobs: # Although asv sets up its own env, deps are still needed # during discovery process - - uses: conda-incubator/setup-miniconda@v2.1.1 - with: - activate-environment: pandas-dev - channel-priority: strict - environment-file: ${{ env.ENV_FILE }} - use-only-tar-bz2: true - condarc-file: ci/condarc.yml + - name: Set up Conda + uses: ./.github/actions/setup-conda - name: Run benchmarks id: bench diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml index 9d51062754f35..85d8bedb95708 100644 --- a/.github/workflows/code-checks.yml +++ b/.github/workflows/code-checks.yml @@ -58,15 +58,8 @@ jobs: path: ~/conda_pkgs_dir key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }} - - uses: conda-incubator/setup-miniconda@v2.1.1 - with: - mamba-version: "*" - channels: conda-forge - activate-environment: pandas-dev - channel-priority: strict - environment-file: ${{ env.ENV_FILE }} - use-only-tar-bz2: true - condarc-file: ci/condarc.yml + - Name: Set up Conda + uses: ./.github/actions/setup-conda - name: Build Pandas id: build @@ -128,15 +121,8 @@ jobs: path: ~/conda_pkgs_dir key: ${{ runner.os }}-conda-${{ hashFiles('${{ env.ENV_FILE }}') }} - - uses: conda-incubator/setup-miniconda@v2.1.1 - with: - mamba-version: "*" - channels: conda-forge - activate-environment: pandas-dev - channel-priority: strict - environment-file: ${{ env.ENV_FILE }} - use-only-tar-bz2: true - condarc-file: ci/condarc.yml + - name: Set up Conda + uses: ./.github/actions/setup-conda - name: Build Pandas id: build diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 28d2ae6d26bda..061b2b361ca62 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -147,19 +147,11 @@ jobs: # xsel for clipboard tests run: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 xsel ${{ env.EXTRA_APT }} - - uses: conda-incubator/setup-miniconda@v2.1.1 + - name: Set up Conda + uses: ./.github/actions/setup-conda with: - mamba-version: "*" - channels: conda-forge - activate-environment: pandas-dev - channel-priority: flexible environment-file: ${{ env.ENV_FILE }} - use-only-tar-bz2: true - condarc-file: ci/condarc.yml - - - name: Upgrade Arrow version - run: conda install -n pandas-dev -c conda-forge --no-update-deps pyarrow=${{ matrix.pyarrow_version }} - if: ${{ matrix.pyarrow_version }} + pyarrow-version: ${{ matrix.pyarrow_version }} - name: Build Pandas uses: ./.github/actions/build_pandas diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml index 82a80d5ddf8f6..5ae2280c5069f 100644 --- a/.github/workflows/sdist.yml +++ b/.github/workflows/sdist.yml @@ -59,12 +59,12 @@ jobs: name: ${{matrix.python-version}}-sdist.gz path: dist/*.gz - - uses: conda-incubator/setup-miniconda@v2.1.1 + - name: Set up Conda + uses: ./.github/actions/setup-conda with: - activate-environment: pandas-sdist - channels: conda-forge - python-version: '${{ matrix.python-version }}' - condarc-file: ci/condarc.yml + environment-file: "" + environment-name: pandas-sdist + python-version: ${{ matrix.python-version }} - name: Install pandas from sdist run: |
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47293
2022-06-09T14:02:16Z
2022-06-10T21:39:32Z
2022-06-10T21:39:31Z
2022-06-10T21:39:53Z
Add run-tests action
diff --git a/.github/actions/run-tests/action.yml b/.github/actions/run-tests/action.yml new file mode 100644 index 0000000000000..2a7601f196ec4 --- /dev/null +++ b/.github/actions/run-tests/action.yml @@ -0,0 +1,27 @@ +name: Run tests and report results +runs: + using: composite + steps: + - name: Test + run: ci/run_tests.sh + shell: bash -el {0} + + - name: Publish test results + uses: actions/upload-artifact@v2 + with: + name: Test results + path: test-data.xml + if: failure() + + - name: Report Coverage + run: coverage report -m + shell: bash -el {0} + if: failure() + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + with: + flags: unittests + name: codecov-pandas + fail_ci_if_error: false + if: failure() diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml index 26e6c8699ca64..4c48d83b68947 100644 --- a/.github/workflows/macos-windows.yml +++ b/.github/workflows/macos-windows.yml @@ -53,18 +53,4 @@ jobs: uses: ./.github/actions/build_pandas - name: Test - run: ci/run_tests.sh - - - name: Publish test results - uses: actions/upload-artifact@v3 - with: - name: Test results - path: test-data.xml - if: failure() - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v2 - with: - flags: unittests - name: codecov-pandas - fail_ci_if_error: false + uses: ./.github/actions/run-tests diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 28d2ae6d26bda..539222d95c3dc 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -165,23 +165,6 @@ jobs: uses: ./.github/actions/build_pandas - name: Test - run: ci/run_tests.sh + uses: ./.github/actions/run-tests # TODO: Don't continue on error for PyPy continue-on-error: ${{ env.IS_PYPY == 'true' }} - - - name: Build Version - run: conda list - - - name: Publish test results - uses: actions/upload-artifact@v3 - with: - name: Test results - path: test-data.xml - if: failure() - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v2 - with: - flags: unittests - name: codecov-pandas - fail_ci_if_error: false diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 753e288f5e391..09639acafbba1 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -57,40 +57,20 @@ jobs: - name: Install dependencies shell: bash -el {0} run: | - python -m pip install --upgrade pip setuptools wheel - pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy - pip install git+https://github.com/nedbat/coveragepy.git - pip install cython python-dateutil pytz hypothesis pytest>=6.2.5 pytest-xdist pytest-cov - pip list + python3 -m pip install --upgrade pip setuptools wheel + python3 -m pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy + python3 -m pip install git+https://github.com/nedbat/coveragepy.git + python3 -m pip install cython python-dateutil pytz hypothesis pytest>=6.2.5 pytest-xdist pytest-cov pytest-asyncio>=0.17 + python3 -m pip list - name: Build Pandas run: | - python setup.py build_ext -q -j2 - python -m pip install -e . --no-build-isolation --no-use-pep517 + python3 setup.py build_ext -q -j2 + python3 -m pip install -e . --no-build-isolation --no-use-pep517 - name: Build Version run: | - python -c "import pandas; pandas.show_versions();" + python3 -c "import pandas; pandas.show_versions();" - - name: Test with pytest - shell: bash -el {0} - run: | - ci/run_tests.sh - - - name: Publish test results - uses: actions/upload-artifact@v3 - with: - name: Test results - path: test-data.xml - if: failure() - - - name: Report Coverage - run: | - coverage report -m - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v2 - with: - flags: unittests - name: codecov-pandas - fail_ci_if_error: true + - name: Test + uses: ./.github/actions/run-tests
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47292
2022-06-09T13:44:22Z
2022-06-14T16:49:17Z
2022-06-14T16:49:17Z
2022-06-14T16:49:26Z
DEPS: Sync environment.yml with CI dep files
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml index 96088547634c5..e8f54b33a92c0 100644 --- a/.github/workflows/code-checks.yml +++ b/.github/workflows/code-checks.yml @@ -157,3 +157,32 @@ jobs: - name: Build image run: docker build --pull --no-cache --tag pandas-dev-env . + + requirements-dev-text-installable: + name: Test install requirements-dev.txt + runs-on: ubuntu-latest + + concurrency: + # https://github.community/t/concurrecy-not-work-for-push/183068/7 + group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-requirements-dev-text-installable + cancel-in-progress: true + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Setup Python + id: setup_python + uses: actions/setup-python@v3 + with: + python-version: '3.8' + cache: 'pip' + cache-dependency-path: 'requirements-dev.txt' + + - name: Install requirements-dev.txt + run: pip install -r requirements-dev.txt + + - name: Check Pip Cache Hit + run: echo ${{ steps.setup_python.outputs.cache-hit }} diff --git a/.github/workflows/posix.yml b/.github/workflows/ubuntu.yml similarity index 97% rename from .github/workflows/posix.yml rename to .github/workflows/ubuntu.yml index 831bbd8bb3233..961ba57d36b94 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/ubuntu.yml @@ -1,4 +1,4 @@ -name: Posix +name: Ubuntu on: push: @@ -145,7 +145,7 @@ jobs: - name: Extra installs # xsel for clipboard tests - run: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 xsel ${{ env.EXTRA_APT }} + run: sudo apt-get update && sudo apt-get install -y xsel ${{ env.EXTRA_APT }} - name: Set up Conda uses: ./.github/actions/setup-conda diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index d17d29ef38e7f..73700c0da0d47 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -31,8 +31,7 @@ dependencies: - jinja2 - lxml - matplotlib - # TODO: uncomment after numba supports py310 - #- numba + - numba - numexpr - openpyxl - odfpy diff --git a/environment.yml b/environment.yml index 1f1583354339c..98631d8485736 100644 --- a/environment.yml +++ b/environment.yml @@ -1,21 +1,85 @@ +# Local development dependencies including docs building, website upload, ASV benchmark name: pandas-dev channels: - conda-forge dependencies: - # required - - numpy>=1.19.5 - python=3.8 - - python-dateutil>=2.8.1 + + # test dependencies + - cython=0.29.30 + - pytest>=6.0 + - pytest-cov + - pytest-xdist>=1.31 + - psutil + - pytest-asyncio>=0.17 + - boto3 + + # required dependencies + - python-dateutil + - numpy - pytz + # optional dependencies + - beautifulsoup4 + - blosc + - brotlipy + - bottleneck + - fastparquet + - fsspec + - html5lib + - hypothesis + - gcsfs + - jinja2 + - lxml + - matplotlib + - numba>=0.53.1 + - numexpr>=2.8.0 # pin for "Run checks on imported code" job + - openpyxl + - odfpy + - pandas-gbq + - psycopg2 + - pyarrow + - pymysql + - pyreadstat + - pytables + - python-snappy + - pyxlsb + - s3fs + - scipy + - sqlalchemy + - tabulate + - xarray + - xlrd + - xlsxwriter + - xlwt + - zstandard + + # downstream packages + - aiobotocore<2.0.0 # GH#44311 pinned to fix docbuild + - botocore + - cftime + - dask + - ipython + - geopandas-base + - seaborn + - scikit-learn + - statsmodels + - coverage + - pandas-datareader + - pyyaml + - py + - pytorch + + # local testing dependencies + - moto + - flask + # benchmarks - asv - # building # The compiler packages are meta-packages and install the correct compiler (activation) packages on the respective platforms. - c-compiler - cxx-compiler - - cython>=0.29.30 # code checks - black=22.3.0 @@ -32,10 +96,11 @@ dependencies: # documentation - gitpython # obtain contributors from git for whatsnew - gitdb + - natsort # DataFrame.sort_values doctest - numpydoc - pandas-dev-flaker=0.5.0 - pydata-sphinx-theme=0.8.0 - - pytest-cython + - pytest-cython # doctest - sphinx - sphinx-panels - types-python-dateutil @@ -47,77 +112,14 @@ dependencies: - nbconvert>=6.4.5 - nbsphinx - pandoc - - # Dask and its dependencies (that dont install with dask) - - dask-core - - toolz>=0.7.3 - - partd>=0.3.10 - - cloudpickle>=0.2.1 - - # web (jinja2 is also needed, but it's also an optional pandas dependency) - - markdown - - feedparser - - pyyaml - - requests - - # testing - - boto3 - - botocore>=1.11 - - hypothesis>=5.5.3 - - moto # mock S3 - - flask - - pytest>=6.0 - - pytest-cov - - pytest-xdist>=1.31 - - pytest-asyncio>=0.17 - - pytest-instafail - - # downstream tests - - seaborn - - statsmodels - - # unused (required indirectly may be?) - ipywidgets - nbformat - notebook>=6.0.3 - - # optional - - blosc - - bottleneck>=1.3.1 - ipykernel - - ipython>=7.11.1 - - jinja2 # pandas.Styler - - matplotlib>=3.3.2 # pandas.plotting, Series.plot, DataFrame.plot - - numexpr>=2.7.1 - - scipy>=1.4.1 - - numba>=0.50.1 - - # optional for io - # --------------- - # pd.read_html - - beautifulsoup4>=4.8.2 - - html5lib - - lxml - - # pd.read_excel, DataFrame.to_excel, pd.ExcelWriter, pd.ExcelFile - - openpyxl - - xlrd - - xlsxwriter - - xlwt - - odfpy - - - fastparquet>=0.4.0 # pandas.read_parquet, DataFrame.to_parquet - - pyarrow>2.0.1 # pandas.read_parquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather - - python-snappy # required by pyarrow - - pytables>=3.6.1 # pandas.read_hdf, DataFrame.to_hdf - - s3fs>=0.4.0 # file IO when using 's3://...' path - - aiobotocore<2.0.0 # GH#44311 pinned to fix docbuild - - fsspec>=0.7.4 # for generic remote file operations - - gcsfs>=0.6.0 # file IO when using 'gcs://...' path - - sqlalchemy # pandas.read_sql, DataFrame.to_sql - - xarray # DataFrame.to_xarray - - cftime # Needed for downstream xarray.CFTimeIndex test - - pyreadstat # pandas.read_spss - - tabulate>=0.8.3 # DataFrame.to_markdown - - natsort # DataFrame.sort_values + # web + - jinja2 # in optional dependencies, but documented here as needed + - markdown + - feedparser + - pyyaml + - requests diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index f1fbdafa04288..72f6a7bce4d0e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1064,12 +1064,7 @@ def checked_add_with_arr( elif arr_mask is not None: not_nan = np.logical_not(arr_mask) elif b_mask is not None: - # Argument 1 to "__call__" of "_UFunc_Nin1_Nout1" has incompatible type - # "Optional[ndarray[Any, dtype[bool_]]]"; expected - # "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[An - # y]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, - # int, float, complex, str, bytes]]]" [arg-type] - not_nan = np.logical_not(b2_mask) # type: ignore[arg-type] + not_nan = np.logical_not(b2_mask) else: not_nan = np.empty(arr.shape, dtype=bool) not_nan.fill(True) diff --git a/pandas/core/array_algos/quantile.py b/pandas/core/array_algos/quantile.py index 78e12fb3995fd..de7945a96c69e 100644 --- a/pandas/core/array_algos/quantile.py +++ b/pandas/core/array_algos/quantile.py @@ -143,10 +143,7 @@ def _nanpercentile_1d( return np.percentile( values, qs, - # error: No overload variant of "percentile" matches argument types - # "ndarray[Any, Any]", "ndarray[Any, dtype[floating[_64Bit]]]", - # "int", "Dict[str, str]" - **{np_percentile_argname: interpolation}, # type: ignore[call-overload] + **{np_percentile_argname: interpolation}, ) @@ -215,8 +212,5 @@ def _nanpercentile( values, qs, axis=1, - # error: No overload variant of "percentile" matches argument types - # "ndarray[Any, Any]", "ndarray[Any, dtype[floating[_64Bit]]]", - # "int", "Dict[str, str]" - **{np_percentile_argname: interpolation}, # type: ignore[call-overload] + **{np_percentile_argname: interpolation}, ) diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index b6e9bf1420b21..e241fc119ae02 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -265,7 +265,11 @@ def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any) return result # Determine if we should defer. - no_defer = (np.ndarray.__array_ufunc__, cls.__array_ufunc__) + # error: "Type[ndarray[Any, Any]]" has no attribute "__array_ufunc__" + no_defer = ( + np.ndarray.__array_ufunc__, # type: ignore[attr-defined] + cls.__array_ufunc__, + ) for item in inputs: higher_priority = ( diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 1f35013075751..c1380fcdbba06 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -496,7 +496,7 @@ def _indexing_key_to_indices( if isinstance(key, slice): indices = np.arange(n)[key] elif is_integer(key): - indices = np.arange(n)[[key]] # type: ignore[index] + indices = np.arange(n)[[key]] elif is_bool_dtype(key): key = np.asarray(key) if len(key) != n: diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 5f060542526d3..97dae33bc0311 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -487,7 +487,10 @@ def _generate_range( np.linspace(0, end.value - start.value, periods, dtype="int64") + start.value ) - if i8values.dtype != "i8": + # error: Non-overlapping equality check + # (left operand type: "dtype[signedinteger[Any]]", + # right operand type: "Literal['i8']") + if i8values.dtype != "i8": # type: ignore[comparison-overlap] # 2022-01-09 I (brock) am not sure if it is possible for this # to overflow and cast to e.g. f8, but if it does we need to cast i8values = i8values.astype("i8") diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index eecf1dff4dd48..69814863afefc 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -687,7 +687,21 @@ def __getitem__( if is_scalar(left) and isna(left): return self._fill_value return Interval(left, right, inclusive=self.inclusive) - if np.ndim(left) > 1: + # error: Argument 1 to "ndim" has incompatible type + # "Union[ndarray[Any, Any], ExtensionArray]"; expected + # "Union[Sequence[Sequence[Sequence[Sequence[Sequence[Any]]]]], + # Union[Union[_SupportsArray[dtype[Any]], + # Sequence[_SupportsArray[dtype[Any]]], + # Sequence[Sequence[_SupportsArray[dtype[Any]]]], + # Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]], + # Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]]]], + # Union[bool, int, float, complex, str, bytes, + # Sequence[Union[bool, int, float, complex, str, bytes]], + # Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]], + # Sequence[Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]]], + # Sequence[Sequence[Sequence[Sequence[Union[bool, int, float, + # complex, str, bytes]]]]]]]]" + if np.ndim(left) > 1: # type: ignore[arg-type] # GH#30588 multi-dimensional indexer disallowed raise ValueError("multi-dimensional indexing not allowed") return self._shallow_copy(left, right) @@ -1665,13 +1679,7 @@ def isin(self, values) -> np.ndarray: # complex128 ndarray is much more performant. left = self._combined.view("complex128") right = values._combined.view("complex128") - # Argument 1 to "in1d" has incompatible type "Union[ExtensionArray, - # ndarray[Any, Any], ndarray[Any, dtype[Any]]]"; expected - # "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[ - # dtype[Any]]], bool, int, float, complex, str, bytes, - # _NestedSequence[Union[bool, int, float, complex, str, bytes]]]" - # [arg-type] - return np.in1d(left, right) # type: ignore[arg-type] + return np.in1d(left, right) elif needs_i8_conversion(self.left.dtype) ^ needs_i8_conversion( values.left.dtype diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 3616e3512c6fe..d2c082c472e5e 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -110,7 +110,13 @@ def __init__( self, values: np.ndarray, mask: npt.NDArray[np.bool_], copy: bool = False ) -> None: # values is supposed to already be validated in the subclass - if not (isinstance(mask, np.ndarray) and mask.dtype == np.bool_): + if not ( + isinstance(mask, np.ndarray) + and + # error: Non-overlapping equality check + # (left operand type: "dtype[bool_]", right operand type: "Type[bool_]") + mask.dtype == np.bool_ # type: ignore[comparison-overlap] + ): raise TypeError( "mask should be boolean numpy array. Use " "the 'pd.array' function instead" @@ -1151,11 +1157,7 @@ def any(self, *, skipna: bool = True, **kwargs): nv.validate_any((), kwargs) values = self._data.copy() - # Argument 3 to "putmask" has incompatible type "object"; expected - # "Union[_SupportsArray[dtype[Any]], _NestedSequence[ - # _SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _Nested - # Sequence[Union[bool, int, float, complex, str, bytes]]]" [arg-type] - np.putmask(values, self._mask, self._falsey_value) # type: ignore[arg-type] + np.putmask(values, self._mask, self._falsey_value) result = values.any() if skipna: return result @@ -1231,11 +1233,7 @@ def all(self, *, skipna: bool = True, **kwargs): nv.validate_all((), kwargs) values = self._data.copy() - # Argument 3 to "putmask" has incompatible type "object"; expected - # "Union[_SupportsArray[dtype[Any]], _NestedSequence[ - # _SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _Neste - # dSequence[Union[bool, int, float, complex, str, bytes]]]" [arg-type] - np.putmask(values, self._mask, self._truthy_value) # type: ignore[arg-type] + np.putmask(values, self._mask, self._truthy_value) result = values.all() if skipna: diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 427bf50ca7424..8215abf294221 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -944,15 +944,7 @@ def __getitem__( if is_integer(key): return self._get_val_at(key) elif isinstance(key, tuple): - # Invalid index type "Tuple[Union[int, ellipsis], ...]" for - # "ndarray[Any, Any]"; expected type "Union[SupportsIndex, - # _SupportsArray[dtype[Union[bool_, integer[Any]]]], _NestedSequence[_Su - # pportsArray[dtype[Union[bool_, integer[Any]]]]], - # _NestedSequence[Union[bool, int]], Tuple[Union[SupportsIndex, - # _SupportsArray[dtype[Union[bool_, integer[Any]]]], - # _NestedSequence[_SupportsArray[dtype[Union[bool_, integer[Any]]]]], _N - # estedSequence[Union[bool, int]]], ...]]" [index] - data_slice = self.to_dense()[key] # type: ignore[index] + data_slice = self.to_dense()[key] elif isinstance(key, slice): # Avoid densifying when handling contiguous slices @@ -1192,9 +1184,7 @@ def _concat_same_type( data = np.concatenate(values) indices_arr = np.concatenate(indices) - # Argument 2 to "IntIndex" has incompatible type "ndarray[Any, - # dtype[signedinteger[_32Bit]]]"; expected "Sequence[int]" - sp_index = IntIndex(length, indices_arr) # type: ignore[arg-type] + sp_index = IntIndex(length, indices_arr) else: # when concatenating block indices, we don't claim that you'll @@ -1384,8 +1374,7 @@ def __setstate__(self, state): if isinstance(state, tuple): # Compat for pandas < 0.24.0 nd_state, (fill_value, sp_index) = state - # Need type annotation for "sparse_values" [var-annotated] - sparse_values = np.array([]) # type: ignore[var-annotated] + sparse_values = np.array([]) sparse_values.__setstate__(nd_state) self._sparse_values = sparse_values diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 8d1427976276c..7dc2c81746454 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -113,7 +113,9 @@ def astype_nansafe( ).reshape(shape) elif is_datetime64_dtype(arr.dtype): - if dtype == np.int64: + # error: Non-overlapping equality check (left + # operand type: "dtype[Any]", right operand type: "Type[signedinteger[Any]]") + if dtype == np.int64: # type: ignore[comparison-overlap] if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") return arr.view(dtype) @@ -125,7 +127,9 @@ def astype_nansafe( raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]") elif is_timedelta64_dtype(arr.dtype): - if dtype == np.int64: + # error: Non-overlapping equality check (left + # operand type: "dtype[Any]", right operand type: "Type[signedinteger[Any]]") + if dtype == np.int64: # type: ignore[comparison-overlap] if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") return arr.view(dtype) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index ed3f9ee525c9e..27cf2e5e7ea58 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -305,7 +305,7 @@ def maybe_downcast_to_dtype(result: ArrayLike, dtype: str | np.dtype) -> ArrayLi result = cast(np.ndarray, result) result = array_to_timedelta64(result) - elif dtype == "M8[ns]" and result.dtype == _dtype_obj: + elif dtype == np.dtype("M8[ns]") and result.dtype == _dtype_obj: return np.asarray(maybe_cast_to_datetime(result, dtype=dtype)) return result diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index a192337daf59b..bdbad2560b2d7 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -534,7 +534,9 @@ def is_string_or_object_np_dtype(dtype: np.dtype) -> bool: """ Faster alternative to is_string_dtype, assumes we have a np.dtype object. """ - return dtype == object or dtype.kind in "SU" + # error: Non-overlapping equality check (left operand type: + # "dtype[Any]", right operand type: "Type[object]") + return dtype == object or dtype.kind in "SU" # type: ignore[comparison-overlap] def is_string_dtype(arr_or_dtype) -> bool: diff --git a/pandas/core/exchange/buffer.py b/pandas/core/exchange/buffer.py index 098c596bff4cd..65f2ac6dabef5 100644 --- a/pandas/core/exchange/buffer.py +++ b/pandas/core/exchange/buffer.py @@ -57,7 +57,8 @@ def __dlpack__(self): Represent this structure as DLPack interface. """ if _NUMPY_HAS_DLPACK: - return self._x.__dlpack__() + # error: "ndarray[Any, Any]" has no attribute "__dlpack__" + return self._x.__dlpack__() # type: ignore[attr-defined] raise NotImplementedError("__dlpack__") def __dlpack_device__(self) -> Tuple[DlpackDeviceType, Optional[int]]: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8711d53353185..2006aba85cb24 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2481,9 +2481,7 @@ def to_records( if dtype_mapping is None: formats.append(v.dtype) elif isinstance(dtype_mapping, (type, np.dtype, str)): - # Argument 1 to "append" of "list" has incompatible type - # "Union[type, dtype[Any], str]"; expected "dtype[_SCT]" [arg-type] - formats.append(dtype_mapping) # type: ignore[arg-type] + formats.append(dtype_mapping) else: element = "row" if i < index_len else "column" msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}" diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 7f74c60c8e534..d056b4b03d904 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -171,7 +171,7 @@ def _get_cython_function( f = getattr(libgroupby, ftype) if is_numeric: return f - elif dtype == object: + elif dtype == np.dtype(object): if how in ["median", "cumprod"]: # no fused types -> no __signatures__ raise NotImplementedError( diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 01bbc424c3764..7e6233d247251 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4834,12 +4834,7 @@ def _join_non_unique( right = other._values.take(right_idx) if isinstance(join_array, np.ndarray): - # Argument 3 to "putmask" has incompatible type "Union[ExtensionArray, - # ndarray[Any, Any]]"; expected "Union[_SupportsArray[dtype[Any]], - # _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, f - # loat, complex, str, bytes, _NestedSequence[Union[bool, int, float, - # complex, str, bytes]]]" [arg-type] - np.putmask(join_array, mask, right) # type: ignore[arg-type] + np.putmask(join_array, mask, right) else: join_array._putmask(mask, right) @@ -5351,11 +5346,9 @@ def __getitem__(self, key): if result.ndim > 1: deprecate_ndim_indexing(result) if hasattr(result, "_ndarray"): - # error: Item "ndarray[Any, Any]" of "Union[ExtensionArray, - # ndarray[Any, Any]]" has no attribute "_ndarray" [union-attr] # i.e. NDArrayBackedExtensionArray # Unpack to ndarray for MPL compat - return result._ndarray # type: ignore[union-attr] + return result._ndarray return result # NB: Using _constructor._simple_new would break if MultiIndex @@ -6893,9 +6886,7 @@ def insert(self, loc: int, item) -> Index: new_values = np.insert(arr, loc, casted) else: - # No overload variant of "insert" matches argument types - # "ndarray[Any, Any]", "int", "None" [call-overload] - new_values = np.insert(arr, loc, None) # type: ignore[call-overload] + new_values = np.insert(arr, loc, None) loc = loc if loc >= 0 else loc - 1 new_values[loc] = item diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index ef0a2d5bf1b0f..101eac992e95d 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -363,9 +363,7 @@ def _validate_codes(self, level: list, code: list): """ null_mask = isna(level) if np.any(null_mask): - # Incompatible types in assignment (expression has type - # "ndarray[Any, dtype[Any]]", variable has type "List[Any]") - code = np.where(null_mask[code], -1, code) # type: ignore[assignment] + code = np.where(null_mask[code], -1, code) return code def _verify_integrity(self, codes: list | None = None, levels: list | None = None): @@ -1579,12 +1577,7 @@ def is_monotonic_increasing(self) -> bool: self._get_level_values(i)._values for i in reversed(range(len(self.levels))) ] try: - # Argument 1 to "lexsort" has incompatible type "List[Union[ExtensionArray, - # ndarray[Any, Any]]]"; expected "Union[_SupportsArray[dtype[Any]], - # _NestedSequence[_SupportsArray[dtype[Any]]], bool, - # int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, - # complex, str, bytes]]]" [arg-type] - sort_order = np.lexsort(values) # type: ignore[arg-type] + sort_order = np.lexsort(values) return Index(sort_order).is_monotonic_increasing except TypeError: diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py index 1160d3b2a8e3a..c938a018574f9 100644 --- a/pandas/core/internals/ops.py +++ b/pandas/core/internals/ops.py @@ -125,7 +125,9 @@ def _get_same_shape_values( # argument type "Tuple[Union[ndarray, slice], slice]" lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[call-overload] assert lvals.shape[0] == 1, lvals.shape - lvals = lvals[0, :] + # error: No overload variant of "__getitem__" of "ExtensionArray" matches + # argument type "Tuple[int, slice]" + lvals = lvals[0, :] # type: ignore[call-overload] else: # lvals are 1D, rvals are 2D assert rvals.shape[0] == 1, rvals.shape diff --git a/pandas/core/missing.py b/pandas/core/missing.py index b0bfbf13fbb2c..6224b35f7e680 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -333,15 +333,7 @@ def func(yvalues: np.ndarray) -> None: **kwargs, ) - # Argument 1 to "apply_along_axis" has incompatible type - # "Callable[[ndarray[Any, Any]], None]"; expected - # "Callable[..., Union[_SupportsArray[dtype[<nothing>]], - # Sequence[_SupportsArray[dtype[<nothing> - # ]]], Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]], - # Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]], - # Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]]]]]" - # interp each column independently - np.apply_along_axis(func, axis, data) # type: ignore[arg-type] + np.apply_along_axis(func, axis, data) return @@ -779,23 +771,14 @@ def interpolate_2d( Modifies values in-place. """ if limit_area is not None: - # Argument 1 to "apply_along_axis" has incompatible type "partial[None]"; - # expected "Callable[..., Union[_SupportsArray[dtype[<nothing>]], - # Sequence[_SupportsArray[dtype[<nothing>]]], Sequence[Sequence - # [_SupportsArray[dtype[<nothing>]]]], - # Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]], - # Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]]]]]" - - # Argument 2 to "apply_along_axis" has incompatible type "Union[str, int]"; - # expected "SupportsIndex" [arg-type] np.apply_along_axis( partial( _interpolate_with_limit_area, method=method, limit=limit, limit_area=limit_area, - ), # type: ignore[arg-type] - axis, # type: ignore[arg-type] + ), + axis, values, ) return diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 262cd9774f694..aa426d24db75d 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -133,9 +133,7 @@ def melt( if is_extension_array_dtype(id_data): id_data = concat([id_data] * K, ignore_index=True) else: - # Incompatible types in assignment (expression has type - # "ndarray[Any, dtype[Any]]", variable has type "Series") [assignment] - id_data = np.tile(id_data._values, K) # type: ignore[assignment] + id_data = np.tile(id_data._values, K) mdata[col] = id_data mcolumns = id_vars + var_name + [value_name] diff --git a/pandas/core/series.py b/pandas/core/series.py index 6b1b9dc6c88ac..cf602115f683f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2024,9 +2024,7 @@ def count(self, level=None): lev = lev.insert(cnt, lev._na_value) obs = level_codes[notna(self._values)] - # Argument "minlength" to "bincount" has incompatible type "Optional[int]"; - # expected "SupportsIndex" [arg-type] - out = np.bincount(obs, minlength=len(lev) or None) # type: ignore[arg-type] + out = np.bincount(obs, minlength=len(lev) or None) return self._constructor(out, index=lev, dtype="int64").__finalize__( self, method="count" ) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b45f43adbe952..886d81af8ba6b 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -409,7 +409,10 @@ def _prep_values(self, values: ArrayLike) -> np.ndarray: if inf.any(): values = np.where(inf, np.nan, values) - return values + # error: Incompatible return value type + # (got "Union[ExtensionArray, ndarray[Any, Any], + # ndarray[Any, dtype[floating[_64Bit]]]]", expected "ndarray[Any, Any]") + return values # type: ignore[return-value] def _insert_on_column(self, result: DataFrame, obj: DataFrame) -> None: # if we have an 'on' column we want to put it back into diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 24669e84443a6..1f42329389a18 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -3860,10 +3860,24 @@ def _highlight_between( Return an array of css props based on condition of data values within given range. """ if np.iterable(left) and not isinstance(left, str): - left = _validate_apply_axis_arg(left, "left", None, data) + # error: Argument 1 to "_validate_apply_axis_arg" + # has incompatible type "Union[str, float, Period, + # Timedelta, Interval[Any], datetime64, timedelta64, + # datetime, Sequence[Any], ndarray[Any, Any], NDFrame, None]"; + # expected "Union[NDFrame, Sequence[Any], ndarray[Any, Any]]" + left = _validate_apply_axis_arg( + left, "left", None, data # type: ignore[arg-type] + ) if np.iterable(right) and not isinstance(right, str): - right = _validate_apply_axis_arg(right, "right", None, data) + # error: Argument 1 to "_validate_apply_axis_arg" + # has incompatible type "Union[str, float, Period, + # Timedelta, Interval[Any], datetime64, timedelta64, + # datetime, Sequence[Any], ndarray[Any, Any], NDFrame, None]"; + # expected "Union[NDFrame, Sequence[Any], ndarray[Any, Any]]" + right = _validate_apply_axis_arg( + right, "right", None, data # type: ignore[arg-type] + ) # get ops with correct boundary attribution if inclusive == "both": diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 91c37a0e43505..7781860f0d61e 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -383,7 +383,7 @@ def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict: numpy_dtypes, # type: ignore[arg-type] [], ) - if common_type == object: + if common_type == np.dtype(object): warning_columns.append(str(name)) dtype = dtypes.pop() @@ -400,14 +400,7 @@ def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict: arrs # type: ignore[arg-type] ) else: - # Argument 1 to "concatenate" has incompatible type - # "List[Union[ExtensionArray, ndarray[Any, Any]]]"; expected - # "Union[_SupportsArray[dtype[Any]], - # Sequence[_SupportsArray[dtype[Any]]], - # Sequence[Sequence[_SupportsArray[dtype[Any]]]], - # Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]], - # Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]]]]" - result[name] = np.concatenate(arrs) # type: ignore[arg-type] + result[name] = np.concatenate(arrs) if warning_columns: warning_names = ",".join(warning_columns) diff --git a/pandas/tests/extension/date/array.py b/pandas/tests/extension/date/array.py index b14b9921be3d3..d29ed293e71ed 100644 --- a/pandas/tests/extension/date/array.py +++ b/pandas/tests/extension/date/array.py @@ -109,10 +109,7 @@ def __init__( self._month = np.zeros(ldates, dtype=np.uint8) # 255 (1, 31) self._day = np.zeros(ldates, dtype=np.uint8) # 255 (1, 12) - # "object_" object is not iterable [misc] - for (i,), (y, m, d) in np.ndenumerate( # type: ignore[misc] - np.char.split(dates, sep="-") - ): + for (i,), (y, m, d) in np.ndenumerate(np.char.split(dates, sep="-")): self._year[i] = int(y) self._month[i] = int(m) self._day[i] = int(d) diff --git a/requirements-dev.txt b/requirements-dev.txt index 7640587b85a1c..2b8aee80882a5 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,11 +1,66 @@ # This file is auto-generated from environment.yml, do not modify. # See that file for comments about the need/usage of each dependency. -numpy>=1.19.5 -python-dateutil>=2.8.1 +cython==0.29.30 +pytest>=6.0 +pytest-cov +pytest-xdist>=1.31 +psutil +pytest-asyncio>=0.17 +boto3 +python-dateutil +numpy pytz +beautifulsoup4 +blosc +brotlipy +bottleneck +fastparquet +fsspec +html5lib +hypothesis +gcsfs +jinja2 +lxml +matplotlib +numba>=0.53.1 +numexpr>=2.8.0 +openpyxl +odfpy +pandas-gbq +psycopg2 +pyarrow +pymysql +pyreadstat +tables +python-snappy +pyxlsb +s3fs +scipy +sqlalchemy +tabulate +xarray +xlrd +xlsxwriter +xlwt +zstandard +aiobotocore<2.0.0 +botocore +cftime +dask +ipython +geopandas +seaborn +scikit-learn +statsmodels +coverage +pandas-datareader +pyyaml +py +torch +moto +flask asv -cython>=0.29.30 black==22.3.0 cpplint flake8==4.0.1 @@ -18,6 +73,7 @@ pycodestyle pyupgrade gitpython gitdb +natsort numpydoc pandas-dev-flaker==0.5.0 pydata-sphinx-theme==0.8.0 @@ -31,58 +87,13 @@ types-setuptools nbconvert>=6.4.5 nbsphinx pandoc -dask -toolz>=0.7.3 -partd>=0.3.10 -cloudpickle>=0.2.1 -markdown -feedparser -pyyaml -requests -boto3 -botocore>=1.11 -hypothesis>=5.5.3 -moto -flask -pytest>=6.0 -pytest-cov -pytest-xdist>=1.31 -pytest-asyncio>=0.17 -pytest-instafail -seaborn -statsmodels ipywidgets nbformat notebook>=6.0.3 -blosc -bottleneck>=1.3.1 ipykernel -ipython>=7.11.1 jinja2 -matplotlib>=3.3.2 -numexpr>=2.7.1 -scipy>=1.4.1 -numba>=0.50.1 -beautifulsoup4>=4.8.2 -html5lib -lxml -openpyxl -xlrd -xlsxwriter -xlwt -odfpy -fastparquet>=0.4.0 -pyarrow>2.0.1 -python-snappy -tables>=3.6.1 -s3fs>=0.4.0 -aiobotocore<2.0.0 -fsspec>=0.7.4 -gcsfs>=0.6.0 -sqlalchemy -xarray -cftime -pyreadstat -tabulate>=0.8.3 -natsort +markdown +feedparser +pyyaml +requests setuptools>=51.0.0 diff --git a/scripts/generate_pip_deps_from_conda.py b/scripts/generate_pip_deps_from_conda.py index 2ea50fa3ac8d4..8cb539d3b02c8 100755 --- a/scripts/generate_pip_deps_from_conda.py +++ b/scripts/generate_pip_deps_from_conda.py @@ -21,7 +21,7 @@ import yaml EXCLUDE = {"python", "c-compiler", "cxx-compiler"} -RENAME = {"pytables": "tables", "dask-core": "dask"} +RENAME = {"pytables": "tables", "geopandas-base": "geopandas", "pytorch": "torch"} def conda_package_to_pip(package: str):
- [x] closes #45178 (Replace xxxx with the Github issue number) - [x] closes #43804 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Also add a GHA job to check that the generated `requirements-dev.txt` file, synced from `environment.yml`, can be installed.
https://api.github.com/repos/pandas-dev/pandas/pulls/47287
2022-06-08T19:56:28Z
2022-06-22T01:22:20Z
2022-06-22T01:22:20Z
2022-08-03T21:08:46Z
DEPR: display.column_space
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 8a947e4505ec5..66f5ea11f87ff 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -686,6 +686,7 @@ Other Deprecations - Deprecated the ``closed`` argument in :class:`intervaltree` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`) - Deprecated the ``closed`` argument in :class:`ArrowInterval` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`) - Deprecated allowing ``unit="M"`` or ``unit="Y"`` in :class:`Timestamp` constructor with a non-round float value (:issue:`47267`) +- Deprecated the ``display.column_space`` global configuration option (:issue:`7576`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index dd106b6dbb63c..47cf64ba24022 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -361,7 +361,17 @@ def is_terminal() -> bool: float_format_doc, validator=is_one_of_factory([None, is_callable]), ) - cf.register_option("column_space", 12, validator=is_int) + + def _deprecate_column_space(key): + warnings.warn( + "column_space is deprecated and will be removed " + "in a future version. Use df.to_string(col_space=...) " + "instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + cf.register_option("column_space", 12, validator=is_int, cb=_deprecate_column_space) cf.register_option( "max_info_rows", 1690785, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 3019aa1fc2dc7..045e74c1b6083 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1294,7 +1294,7 @@ def format_array( fmt_klass = GenericArrayFormatter if space is None: - space = get_option("display.column_space") + space = 12 if float_format is None: float_format = get_option("display.float_format") @@ -2099,7 +2099,6 @@ def set_eng_float_format(accuracy: int = 3, use_eng_prefix: bool = False) -> Non See also EngFormatter. """ set_option("display.float_format", EngFormatter(accuracy, use_eng_prefix)) - set_option("display.column_space", max(12, accuracy + 9)) def get_level_lengths( diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index 765640c94673e..f42660b297cb0 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -219,7 +219,7 @@ def test_repr_unsortable(self, float_frame): ) repr(unsortable) - fmt.set_option("display.precision", 3, "display.column_space", 10) + fmt.set_option("display.precision", 3) repr(float_frame) fmt.set_option("display.max_rows", 10, "display.max_columns", 2) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 04f4b0a313fdc..a7c9c86b3d9a5 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1442,8 +1442,6 @@ def test_to_string_float_formatting(self): fmt.set_option( "display.precision", 5, - "display.column_space", - 12, "display.notebook_repr_html", False, ) @@ -3402,3 +3400,9 @@ def test_filepath_or_buffer_bad_arg_raises(float_frame, method): msg = "buf is not a file name and it has no write method" with pytest.raises(TypeError, match=msg): getattr(float_frame, method)(buf=object()) + + +def test_col_space_deprecated(): + # GH 7576 + with tm.assert_produces_warning(FutureWarning, match="column_space is"): + set_option("display.column_space", 11)
- [x] closes #7576 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47280
2022-06-07T23:50:40Z
2022-06-10T23:42:59Z
2022-06-10T23:42:59Z
2022-06-10T23:43:56Z
BUG/PERF: DataFrame.to_records inconsistent dtypes for MultiIndex
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 2f0f40de92056..a28e20a636ce2 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -288,6 +288,26 @@ def time_values_mixed_wide(self): self.df_mixed_wide.values +class ToRecords: + def setup(self): + N = 100_000 + data = np.random.randn(N, 2) + mi = MultiIndex.from_arrays( + [ + np.arange(N), + date_range("1970-01-01", periods=N, freq="ms"), + ] + ) + self.df = DataFrame(data) + self.df_mi = DataFrame(data, index=mi) + + def time_to_records(self): + self.df.to_records(index=True) + + def time_to_records_multiindex(self): + self.df_mi.to_records(index=True) + + class Repr: def setup(self): nrows = 10000 diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 8a947e4505ec5..ac2faa673ca48 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -701,6 +701,7 @@ Performance improvements - Performance improvement in :meth:`.GroupBy.transform` for user-defined functions when only a single group exists (:issue:`44977`) - Performance improvement in :meth:`.GroupBy.apply` when grouping on a non-unique unsorted index (:issue:`46527`) - Performance improvement in :meth:`DataFrame.loc` and :meth:`Series.loc` for tuple-based indexing of a :class:`MultiIndex` (:issue:`45681`, :issue:`46040`, :issue:`46330`) +- Performance improvement in :meth:`DataFrame.to_records` when the index is a :class:`MultiIndex` (:issue:`47263`) - Performance improvement in :attr:`MultiIndex.values` when the MultiIndex contains levels of type DatetimeIndex, TimedeltaIndex or ExtensionDtypes (:issue:`46288`) - Performance improvement in :func:`merge` when left and/or right are empty (:issue:`45838`) - Performance improvement in :meth:`DataFrame.join` when left and/or right are empty (:issue:`46015`) @@ -762,6 +763,7 @@ Conversion - Bug in :func:`array` with ``FloatingDtype`` and values containing float-castable strings incorrectly raising (:issue:`45424`) - Bug when comparing string and datetime64ns objects causing ``OverflowError`` exception. (:issue:`45506`) - Bug in metaclass of generic abstract dtypes causing :meth:`DataFrame.apply` and :meth:`Series.apply` to raise for the built-in function ``type`` (:issue:`46684`) +- Bug in :meth:`DataFrame.to_records` returning inconsistent numpy types if the index was a :class:`MultiIndex` (:issue:`47263`) - Bug in :meth:`DataFrame.to_dict` for ``orient="list"`` or ``orient="index"`` was not returning native types (:issue:`46751`) Strings diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 54ee5ed2f35d1..ed5ecd67b1ef3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2416,13 +2416,10 @@ def to_records( dtype=[('I', 'S1'), ('A', '<i8'), ('B', '<f8')]) """ if index: - if isinstance(self.index, MultiIndex): - # array of tuples to numpy cols. copy copy copy - ix_vals = list(map(np.array, zip(*self.index._values))) - else: - # error: List item 0 has incompatible type "ArrayLike"; expected - # "ndarray" - ix_vals = [self.index.values] # type: ignore[list-item] + ix_vals = [ + np.asarray(self.index.get_level_values(i)) + for i in range(self.index.nlevels) + ] arrays = ix_vals + [ np.asarray(self.iloc[:, i]) for i in range(len(self.columns)) diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py index 6332ffd181eba..32cccddc9d515 100644 --- a/pandas/tests/frame/methods/test_to_records.py +++ b/pandas/tests/frame/methods/test_to_records.py @@ -96,7 +96,7 @@ def test_to_records_index_name(self): + [np.asarray(df.iloc[:, i]) for i in range(3)], dtype={ "names": ["A", "level_1", "0", "1", "2"], - "formats": ["<U1", "<U1", "<f8", "<f8", "<f8"], + "formats": ["O", "O", "<f8", "<f8", "<f8"], }, ) tm.assert_numpy_array_equal(result, expected) @@ -108,6 +108,33 @@ def test_to_records_with_unicode_index(self): expected = np.rec.array([("x", "y")], dtype=[("a", "O"), ("b", "O")]) tm.assert_almost_equal(result, expected) + def test_to_records_index_dtype(self): + # GH 47263: consistent data types for Index and MultiIndex + df = DataFrame( + { + 1: date_range("2022-01-01", periods=2), + 2: date_range("2022-01-01", periods=2), + 3: date_range("2022-01-01", periods=2), + } + ) + + expected = np.rec.array( + [ + ("2022-01-01", "2022-01-01", "2022-01-01"), + ("2022-01-02", "2022-01-02", "2022-01-02"), + ], + dtype=[("1", "<M8[ns]"), ("2", "<M8[ns]"), ("3", "<M8[ns]")], + ) + + result = df.to_records(index=False) + tm.assert_almost_equal(result, expected) + + result = df.set_index(1).to_records(index=True) + tm.assert_almost_equal(result, expected) + + result = df.set_index([1, 2]).to_records(index=True) + tm.assert_almost_equal(result, expected) + def test_to_records_with_unicode_column_names(self): # xref issue: https://github.com/numpy/numpy/issues/2407 # Issue GH#11879. to_records used to raise an exception when used
- [x] closes #47263 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added an entry in the latest `doc/source/whatsnew/v1.5.0.rst` file if fixing a bug or adding a new feature. Fixes a bug/inconsistency in DataFrame.to_records that produced different numpy dtypes for Index vs MultiIndex. **NOTE**: one existing test was updated to reflect the change: `test_to_records_index_name` The fix is also beneficial in terms of performance: ``` import pandas as pd import numpy as np n = 5_000_000 mi = pd.MultiIndex.from_arrays( [ np.arange(n), pd.date_range('1970-01-01', periods=n, freq='ms'), ] ) df = pd.DataFrame(np.random.randn(n), index=mi) %timeit df.to_records(index=True) ``` ``` # 6.78 s ± 264 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) <- main # 90.9 ms ± 3.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/47279
2022-06-07T22:38:55Z
2022-06-08T16:53:37Z
2022-06-08T16:53:37Z
2022-09-10T00:49:47Z
ENH: TDA fields support non-nano
diff --git a/pandas/_libs/tslibs/fields.pyi b/pandas/_libs/tslibs/fields.pyi index 71363ad836370..8b4bc1a31a1aa 100644 --- a/pandas/_libs/tslibs/fields.pyi +++ b/pandas/_libs/tslibs/fields.pyi @@ -28,6 +28,7 @@ def get_date_field( def get_timedelta_field( tdindex: npt.NDArray[np.int64], # const int64_t[:] field: str, + reso: int = ..., # NPY_DATETIMEUNIT ) -> npt.NDArray[np.int32]: ... def isleapyear_arr( years: np.ndarray, diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index bc5e5b37b9a76..71a0f2727445f 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -48,8 +48,8 @@ from pandas._libs.tslibs.np_datetime cimport ( get_unit_from_dtype, npy_datetimestruct, pandas_datetime_to_datetimestruct, + pandas_timedelta_to_timedeltastruct, pandas_timedeltastruct, - td64_to_tdstruct, ) @@ -491,7 +491,11 @@ def get_date_field(const int64_t[:] dtindex, str field, NPY_DATETIMEUNIT reso=NP @cython.wraparound(False) @cython.boundscheck(False) -def get_timedelta_field(const int64_t[:] tdindex, str field): +def get_timedelta_field( + const int64_t[:] tdindex, + str field, + NPY_DATETIMEUNIT reso=NPY_FR_ns, +): """ Given a int64-based timedelta index, extract the days, hrs, sec., field and return an array of these values. @@ -510,7 +514,7 @@ def get_timedelta_field(const int64_t[:] tdindex, str field): out[i] = -1 continue - td64_to_tdstruct(tdindex[i], &tds) + pandas_timedelta_to_timedeltastruct(tdindex[i], reso, &tds) out[i] = tds.days return out @@ -521,7 +525,7 @@ def get_timedelta_field(const int64_t[:] tdindex, str field): out[i] = -1 continue - td64_to_tdstruct(tdindex[i], &tds) + pandas_timedelta_to_timedeltastruct(tdindex[i], reso, &tds) out[i] = tds.seconds return out @@ -532,7 +536,7 @@ def get_timedelta_field(const int64_t[:] tdindex, str field): out[i] = -1 continue - td64_to_tdstruct(tdindex[i], &tds) + pandas_timedelta_to_timedeltastruct(tdindex[i], reso, &tds) out[i] = tds.microseconds return out @@ -543,7 +547,7 @@ def get_timedelta_field(const int64_t[:] tdindex, str field): out[i] = -1 continue - td64_to_tdstruct(tdindex[i], &tds) + pandas_timedelta_to_timedeltastruct(tdindex[i], reso, &tds) out[i] = tds.nanoseconds return out diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index f072dab3763aa..d4dbcbe2acd6e 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -77,7 +77,6 @@ cdef check_dts_bounds(npy_datetimestruct *dts, NPY_DATETIMEUNIT unit=?) cdef int64_t dtstruct_to_dt64(npy_datetimestruct* dts) nogil cdef void dt64_to_dtstruct(int64_t dt64, npy_datetimestruct* out) nogil -cdef void td64_to_tdstruct(int64_t td64, pandas_timedeltastruct* out) nogil cdef int64_t pydatetime_to_dt64(datetime val, npy_datetimestruct *dts) cdef int64_t pydate_to_dt64(date val, npy_datetimestruct *dts) diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index bab4743dce38c..cf967509a84c0 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -221,14 +221,6 @@ cdef inline void dt64_to_dtstruct(int64_t dt64, return -cdef inline void td64_to_tdstruct(int64_t td64, - pandas_timedeltastruct* out) nogil: - """Convenience function to call pandas_timedelta_to_timedeltastruct - with the by-far-most-common frequency NPY_FR_ns""" - pandas_timedelta_to_timedeltastruct(td64, NPY_FR_ns, out) - return - - # just exposed for testing at the moment def py_td64_to_tdstruct(int64_t td64, NPY_DATETIMEUNIT unit): cdef: diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 36e8e44e2034f..3bbb03d88e38d 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -74,7 +74,7 @@ def _field_accessor(name: str, alias: str, docstring: str): def f(self) -> np.ndarray: values = self.asi8 - result = get_timedelta_field(values, alias) + result = get_timedelta_field(values, alias, reso=self._reso) if self._hasna: result = self._maybe_mask_results( result, fill_value=None, convert="float64" diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index 46306167878f6..c8b850d35035a 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit + import pandas as pd from pandas import Timedelta import pandas._testing as tm @@ -8,7 +10,21 @@ class TestNonNano: - @pytest.mark.parametrize("unit,reso", [("s", 7), ("ms", 8), ("us", 9)]) + @pytest.fixture(params=["s", "ms", "us"]) + def unit(self, request): + return request.param + + @pytest.fixture + def reso(self, unit): + if unit == "s": + return NpyDatetimeUnit.NPY_FR_s.value + elif unit == "ms": + return NpyDatetimeUnit.NPY_FR_ms.value + elif unit == "us": + return NpyDatetimeUnit.NPY_FR_us.value + else: + raise NotImplementedError(unit) + def test_non_nano(self, unit, reso): arr = np.arange(5, dtype=np.int64).view(f"m8[{unit}]") tda = TimedeltaArray._simple_new(arr, dtype=arr.dtype) @@ -16,6 +32,18 @@ def test_non_nano(self, unit, reso): assert tda.dtype == arr.dtype assert tda[0]._reso == reso + @pytest.mark.parametrize("field", TimedeltaArray._field_ops) + def test_fields(self, unit, reso, field): + arr = np.arange(5, dtype=np.int64).view(f"m8[{unit}]") + tda = TimedeltaArray._simple_new(arr, dtype=arr.dtype) + + as_nano = arr.astype("m8[ns]") + tda_nano = TimedeltaArray._simple_new(as_nano, dtype=as_nano.dtype) + + result = getattr(tda, field) + expected = getattr(tda_nano, field) + tm.assert_numpy_array_equal(result, expected) + class TestTimedeltaArray: @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) diff --git a/pandas/tests/tslibs/test_np_datetime.py b/pandas/tests/tslibs/test_np_datetime.py index 9ae491f1618f6..cc09f0fc77039 100644 --- a/pandas/tests/tslibs/test_np_datetime.py +++ b/pandas/tests/tslibs/test_np_datetime.py @@ -1,6 +1,7 @@ import numpy as np import pytest +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit from pandas._libs.tslibs.np_datetime import ( OutOfBoundsDatetime, OutOfBoundsTimedelta, @@ -37,42 +38,42 @@ def test_is_unitless(): def test_get_unit_from_dtype(): # datetime64 - assert py_get_unit_from_dtype(np.dtype("M8[Y]")) == 0 - assert py_get_unit_from_dtype(np.dtype("M8[M]")) == 1 - assert py_get_unit_from_dtype(np.dtype("M8[W]")) == 2 + assert py_get_unit_from_dtype(np.dtype("M8[Y]")) == NpyDatetimeUnit.NPY_FR_Y.value + assert py_get_unit_from_dtype(np.dtype("M8[M]")) == NpyDatetimeUnit.NPY_FR_M.value + assert py_get_unit_from_dtype(np.dtype("M8[W]")) == NpyDatetimeUnit.NPY_FR_W.value # B has been deprecated and removed -> no 3 - assert py_get_unit_from_dtype(np.dtype("M8[D]")) == 4 - assert py_get_unit_from_dtype(np.dtype("M8[h]")) == 5 - assert py_get_unit_from_dtype(np.dtype("M8[m]")) == 6 - assert py_get_unit_from_dtype(np.dtype("M8[s]")) == 7 - assert py_get_unit_from_dtype(np.dtype("M8[ms]")) == 8 - assert py_get_unit_from_dtype(np.dtype("M8[us]")) == 9 - assert py_get_unit_from_dtype(np.dtype("M8[ns]")) == 10 - assert py_get_unit_from_dtype(np.dtype("M8[ps]")) == 11 - assert py_get_unit_from_dtype(np.dtype("M8[fs]")) == 12 - assert py_get_unit_from_dtype(np.dtype("M8[as]")) == 13 + assert py_get_unit_from_dtype(np.dtype("M8[D]")) == NpyDatetimeUnit.NPY_FR_D.value + assert py_get_unit_from_dtype(np.dtype("M8[h]")) == NpyDatetimeUnit.NPY_FR_h.value + assert py_get_unit_from_dtype(np.dtype("M8[m]")) == NpyDatetimeUnit.NPY_FR_m.value + assert py_get_unit_from_dtype(np.dtype("M8[s]")) == NpyDatetimeUnit.NPY_FR_s.value + assert py_get_unit_from_dtype(np.dtype("M8[ms]")) == NpyDatetimeUnit.NPY_FR_ms.value + assert py_get_unit_from_dtype(np.dtype("M8[us]")) == NpyDatetimeUnit.NPY_FR_us.value + assert py_get_unit_from_dtype(np.dtype("M8[ns]")) == NpyDatetimeUnit.NPY_FR_ns.value + assert py_get_unit_from_dtype(np.dtype("M8[ps]")) == NpyDatetimeUnit.NPY_FR_ps.value + assert py_get_unit_from_dtype(np.dtype("M8[fs]")) == NpyDatetimeUnit.NPY_FR_fs.value + assert py_get_unit_from_dtype(np.dtype("M8[as]")) == NpyDatetimeUnit.NPY_FR_as.value # timedelta64 - assert py_get_unit_from_dtype(np.dtype("m8[Y]")) == 0 - assert py_get_unit_from_dtype(np.dtype("m8[M]")) == 1 - assert py_get_unit_from_dtype(np.dtype("m8[W]")) == 2 + assert py_get_unit_from_dtype(np.dtype("m8[Y]")) == NpyDatetimeUnit.NPY_FR_Y.value + assert py_get_unit_from_dtype(np.dtype("m8[M]")) == NpyDatetimeUnit.NPY_FR_M.value + assert py_get_unit_from_dtype(np.dtype("m8[W]")) == NpyDatetimeUnit.NPY_FR_W.value # B has been deprecated and removed -> no 3 - assert py_get_unit_from_dtype(np.dtype("m8[D]")) == 4 - assert py_get_unit_from_dtype(np.dtype("m8[h]")) == 5 - assert py_get_unit_from_dtype(np.dtype("m8[m]")) == 6 - assert py_get_unit_from_dtype(np.dtype("m8[s]")) == 7 - assert py_get_unit_from_dtype(np.dtype("m8[ms]")) == 8 - assert py_get_unit_from_dtype(np.dtype("m8[us]")) == 9 - assert py_get_unit_from_dtype(np.dtype("m8[ns]")) == 10 - assert py_get_unit_from_dtype(np.dtype("m8[ps]")) == 11 - assert py_get_unit_from_dtype(np.dtype("m8[fs]")) == 12 - assert py_get_unit_from_dtype(np.dtype("m8[as]")) == 13 + assert py_get_unit_from_dtype(np.dtype("m8[D]")) == NpyDatetimeUnit.NPY_FR_D.value + assert py_get_unit_from_dtype(np.dtype("m8[h]")) == NpyDatetimeUnit.NPY_FR_h.value + assert py_get_unit_from_dtype(np.dtype("m8[m]")) == NpyDatetimeUnit.NPY_FR_m.value + assert py_get_unit_from_dtype(np.dtype("m8[s]")) == NpyDatetimeUnit.NPY_FR_s.value + assert py_get_unit_from_dtype(np.dtype("m8[ms]")) == NpyDatetimeUnit.NPY_FR_ms.value + assert py_get_unit_from_dtype(np.dtype("m8[us]")) == NpyDatetimeUnit.NPY_FR_us.value + assert py_get_unit_from_dtype(np.dtype("m8[ns]")) == NpyDatetimeUnit.NPY_FR_ns.value + assert py_get_unit_from_dtype(np.dtype("m8[ps]")) == NpyDatetimeUnit.NPY_FR_ps.value + assert py_get_unit_from_dtype(np.dtype("m8[fs]")) == NpyDatetimeUnit.NPY_FR_fs.value + assert py_get_unit_from_dtype(np.dtype("m8[as]")) == NpyDatetimeUnit.NPY_FR_as.value def test_td64_to_tdstruct(): val = 12454636234 # arbitrary value - res1 = py_td64_to_tdstruct(val, 10) # ns + res1 = py_td64_to_tdstruct(val, NpyDatetimeUnit.NPY_FR_ns.value) exp1 = { "days": 0, "hrs": 0, @@ -87,7 +88,7 @@ def test_td64_to_tdstruct(): } assert res1 == exp1 - res2 = py_td64_to_tdstruct(val, 9) # us + res2 = py_td64_to_tdstruct(val, NpyDatetimeUnit.NPY_FR_us.value) exp2 = { "days": 0, "hrs": 3, @@ -102,7 +103,7 @@ def test_td64_to_tdstruct(): } assert res2 == exp2 - res3 = py_td64_to_tdstruct(val, 8) # ms + res3 = py_td64_to_tdstruct(val, NpyDatetimeUnit.NPY_FR_ms.value) exp3 = { "days": 144, "hrs": 3, @@ -118,7 +119,7 @@ def test_td64_to_tdstruct(): assert res3 == exp3 # Note this out of bounds for nanosecond Timedelta - res4 = py_td64_to_tdstruct(val, 7) # s + res4 = py_td64_to_tdstruct(val, NpyDatetimeUnit.NPY_FR_s.value) exp4 = { "days": 144150, "hrs": 21,
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47278
2022-06-07T21:51:41Z
2022-06-08T00:34:38Z
2022-06-08T00:34:38Z
2022-06-08T01:16:06Z
DOC: Move all relevant wiki items to docs
diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 3437ddfbffdcf..81cd69aa384a4 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -304,8 +304,8 @@ This is an example of a green build. .. _contributing.tdd: -Test-driven development/code writing ------------------------------------- +Test-driven development +----------------------- pandas is serious about testing and strongly encourages contributors to embrace `test-driven development (TDD) <https://en.wikipedia.org/wiki/Test-driven_development>`_. @@ -337,10 +337,11 @@ pandas existing test structure is *mostly* class-based, meaning that you will ty .. code-block:: python - class TestReallyCoolFeature: - pass + class TestReallyCoolFeature: + def test_cool_feature_aspect(self): + pass -Going forward, we are moving to a more *functional* style using the `pytest <https://docs.pytest.org/en/latest/>`__ framework, which offers a richer testing +We prefer a more *functional* style using the `pytest <https://docs.pytest.org/en/latest/>`__ framework, which offers a richer testing framework that will facilitate testing and developing. Thus, instead of writing test classes, we will write test functions like this: .. code-block:: python @@ -348,8 +349,8 @@ framework that will facilitate testing and developing. Thus, instead of writing def test_really_cool_feature(): pass -Preferred idioms -^^^^^^^^^^^^^^^^ +Preferred ``pytest`` idioms +^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Functional tests named ``def test_*`` and *only* take arguments that are either fixtures or parameters. * Use a bare ``assert`` for testing scalars and truth-testing @@ -387,9 +388,66 @@ xfail is not to be used for tests involving failure due to invalid user argument For these tests, we need to verify the correct exception type and error message is being raised, using ``pytest.raises`` instead. -If your test requires working with files or -network connectivity, there is more information on the :wiki:`Testing` of the wiki. +Testing a warning +^^^^^^^^^^^^^^^^^ + +Use ``tm.assert_produces_warning`` as a context manager to check that a block of code raises a warning. + +.. code-block:: python + + with tm.assert_produces_warning(DeprecationWarning): + pd.deprecated_function() + +If a warning should specifically not happen in a block of code, pass ``False`` into the context manager. + +.. code-block:: python + + with tm.assert_produces_warning(False): + pd.no_warning_function() + +Testing an exception +^^^^^^^^^^^^^^^^^^^^ + +Use `pytest.raises <https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises>`_ as a context manager +with the specific exception subclass (i.e. never use :py:class:`Exception`) and the exception message in ``match``. + +.. code-block:: python + + with pytest.raises(ValueError, match="an error"): + raise ValueError("an error") + +Testing involving files +^^^^^^^^^^^^^^^^^^^^^^^ + +The ``tm.ensure_clean`` context manager creates a temporary file for testing, +with a generated filename (or your filename if provided), that is automatically +deleted when the context block is exited. + +.. code-block:: python + + with tm.ensure_clean('my_file_path') as path: + # do something with the path + +Testing involving network connectivity +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +It is highly discouraged to add a test that connects to the internet due to flakiness of network connections and +lack of ownership of the server that is being connected to. If network connectivity is absolutely required, use the +``tm.network`` decorator. + +.. code-block:: python + + @tm.network # noqa + def test_network(): + result = package.call_to_internet() + +If the test requires data from a specific website, specify ``check_before_test=True`` and the site in the decorator. + +.. code-block:: python + @tm.network("https://www.somespecificsite.com", check_before_test=True) + def test_network(): + result = pd.read_html("https://www.somespecificsite.com") Example ^^^^^^^ diff --git a/doc/source/development/maintaining.rst b/doc/source/development/maintaining.rst index a8521039c5427..1bff2eccd3d27 100644 --- a/doc/source/development/maintaining.rst +++ b/doc/source/development/maintaining.rst @@ -138,7 +138,7 @@ Reviewing pull requests ----------------------- Anybody can review a pull request: regular contributors, triagers, or core-team -members. But only core-team members can merge pull requets when they're ready. +members. But only core-team members can merge pull requests when they're ready. Here are some things to check when reviewing a pull request. @@ -151,16 +151,37 @@ Here are some things to check when reviewing a pull request. for regression fixes and small bug fixes, the next minor milestone otherwise) * Changes should comply with our :ref:`policies.version`. + +.. _maintaining.backporting: + Backporting ----------- -In the case you want to apply changes to a stable branch from a newer branch then you -can comment:: +pandas supports point releases (e.g. ``1.4.3``) that aim to: + +1. Fix bugs in new features introduced in the first minor version release. + + * e.g. If a new feature was added in ``1.4`` and contains a bug, a fix can be applied in ``1.4.3`` + +2. Fix bugs that used to work in a few minor releases prior. There should be agreement between core team members that a backport is appropriate. + + * e.g. If a feature worked in ``1.2`` and stopped working since ``1.3``, a fix can be applied in ``1.4.3``. + +Since pandas minor releases are based on Github branches (e.g. point release of ``1.4`` are based off the ``1.4.x`` branch), +"backporting" means merging a pull request fix to the ``main`` branch and correct minor branch associated with the next point release. + +By default, if a pull request is assigned to the next point release milestone within the Github interface, +the backporting process should happen automatically by the ``@meeseeksdev`` bot once the pull request is merged. +A new pull request will be made backporting the pull request to the correct version branch. +Sometimes due to merge conflicts, a manual pull request will need to be made addressing the code conflict. + +If the bot does not automatically start the backporting process, you can also write a Github comment in the merged pull request +to trigger the backport:: @meeseeksdev backport version-branch This will trigger a workflow which will backport a given change to a branch -(e.g. @meeseeksdev backport 1.2.x) +(e.g. @meeseeksdev backport 1.4.x) Cleaning up old issues ---------------------- @@ -204,6 +225,18 @@ The full process is outlined in our `governance documents`_. In summary, we're happy to give triage permissions to anyone who shows interest by being helpful on the issue tracker. +The required steps for adding a maintainer are: + +1. Contact the contributor and ask their interest to join. +2. Add the contributor to the appropriate `Github Team <https://github.com/orgs/pandas-dev/teams>`_ if accepted the invitation. + + * ``pandas-core`` is for core team members + * ``pandas-triage`` is for pandas triage members + +3. Add the contributor to the pandas Google group. +4. Create a pull request to add the contributor's Github handle to ``pandas-dev/pandas/web/pandas/config.yml``. +5. Create a pull request to add the contributor's name/Github handle to the `governance document <https://github.com/pandas-dev/pandas-governance/blob/master/people.md>`_. + The current list of core-team members is at https://github.com/pandas-dev/pandas-governance/blob/master/people.md @@ -236,5 +269,40 @@ a milestone before tagging, you can request the bot to backport it with: @Meeseeksdev backport <branch> +.. _maintaining.asv-machine: + +Benchmark machine +----------------- + +The team currently owns dedicated hardware for hosting a website for pandas' ASV performance benchmark. The results +are published to http://pandas.pydata.org/speed/pandas/ + +Configuration +````````````` + +The machine can be configured with the `Ansible <http://docs.ansible.com/ansible/latest/index.html>`_ playbook in https://github.com/tomaugspurger/asv-runner. + +Publishing +`````````` + +The results are published to another Github repository, https://github.com/tomaugspurger/asv-collection. +Finally, we have a cron job on our docs server to pull from https://github.com/tomaugspurger/asv-collection, to serve them from ``/speed``. +Ask Tom or Joris for access to the webserver. + +Debugging +````````` + +The benchmarks are scheduled by Airflow. It has a dashboard for viewing and debugging the results. You'll need to setup an SSH tunnel to view them + + ssh -L 8080:localhost:8080 pandas@panda.likescandy.com + + +.. _maintaining.release: + +Release process +--------------- + +The process for releasing a new version of pandas can be found at https://github.com/pandas-dev/pandas-release + .. _governance documents: https://github.com/pandas-dev/pandas-governance .. _list of permissions: https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization diff --git a/doc/source/development/roadmap.rst b/doc/source/development/roadmap.rst index ccdb4f1fafae4..f935c27d9917d 100644 --- a/doc/source/development/roadmap.rst +++ b/doc/source/development/roadmap.rst @@ -128,7 +128,51 @@ We propose that it should only work with positional indexing, and the translatio to positions should be entirely done at a higher level. Indexing is a complicated API with many subtleties. This refactor will require care -and attention. More details are discussed at :wiki:`(Tentative)-rules-for-restructuring-indexing-code` +and attention. The following principles should inspire refactoring of indexing code and +should result on cleaner, simpler, and more performant code. + +1. **Label indexing must never involve looking in an axis twice for the same label(s).** +This implies that any validation step must either: + + * limit validation to general features (e.g. dtype/structure of the key/index), or + * reuse the result for the actual indexing. + +2. **Indexers must never rely on an explicit call to other indexers.** +For instance, it is OK to have some internal method of ``.loc`` call some +internal method of ``__getitem__`` (or of their common base class), +but never in the code flow of ``.loc`` should ``the_obj[something]`` appear. + +3. **Execution of positional indexing must never involve labels** (as currently, sadly, happens). +That is, the code flow of a getter call (or a setter call in which the right hand side is non-indexed) +to ``.iloc`` should never involve the axes of the object in any way. + +4. **Indexing must never involve accessing/modifying values** (i.e., act on ``._data`` or ``.values``) **more than once.** +The following steps must hence be clearly decoupled: + + * find positions we need to access/modify on each axis + * (if we are accessing) derive the type of object we need to return (dimensionality) + * actually access/modify the values + * (if we are accessing) construct the return object + +5. As a corollary to the decoupling between 4.i and 4.iii, **any code which deals on how data is stored** +(including any combination of handling multiple dtypes, and sparse storage, categoricals, third-party types) +**must be independent from code that deals with identifying affected rows/columns**, +and take place only once step 4.i is completed. + + * In particular, such code should most probably not live in ``pandas/core/indexing.py`` + * ... and must not depend in any way on the type(s) of axes (e.g. no ``MultiIndex`` special cases) + +6. As a corollary to point 1.i, **``Index`` (sub)classes must provide separate methods for any desired validity check of label(s) which does not involve actual lookup**, +on the one side, and for any required conversion/adaptation/lookup of label(s), on the other. + +7. **Use of trial and error should be limited**, and anyway restricted to catch only exceptions +which are actually expected (typically ``KeyError``). + + * In particular, code should never (intentionally) raise new exceptions in the ``except`` portion of a ``try... exception`` + +8. **Any code portion which is not specific to setters and getters must be shared**, +and when small differences in behavior are expected (e.g. getting with ``.loc`` raises for +missing labels, setting still doesn't), they can be managed with a specific parameter. Numba-accelerated operations ---------------------------- diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 53e003e2ed7dd..bedd7adeb45a2 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -54,7 +54,6 @@ round_trip_localpath, round_trip_pathlib, round_trip_pickle, - with_connectivity_check, write_to_compressed, ) from pandas._testing._random import ( # noqa:F401 diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py index 1ef65f761c3f6..46f1545a67fab 100644 --- a/pandas/_testing/_io.py +++ b/pandas/_testing/_io.py @@ -250,9 +250,6 @@ def wrapper(*args, **kwargs): return wrapper -with_connectivity_check = network - - def can_connect(url, error_classes=None): """ Try to connect to the given url. True if succeeds, False if OSError
- [x] closes #30410 - [x] closes #20501 - [x] closes #30232 Moved all relevant and current information documented in https://github.com/pandas-dev/pandas/wiki to our sphinx docs. After this is merged, the wiki tab can be disabled in the repo cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/47277
2022-06-07T20:43:03Z
2022-06-08T22:54:27Z
2022-06-08T22:54:27Z
2022-06-08T23:54:35Z
Fix typos
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 266e5a015e408..30dbcfdffd61c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,7 +26,6 @@ repos: hooks: - id: codespell types_or: [python, rst, markdown] - files: ^(pandas|doc)/ - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.2.0 hooks: diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index 141142c2b3d97..20c0c0ea2f6fe 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -37,7 +37,7 @@ def setup(self): self.dict_list = frame.to_dict(orient="records") self.data2 = {i: {j: float(j) for j in range(100)} for i in range(2000)} - # arrays which we wont consolidate + # arrays which we won't consolidate self.dict_of_categoricals = {i: Categorical(np.arange(N)) for i in range(K)} def time_list_of_dict(self): @@ -60,7 +60,7 @@ def time_nested_dict_int64(self): DataFrame(self.data2) def time_dict_of_categoricals(self): - # dict of arrays that we wont consolidate + # dict of arrays that we won't consolidate DataFrame(self.dict_of_categoricals) diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index c8e15f2645e56..2de1f25fceace 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -527,7 +527,7 @@ def time_dtype_as_field(self, dtype, method, application, ncols): class GroupByCythonAgg: """ - Benchmarks specifically targetting our cython aggregation algorithms + Benchmarks specifically targeting our cython aggregation algorithms (using a big enough dataframe with simple key, so a large part of the time is actually spent in the grouped aggregation). """ diff --git a/asv_bench/benchmarks/libs.py b/asv_bench/benchmarks/libs.py index 4e3f938a33eb1..f041499c9c622 100644 --- a/asv_bench/benchmarks/libs.py +++ b/asv_bench/benchmarks/libs.py @@ -2,7 +2,7 @@ Benchmarks for code in pandas/_libs, excluding pandas/_libs/tslibs, which has its own directory. -If a PR does not edit anything in _libs/, then it is unlikely that thes +If a PR does not edit anything in _libs/, then it is unlikely that the benchmarks will be affected. """ import numpy as np diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py index c4c50f5ca8eb5..8d4fc0240f2cc 100644 --- a/asv_bench/benchmarks/replace.py +++ b/asv_bench/benchmarks/replace.py @@ -50,7 +50,7 @@ def time_replace_list(self, inplace): self.df.replace([np.inf, -np.inf], np.nan, inplace=inplace) def time_replace_list_one_match(self, inplace): - # the 1 can be held in self._df.blocks[0], while the inf and -inf cant + # the 1 can be held in self._df.blocks[0], while the inf and -inf can't self.df.replace([np.inf, -np.inf, 1], np.nan, inplace=inplace) diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py index b42729476c818..89c627865049e 100644 --- a/asv_bench/benchmarks/reshape.py +++ b/asv_bench/benchmarks/reshape.py @@ -78,7 +78,7 @@ def time_stack(self, dtype): self.df.stack() def time_unstack_fast(self, dtype): - # last level -> doesnt have to make copies + # last level -> doesn't have to make copies self.ser.unstack("bar") def time_unstack_slow(self, dtype): diff --git a/asv_bench/benchmarks/tslibs/period.py b/asv_bench/benchmarks/tslibs/period.py index 6cb1011e3c037..af10102749627 100644 --- a/asv_bench/benchmarks/tslibs/period.py +++ b/asv_bench/benchmarks/tslibs/period.py @@ -1,6 +1,6 @@ """ -Period benchmarks that rely only on tslibs. See benchmarks.period for -Period benchmarks that rely on other parts fo pandas. +Period benchmarks that rely only on tslibs. See benchmarks.period for +Period benchmarks that rely on other parts of pandas. """ import numpy as np diff --git a/asv_bench/benchmarks/tslibs/timedelta.py b/asv_bench/benchmarks/tslibs/timedelta.py index 6ed273281569b..2daf1861eb80a 100644 --- a/asv_bench/benchmarks/tslibs/timedelta.py +++ b/asv_bench/benchmarks/tslibs/timedelta.py @@ -1,6 +1,6 @@ """ -Timedelta benchmarks that rely only on tslibs. See benchmarks.timedeltas for -Timedelta benchmarks that rely on other parts fo pandas. +Timedelta benchmarks that rely only on tslibs. See benchmarks.timedeltas for +Timedelta benchmarks that rely on other parts of pandas. """ import datetime diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb index 0b2341bef413e..58187b3052819 100644 --- a/doc/source/user_guide/style.ipynb +++ b/doc/source/user_guide/style.ipynb @@ -1762,7 +1762,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In the above case the text is blue because the selector `#T_b_ .cls-1` is worth 110 (ID plus class), which takes precendence." + "In the above case the text is blue because the selector `#T_b_ .cls-1` is worth 110 (ID plus class), which takes precedence." ] }, { diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 7f5fe85e07f40..db785bd962f96 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -1011,7 +1011,7 @@ cdef numeric_t _get_na_val(numeric_t val, bint is_datetimelike): elif numeric_t is int64_t and is_datetimelike: na_val = NPY_NAT else: - # Will not be used, but define to avoid unitialized warning. + # Will not be used, but define to avoid uninitialized warning. na_val = 0 return na_val diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx index cb2de79cd8b26..f843f6ccdfc58 100644 --- a/pandas/_libs/tslibs/dtypes.pyx +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -349,7 +349,7 @@ cpdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=NPY_DATETIMEUNIT.NPY_FR_ns) if reso == NPY_DATETIMEUNIT.NPY_FR_ps: # pico is the smallest unit for which we don't overflow, so - # we exclude fempto and atto + # we exclude femto and atto day_units = 24 * 3600 * 1_000_000_000_000 elif reso == NPY_DATETIMEUNIT.NPY_FR_ns: day_units = 24 * 3600 * 1_000_000_000 diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 8e459e8f2670d..028371633a2c1 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -202,7 +202,7 @@ def ints_to_pytimedelta(ndarray m8values, box=False): elif reso == NPY_DATETIMEUNIT.NPY_FR_W: res_val = timedelta(weeks=value) else: - # Month, Year, NPY_FR_GENERIC, pico, fempto, atto + # Month, Year, NPY_FR_GENERIC, pico, femto, atto raise NotImplementedError(reso) # Note: we can index result directly instead of using PyArray_MultiIter_DATA diff --git a/pandas/io/common.py b/pandas/io/common.py index bf1355d769758..5aecc55bb363a 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -590,7 +590,6 @@ def check_parent_directory(path: Path | str) -> None: ---------- path: Path or str Path to check parent directory of - """ parent = Path(path).parent if not parent.is_dir(): diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index c98aedc9a2cf0..4c34b0c0aec0a 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -610,7 +610,7 @@ def test_to_datetime_YYYYMMDD(self): actual = to_datetime("20080115") assert actual == datetime(2008, 1, 15) - def test_to_datetime_unparseable_ignore(self): + def test_to_datetime_unparsable_ignore(self): # unparsable ser = "Month 1, 1999" assert to_datetime(ser, errors="ignore") == ser diff --git a/setup.cfg b/setup.cfg index fdd6bdd9d579f..d3c4fe0cb35ce 100644 --- a/setup.cfg +++ b/setup.cfg @@ -160,7 +160,7 @@ exclude = [codespell] ignore-words-list = ba,blocs,coo,hist,nd,sav,ser -ignore-regex = https://(\w+\.)+ +ignore-regex = https://([\w/\.])+ [coverage:run] branch = True diff --git a/versioneer.py b/versioneer.py index 68c9bb161f206..c98dbd83271d7 100644 --- a/versioneer.py +++ b/versioneer.py @@ -691,7 +691,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces @@ -1105,7 +1105,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces diff --git a/web/pandas/community/blog/2019-user-survey.md b/web/pandas/community/blog/2019-user-survey.md index 73c426e7cbec9..312ee49bdf387 100644 --- a/web/pandas/community/blog/2019-user-survey.md +++ b/web/pandas/community/blog/2019-user-survey.md @@ -26,11 +26,11 @@ This analysis and the raw data can be found [on GitHub](https://github.com/panda [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/pandas-dev/pandas-user-surveys/master?filepath=2019.ipynb) -We had about 1250 repsonses over the 15 days we ran the survey in the summer of 2019. +We had about 1250 responses over the 15 days we ran the survey in the summer of 2019. ## About the Respondents -There was a fair amount of representation across pandas experience and frequeny of use, though the majority of respondents are on the more experienced side. +There was a fair amount of representation across pandas experience and frequency of use, though the majority of respondents are on the more experienced side. @@ -101,7 +101,7 @@ CSV and Excel are (for better or worse) the most popular formats. ![png]({{ base_url }}/static/img/blog/2019-user-survey/2019_18_0.png) -In preperation for a possible refactor of pandas internals, we wanted to get a sense for +In preparation for a possible refactor of pandas internals, we wanted to get a sense for how common wide (100s of columns or more) DataFrames are. @@ -109,7 +109,7 @@ how common wide (100s of columns or more) DataFrames are. ![png]({{ base_url }}/static/img/blog/2019-user-survey/2019_20_0.png) -Pandas is slowly growing new exentension types. Categoricals are the most popular, +Pandas is slowly growing new extension types. Categoricals are the most popular, and the nullable integer type is already almost as popular as datetime with timezone. @@ -139,7 +139,7 @@ Of these, the clear standout is "scaling" to large datasets. A couple observatio 1. Perhaps pandas' documentation should do a better job of promoting libraries that provide scalable dataframes (like [Dask](https://dask.org), [vaex](https://dask.org), and [modin](https://modin.readthedocs.io/en/latest/)) 2. Memory efficiency (perhaps from a native string data type, fewer internal copies, etc.) is a valuable goal. -After that, the next-most critical improvement is integer missing values. Those were actually added in [Pandas 0.24](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.24.0.html#optional-integer-na-support), but they're not the default, and there's still some incompatibilites with the rest of pandas API. +After that, the next-most critical improvement is integer missing values. Those were actually added in [Pandas 0.24](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.24.0.html#optional-integer-na-support), but they're not the default, and there's still some incompatibilities with the rest of pandas API. Pandas is a less conservative library than, say, NumPy. We're approaching 1.0, but on the way we've made many deprecations and some outright API breaking changes. Fortunately, most people are OK with the tradeoff. diff --git a/web/pandas/community/ecosystem.md b/web/pandas/community/ecosystem.md index 3e35b3ac4ea30..1d77c596c1eb0 100644 --- a/web/pandas/community/ecosystem.md +++ b/web/pandas/community/ecosystem.md @@ -177,7 +177,7 @@ users to view, manipulate and edit pandas `Index`, `Series`, and `DataFrame` objects like a "spreadsheet", including copying and modifying values, sorting, displaying a "heatmap", converting data types and more. Pandas objects can also be renamed, duplicated, new -columns added, copyed/pasted to/from the clipboard (as TSV), and +columns added, copied/pasted to/from the clipboard (as TSV), and saved/loaded to/from a file. Spyder can also import data from a variety of plain text and binary files or the clipboard into a new pandas DataFrame via a sophisticated import wizard. @@ -379,8 +379,8 @@ A directory of projects providing `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 | - | ---------------------------------------------------------------------|------------|-----------------------| + | Library | Accessor | Classes | + | -------------------------------------------------------------------- | ---------- | --------------------- | | [cyberpandas](https://cyberpandas.readthedocs.io/en/latest) | `ip` | `Series` | | [pdvega](https://altair-viz.github.io/pdvega/) | `vgplot` | `Series`, `DataFrame` | | [pandas-genomics](https://pandas-genomics.readthedocs.io/en/latest/) | `genomics` | `Series`, `DataFrame` |
Some violations raised by the codespell `pre-commit` hook I noticed during #46718. - [ ] closes - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47275
2022-06-07T17:57:06Z
2022-06-08T17:02:18Z
2022-06-08T17:02:18Z
2022-06-08T17:02:18Z
DOC: cross reference similar `Series.unique` and `Series.drop_duplicates` methods
diff --git a/pandas/core/series.py b/pandas/core/series.py index 4add3362d2391..6ef024f13fbb1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2073,6 +2073,7 @@ def unique(self) -> ArrayLike: See Also -------- + Series.drop_duplicates : Return Series with duplicate values removed. unique : Top-level unique method for any 1-d array-like object. Index.unique : Return Index with unique values from an Index object. @@ -2163,6 +2164,7 @@ def drop_duplicates(self, keep="first", inplace=False) -> Series | None: DataFrame.drop_duplicates : Equivalent method on DataFrame. Series.duplicated : Related method on Series, indicating duplicate Series values. + Series.unique : Return unique values as an array. Examples --------
- [x] closes #xxxx (Replace xxxx with the Github issue number) - [N/A] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [N/A] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [N/A] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Personally, I found `unique()` before I found `drop_duplicates()`, even though the latter is closer to what I wanted to achieve. As discussed in https://github.com/pandas-dev/pandas/issues/1923#issuecomment-515465111, cross-referencing these methods would help with discovering the desired method. Closes #1923
https://api.github.com/repos/pandas-dev/pandas/pulls/47274
2022-06-07T15:32:00Z
2022-06-07T16:33:52Z
2022-06-07T16:33:52Z
2022-06-07T17:22:00Z
Error raised message: DataFrame eval will not work with 'Timestamp' column name
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index a0d33cb513722..1379a13f0e42a 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -932,6 +932,8 @@ Conversion - Bug in :meth:`DataFrame.to_dict` for ``orient="list"`` or ``orient="index"`` was not returning native types (:issue:`46751`) - Bug in :meth:`DataFrame.apply` that returns a :class:`DataFrame` instead of a :class:`Series` when applied to an empty :class:`DataFrame` and ``axis=1`` (:issue:`39111`) - Bug when inferring the dtype from an iterable that is *not* a NumPy ``ndarray`` consisting of all NumPy unsigned integer scalars did not result in an unsigned integer dtype (:issue:`47294`) +- Bug in :meth:`DataFrame.eval` when pandas objects (e.g. ``'Timestamp'``) were column names (:issue:`44603`) +- Strings ^^^^^^^ diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index e331fc89f69b7..cb7b33e40d989 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -99,7 +99,14 @@ def evaluate(self, *args, **kwargs) -> Term: return self def _resolve_name(self): - res = self.env.resolve(self.local_name, is_local=self.is_local) + local_name = str(self.local_name) + is_local = self.is_local + if local_name in self.env.scope and isinstance( + self.env.scope[local_name], type + ): + is_local = False + + res = self.env.resolve(local_name, is_local=is_local) self.update(res) if hasattr(res, "ndim") and res.ndim > 2: diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index b0ad2f69a75b9..672a87edbad66 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -49,6 +49,7 @@ _binary_ops_dict, _unary_math_ops, ) +from pandas.core.computation.scope import DEFAULT_GLOBALS @pytest.fixture( @@ -1890,6 +1891,27 @@ def test_negate_lt_eq_le(engine, parser): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize( + "column", + DEFAULT_GLOBALS.keys(), +) +def test_eval_no_support_column_name(request, column): + # GH 44603 + if column in ["True", "False", "inf", "Inf"]: + request.node.add_marker( + pytest.mark.xfail( + raises=KeyError, + reason=f"GH 47859 DataFrame eval not supported with {column}", + ) + ) + + df = DataFrame(np.random.randint(0, 100, size=(10, 2)), columns=[column, "col1"]) + expected = df[df[column] > 6] + result = df.query(f"{column}>6") + + tm.assert_frame_equal(result, expected) + + class TestValidate: @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) def test_validate_bool_args(self, value):
- [ ] closes #44603 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47273
2022-06-07T15:08:34Z
2022-08-12T00:15:49Z
2022-08-12T00:15:49Z
2022-08-12T01:02:32Z
Backport PR #47121 on branch 1.4.x (BUG: read_excel loading some xlsx ints as floats)
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index f594aae2c7f9f..ca8b8ca15ec47 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :func:`read_csv` with ``index_col=False`` identifying first row as index names when ``header=None`` (:issue:`46955`) - Fixed regression in :meth:`.DataFrameGroupBy.agg` when used with list-likes or dict-likes and ``axis=1`` that would give incorrect results; now raises ``NotImplementedError`` (:issue:`46995`) - Fixed regression in :meth:`DataFrame.resample` and :meth:`DataFrame.rolling` when used with list-likes or dict-likes and ``axis=1`` that would raise an unintuitive error message; now raises ``NotImplementedError`` (:issue:`46904`) +- Fixed regression in :func:`read_excel` returning ints as floats on certain input sheets (:issue:`46988`) - Fixed regression in :meth:`DataFrame.shift` when ``axis`` is ``columns`` and ``fill_value`` is absent, ``freq`` is ignored (:issue:`47039`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 27c03d4a74bc1..8ec24b35779a0 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -560,8 +560,14 @@ def _convert_cell(self, cell, convert_float: bool) -> Scalar: return "" # compat with xlrd elif cell.data_type == TYPE_ERROR: return np.nan - elif not convert_float and cell.data_type == TYPE_NUMERIC: - return float(cell.value) + elif cell.data_type == TYPE_NUMERIC: + # GH5394, GH46988 + if convert_float: + val = int(cell.value) + if val == cell.value: + return val + else: + return float(cell.value) return cell.value diff --git a/pandas/tests/io/data/excel/ints_spelled_with_decimals.xlsx b/pandas/tests/io/data/excel/ints_spelled_with_decimals.xlsx new file mode 100644 index 0000000000000..a667be86283b8 Binary files /dev/null and b/pandas/tests/io/data/excel/ints_spelled_with_decimals.xlsx differ diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index e0d4a0c12ecdf..e420b9e806f65 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -375,3 +375,11 @@ def test_read_empty_with_blank_row(datapath, ext, read_only): wb.close() expected = DataFrame() tm.assert_frame_equal(result, expected) + + +def test_ints_spelled_with_decimals(datapath, ext): + # GH 46988 - openpyxl returns this sheet with floats + path = datapath("io", "data", "excel", f"ints_spelled_with_decimals{ext}") + result = pd.read_excel(path) + expected = DataFrame(range(2, 12), columns=[1]) + tm.assert_frame_equal(result, expected)
Backport PR #47121
https://api.github.com/repos/pandas-dev/pandas/pulls/47271
2022-06-07T13:06:26Z
2022-06-07T14:16:07Z
2022-06-07T14:16:07Z
2022-06-07T14:16:12Z
BUG: pd.Timedelta(big_int, unit=W) silent overflow
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 71af2ff650a01..7199a23876b8e 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -436,6 +436,7 @@ Other API changes The ``auth_local_webserver = False`` option is planned to stop working in October 2022. (:issue:`46312`) - :func:`read_json` now raises ``FileNotFoundError`` (previously ``ValueError``) when input is a string ending in ``.json``, ``.json.gz``, ``.json.bz2``, etc. but no such file exists. (:issue:`29102`) +- Operations with :class:`Timestamp` or :class:`Timedelta` that would previously raise ``OverflowError`` instead raise ``OutOfBoundsDatetime`` or ``OutOfBoundsTimedelta`` where appropriate (:issue:`47268`) - .. --------------------------------------------------------------------------- @@ -736,6 +737,7 @@ Timedelta ^^^^^^^^^ - Bug in :func:`astype_nansafe` astype("timedelta64[ns]") fails when np.nan is included (:issue:`45798`) - Bug in constructing a :class:`Timedelta` with a ``np.timedelta64`` object and a ``unit`` sometimes silently overflowing and returning incorrect results instead of raising ``OutOfBoundsTimedelta`` (:issue:`46827`) +- Bug in constructing a :class:`Timedelta` from a large integer or float with ``unit="W"`` silently overflowing and returning incorrect results instead of raising ``OutOfBoundsTimedelta`` (:issue:`47268`) - Time Zones diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 28a6480f368d9..d8a069245f9d7 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -316,6 +316,8 @@ cdef convert_to_timedelta64(object ts, str unit): Return an ns based int64 """ + # Caller is responsible for checking unit not in ["Y", "y", "M"] + if checknull_with_nat(ts): return np.timedelta64(NPY_NAT, "ns") elif isinstance(ts, _Timedelta): @@ -329,17 +331,9 @@ cdef convert_to_timedelta64(object ts, str unit): if ts == NPY_NAT: return np.timedelta64(NPY_NAT, "ns") else: - if unit in ["Y", "M", "W"]: - ts = np.timedelta64(ts, unit) - else: - ts = cast_from_unit(ts, unit) - ts = np.timedelta64(ts, "ns") + ts = _maybe_cast_from_unit(ts, unit) elif is_float_object(ts): - if unit in ["Y", "M", "W"]: - ts = np.timedelta64(int(ts), unit) - else: - ts = cast_from_unit(ts, unit) - ts = np.timedelta64(ts, "ns") + ts = _maybe_cast_from_unit(ts, unit) elif isinstance(ts, str): if (len(ts) > 0 and ts[0] == "P") or (len(ts) > 1 and ts[:2] == "-P"): ts = parse_iso_format_string(ts) @@ -356,6 +350,20 @@ cdef convert_to_timedelta64(object ts, str unit): return ts.astype("timedelta64[ns]") +cdef _maybe_cast_from_unit(ts, str unit): + # caller is responsible for checking + # assert unit not in ["Y", "y", "M"] + try: + ts = cast_from_unit(ts, unit) + except OverflowError as err: + raise OutOfBoundsTimedelta( + f"Cannot cast {ts} from {unit} to 'ns' without overflow." + ) from err + + ts = np.timedelta64(ts, "ns") + return ts + + @cython.boundscheck(False) @cython.wraparound(False) def array_to_timedelta64( @@ -370,6 +378,8 @@ def array_to_timedelta64( ------- np.ndarray[timedelta64ns] """ + # Caller is responsible for checking + assert unit not in ["Y", "y", "M"] cdef: Py_ssize_t i, n = values.size @@ -652,24 +662,20 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): cdef: str n - try: - unit = ''.join(unit) - - if unit in ["M", "Y", "y"]: - warnings.warn( - "Units 'M', 'Y' and 'y' do not represent unambiguous " - "timedelta values and will be removed in a future version.", - FutureWarning, - stacklevel=2, - ) + unit = ''.join(unit) + if unit in ["M", "Y", "y"]: + warnings.warn( + "Units 'M', 'Y' and 'y' do not represent unambiguous " + "timedelta values and will be removed in a future version.", + FutureWarning, + stacklevel=3, + ) - if unit == 'M': - # To parse ISO 8601 string, 'M' should be treated as minute, - # not month - unit = 'm' - unit = parse_timedelta_unit(unit) - except KeyError: - raise ValueError(f"invalid abbreviation: {unit}") + if unit == 'M': + # To parse ISO 8601 string, 'M' should be treated as minute, + # not month + unit = 'm' + unit = parse_timedelta_unit(unit) n = ''.join(number) + '.' + ''.join(frac) return cast_from_unit(float(n), unit) @@ -696,7 +702,7 @@ cpdef inline str parse_timedelta_unit(str unit): return unit try: return timedelta_abbrevs[unit.lower()] - except (KeyError, AttributeError): + except KeyError: raise ValueError(f"invalid unit abbreviation: {unit}") # ---------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 67aae23f7fdd1..c25a8687ba33e 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -90,7 +90,10 @@ from pandas._libs.tslibs.np_datetime cimport ( pydatetime_to_dt64, ) -from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime +from pandas._libs.tslibs.np_datetime import ( + OutOfBoundsDatetime, + OutOfBoundsTimedelta, +) from pandas._libs.tslibs.offsets cimport ( BaseOffset, @@ -455,7 +458,7 @@ cdef class _Timestamp(ABCTimestamp): # Timedelta try: return Timedelta(self.value - other.value) - except (OverflowError, OutOfBoundsDatetime) as err: + except (OverflowError, OutOfBoundsDatetime, OutOfBoundsTimedelta) as err: if isinstance(other, _Timestamp): if both_timestamps: raise OutOfBoundsDatetime( diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 793bddee7f3cc..36e8e44e2034f 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -270,6 +270,8 @@ def _from_sequence_not_strict( if dtype: _validate_td64_dtype(dtype) + assert unit not in ["Y", "y", "M"] # caller is responsible for checking + explicit_none = freq is None freq = freq if freq is not lib.no_default else None @@ -923,6 +925,8 @@ def sequence_to_td64ns( errors to be ignored; they are caught and subsequently ignored at a higher level. """ + assert unit not in ["Y", "y", "M"] # caller is responsible for checking + inferred_freq = None if unit is not None: unit = parse_timedelta_unit(unit) @@ -954,7 +958,7 @@ def sequence_to_td64ns( # Convert whatever we have into timedelta64[ns] dtype if is_object_dtype(data.dtype) or is_string_dtype(data.dtype): # no need to make a copy, need to convert if string-dtyped - data = objects_to_td64ns(data, unit=unit, errors=errors) + data = _objects_to_td64ns(data, unit=unit, errors=errors) copy = False elif is_integer_dtype(data.dtype): @@ -1032,7 +1036,7 @@ def ints_to_td64ns(data, unit="ns"): return data, copy_made -def objects_to_td64ns(data, unit=None, errors="raise"): +def _objects_to_td64ns(data, unit=None, errors="raise"): """ Convert a object-dtyped or string-dtyped array into an timedelta64[ns]-dtyped array. diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index c9e096bb3678e..614245ec7a93e 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -99,8 +99,8 @@ def test_td_add_datetimelike_scalar(self, op): assert result is NaT def test_td_add_timestamp_overflow(self): - msg = "int too (large|big) to convert" - with pytest.raises(OverflowError, match=msg): + msg = "Cannot cast 259987 from D to 'ns' without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=msg): Timestamp("1700-01-01") + Timedelta(13 * 19999, unit="D") msg = "Cannot cast 259987 days, 0:00:00 to unit=ns without overflow" diff --git a/pandas/tests/scalar/timedelta/test_constructors.py b/pandas/tests/scalar/timedelta/test_constructors.py index 3a12fa031545b..5b2438ec30f3a 100644 --- a/pandas/tests/scalar/timedelta/test_constructors.py +++ b/pandas/tests/scalar/timedelta/test_constructors.py @@ -13,6 +13,15 @@ ) +def test_construct_with_weeks_unit_overflow(): + # GH#47268 don't silently wrap around + with pytest.raises(OutOfBoundsTimedelta, match="without overflow"): + Timedelta(1000000000000000000, unit="W") + + with pytest.raises(OutOfBoundsTimedelta, match="without overflow"): + Timedelta(1000000000000000000.0, unit="W") + + def test_construct_from_td64_with_unit(): # ignore the unit, as it may cause silently overflows leading to incorrect # results, and in non-overflow cases is irrelevant GH#46827 @@ -204,15 +213,15 @@ def test_td_from_repr_roundtrip(val): def test_overflow_on_construction(): - msg = "int too (large|big) to convert" - # GH#3374 value = Timedelta("1day").value * 20169940 - with pytest.raises(OverflowError, match=msg): + msg = "Cannot cast 1742682816000000000000 from ns to 'ns' without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=msg): Timedelta(value) # xref GH#17637 - with pytest.raises(OverflowError, match=msg): + msg = "Cannot cast 139993 from D to 'ns' without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=msg): Timedelta(7 * 19999, unit="D") msg = "Cannot cast 259987 days, 0:00:00 to unit=ns without overflow" diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 5ef69075c5e2f..90c090d816c9d 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -744,10 +744,12 @@ def test_implementation_limits(self): td = Timedelta(min_td.value - 1, "ns") assert td is NaT - with pytest.raises(OverflowError, match=msg): + msg = "Cannot cast -9223372036854775809 from ns to 'ns' without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=msg): Timedelta(min_td.value - 2, "ns") - with pytest.raises(OverflowError, match=msg): + msg = "Cannot cast 9223372036854775808 from ns to 'ns' without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=msg): Timedelta(max_td.value + 1, "ns") def test_total_seconds_precision(self):
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47268
2022-06-07T03:29:30Z
2022-06-07T18:53:06Z
2022-06-07T18:53:06Z
2022-09-23T15:14:27Z
DEPR: Timestamp(150.5, unit=Y)
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 8a7ad077c2a90..4590e2296f633 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -682,6 +682,8 @@ Other Deprecations - Deprecated the ``closed`` argument in :class:`IntervalArray` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`) - Deprecated the ``closed`` argument in :class:`intervaltree` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`) - Deprecated the ``closed`` argument in :class:`ArrowInterval` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`) +- Deprecated allowing ``unit="M"`` or ``unit="Y"`` in :class:`Timestamp` constructor with a non-round float value (:issue:`47267`) +- .. --------------------------------------------------------------------------- .. _whatsnew_150.performance: diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 808f750c18c9d..44335836dc2ee 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1,5 +1,7 @@ cimport cython +import warnings + import numpy as np cimport numpy as cnp @@ -255,6 +257,18 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, if ts != ts or ts == NPY_NAT: obj.value = NPY_NAT else: + if unit in ["Y", "M"]: + if ts != int(ts): + # GH#47267 it is clear that 2 "M" corresponds to 1970-02-01, + # but not clear what 2.5 "M" corresponds to, so we will + # disallow that case. + warnings.warn( + "Conversion of non-round float with unit={unit} is ambiguous " + "and will raise in a future version.", + FutureWarning, + stacklevel=1, + ) + ts = cast_from_unit(ts, unit) obj.value = ts dt64_to_dtstruct(ts, &obj.dts) diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index a5641473c4d52..daf1730df489d 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -25,6 +25,15 @@ class TestTimestampConstructors: + def test_constructor_float_not_round_with_YM_unit_deprecated(self): + # GH#47267 avoid the conversions in cast_from-unit + + with tm.assert_produces_warning(FutureWarning, match="ambiguous"): + Timestamp(150.5, unit="Y") + + with tm.assert_produces_warning(FutureWarning, match="ambiguous"): + Timestamp(150.5, unit="M") + def test_constructor_datetime64_with_tz(self): # GH#42288, GH#24559 dt = np.datetime64("1970-01-01 05:00:00")
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. will have merge conflict with #47266, doesn't matter which order we do these in
https://api.github.com/repos/pandas-dev/pandas/pulls/47267
2022-06-07T02:31:56Z
2022-06-07T16:47:05Z
2022-06-07T16:47:05Z
2022-06-07T16:54:12Z
BUG: Timestamp with unit=Y or unit=M
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 963acdc03d1f5..8a947e4505ec5 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -731,6 +731,7 @@ Datetimelike - Bug in :meth:`SeriesGroupBy.value_counts` index when passing categorical column (:issue:`44324`) - Bug in :meth:`DatetimeIndex.tz_localize` localizing to UTC failing to make a copy of the underlying data (:issue:`46460`) - Bug in :meth:`DatetimeIndex.resolution` incorrectly returning "day" instead of "nanosecond" for nanosecond-resolution indexes (:issue:`46903`) +- Bug in :class:`Timestamp` with an integer or float value and ``unit="Y"`` or ``unit="M"`` giving slightly-wrong results (:issue:`47266`) - Timedelta diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 44335836dc2ee..fe558d5c58368 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -250,6 +250,12 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, if ts == NPY_NAT: obj.value = NPY_NAT else: + if unit in ["Y", "M"]: + # GH#47266 cast_from_unit leads to weird results e.g. with "Y" + # and 150 we'd get 2120-01-01 09:00:00 + ts = np.datetime64(ts, unit) + return convert_to_tsobject(ts, tz, None, False, False) + ts = ts * cast_from_unit(None, unit) obj.value = ts dt64_to_dtstruct(ts, &obj.dts) @@ -258,7 +264,11 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, obj.value = NPY_NAT else: if unit in ["Y", "M"]: - if ts != int(ts): + if ts == int(ts): + # GH#47266 Avoid cast_from_unit, which would give weird results + # e.g. with "Y" and 150.0 we'd get 2120-01-01 09:00:00 + return convert_to_tsobject(int(ts), tz, unit, False, False) + else: # GH#47267 it is clear that 2 "M" corresponds to 1970-02-01, # but not clear what 2.5 "M" corresponds to, so we will # disallow that case. diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index daf1730df489d..7b3647dc6cbef 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -25,6 +25,19 @@ class TestTimestampConstructors: + @pytest.mark.parametrize("typ", [int, float]) + def test_constructor_int_float_with_YM_unit(self, typ): + # GH#47266 avoid the conversions in cast_from_unit + val = typ(150) + + ts = Timestamp(val, unit="Y") + expected = Timestamp("2120-01-01") + assert ts == expected + + ts = Timestamp(val, unit="M") + expected = Timestamp("1982-07-01") + assert ts == expected + def test_constructor_float_not_round_with_YM_unit_deprecated(self): # GH#47267 avoid the conversions in cast_from-unit
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47266
2022-06-07T02:29:24Z
2022-06-07T23:47:10Z
2022-06-07T23:47:09Z
2022-06-08T01:19:09Z
ENH: Add numeric_only to window ops
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 8a947e4505ec5..e9b2c9f7d27b2 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -654,6 +654,9 @@ gained the ``numeric_only`` argument. - :meth:`.Resampler.sem` - :meth:`.Resampler.std` - :meth:`.Resampler.var` +- :meth:`DataFrame.rolling` operations +- :meth:`DataFrame.expanding` operations +- :meth:`DataFrame.ewm` operations .. _whatsnew_150.deprecations.other: diff --git a/pandas/core/window/doc.py b/pandas/core/window/doc.py index 930c12841e4e4..61cfa29ffc481 100644 --- a/pandas/core/window/doc.py +++ b/pandas/core/window/doc.py @@ -29,6 +29,15 @@ def create_section_header(header: str) -> str: """ ).replace("\n", "", 1) +kwargs_numeric_only = dedent( + """ + numeric_only : bool, default False + Include only float, int, boolean columns. + + .. versionadded:: 1.5.0\n + """ +).replace("\n", "", 1) + args_compat = dedent( """ *args diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index d2b4db75f839b..a153761f377b3 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -26,7 +26,10 @@ from pandas.util._decorators import doc from pandas.util._exceptions import find_stack_level -from pandas.core.dtypes.common import is_datetime64_ns_dtype +from pandas.core.dtypes.common import ( + is_datetime64_ns_dtype, + is_numeric_dtype, +) from pandas.core.dtypes.missing import isna import pandas.core.common as common # noqa: PDF018 @@ -45,6 +48,7 @@ args_compat, create_section_header, kwargs_compat, + kwargs_numeric_only, numba_notes, template_header, template_returns, @@ -518,6 +522,7 @@ def aggregate(self, func, *args, **kwargs): @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -531,7 +536,14 @@ def aggregate(self, func, *args, **kwargs): aggregation_description="(exponential weighted moment) mean", agg_method="mean", ) - def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): + def mean( + self, + numeric_only: bool = False, + *args, + engine=None, + engine_kwargs=None, + **kwargs, + ): if maybe_use_numba(engine): if self.method == "single": func = generate_numba_ewm_func @@ -545,7 +557,7 @@ def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): deltas=tuple(self._deltas), normalize=True, ) - return self._apply(ewm_func) + return self._apply(ewm_func, name="mean") elif engine in ("cython", None): if engine_kwargs is not None: raise ValueError("cython engine does not accept engine_kwargs") @@ -560,13 +572,14 @@ def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): deltas=deltas, normalize=True, ) - return self._apply(window_func) + return self._apply(window_func, name="mean", numeric_only=numeric_only) else: raise ValueError("engine must be either 'numba' or 'cython'") @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -580,7 +593,14 @@ def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): aggregation_description="(exponential weighted moment) sum", agg_method="sum", ) - def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): + def sum( + self, + numeric_only: bool = False, + *args, + engine=None, + engine_kwargs=None, + **kwargs, + ): if not self.adjust: raise NotImplementedError("sum is not implemented with adjust=False") if maybe_use_numba(engine): @@ -596,7 +616,7 @@ def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): deltas=tuple(self._deltas), normalize=False, ) - return self._apply(ewm_func) + return self._apply(ewm_func, name="sum") elif engine in ("cython", None): if engine_kwargs is not None: raise ValueError("cython engine does not accept engine_kwargs") @@ -611,7 +631,7 @@ def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): deltas=deltas, normalize=False, ) - return self._apply(window_func) + return self._apply(window_func, name="sum", numeric_only=numeric_only) else: raise ValueError("engine must be either 'numba' or 'cython'") @@ -624,6 +644,7 @@ def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): Use a standard estimation bias correction. """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, kwargs_compat, create_section_header("Returns"), @@ -634,9 +655,18 @@ def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): aggregation_description="(exponential weighted moment) standard deviation", agg_method="std", ) - def std(self, bias: bool = False, *args, **kwargs): + def std(self, bias: bool = False, numeric_only: bool = False, *args, **kwargs): nv.validate_window_func("std", args, kwargs) - return zsqrt(self.var(bias=bias, **kwargs)) + if ( + numeric_only + and self._selected_obj.ndim == 1 + and not is_numeric_dtype(self._selected_obj.dtype) + ): + # Raise directly so error message says std instead of var + raise NotImplementedError( + f"{type(self).__name__}.std does not implement numeric_only" + ) + return zsqrt(self.var(bias=bias, numeric_only=numeric_only, **kwargs)) def vol(self, bias: bool = False, *args, **kwargs): warnings.warn( @@ -658,6 +688,7 @@ def vol(self, bias: bool = False, *args, **kwargs): Use a standard estimation bias correction. """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, kwargs_compat, create_section_header("Returns"), @@ -668,7 +699,7 @@ def vol(self, bias: bool = False, *args, **kwargs): aggregation_description="(exponential weighted moment) variance", agg_method="var", ) - def var(self, bias: bool = False, *args, **kwargs): + def var(self, bias: bool = False, numeric_only: bool = False, *args, **kwargs): nv.validate_window_func("var", args, kwargs) window_func = window_aggregations.ewmcov wfunc = partial( @@ -682,7 +713,7 @@ def var(self, bias: bool = False, *args, **kwargs): def var_func(values, begin, end, min_periods): return wfunc(values, begin, end, min_periods, values) - return self._apply(var_func) + return self._apply(var_func, name="var", numeric_only=numeric_only) @doc( template_header, @@ -703,6 +734,7 @@ def var_func(values, begin, end, min_periods): Use a standard estimation bias correction. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -717,10 +749,13 @@ def cov( other: DataFrame | Series | None = None, pairwise: bool | None = None, bias: bool = False, + numeric_only: bool = False, **kwargs, ): from pandas import Series + self._validate_numeric_only("cov", numeric_only) + def cov_func(x, y): x_array = self._prep_values(x) y_array = self._prep_values(y) @@ -752,7 +787,9 @@ def cov_func(x, y): ) return Series(result, index=x.index, name=x.name) - return self._apply_pairwise(self._selected_obj, other, pairwise, cov_func) + return self._apply_pairwise( + self._selected_obj, other, pairwise, cov_func, numeric_only + ) @doc( template_header, @@ -771,6 +808,7 @@ def cov_func(x, y): observations will be used. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -784,10 +822,13 @@ def corr( self, other: DataFrame | Series | None = None, pairwise: bool | None = None, + numeric_only: bool = False, **kwargs, ): from pandas import Series + self._validate_numeric_only("corr", numeric_only) + def cov_func(x, y): x_array = self._prep_values(x) y_array = self._prep_values(y) @@ -825,7 +866,9 @@ def _cov(X, Y): result = cov / zsqrt(x_var * y_var) return Series(result, index=x.index, name=x.name) - return self._apply_pairwise(self._selected_obj, other, pairwise, cov_func) + return self._apply_pairwise( + self._selected_obj, other, pairwise, cov_func, numeric_only + ) class ExponentialMovingWindowGroupby(BaseWindowGroupby, ExponentialMovingWindow): @@ -921,6 +964,7 @@ def corr( self, other: DataFrame | Series | None = None, pairwise: bool | None = None, + numeric_only: bool = False, **kwargs, ): return NotImplementedError @@ -930,6 +974,7 @@ def cov( other: DataFrame | Series | None = None, pairwise: bool | None = None, bias: bool = False, + numeric_only: bool = False, **kwargs, ): return NotImplementedError diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 36a1da0dbf837..7f9dfece959de 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -29,6 +29,7 @@ args_compat, create_section_header, kwargs_compat, + kwargs_numeric_only, numba_notes, template_header, template_returns, @@ -192,8 +193,8 @@ def aggregate(self, func, *args, **kwargs): aggregation_description="count of non NaN observations", agg_method="count", ) - def count(self): - return super().count() + def count(self, numeric_only: bool = False): + return super().count(numeric_only=numeric_only) @doc( template_header, @@ -228,6 +229,7 @@ def apply( @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -243,17 +245,24 @@ def apply( ) def sum( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_expanding_func("sum", args, kwargs) - return super().sum(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().sum( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -269,17 +278,24 @@ def sum( ) def max( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_expanding_func("max", args, kwargs) - return super().max(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().max( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -295,17 +311,24 @@ def max( ) def min( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_expanding_func("min", args, kwargs) - return super().min(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().min( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -321,17 +344,24 @@ def min( ) def mean( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_expanding_func("mean", args, kwargs) - return super().mean(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().mean( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, window_agg_numba_parameters(), kwargs_compat, create_section_header("Returns"), @@ -346,11 +376,17 @@ def mean( ) def median( self, + numeric_only: bool = False, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): - return super().median(engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().median( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, @@ -362,6 +398,7 @@ def median( is ``N - ddof``, where ``N`` represents the number of elements.\n """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, window_agg_numba_parameters("1.4"), kwargs_compat, @@ -402,6 +439,7 @@ def median( def std( self, ddof: int = 1, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -409,7 +447,11 @@ def std( ): nv.validate_expanding_func("std", args, kwargs) return super().std( - ddof=ddof, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ddof=ddof, + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, ) @doc( @@ -422,6 +464,7 @@ def std( is ``N - ddof``, where ``N`` represents the number of elements.\n """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, window_agg_numba_parameters("1.4"), kwargs_compat, @@ -462,6 +505,7 @@ def std( def var( self, ddof: int = 1, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -469,7 +513,11 @@ def var( ): nv.validate_expanding_func("var", args, kwargs) return super().var( - ddof=ddof, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ddof=ddof, + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, ) @doc( @@ -482,6 +530,7 @@ def var( is ``N - ddof``, where ``N`` represents the number of elements.\n """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, kwargs_compat, create_section_header("Returns"), @@ -513,6 +562,7 @@ def sem(self, ddof: int = 1, *args, **kwargs): @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -525,12 +575,13 @@ def sem(self, ddof: int = 1, *args, **kwargs): aggregation_description="unbiased skewness", agg_method="skew", ) - def skew(self, **kwargs): - return super().skew(**kwargs) + def skew(self, numeric_only: bool = False, **kwargs): + return super().skew(numeric_only=numeric_only, **kwargs) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -565,8 +616,8 @@ def skew(self, **kwargs): aggregation_description="Fisher's definition of kurtosis without bias", agg_method="kurt", ) - def kurt(self, **kwargs): - return super().kurt(**kwargs) + def kurt(self, numeric_only: bool = False, **kwargs): + return super().kurt(numeric_only=numeric_only, **kwargs) @doc( template_header, @@ -587,6 +638,7 @@ def kurt(self, **kwargs): * midpoint: (`i` + `j`) / 2. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -600,11 +652,13 @@ def quantile( self, quantile: float, interpolation: str = "linear", + numeric_only: bool = False, **kwargs, ): return super().quantile( quantile=quantile, interpolation=interpolation, + numeric_only=numeric_only, **kwargs, ) @@ -628,6 +682,7 @@ def quantile( form. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -674,12 +729,14 @@ def rank( method: WindowingRankType = "average", ascending: bool = True, pct: bool = False, + numeric_only: bool = False, **kwargs, ): return super().rank( method=method, ascending=ascending, pct=pct, + numeric_only=numeric_only, **kwargs, ) @@ -703,6 +760,7 @@ def rank( is ``N - ddof``, where ``N`` represents the number of elements. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -717,9 +775,16 @@ def cov( other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, + numeric_only: bool = False, **kwargs, ): - return super().cov(other=other, pairwise=pairwise, ddof=ddof, **kwargs) + return super().cov( + other=other, + pairwise=pairwise, + ddof=ddof, + numeric_only=numeric_only, + **kwargs, + ) @doc( template_header, @@ -738,6 +803,7 @@ def cov( observations will be used. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -782,9 +848,16 @@ def corr( other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, + numeric_only: bool = False, **kwargs, ): - return super().corr(other=other, pairwise=pairwise, ddof=ddof, **kwargs) + return super().corr( + other=other, + pairwise=pairwise, + ddof=ddof, + numeric_only=numeric_only, + **kwargs, + ) class ExpandingGroupby(BaseWindowGroupby, Expanding): diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 9e8f95cf340c4..4d506fbf896b6 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -42,6 +42,7 @@ is_bool, is_integer, is_list_like, + is_numeric_dtype, is_scalar, needs_i8_conversion, ) @@ -84,6 +85,7 @@ args_compat, create_section_header, kwargs_compat, + kwargs_numeric_only, kwargs_scipy, numba_notes, template_header, @@ -258,18 +260,53 @@ def _slice_axis_for_step(self, index: Index, result: Sized | None = None) -> Ind else index[:: self.step] ) - def _create_data(self, obj: NDFrameT) -> NDFrameT: + def _validate_numeric_only(self, name: str, numeric_only: bool) -> None: + """ + Validate numeric_only argument, raising if invalid for the input. + + Parameters + ---------- + name : str + Name of the operator (kernel). + numeric_only : bool + Value passed by user. + """ + if ( + self._selected_obj.ndim == 1 + and numeric_only + and not is_numeric_dtype(self._selected_obj.dtype) + ): + raise NotImplementedError( + f"{type(self).__name__}.{name} does not implement numeric_only" + ) + + def _make_numeric_only(self, obj: NDFrameT) -> NDFrameT: + """Subset DataFrame to numeric columns. + + Parameters + ---------- + obj : DataFrame + + Returns + ------- + obj subset to numeric-only columns. + """ + result = obj.select_dtypes(include=["number"], exclude=["timedelta"]) + return result + + def _create_data(self, obj: NDFrameT, numeric_only: bool = False) -> NDFrameT: """ Split data into blocks & return conformed data. """ # filter out the on from the object if self.on is not None and not isinstance(self.on, Index) and obj.ndim == 2: obj = obj.reindex(columns=obj.columns.difference([self.on]), copy=False) - if self.axis == 1: + if obj.ndim > 1 and (numeric_only or self.axis == 1): # GH: 20649 in case of mixed dtype and axis=1 we have to convert everything # to float to calculate the complete row at once. We exclude all non-numeric # dtypes. - obj = obj.select_dtypes(include=["number"], exclude=["timedelta"]) + obj = self._make_numeric_only(obj) + if self.axis == 1: obj = obj.astype("float64", copy=False) obj._mgr = obj._mgr.consolidate() return obj @@ -451,16 +488,20 @@ def _apply_series( return obj._constructor(result, index=index, name=obj.name) def _apply_blockwise( - self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None + self, + homogeneous_func: Callable[..., ArrayLike], + name: str, + numeric_only: bool = False, ) -> DataFrame | Series: """ Apply the given function to the DataFrame broken down into homogeneous sub-frames. """ + self._validate_numeric_only(name, numeric_only) if self._selected_obj.ndim == 1: return self._apply_series(homogeneous_func, name) - obj = self._create_data(self._selected_obj) + obj = self._create_data(self._selected_obj, numeric_only) if name == "count": # GH 12541: Special case for count where we support date-like types obj = notna(obj).astype(int) @@ -513,14 +554,17 @@ def hfunc(values: ArrayLike) -> ArrayLike: return self._resolve_output(df, obj) def _apply_tablewise( - self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None + self, + homogeneous_func: Callable[..., ArrayLike], + name: str | None = None, + numeric_only: bool = False, ) -> DataFrame | Series: """ Apply the given function to the DataFrame across the entire object """ if self._selected_obj.ndim == 1: raise ValueError("method='table' not applicable for Series objects.") - obj = self._create_data(self._selected_obj) + obj = self._create_data(self._selected_obj, numeric_only) values = self._prep_values(obj.to_numpy()) values = values.T if self.axis == 1 else values result = homogeneous_func(values) @@ -541,23 +585,28 @@ def _apply_pairwise( other: DataFrame | Series | None, pairwise: bool | None, func: Callable[[DataFrame | Series, DataFrame | Series], DataFrame | Series], + numeric_only: bool, ) -> DataFrame | Series: """ Apply the given pairwise function given 2 pandas objects (DataFrame/Series) """ + target = self._create_data(target, numeric_only) if other is None: other = target # only default unset pairwise = True if pairwise is None else pairwise elif not isinstance(other, (ABCDataFrame, ABCSeries)): raise ValueError("other must be a DataFrame or Series") + elif other.ndim == 2 and numeric_only: + other = self._make_numeric_only(other) return flex_binary_moment(target, other, func, pairwise=bool(pairwise)) def _apply( self, func: Callable[..., Any], - name: str | None = None, + name: str, + numeric_only: bool = False, numba_args: tuple[Any, ...] = (), **kwargs, ): @@ -610,9 +659,9 @@ def calc(x): return result if self.method == "single": - return self._apply_blockwise(homogeneous_func, name) + return self._apply_blockwise(homogeneous_func, name, numeric_only) else: - return self._apply_tablewise(homogeneous_func, name) + return self._apply_tablewise(homogeneous_func, name, numeric_only) def _numba_apply( self, @@ -699,13 +748,15 @@ def __init__( def _apply( self, func: Callable[..., Any], - name: str | None = None, + name: str, + numeric_only: bool = False, numba_args: tuple[Any, ...] = (), **kwargs, ) -> DataFrame | Series: result = super()._apply( func, name, + numeric_only, numba_args, **kwargs, ) @@ -761,14 +812,14 @@ def _apply_pairwise( other: DataFrame | Series | None, pairwise: bool | None, func: Callable[[DataFrame | Series, DataFrame | Series], DataFrame | Series], + numeric_only: bool, ) -> DataFrame | Series: """ Apply the given pairwise function given 2 pandas objects (DataFrame/Series) """ # Manually drop the grouping column first target = target.drop(columns=self._grouper.names, errors="ignore") - target = self._create_data(target) - result = super()._apply_pairwise(target, other, pairwise, func) + result = super()._apply_pairwise(target, other, pairwise, func, numeric_only) # 1) Determine the levels + codes of the groupby levels if other is not None and not all( len(group) == len(other) for group in self._grouper.indices.values() @@ -839,7 +890,7 @@ def _apply_pairwise( result.index = result_index return result - def _create_data(self, obj: NDFrameT) -> NDFrameT: + def _create_data(self, obj: NDFrameT, numeric_only: bool = False) -> NDFrameT: """ Split data into blocks & return conformed data. """ @@ -851,7 +902,7 @@ def _create_data(self, obj: NDFrameT) -> NDFrameT: np.int64 ) obj = obj.take(groupby_order) - return super()._create_data(obj) + return super()._create_data(obj, numeric_only) def _gotitem(self, key, ndim, subset=None): # we are setting the index on the actual object @@ -1137,7 +1188,8 @@ def _center_window(self, result: np.ndarray, offset: int) -> np.ndarray: def _apply( self, func: Callable[[np.ndarray, int, int], np.ndarray], - name: str | None = None, + name: str, + numeric_only: bool = False, numba_args: tuple[Any, ...] = (), **kwargs, ): @@ -1150,6 +1202,8 @@ def _apply( ---------- func : callable function to apply name : str, + numeric_only : bool, default False + Whether to only operate on bool, int, and float columns numba_args : tuple unused **kwargs @@ -1185,7 +1239,7 @@ def calc(x): return result - return self._apply_blockwise(homogeneous_func, name)[:: self.step] + return self._apply_blockwise(homogeneous_func, name, numeric_only)[:: self.step] @doc( _shared_docs["aggregate"], @@ -1232,6 +1286,7 @@ def aggregate(self, func, *args, **kwargs): @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, kwargs_scipy, create_section_header("Returns"), template_returns, @@ -1241,17 +1296,23 @@ def aggregate(self, func, *args, **kwargs): aggregation_description="weighted window sum", agg_method="sum", ) - def sum(self, *args, **kwargs): + def sum(self, numeric_only: bool = False, *args, **kwargs): nv.validate_window_func("sum", args, kwargs) window_func = window_aggregations.roll_weighted_sum # error: Argument 1 to "_apply" of "Window" has incompatible type # "Callable[[ndarray, ndarray, int], ndarray]"; expected # "Callable[[ndarray, int, int], ndarray]" - return self._apply(window_func, name="sum", **kwargs) # type: ignore[arg-type] + return self._apply( + window_func, # type: ignore[arg-type] + name="sum", + numeric_only=numeric_only, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, kwargs_scipy, create_section_header("Returns"), template_returns, @@ -1261,18 +1322,24 @@ def sum(self, *args, **kwargs): aggregation_description="weighted window mean", agg_method="mean", ) - def mean(self, *args, **kwargs): + def mean(self, numeric_only: bool = False, *args, **kwargs): nv.validate_window_func("mean", args, kwargs) window_func = window_aggregations.roll_weighted_mean # error: Argument 1 to "_apply" of "Window" has incompatible type # "Callable[[ndarray, ndarray, int], ndarray]"; expected # "Callable[[ndarray, int, int], ndarray]" - return self._apply(window_func, name="mean", **kwargs) # type: ignore[arg-type] + return self._apply( + window_func, # type: ignore[arg-type] + name="mean", + numeric_only=numeric_only, + **kwargs, + ) @doc( template_header, ".. versionadded:: 1.0.0 \n\n", create_section_header("Parameters"), + kwargs_numeric_only, kwargs_scipy, create_section_header("Returns"), template_returns, @@ -1282,16 +1349,17 @@ def mean(self, *args, **kwargs): aggregation_description="weighted window variance", agg_method="var", ) - def var(self, ddof: int = 1, *args, **kwargs): + def var(self, ddof: int = 1, numeric_only: bool = False, *args, **kwargs): nv.validate_window_func("var", args, kwargs) window_func = partial(window_aggregations.roll_weighted_var, ddof=ddof) kwargs.pop("name", None) - return self._apply(window_func, name="var", **kwargs) + return self._apply(window_func, name="var", numeric_only=numeric_only, **kwargs) @doc( template_header, ".. versionadded:: 1.0.0 \n\n", create_section_header("Parameters"), + kwargs_numeric_only, kwargs_scipy, create_section_header("Returns"), template_returns, @@ -1301,15 +1369,17 @@ def var(self, ddof: int = 1, *args, **kwargs): aggregation_description="weighted window standard deviation", agg_method="std", ) - def std(self, ddof: int = 1, *args, **kwargs): + def std(self, ddof: int = 1, numeric_only: bool = False, *args, **kwargs): nv.validate_window_func("std", args, kwargs) - return zsqrt(self.var(ddof=ddof, name="std", **kwargs)) + return zsqrt( + self.var(ddof=ddof, name="std", numeric_only=numeric_only, **kwargs) + ) class RollingAndExpandingMixin(BaseWindow): - def count(self): + def count(self, numeric_only: bool = False): window_func = window_aggregations.roll_sum - return self._apply(window_func, name="count") + return self._apply(window_func, name="count", numeric_only=numeric_only) def apply( self, @@ -1350,6 +1420,7 @@ def apply( return self._apply( apply_func, + name="apply", numba_args=numba_args, ) @@ -1380,6 +1451,7 @@ def apply_func(values, begin, end, min_periods, raw=raw): def sum( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -1400,10 +1472,11 @@ def sum( return self._numba_apply(sliding_sum, engine_kwargs) window_func = window_aggregations.roll_sum - return self._apply(window_func, name="sum", **kwargs) + return self._apply(window_func, name="sum", numeric_only=numeric_only, **kwargs) def max( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -1424,10 +1497,11 @@ def max( return self._numba_apply(sliding_min_max, engine_kwargs, True) window_func = window_aggregations.roll_max - return self._apply(window_func, name="max", **kwargs) + return self._apply(window_func, name="max", numeric_only=numeric_only, **kwargs) def min( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -1448,10 +1522,11 @@ def min( return self._numba_apply(sliding_min_max, engine_kwargs, False) window_func = window_aggregations.roll_min - return self._apply(window_func, name="min", **kwargs) + return self._apply(window_func, name="min", numeric_only=numeric_only, **kwargs) def mean( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -1472,10 +1547,13 @@ def mean( return self._numba_apply(sliding_mean, engine_kwargs) window_func = window_aggregations.roll_mean - return self._apply(window_func, name="mean", **kwargs) + return self._apply( + window_func, name="mean", numeric_only=numeric_only, **kwargs + ) def median( self, + numeric_only: bool = False, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, @@ -1493,11 +1571,14 @@ def median( engine_kwargs=engine_kwargs, ) window_func = window_aggregations.roll_median_c - return self._apply(window_func, name="median", **kwargs) + return self._apply( + window_func, name="median", numeric_only=numeric_only, **kwargs + ) def std( self, ddof: int = 1, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -1519,12 +1600,14 @@ def zsqrt_func(values, begin, end, min_periods): return self._apply( zsqrt_func, name="std", + numeric_only=numeric_only, **kwargs, ) def var( self, ddof: int = 1, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -1542,29 +1625,43 @@ def var( return self._apply( window_func, name="var", + numeric_only=numeric_only, **kwargs, ) - def skew(self, **kwargs): + def skew(self, numeric_only: bool = False, **kwargs): window_func = window_aggregations.roll_skew return self._apply( window_func, name="skew", + numeric_only=numeric_only, **kwargs, ) - def sem(self, ddof: int = 1, *args, **kwargs): - return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5) + def sem(self, ddof: int = 1, numeric_only: bool = False, *args, **kwargs): + nv.validate_rolling_func("sem", args, kwargs) + # Raise here so error message says sem instead of std + self._validate_numeric_only("sem", numeric_only) + return self.std(numeric_only=numeric_only, **kwargs) / ( + self.count(numeric_only=numeric_only) - ddof + ).pow(0.5) - def kurt(self, **kwargs): + def kurt(self, numeric_only: bool = False, **kwargs): window_func = window_aggregations.roll_kurt return self._apply( window_func, name="kurt", + numeric_only=numeric_only, **kwargs, ) - def quantile(self, quantile: float, interpolation: str = "linear", **kwargs): + def quantile( + self, + quantile: float, + interpolation: str = "linear", + numeric_only: bool = False, + **kwargs, + ): if quantile == 1.0: window_func = window_aggregations.roll_max elif quantile == 0.0: @@ -1576,13 +1673,16 @@ def quantile(self, quantile: float, interpolation: str = "linear", **kwargs): interpolation=interpolation, ) - return self._apply(window_func, name="quantile", **kwargs) + return self._apply( + window_func, name="quantile", numeric_only=numeric_only, **kwargs + ) def rank( self, method: WindowingRankType = "average", ascending: bool = True, pct: bool = False, + numeric_only: bool = False, **kwargs, ): window_func = partial( @@ -1592,17 +1692,21 @@ def rank( percentile=pct, ) - return self._apply(window_func, name="rank", **kwargs) + return self._apply( + window_func, name="rank", numeric_only=numeric_only, **kwargs + ) def cov( self, other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, + numeric_only: bool = False, **kwargs, ): if self.step is not None: raise NotImplementedError("step not implemented for cov") + self._validate_numeric_only("cov", numeric_only) from pandas import Series @@ -1636,17 +1740,21 @@ def cov_func(x, y): result = (mean_x_y - mean_x * mean_y) * (count_x_y / (count_x_y - ddof)) return Series(result, index=x.index, name=x.name) - return self._apply_pairwise(self._selected_obj, other, pairwise, cov_func) + return self._apply_pairwise( + self._selected_obj, other, pairwise, cov_func, numeric_only + ) def corr( self, other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, + numeric_only: bool = False, **kwargs, ): if self.step is not None: raise NotImplementedError("step not implemented for corr") + self._validate_numeric_only("corr", numeric_only) from pandas import Series @@ -1690,7 +1798,9 @@ def corr_func(x, y): result = numerator / denominator return Series(result, index=x.index, name=x.name) - return self._apply_pairwise(self._selected_obj, other, pairwise, corr_func) + return self._apply_pairwise( + self._selected_obj, other, pairwise, corr_func, numeric_only + ) class Rolling(RollingAndExpandingMixin): @@ -1815,6 +1925,8 @@ def aggregate(self, func, *args, **kwargs): @doc( template_header, + create_section_header("Parameters"), + kwargs_numeric_only, create_section_header("Returns"), template_returns, create_section_header("See Also"), @@ -1847,7 +1959,7 @@ def aggregate(self, func, *args, **kwargs): aggregation_description="count of non NaN observations", agg_method="count", ) - def count(self): + def count(self, numeric_only: bool = False): if self.min_periods is None: warnings.warn( ( @@ -1862,7 +1974,7 @@ def count(self): result = super().count() self.min_periods = None else: - result = super().count() + result = super().count(numeric_only) return result @doc( @@ -1898,6 +2010,7 @@ def apply( @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -1961,17 +2074,24 @@ def apply( ) def sum( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_rolling_func("sum", args, kwargs) - return super().sum(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().sum( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -1987,17 +2107,24 @@ def sum( ) def max( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_rolling_func("max", args, kwargs) - return super().max(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().max( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -2028,17 +2155,24 @@ def max( ) def min( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_rolling_func("min", args, kwargs) - return super().min(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().min( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, args_compat, window_agg_numba_parameters(), kwargs_compat, @@ -2076,17 +2210,24 @@ def min( ) def mean( self, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): nv.validate_rolling_func("mean", args, kwargs) - return super().mean(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().mean( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, window_agg_numba_parameters(), kwargs_compat, create_section_header("Returns"), @@ -2116,11 +2257,17 @@ def mean( ) def median( self, + numeric_only: bool = False, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, **kwargs, ): - return super().median(engine=engine, engine_kwargs=engine_kwargs, **kwargs) + return super().median( + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) @doc( template_header, @@ -2132,6 +2279,7 @@ def median( is ``N - ddof``, where ``N`` represents the number of elements. """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, window_agg_numba_parameters("1.4"), kwargs_compat, @@ -2171,6 +2319,7 @@ def median( def std( self, ddof: int = 1, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -2178,7 +2327,11 @@ def std( ): nv.validate_rolling_func("std", args, kwargs) return super().std( - ddof=ddof, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ddof=ddof, + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, ) @doc( @@ -2191,6 +2344,7 @@ def std( is ``N - ddof``, where ``N`` represents the number of elements. """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, window_agg_numba_parameters("1.4"), kwargs_compat, @@ -2230,6 +2384,7 @@ def std( def var( self, ddof: int = 1, + numeric_only: bool = False, *args, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, @@ -2237,12 +2392,17 @@ def var( ): nv.validate_rolling_func("var", args, kwargs) return super().var( - ddof=ddof, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ddof=ddof, + numeric_only=numeric_only, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, ) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -2255,8 +2415,8 @@ def var( aggregation_description="unbiased skewness", agg_method="skew", ) - def skew(self, **kwargs): - return super().skew(**kwargs) + def skew(self, numeric_only: bool = False, **kwargs): + return super().skew(numeric_only=numeric_only, **kwargs) @doc( template_header, @@ -2268,6 +2428,7 @@ def skew(self, **kwargs): is ``N - ddof``, where ``N`` represents the number of elements. """ ).replace("\n", "", 1), + kwargs_numeric_only, args_compat, kwargs_compat, create_section_header("Returns"), @@ -2292,12 +2453,18 @@ def skew(self, **kwargs): aggregation_description="standard error of mean", agg_method="sem", ) - def sem(self, ddof: int = 1, *args, **kwargs): - return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5) + def sem(self, ddof: int = 1, numeric_only: bool = False, *args, **kwargs): + nv.validate_rolling_func("sem", args, kwargs) + # Raise here so error message says sem instead of std + self._validate_numeric_only("sem", numeric_only) + return self.std(numeric_only=numeric_only, **kwargs) / ( + self.count(numeric_only) - ddof + ).pow(0.5) @doc( template_header, create_section_header("Parameters"), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -2332,8 +2499,8 @@ def sem(self, ddof: int = 1, *args, **kwargs): aggregation_description="Fisher's definition of kurtosis without bias", agg_method="kurt", ) - def kurt(self, **kwargs): - return super().kurt(**kwargs) + def kurt(self, numeric_only: bool = False, **kwargs): + return super().kurt(numeric_only=numeric_only, **kwargs) @doc( template_header, @@ -2354,6 +2521,7 @@ def kurt(self, **kwargs): * midpoint: (`i` + `j`) / 2. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -2382,10 +2550,17 @@ def kurt(self, **kwargs): aggregation_description="quantile", agg_method="quantile", ) - def quantile(self, quantile: float, interpolation: str = "linear", **kwargs): + def quantile( + self, + quantile: float, + interpolation: str = "linear", + numeric_only: bool = False, + **kwargs, + ): return super().quantile( quantile=quantile, interpolation=interpolation, + numeric_only=numeric_only, **kwargs, ) @@ -2409,6 +2584,7 @@ def quantile(self, quantile: float, interpolation: str = "linear", **kwargs): form. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -2455,12 +2631,14 @@ def rank( method: WindowingRankType = "average", ascending: bool = True, pct: bool = False, + numeric_only: bool = False, **kwargs, ): return super().rank( method=method, ascending=ascending, pct=pct, + numeric_only=numeric_only, **kwargs, ) @@ -2484,6 +2662,7 @@ def rank( is ``N - ddof``, where ``N`` represents the number of elements. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -2498,9 +2677,16 @@ def cov( other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, + numeric_only: bool = False, **kwargs, ): - return super().cov(other=other, pairwise=pairwise, ddof=ddof, **kwargs) + return super().cov( + other=other, + pairwise=pairwise, + ddof=ddof, + numeric_only=numeric_only, + **kwargs, + ) @doc( template_header, @@ -2522,6 +2708,7 @@ def cov( is ``N - ddof``, where ``N`` represents the number of elements. """ ).replace("\n", "", 1), + kwargs_numeric_only, kwargs_compat, create_section_header("Returns"), template_returns, @@ -2623,9 +2810,16 @@ def corr( other: DataFrame | Series | None = None, pairwise: bool | None = None, ddof: int = 1, + numeric_only: bool = False, **kwargs, ): - return super().corr(other=other, pairwise=pairwise, ddof=ddof, **kwargs) + return super().corr( + other=other, + pairwise=pairwise, + ddof=ddof, + numeric_only=numeric_only, + **kwargs, + ) Rolling.__doc__ = Window.__doc__ diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py index 8977d1a0d9d1b..d05bb3d51bcde 100644 --- a/pandas/tests/window/conftest.py +++ b/pandas/tests/window/conftest.py @@ -84,6 +84,12 @@ def ignore_na(request): return request.param +@pytest.fixture(params=[True, False]) +def numeric_only(request): + """numeric_only keyword argument""" + return request.param + + @pytest.fixture(params=[pytest.param("numba", marks=td.skip_if_no("numba")), "cython"]) def engine(request): """engine keyword argument for rolling.apply""" diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index 66cd36d121750..e0051ee6d51c6 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -666,3 +666,86 @@ def test_ewm_pairwise_cov_corr(func, frame): result.index = result.index.droplevel(1) expected = getattr(frame[1].ewm(span=10, min_periods=5), func)(frame[5]) tm.assert_series_equal(result, expected, check_names=False) + + +def test_numeric_only_frame(arithmetic_win_operators, numeric_only): + # GH#46560 + kernel = arithmetic_win_operators + df = DataFrame({"a": [1], "b": 2, "c": 3}) + df["c"] = df["c"].astype(object) + ewm = df.ewm(span=2, min_periods=1) + op = getattr(ewm, kernel, None) + if op is not None: + result = op(numeric_only=numeric_only) + + columns = ["a", "b"] if numeric_only else ["a", "b", "c"] + expected = df[columns].agg([kernel]).reset_index(drop=True).astype(float) + assert list(expected.columns) == columns + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("kernel", ["corr", "cov"]) +@pytest.mark.parametrize("use_arg", [True, False]) +def test_numeric_only_corr_cov_frame(kernel, numeric_only, use_arg): + # GH#46560 + df = DataFrame({"a": [1, 2, 3], "b": 2, "c": 3}) + df["c"] = df["c"].astype(object) + arg = (df,) if use_arg else () + ewm = df.ewm(span=2, min_periods=1) + op = getattr(ewm, kernel) + result = op(*arg, numeric_only=numeric_only) + + # Compare result to op using float dtypes, dropping c when numeric_only is True + columns = ["a", "b"] if numeric_only else ["a", "b", "c"] + df2 = df[columns].astype(float) + arg2 = (df2,) if use_arg else () + ewm2 = df2.ewm(span=2, min_periods=1) + op2 = getattr(ewm2, kernel) + expected = op2(*arg2, numeric_only=numeric_only) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [int, object]) +def test_numeric_only_series(arithmetic_win_operators, numeric_only, dtype): + # GH#46560 + kernel = arithmetic_win_operators + ser = Series([1], dtype=dtype) + ewm = ser.ewm(span=2, min_periods=1) + op = getattr(ewm, kernel, None) + if op is None: + # Nothing to test + return + if numeric_only and dtype is object: + msg = f"ExponentialMovingWindow.{kernel} does not implement numeric_only" + with pytest.raises(NotImplementedError, match=msg): + op(numeric_only=numeric_only) + else: + result = op(numeric_only=numeric_only) + expected = ser.agg([kernel]).reset_index(drop=True).astype(float) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("kernel", ["corr", "cov"]) +@pytest.mark.parametrize("use_arg", [True, False]) +@pytest.mark.parametrize("dtype", [int, object]) +def test_numeric_only_corr_cov_series(kernel, use_arg, numeric_only, dtype): + # GH#46560 + ser = Series([1, 2, 3], dtype=dtype) + arg = (ser,) if use_arg else () + ewm = ser.ewm(span=2, min_periods=1) + op = getattr(ewm, kernel) + if numeric_only and dtype is object: + msg = f"ExponentialMovingWindow.{kernel} does not implement numeric_only" + with pytest.raises(NotImplementedError, match=msg): + op(*arg, numeric_only=numeric_only) + else: + result = op(*arg, numeric_only=numeric_only) + + ser2 = ser.astype(float) + arg2 = (ser2,) if use_arg else () + ewm2 = ser2.ewm(span=2, min_periods=1) + op2 = getattr(ewm2, kernel) + expected = op2(*arg2, numeric_only=numeric_only) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index 7ba81e84dfe3e..e0c9294c445f2 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -651,3 +651,83 @@ def mean_w_arg(x, const): result = df.expanding().apply(mean_w_arg, raw=raw, kwargs={"const": 20}) tm.assert_frame_equal(result, expected) + + +def test_numeric_only_frame(arithmetic_win_operators, numeric_only): + # GH#46560 + kernel = arithmetic_win_operators + df = DataFrame({"a": [1], "b": 2, "c": 3}) + df["c"] = df["c"].astype(object) + expanding = df.expanding() + op = getattr(expanding, kernel, None) + if op is not None: + result = op(numeric_only=numeric_only) + + columns = ["a", "b"] if numeric_only else ["a", "b", "c"] + expected = df[columns].agg([kernel]).reset_index(drop=True).astype(float) + assert list(expected.columns) == columns + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("kernel", ["corr", "cov"]) +@pytest.mark.parametrize("use_arg", [True, False]) +def test_numeric_only_corr_cov_frame(kernel, numeric_only, use_arg): + # GH#46560 + df = DataFrame({"a": [1, 2, 3], "b": 2, "c": 3}) + df["c"] = df["c"].astype(object) + arg = (df,) if use_arg else () + expanding = df.expanding() + op = getattr(expanding, kernel) + result = op(*arg, numeric_only=numeric_only) + + # Compare result to op using float dtypes, dropping c when numeric_only is True + columns = ["a", "b"] if numeric_only else ["a", "b", "c"] + df2 = df[columns].astype(float) + arg2 = (df2,) if use_arg else () + expanding2 = df2.expanding() + op2 = getattr(expanding2, kernel) + expected = op2(*arg2, numeric_only=numeric_only) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [int, object]) +def test_numeric_only_series(arithmetic_win_operators, numeric_only, dtype): + # GH#46560 + kernel = arithmetic_win_operators + ser = Series([1], dtype=dtype) + expanding = ser.expanding() + op = getattr(expanding, kernel) + if numeric_only and dtype is object: + msg = f"Expanding.{kernel} does not implement numeric_only" + with pytest.raises(NotImplementedError, match=msg): + op(numeric_only=numeric_only) + else: + result = op(numeric_only=numeric_only) + expected = ser.agg([kernel]).reset_index(drop=True).astype(float) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("kernel", ["corr", "cov"]) +@pytest.mark.parametrize("use_arg", [True, False]) +@pytest.mark.parametrize("dtype", [int, object]) +def test_numeric_only_corr_cov_series(kernel, use_arg, numeric_only, dtype): + # GH#46560 + ser = Series([1, 2, 3], dtype=dtype) + arg = (ser,) if use_arg else () + expanding = ser.expanding() + op = getattr(expanding, kernel) + if numeric_only and dtype is object: + msg = f"Expanding.{kernel} does not implement numeric_only" + with pytest.raises(NotImplementedError, match=msg): + op(*arg, numeric_only=numeric_only) + else: + result = op(*arg, numeric_only=numeric_only) + + ser2 = ser.astype(float) + arg2 = (ser2,) if use_arg else () + expanding2 = ser2.expanding() + op2 = getattr(expanding2, kernel) + expected = op2(*arg2, numeric_only=numeric_only) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 4c26cfb95fd85..785603f6e05f0 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -1871,3 +1871,82 @@ def test_rolling_skew_kurt_floating_artifacts(): assert (result[-2:] == 0).all() result = r.kurt() assert (result[-2:] == -3).all() + + +def test_numeric_only_frame(arithmetic_win_operators, numeric_only): + # GH#46560 + kernel = arithmetic_win_operators + df = DataFrame({"a": [1], "b": 2, "c": 3}) + df["c"] = df["c"].astype(object) + rolling = df.rolling(2, min_periods=1) + op = getattr(rolling, kernel) + result = op(numeric_only=numeric_only) + + columns = ["a", "b"] if numeric_only else ["a", "b", "c"] + expected = df[columns].agg([kernel]).reset_index(drop=True).astype(float) + assert list(expected.columns) == columns + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("kernel", ["corr", "cov"]) +@pytest.mark.parametrize("use_arg", [True, False]) +def test_numeric_only_corr_cov_frame(kernel, numeric_only, use_arg): + # GH#46560 + df = DataFrame({"a": [1, 2, 3], "b": 2, "c": 3}) + df["c"] = df["c"].astype(object) + arg = (df,) if use_arg else () + rolling = df.rolling(2, min_periods=1) + op = getattr(rolling, kernel) + result = op(*arg, numeric_only=numeric_only) + + # Compare result to op using float dtypes, dropping c when numeric_only is True + columns = ["a", "b"] if numeric_only else ["a", "b", "c"] + df2 = df[columns].astype(float) + arg2 = (df2,) if use_arg else () + rolling2 = df2.rolling(2, min_periods=1) + op2 = getattr(rolling2, kernel) + expected = op2(*arg2, numeric_only=numeric_only) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [int, object]) +def test_numeric_only_series(arithmetic_win_operators, numeric_only, dtype): + # GH#46560 + kernel = arithmetic_win_operators + ser = Series([1], dtype=dtype) + rolling = ser.rolling(2, min_periods=1) + op = getattr(rolling, kernel) + if numeric_only and dtype is object: + msg = f"Rolling.{kernel} does not implement numeric_only" + with pytest.raises(NotImplementedError, match=msg): + op(numeric_only=numeric_only) + else: + result = op(numeric_only=numeric_only) + expected = ser.agg([kernel]).reset_index(drop=True).astype(float) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("kernel", ["corr", "cov"]) +@pytest.mark.parametrize("use_arg", [True, False]) +@pytest.mark.parametrize("dtype", [int, object]) +def test_numeric_only_corr_cov_series(kernel, use_arg, numeric_only, dtype): + # GH#46560 + ser = Series([1, 2, 3], dtype=dtype) + arg = (ser,) if use_arg else () + rolling = ser.rolling(2, min_periods=1) + op = getattr(rolling, kernel) + if numeric_only and dtype is object: + msg = f"Rolling.{kernel} does not implement numeric_only" + with pytest.raises(NotImplementedError, match=msg): + op(*arg, numeric_only=numeric_only) + else: + result = op(*arg, numeric_only=numeric_only) + + ser2 = ser.astype(float) + arg2 = (ser2,) if use_arg else () + rolling2 = ser2.rolling(2, min_periods=1) + op2 = getattr(rolling2, kernel) + expected = op2(*arg2, numeric_only=numeric_only) + tm.assert_series_equal(result, expected)
Part of #46560 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/47265
2022-06-07T02:29:14Z
2022-06-08T16:25:05Z
2022-06-08T16:25:05Z
2022-06-08T21:07:10Z
add test to check type of df column after loc()
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 1e5e65786a4aa..9b1cb69cc33ad 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2869,6 +2869,15 @@ def test_loc_setitem_using_datetimelike_str_as_index(fill_val, exp_dtype): tm.assert_index_equal(df.index, expected_index, exact=True) +def test_loc_set_int_dtype(): + # GH#23326 + df = DataFrame([list("abc")]) + df.loc[:, "col1"] = 5 + + expected = DataFrame({0: ["a"], 1: ["b"], 2: ["c"], "col1": [5]}) + tm.assert_frame_equal(df, expected) + + class TestLocSeries: @pytest.mark.parametrize("val,expected", [(2**63 - 1, 3), (2**63, 4)]) def test_loc_uint64(self, val, expected):
- [x] closes #23326 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/47264
2022-06-07T02:08:21Z
2022-06-13T00:23:36Z
2022-06-13T00:23:36Z
2022-06-13T00:24:14Z
REF: avoid ravel in ints_to_pytimedelta
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 28a6480f368d9..f8f01afb06812 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -161,42 +161,61 @@ def ints_to_pytimedelta(ndarray m8values, box=False): array of Timedelta or timedeltas objects """ cdef: + NPY_DATETIMEUNIT reso = get_unit_from_dtype(m8values.dtype) Py_ssize_t i, n = m8values.size int64_t value - object[::1] result = np.empty(n, dtype=object) - NPY_DATETIMEUNIT reso = get_unit_from_dtype(m8values.dtype) + object res_val + + # Note that `result` (and thus `result_flat`) is C-order and + # `it` iterates C-order as well, so the iteration matches + # See discussion at + # github.com/pandas-dev/pandas/pull/46886#discussion_r860261305 + ndarray result = cnp.PyArray_EMPTY(m8values.ndim, m8values.shape, cnp.NPY_OBJECT, 0) + object[::1] res_flat = result.ravel() # should NOT be a copy - arr = m8values.view("i8") + ndarray arr = m8values.view("i8") + cnp.flatiter it = cnp.PyArray_IterNew(arr) for i in range(n): + # Analogous to: value = arr[i] + value = (<int64_t*>cnp.PyArray_ITER_DATA(it))[0] - value = arr[i] if value == NPY_NAT: - result[i] = <object>NaT + res_val = <object>NaT else: if box: - result[i] = _timedelta_from_value_and_reso(value, reso=reso) + res_val = _timedelta_from_value_and_reso(value, reso=reso) elif reso == NPY_DATETIMEUNIT.NPY_FR_ns: - result[i] = timedelta(microseconds=int(value) / 1000) + res_val = timedelta(microseconds=int(value) / 1000) elif reso == NPY_DATETIMEUNIT.NPY_FR_us: - result[i] = timedelta(microseconds=value) + res_val = timedelta(microseconds=value) elif reso == NPY_DATETIMEUNIT.NPY_FR_ms: - result[i] = timedelta(milliseconds=value) + res_val = timedelta(milliseconds=value) elif reso == NPY_DATETIMEUNIT.NPY_FR_s: - result[i] = timedelta(seconds=value) + res_val = timedelta(seconds=value) elif reso == NPY_DATETIMEUNIT.NPY_FR_m: - result[i] = timedelta(minutes=value) + res_val = timedelta(minutes=value) elif reso == NPY_DATETIMEUNIT.NPY_FR_h: - result[i] = timedelta(hours=value) + res_val = timedelta(hours=value) elif reso == NPY_DATETIMEUNIT.NPY_FR_D: - result[i] = timedelta(days=value) + res_val = timedelta(days=value) elif reso == NPY_DATETIMEUNIT.NPY_FR_W: - result[i] = timedelta(weeks=value) + res_val = timedelta(weeks=value) else: # Month, Year, NPY_FR_GENERIC, pico, fempto, atto raise NotImplementedError(reso) - return result.base # .base to access underlying np.ndarray + # Note: we can index result directly instead of using PyArray_MultiIter_DATA + # like we do for the other functions because result is known C-contiguous + # and is the first argument to PyArray_MultiIterNew2. The usual pattern + # does not seem to work with object dtype. + # See discussion at + # github.com/pandas-dev/pandas/pull/46886#discussion_r860261305 + res_flat[i] = res_val + + cnp.PyArray_ITER_NEXT(it) + + return result # ---------------------------------------------------------------------- diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index f81859ced01ed..1dfb070e29c30 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -437,9 +437,7 @@ def astype(self, dtype, copy: bool = True): return converted.reshape(self.shape) elif self.dtype.kind == "m": - i8data = self.asi8.ravel() - converted = ints_to_pytimedelta(self._ndarray.ravel(), box=True) - return converted.reshape(self.shape) + return ints_to_pytimedelta(self._ndarray, box=True) return self._box_values(self.asi8.ravel()).reshape(self.shape)
same pattern we use in vectorized.pyx
https://api.github.com/repos/pandas-dev/pandas/pulls/47261
2022-06-06T23:59:27Z
2022-06-07T19:55:47Z
2022-06-07T19:55:47Z
2022-06-07T20:11:45Z
CI: Allow more permissive HTTP retries/timeouts when connecting to conda
diff --git a/.github/actions/setup-conda/action.yml b/.github/actions/setup-conda/action.yml index 1c947ff244fb9..7f5d864330db2 100644 --- a/.github/actions/setup-conda/action.yml +++ b/.github/actions/setup-conda/action.yml @@ -18,10 +18,11 @@ runs: if: ${{ inputs.pyarrow-version }} - name: Install ${{ inputs.environment-file }} - uses: conda-incubator/setup-miniconda@v2 + uses: conda-incubator/setup-miniconda@v2.1.1 with: environment-file: ${{ inputs.environment-file }} channel-priority: ${{ runner.os == 'macOS' && 'flexible' || 'strict' }} channels: conda-forge mamba-version: "0.23" use-mamba: true + condarc-file: ci/condarc.yml diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml index 78c224b84d5d9..50720c5ebf0e2 100644 --- a/.github/workflows/asv-bot.yml +++ b/.github/workflows/asv-bot.yml @@ -47,6 +47,7 @@ jobs: channel-priority: strict environment-file: ${{ env.ENV_FILE }} use-only-tar-bz2: true + condarc-file: ci/condarc.yml - name: Run benchmarks id: bench diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml index 7812c4dd00bcb..9d51062754f35 100644 --- a/.github/workflows/code-checks.yml +++ b/.github/workflows/code-checks.yml @@ -66,6 +66,7 @@ jobs: channel-priority: strict environment-file: ${{ env.ENV_FILE }} use-only-tar-bz2: true + condarc-file: ci/condarc.yml - name: Build Pandas id: build @@ -135,6 +136,7 @@ jobs: channel-priority: strict environment-file: ${{ env.ENV_FILE }} use-only-tar-bz2: true + condarc-file: ci/condarc.yml - name: Build Pandas id: build diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 35c40f2a4aa54..28d2ae6d26bda 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -155,6 +155,7 @@ jobs: channel-priority: flexible environment-file: ${{ env.ENV_FILE }} use-only-tar-bz2: true + condarc-file: ci/condarc.yml - name: Upgrade Arrow version run: conda install -n pandas-dev -c conda-forge --no-update-deps pyarrow=${{ matrix.pyarrow_version }} diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml index 21d252f4cef67..27f7da0b83d27 100644 --- a/.github/workflows/sdist.yml +++ b/.github/workflows/sdist.yml @@ -64,6 +64,7 @@ jobs: activate-environment: pandas-sdist channels: conda-forge python-version: '${{ matrix.python-version }}' + condarc-file: ci/condarc.yml - name: Install pandas from sdist run: | diff --git a/ci/condarc.yml b/ci/condarc.yml new file mode 100644 index 0000000000000..9d750b7102c39 --- /dev/null +++ b/ci/condarc.yml @@ -0,0 +1,32 @@ +# https://docs.conda.io/projects/conda/en/latest/configuration.html + +# always_yes (NoneType, bool) +# aliases: yes +# Automatically choose the 'yes' option whenever asked to proceed with a +# conda operation, such as when running `conda install`. +# +always_yes: true + +# remote_connect_timeout_secs (float) +# The number seconds conda will wait for your client to establish a +# connection to a remote url resource. +# +remote_connect_timeout_secs: 30.0 + +# remote_max_retries (int) +# The maximum number of retries each HTTP connection should attempt. +# +remote_max_retries: 10 + +# remote_backoff_factor (int) +# The factor determines the time HTTP connection should wait for +# attempt. +# +remote_backoff_factor: 3 + +# remote_read_timeout_secs (float) +# Once conda has connected to a remote resource and sent an HTTP +# request, the read timeout is the number of seconds conda will wait for +# the server to send a response. +# +remote_read_timeout_secs: 60.0
Hoping this alleviates the following traceback that has been occurring recently ``` Traceback (most recent call last): File "/usr/share/miniconda/lib/python3.9/site-packages/urllib3/response.py", line 438, in _error_catcher yield File "/usr/share/miniconda/lib/python3.9/site-packages/urllib3/response.py", line 767, in read_chunked chunk = self._handle_chunk(amt) File "/usr/share/miniconda/lib/python3.9/site-packages/urllib3/response.py", line 711, in _handle_chunk value = self._fp._safe_read(amt) File "/usr/share/miniconda/lib/python3.9/http/client.py", line 626, in _safe_read chunk = self.fp.read(min(amt, MAXAMOUNT)) File "/usr/share/miniconda/lib/python3.9/socket.py", line 704, in readinto return self._sock.recv_into(b) File "/usr/share/miniconda/lib/python3.9/ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "/usr/share/miniconda/lib/python3.9/ssl.py", line 1099, in read return self._sslobj.read(len, buffer) ConnectionResetError: [Errno 104] Connection reset by peer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/share/miniconda/lib/python3.9/site-packages/requests/models.py", line 760, in generate for chunk in self.raw.stream(chunk_size, decode_content=True): File "/usr/share/miniconda/lib/python3.9/site-packages/urllib3/response.py", line 572, in stream for line in self.read_chunked(amt, decode_content=decode_content): File "/usr/share/miniconda/lib/python3.9/site-packages/urllib3/response.py", line 793, in read_chunked self._original_response.close() File "/usr/share/miniconda/lib/python3.9/contextlib.py", line 137, in __exit__ self.gen.throw(typ, value, traceback) File "/usr/share/miniconda/lib/python3.9/site-packages/urllib3/response.py", line 455, in _error_catcher raise ProtocolError("Connection broken: %r" % e, e) urllib3.exceptions.ProtocolError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer')) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/47260
2022-06-06T19:10:05Z
2022-06-09T18:57:43Z
2022-06-09T18:57:43Z
2022-06-09T18:57:46Z
TST: xfail unit test on min build
diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index f9c43592d5f62..803f495b311b9 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -11,6 +11,7 @@ np_version_gte1p22 = _nlv >= Version("1.22") is_numpy_dev = _nlv.dev is not None _min_numpy_ver = "1.19.5" +is_numpy_min = _nlv == Version(_min_numpy_ver) if is_numpy_dev or not np_version_under1p22: np_percentile_argname = "method" diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 539b56667ee07..44cdc320148e1 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -10,6 +10,7 @@ import numpy as np import pytest +from pandas.compat.numpy import is_numpy_min import pandas.util._test_decorators as td from pandas import ( @@ -1198,6 +1199,7 @@ def test_iloc_getitem_int_single_ea_block_view(self): arr[2] = arr[-1] assert ser[0] == arr[-1] + @pytest.mark.xfail(is_numpy_min, reason="Column A gets coerced to integer type") def test_iloc_setitem_multicolumn_to_datetime(self, using_array_manager): # GH#20511
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). xref https://github.com/pandas-dev/pandas/runs/6753263999?check_suite_focus=true Not 100% certain why this fails on the min build, but can be investigated later.
https://api.github.com/repos/pandas-dev/pandas/pulls/47259
2022-06-06T18:37:21Z
2022-06-07T00:12:55Z
2022-06-07T00:12:55Z
2022-06-07T00:12:58Z
DEPS/CI: Fix sdist job post numpy 18 drop
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml index 21d252f4cef67..e4bb556359177 100644 --- a/.github/workflows/sdist.yml +++ b/.github/workflows/sdist.yml @@ -74,9 +74,9 @@ jobs: run: | case "${{matrix.python-version}}" in 3.8) - pip install numpy==1.18.5 ;; + pip install numpy==1.19.5 ;; 3.9) - pip install numpy==1.19.3 ;; + pip install numpy==1.19.5 ;; 3.10) pip install numpy==1.21.2 ;; esac
Post https://github.com/pandas-dev/pandas/pull/47226
https://api.github.com/repos/pandas-dev/pandas/pulls/47258
2022-06-06T18:09:59Z
2022-06-07T01:58:25Z
2022-06-07T01:58:25Z
2022-06-07T04:03:22Z
TST: Fix test warnings
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 3adc63e1a27f6..0864032b741c9 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -2007,11 +2007,11 @@ def test_bool_frame_mult_float(): tm.assert_frame_equal(result, expected) -def test_frame_sub_nullable_int(any_int_dtype): +def test_frame_sub_nullable_int(any_int_ea_dtype): # GH 32822 - series1 = Series([1, 2, np.nan], dtype=any_int_dtype) - series2 = Series([1, 2, 3], dtype=any_int_dtype) - expected = DataFrame([0, 0, np.nan], dtype=any_int_dtype) + series1 = Series([1, 2, None], dtype=any_int_ea_dtype) + series2 = Series([1, 2, 3], dtype=any_int_ea_dtype) + expected = DataFrame([0, 0, None], dtype=any_int_ea_dtype) result = series1.to_frame() - series2.to_frame() tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 5360885067c7a..78db4f7ea5c75 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2574,7 +2574,8 @@ def check_views(c_only: bool = False): # FIXME(GH#35417): until GH#35417, iloc.setitem into EA values does not preserve # view, so we have to check in the other direction - df.iloc[:, 2] = pd.array([45, 46], dtype=c.dtype) + with tm.assert_produces_warning(FutureWarning, match="will attempt to set"): + df.iloc[:, 2] = pd.array([45, 46], dtype=c.dtype) assert df.dtypes.iloc[2] == c.dtype if not copy: check_views(True) diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index 9f71c2c2fa0b6..2890b7930611c 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -47,7 +47,7 @@ def incorrect_function(values, index): @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) @@ -76,7 +76,7 @@ def func_numba(values, index): @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) diff --git a/pandas/tests/groupby/test_numba.py b/pandas/tests/groupby/test_numba.py index cce92e0763fb8..4eb7b6a7b5bea 100644 --- a/pandas/tests/groupby/test_numba.py +++ b/pandas/tests/groupby/test_numba.py @@ -10,7 +10,7 @@ @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba class TestEngine: def test_cython_vs_numba_frame( diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index 1b8570dbdc21d..0e26cdc294b55 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -44,7 +44,7 @@ def incorrect_function(values, index): @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) @@ -73,7 +73,7 @@ def func(values, index): @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 240b4b725aacd..449d5a954613b 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -1538,7 +1538,12 @@ def test_date_parser_resolution_if_not_ns(all_parsers): """ def date_parser(dt, time): - return np.array(dt + "T" + time, dtype="datetime64[s]") + try: + arr = dt + "T" + time + except TypeError: + # dt & time are date/time objects + arr = [datetime.combine(d, t) for d, t in zip(dt, time)] + return np.array(arr, dtype="datetime64[s]") result = parser.read_csv( StringIO(data), diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py index a6e51cc2f98d6..1c74950e30c40 100644 --- a/pandas/tests/strings/test_find_replace.py +++ b/pandas/tests/strings/test_find_replace.py @@ -25,7 +25,11 @@ def test_contains(any_string_dtype): values = Series(values, dtype=any_string_dtype) pat = "mmm[_]+" - result = values.str.contains(pat) + with tm.maybe_produces_warning( + PerformanceWarning, + any_string_dtype == "string[pyarrow]" and pa_version_under4p0, + ): + result = values.str.contains(pat) expected_dtype = "object" if any_string_dtype == "object" else "boolean" expected = Series( np.array([False, np.nan, True, True, False], dtype=np.object_), @@ -88,7 +92,11 @@ def test_contains(any_string_dtype): ) tm.assert_series_equal(result, expected) - result = values.str.contains(pat, na=False) + with tm.maybe_produces_warning( + PerformanceWarning, + any_string_dtype == "string[pyarrow]" and pa_version_under4p0, + ): + result = values.str.contains(pat, na=False) expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean" expected = Series(np.array([False, False, True, True]), dtype=expected_dtype) tm.assert_series_equal(result, expected) @@ -181,7 +189,11 @@ def test_contains_moar(any_string_dtype): dtype=any_string_dtype, ) - result = s.str.contains("a") + with tm.maybe_produces_warning( + PerformanceWarning, + any_string_dtype == "string[pyarrow]" and pa_version_under4p0, + ): + result = s.str.contains("a") expected_dtype = "object" if any_string_dtype == "object" else "boolean" expected = Series( [False, False, False, True, True, False, np.nan, False, False, True], @@ -619,7 +631,11 @@ def test_replace_moar(any_string_dtype): dtype=any_string_dtype, ) - result = ser.str.replace("A", "YYY") + with tm.maybe_produces_warning( + PerformanceWarning, + any_string_dtype == "string[pyarrow]" and pa_version_under4p0, + ): + result = ser.str.replace("A", "YYY") expected = Series( ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"], dtype=any_string_dtype, @@ -727,7 +743,11 @@ def test_replace_regex_single_character(regex, any_string_dtype): ): result = s.str.replace(".", "a", regex=regex) else: - result = s.str.replace(".", "a", regex=regex) + with tm.maybe_produces_warning( + PerformanceWarning, + any_string_dtype == "string[pyarrow]" and pa_version_under4p0, + ): + result = s.str.replace(".", "a", regex=regex) expected = Series(["aab", "a", "b", np.nan, ""], dtype=any_string_dtype) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index db99ba8368a8a..aa31a5505b866 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -562,7 +562,11 @@ def test_slice_replace(start, stop, repl, expected, any_string_dtype): def test_strip_lstrip_rstrip(any_string_dtype, method, exp): ser = Series([" aa ", " bb \n", np.nan, "cc "], dtype=any_string_dtype) - result = getattr(ser.str, method)() + with tm.maybe_produces_warning( + PerformanceWarning, + any_string_dtype == "string[pyarrow]" and pa_version_under4p0, + ): + result = getattr(ser.str, method)() expected = Series(exp, dtype=any_string_dtype) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index a029c88fa3a7d..89e00af270a02 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -50,7 +50,7 @@ def arithmetic_numba_supported_operators(request): @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba class TestEngine: @pytest.mark.parametrize("jit", [True, False]) @@ -331,7 +331,7 @@ def test_invalid_kwargs_nopython(): @td.skip_if_no("numba") @pytest.mark.slow -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") # Filter warnings when parallel=True and the function can't be parallelized by Numba class TestTableMethod: def test_table_series_valueerror(self): diff --git a/pandas/tests/window/test_online.py b/pandas/tests/window/test_online.py index b98129e1b07ec..88f462869d8b6 100644 --- a/pandas/tests/window/test_online.py +++ b/pandas/tests/window/test_online.py @@ -24,7 +24,8 @@ @td.skip_if_no("numba") -@pytest.mark.filterwarnings("ignore:\n") +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba class TestEWM: def test_invalid_update(self): df = DataFrame({"a": range(5), "b": range(5)}) diff --git a/pyproject.toml b/pyproject.toml index 2f09b003defc6..0e2e41fba461c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,6 @@ filterwarnings = [ "ignore:pandas.util.testing is deprecated:FutureWarning:importlib", # Will be fixed in numba 0.56: https://github.com/numba/numba/issues/7758 "ignore:`np.MachAr` is deprecated:DeprecationWarning:numba", - ] junit_family = "xunit2" markers = [
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/47257
2022-06-06T17:01:31Z
2022-06-08T22:50:34Z
2022-06-08T22:50:34Z
2022-06-08T23:54:26Z
Backport PR #47143 on branch 1.4.x (REGR: setitem writing into RangeIndex instead of creating a copy)
diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index d274458e24262..f594aae2c7f9f 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`DataFrame.replace` when the replacement value was explicitly ``None`` when passed in a dictionary to ``to_replace`` also casting other columns to object dtype even when there were no values to replace (:issue:`46634`) +- Fixed regression when setting values with :meth:`DataFrame.loc` updating :class:`RangeIndex` when index was set as new column and column was updated afterwards (:issue:`47128`) - Fixed regression in :meth:`DataFrame.nsmallest` led to wrong results when ``np.nan`` in the sorting column (:issue:`46589`) - Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`) - Fixed regression in :func:`concat` not sorting columns for mixed column names (:issue:`47127`) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index e496125683c09..2595cff5c43c4 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -508,7 +508,7 @@ def sanitize_array( dtype = dtype.numpy_dtype # extract ndarray or ExtensionArray, ensure we have no PandasArray - data = extract_array(data, extract_numpy=True) + data = extract_array(data, extract_numpy=True, extract_range=True) if isinstance(data, np.ndarray) and data.ndim == 0: if dtype is None: @@ -583,7 +583,7 @@ def sanitize_array( # materialize e.g. generators, convert e.g. tuples, abc.ValueView if hasattr(data, "__array__"): # e.g. dask array GH#38645 - data = np.asarray(data) + data = np.array(data, copy=copy) else: data = list(data) diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index cd0a0a0467742..673d347917832 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -852,6 +852,15 @@ def test_frame_setitem_newcol_timestamp(self): data[ts] = np.nan # works, mostly a smoke-test assert np.isnan(data[ts]).all() + def test_frame_setitem_rangeindex_into_new_col(self): + # GH#47128 + df = DataFrame({"a": ["a", "b"]}) + df["b"] = df.index + df.loc[[False, True], "b"] = 100 + result = df.loc[[1], :] + expected = DataFrame({"a": ["b"], "b": [100]}, index=[1]) + tm.assert_frame_equal(result, expected) + class TestDataFrameSetItemSlicing: def test_setitem_slice_position(self): diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index be9f187c0c44b..a4180d38c670c 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -269,3 +269,27 @@ def test_missing_required_dependency(): output = exc.value.stdout.decode() for name in ["numpy", "pytz", "dateutil"]: assert name in output + + +def test_frame_setitem_dask_array_into_new_col(): + # GH#47128 + + # dask sets "compute.use_numexpr" to False, so catch the current value + # and ensure to reset it afterwards to avoid impacting other tests + olduse = pd.get_option("compute.use_numexpr") + + try: + dask = import_module("dask") # noqa:F841 + + import dask.array as da + + dda = da.array([1, 2]) + df = DataFrame({"a": ["a", "b"]}) + df["b"] = dda + df["c"] = dda + df.loc[[False, True], "b"] = 100 + result = df.loc[[1], :] + expected = DataFrame({"a": ["b"], "b": [100], "c": [2]}, index=[1]) + tm.assert_frame_equal(result, expected) + finally: + pd.set_option("compute.use_numexpr", olduse)
Backport PR #47143
https://api.github.com/repos/pandas-dev/pandas/pulls/47256
2022-06-06T09:29:01Z
2022-06-06T11:26:18Z
2022-06-06T11:26:18Z
2022-06-06T11:26:22Z
PERF: delta_to_nanoseconds
diff --git a/pandas/_libs/tslibs/dtypes.pxd b/pandas/_libs/tslibs/dtypes.pxd index 9c0eb0f9b0945..e16a389bc5459 100644 --- a/pandas/_libs/tslibs/dtypes.pxd +++ b/pandas/_libs/tslibs/dtypes.pxd @@ -7,7 +7,7 @@ cdef str npy_unit_to_abbrev(NPY_DATETIMEUNIT unit) cdef NPY_DATETIMEUNIT freq_group_code_to_npy_unit(int freq) nogil cpdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=*) except? -1 cdef int64_t periods_per_second(NPY_DATETIMEUNIT reso) except? -1 -cdef int64_t get_conversion_factor(NPY_DATETIMEUNIT from_unit, NPY_DATETIMEUNIT to_unit) +cdef int64_t get_conversion_factor(NPY_DATETIMEUNIT from_unit, NPY_DATETIMEUNIT to_unit) except? -1 cdef dict attrname_to_abbrevs diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx index 8758d70b1a266..cb2de79cd8b26 100644 --- a/pandas/_libs/tslibs/dtypes.pyx +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -384,7 +384,7 @@ cdef int64_t periods_per_second(NPY_DATETIMEUNIT reso) except? -1: @cython.overflowcheck(True) -cdef int64_t get_conversion_factor(NPY_DATETIMEUNIT from_unit, NPY_DATETIMEUNIT to_unit): +cdef int64_t get_conversion_factor(NPY_DATETIMEUNIT from_unit, NPY_DATETIMEUNIT to_unit) except? -1: """ Find the factor by which we need to multiply to convert from from_unit to to_unit. """ diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd index e851665c49d89..3251e10a88b73 100644 --- a/pandas/_libs/tslibs/timedeltas.pxd +++ b/pandas/_libs/tslibs/timedeltas.pxd @@ -6,10 +6,11 @@ from .np_datetime cimport NPY_DATETIMEUNIT # Exposed for tslib, not intended for outside use. cpdef int64_t delta_to_nanoseconds( - delta, NPY_DATETIMEUNIT reso=*, bint round_ok=*, bint allow_year_month=* + delta, NPY_DATETIMEUNIT reso=*, bint round_ok=* ) except? -1 cdef convert_to_timedelta64(object ts, str unit) cdef bint is_any_td_scalar(object obj) +cdef object ensure_td64ns(object ts) cdef class _Timedelta(timedelta): diff --git a/pandas/_libs/tslibs/timedeltas.pyi b/pandas/_libs/tslibs/timedeltas.pyi index 70770e1c0fdc9..cc649e5a62660 100644 --- a/pandas/_libs/tslibs/timedeltas.pyi +++ b/pandas/_libs/tslibs/timedeltas.pyi @@ -76,7 +76,6 @@ def delta_to_nanoseconds( delta: np.timedelta64 | timedelta | Tick, reso: int = ..., # NPY_DATETIMEUNIT round_ok: bool = ..., - allow_year_month: bool = ..., ) -> int: ... class Timedelta(timedelta): diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 0fc1476b43c42..28a6480f368d9 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -206,44 +206,24 @@ cpdef int64_t delta_to_nanoseconds( delta, NPY_DATETIMEUNIT reso=NPY_FR_ns, bint round_ok=True, - bint allow_year_month=False, ) except? -1: + # Note: this will raise on timedelta64 with Y or M unit + cdef: - _Timedelta td NPY_DATETIMEUNIT in_reso - int64_t n + int64_t n, value, factor if is_tick_object(delta): n = delta.n in_reso = delta._reso - if in_reso == reso: - return n - else: - td = Timedelta._from_value_and_reso(delta.n, reso=in_reso) elif isinstance(delta, _Timedelta): - td = delta n = delta.value in_reso = delta._reso - if in_reso == reso: - return n elif is_timedelta64_object(delta): in_reso = get_datetime64_unit(delta) n = get_timedelta64_value(delta) - if in_reso == reso: - return n - else: - # _from_value_and_reso does not support Year, Month, or unit-less, - # so we have special handling if speciifed - try: - td = Timedelta._from_value_and_reso(n, reso=in_reso) - except NotImplementedError: - if allow_year_month: - td64 = ensure_td64ns(delta) - return delta_to_nanoseconds(td64, reso=reso) - else: - raise elif PyDelta_Check(delta): in_reso = NPY_DATETIMEUNIT.NPY_FR_us @@ -256,21 +236,31 @@ cpdef int64_t delta_to_nanoseconds( except OverflowError as err: raise OutOfBoundsTimedelta(*err.args) from err - if in_reso == reso: - return n - else: - td = Timedelta._from_value_and_reso(n, reso=in_reso) - else: raise TypeError(type(delta)) - try: - return td._as_reso(reso, round_ok=round_ok).value - except OverflowError as err: - unit_str = npy_unit_to_abbrev(reso) - raise OutOfBoundsTimedelta( - f"Cannot cast {str(delta)} to unit={unit_str} without overflow." - ) from err + if reso < in_reso: + # e.g. ns -> us + factor = get_conversion_factor(reso, in_reso) + div, mod = divmod(n, factor) + if mod > 0 and not round_ok: + raise ValueError("Cannot losslessly convert units") + + # Note that when mod > 0, we follow np.timedelta64 in always + # rounding down. + value = div + else: + factor = get_conversion_factor(in_reso, reso) + try: + with cython.overflowcheck(True): + value = n * factor + except OverflowError as err: + unit_str = npy_unit_to_abbrev(reso) + raise OutOfBoundsTimedelta( + f"Cannot cast {str(delta)} to unit={unit_str} without overflow." + ) from err + + return value @cython.overflowcheck(True) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 8706d59b084b9..67aae23f7fdd1 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -99,6 +99,7 @@ from pandas._libs.tslibs.offsets cimport ( ) from pandas._libs.tslibs.timedeltas cimport ( delta_to_nanoseconds, + ensure_td64ns, is_any_td_scalar, ) @@ -353,16 +354,25 @@ cdef class _Timestamp(ABCTimestamp): raise NotImplementedError(self._reso) if is_any_td_scalar(other): - if ( - is_timedelta64_object(other) - and get_datetime64_unit(other) == NPY_DATETIMEUNIT.NPY_FR_GENERIC - ): - # TODO: deprecate allowing this? We only get here - # with test_timedelta_add_timestamp_interval - other = np.timedelta64(other.view("i8"), "ns") - # TODO: disallow round_ok, allow_year_month? + if is_timedelta64_object(other): + other_reso = get_datetime64_unit(other) + if ( + other_reso == NPY_DATETIMEUNIT.NPY_FR_GENERIC + ): + # TODO: deprecate allowing this? We only get here + # with test_timedelta_add_timestamp_interval + other = np.timedelta64(other.view("i8"), "ns") + elif ( + other_reso == NPY_DATETIMEUNIT.NPY_FR_Y or other_reso == NPY_DATETIMEUNIT.NPY_FR_M + ): + # TODO: deprecate allowing these? or handle more like the + # corresponding DateOffsets? + # TODO: no tests get here + other = ensure_td64ns(other) + + # TODO: disallow round_ok nanos = delta_to_nanoseconds( - other, reso=self._reso, round_ok=True, allow_year_month=True + other, reso=self._reso, round_ok=True ) try: result = type(self)(self.value + nanos, tz=self.tzinfo) diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index 788d6f3504760..65610bbe14e41 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -45,12 +45,6 @@ def test_overflow_offset_raises(self): r"\<-?\d+ \* Days\> and \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} " "will overflow" ) - lmsg = "|".join( - [ - "Python int too large to convert to C (long|int)", - "int too big to convert", - ] - ) lmsg2 = r"Cannot cast <-?20169940 \* Days> to unit=ns without overflow" with pytest.raises(OutOfBoundsTimedelta, match=lmsg2): @@ -68,13 +62,14 @@ def test_overflow_offset_raises(self): stamp = Timestamp("2000/1/1") offset_overflow = to_offset("D") * 100**5 - with pytest.raises(OverflowError, match=lmsg): + lmsg3 = r"Cannot cast <-?10000000000 \* Days> to unit=ns without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=lmsg3): stamp + offset_overflow with pytest.raises(OverflowError, match=msg): offset_overflow + stamp - with pytest.raises(OverflowError, match=lmsg): + with pytest.raises(OutOfBoundsTimedelta, match=lmsg3): stamp - offset_overflow def test_overflow_timestamp_raises(self): diff --git a/pandas/tests/tslibs/test_timedeltas.py b/pandas/tests/tslibs/test_timedeltas.py index d9e86d53f2587..661bb113e9549 100644 --- a/pandas/tests/tslibs/test_timedeltas.py +++ b/pandas/tests/tslibs/test_timedeltas.py @@ -55,6 +55,18 @@ def test_delta_to_nanoseconds_error(): delta_to_nanoseconds(np.int32(3)) +def test_delta_to_nanoseconds_td64_MY_raises(): + td = np.timedelta64(1234, "Y") + + with pytest.raises(ValueError, match="0, 10"): + delta_to_nanoseconds(td) + + td = np.timedelta64(1234, "M") + + with pytest.raises(ValueError, match="1, 10"): + delta_to_nanoseconds(td) + + def test_huge_nanoseconds_overflow(): # GH 32402 assert delta_to_nanoseconds(Timedelta(1e10)) == 1e10
``` from datetime import timedelta from pandas._libs.tslibs.timedeltas import * td = timedelta(days=4) %timeit delta_to_nanoseconds(td) 1.74 µs ± 25.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <- main 300 ns ± 3.38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <- PR 265 ns ± 7.28 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <- 1.4.2 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/47254
2022-06-06T02:19:35Z
2022-06-06T18:02:48Z
2022-06-06T18:02:48Z
2022-06-06T18:04:03Z