title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
BUG: Avoid intercepting TypeError in DataFrame.agg
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 6d9f5510eb8c5..722de91ba5246 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -663,12 +663,6 @@ def agg(self): result = None try: result = super().agg() - except TypeError as err: - exc = TypeError( - "DataFrame constructor called with " - f"incompatible data and dtype: {err}" - ) - raise exc from err finally: self.obj = obj self.axis = axis diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index 28c776d0a6d35..7bf1621d0acea 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1181,8 +1181,7 @@ def test_agg_multiple_mixed_raises(): ) # sorted index - # TODO: GH#49399 will fix error message - msg = "DataFrame constructor called with" + msg = "does not support reduction" with pytest.raises(TypeError, match=msg): mdf.agg(["min", "sum"]) @@ -1283,7 +1282,7 @@ def test_nuiscance_columns(): ) tm.assert_frame_equal(result, expected) - msg = "DataFrame constructor called with incompatible data and dtype" + msg = "does not support reduction" with pytest.raises(TypeError, match=msg): df.agg("sum") @@ -1291,8 +1290,7 @@ def test_nuiscance_columns(): expected = Series([6, 6.0, "foobarbaz"], index=["A", "B", "C"]) tm.assert_series_equal(result, expected) - # TODO: GH#49399 will fix error message - msg = "DataFrame constructor called with" + msg = "does not support reduction" with pytest.raises(TypeError, match=msg): df.agg(["sum"])
- [x] closes #49399 - [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. - [ ] 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/49969
2022-11-30T02:59:45Z
2022-12-01T20:31:02Z
2022-12-01T20:31:02Z
2022-12-01T20:31:09Z
BUG: Allow read_sql to work with chunksize.
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 2c98ff61cbef6..62a54a548a990 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -9,7 +9,10 @@ ABC, abstractmethod, ) -from contextlib import contextmanager +from contextlib import ( + ExitStack, + contextmanager, +) from datetime import ( date, datetime, @@ -69,6 +72,14 @@ # -- Helper functions +def _cleanup_after_generator(generator, exit_stack: ExitStack): + """Does the cleanup after iterating through the generator.""" + try: + yield from generator + finally: + exit_stack.close() + + def _convert_params(sql, params): """Convert SQL and params args to DBAPI2.0 compliant format.""" args = [sql] @@ -772,12 +783,11 @@ def has_table(table_name: str, con, schema: str | None = None) -> bool: table_exists = has_table -@contextmanager def pandasSQL_builder( con, schema: str | None = None, need_transaction: bool = False, -) -> Iterator[PandasSQL]: +) -> PandasSQL: """ Convenience function to return the correct PandasSQL subclass based on the provided parameters. Also creates a sqlalchemy connection and transaction @@ -786,45 +796,24 @@ def pandasSQL_builder( import sqlite3 if isinstance(con, sqlite3.Connection) or con is None: - yield SQLiteDatabase(con) - else: - sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore") + return SQLiteDatabase(con) - if sqlalchemy is not None and isinstance( - con, (str, sqlalchemy.engine.Connectable) - ): - with _sqlalchemy_con(con, need_transaction) as con: - yield SQLDatabase(con, schema=schema) - elif isinstance(con, str) and sqlalchemy is None: - raise ImportError("Using URI string without sqlalchemy installed.") - else: - - warnings.warn( - "pandas only supports SQLAlchemy connectable (engine/connection) or " - "database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 " - "objects are not tested. Please consider using SQLAlchemy.", - UserWarning, - stacklevel=find_stack_level() + 2, - ) - yield SQLiteDatabase(con) + sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore") + if isinstance(con, str) and sqlalchemy is None: + raise ImportError("Using URI string without sqlalchemy installed.") -@contextmanager -def _sqlalchemy_con(connectable, need_transaction: bool): - """Create a sqlalchemy connection and a transaction if necessary.""" - sqlalchemy = import_optional_dependency("sqlalchemy", errors="raise") + if sqlalchemy is not None and isinstance(con, (str, sqlalchemy.engine.Connectable)): + return SQLDatabase(con, schema, need_transaction) - if isinstance(connectable, str): - connectable = sqlalchemy.create_engine(connectable) - if isinstance(connectable, sqlalchemy.engine.Engine): - with connectable.connect() as con: - if need_transaction: - with con.begin(): - yield con - else: - yield con - else: - yield connectable + warnings.warn( + "pandas only supports SQLAlchemy connectable (engine/connection) or " + "database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 " + "objects are not tested. Please consider using SQLAlchemy.", + UserWarning, + stacklevel=find_stack_level(), + ) + return SQLiteDatabase(con) class SQLTable(PandasObject): @@ -1049,6 +1038,7 @@ def _query_iterator( def read( self, + exit_stack: ExitStack, coerce_float: bool = True, parse_dates=None, columns=None, @@ -1069,13 +1059,16 @@ def read( column_names = result.keys() if chunksize is not None: - return self._query_iterator( - result, - chunksize, - column_names, - coerce_float=coerce_float, - parse_dates=parse_dates, - use_nullable_dtypes=use_nullable_dtypes, + return _cleanup_after_generator( + self._query_iterator( + result, + chunksize, + column_names, + coerce_float=coerce_float, + parse_dates=parse_dates, + use_nullable_dtypes=use_nullable_dtypes, + ), + exit_stack, ) else: data = result.fetchall() @@ -1327,6 +1320,12 @@ class PandasSQL(PandasObject, ABC): Subclasses Should define read_query and to_sql. """ + def __enter__(self): + return self + + def __exit__(self, *args) -> None: + pass + def read_table( self, table_name: str, @@ -1482,20 +1481,38 @@ class SQLDatabase(PandasSQL): Parameters ---------- - con : SQLAlchemy Connection - Connection to connect with the database. Using SQLAlchemy makes it + con : SQLAlchemy Connectable or URI string. + Connectable to connect with the database. Using SQLAlchemy makes it possible to use any DB supported by that library. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). + need_transaction : bool, default False + If True, SQLDatabase will create a transaction. """ - def __init__(self, con, schema: str | None = None) -> None: + def __init__( + self, con, schema: str | None = None, need_transaction: bool = False + ) -> None: + from sqlalchemy import create_engine + from sqlalchemy.engine import Engine from sqlalchemy.schema import MetaData + self.exit_stack = ExitStack() + if isinstance(con, str): + con = create_engine(con) + if isinstance(con, Engine): + con = self.exit_stack.enter_context(con.connect()) + if need_transaction: + self.exit_stack.enter_context(con.begin()) self.con = con self.meta = MetaData(schema=schema) + self.returns_generator = False + + def __exit__(self, *args) -> None: + if not self.returns_generator: + self.exit_stack.close() @contextmanager def run_transaction(self): @@ -1566,7 +1583,10 @@ def read_table( """ self.meta.reflect(bind=self.con, only=[table_name]) table = SQLTable(table_name, self, index=index_col, schema=schema) + if chunksize is not None: + self.returns_generator = True return table.read( + self.exit_stack, coerce_float=coerce_float, parse_dates=parse_dates, columns=columns, @@ -1675,15 +1695,19 @@ def read_query( columns = result.keys() if chunksize is not None: - return self._query_iterator( - result, - chunksize, - columns, - index_col=index_col, - coerce_float=coerce_float, - parse_dates=parse_dates, - dtype=dtype, - use_nullable_dtypes=use_nullable_dtypes, + self.returns_generator = True + return _cleanup_after_generator( + self._query_iterator( + result, + chunksize, + columns, + index_col=index_col, + coerce_float=coerce_float, + parse_dates=parse_dates, + dtype=dtype, + use_nullable_dtypes=use_nullable_dtypes, + ), + self.exit_stack, ) else: data = result.fetchall() diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 490b425ee52bf..b7cff1627a81f 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -260,24 +260,34 @@ def check_iris_frame(frame: DataFrame): row = frame.iloc[0] assert issubclass(pytype, np.floating) tm.equalContents(row.values, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"]) + assert frame.shape in ((150, 5), (8, 5)) def count_rows(conn, table_name: str): stmt = f"SELECT count(*) AS count_1 FROM {table_name}" if isinstance(conn, sqlite3.Connection): cur = conn.cursor() - result = cur.execute(stmt) + return cur.execute(stmt).fetchone()[0] else: - from sqlalchemy import text + from sqlalchemy import ( + create_engine, + text, + ) from sqlalchemy.engine import Engine stmt = text(stmt) - if isinstance(conn, Engine): + if isinstance(conn, str): + try: + engine = create_engine(conn) + with engine.connect() as conn: + return conn.execute(stmt).scalar_one() + finally: + engine.dispose() + elif isinstance(conn, Engine): with conn.connect() as conn: - result = conn.execute(stmt) + return conn.execute(stmt).scalar_one() else: - result = conn.execute(stmt) - return result.fetchone()[0] + return conn.execute(stmt).scalar_one() @pytest.fixture @@ -388,6 +398,7 @@ def mysql_pymysql_engine(iris_path, types_data): engine = sqlalchemy.create_engine( "mysql+pymysql://root@localhost:3306/pandas", connect_args={"client_flag": pymysql.constants.CLIENT.MULTI_STATEMENTS}, + poolclass=sqlalchemy.pool.NullPool, ) insp = sqlalchemy.inspect(engine) if not insp.has_table("iris"): @@ -414,7 +425,8 @@ def postgresql_psycopg2_engine(iris_path, types_data): sqlalchemy = pytest.importorskip("sqlalchemy") pytest.importorskip("psycopg2") engine = sqlalchemy.create_engine( - "postgresql+psycopg2://postgres:postgres@localhost:5432/pandas" + "postgresql+psycopg2://postgres:postgres@localhost:5432/pandas", + poolclass=sqlalchemy.pool.NullPool, ) insp = sqlalchemy.inspect(engine) if not insp.has_table("iris"): @@ -435,9 +447,16 @@ def postgresql_psycopg2_conn(postgresql_psycopg2_engine): @pytest.fixture -def sqlite_engine(): +def sqlite_str(): + pytest.importorskip("sqlalchemy") + with tm.ensure_clean() as name: + yield "sqlite:///" + name + + +@pytest.fixture +def sqlite_engine(sqlite_str): sqlalchemy = pytest.importorskip("sqlalchemy") - engine = sqlalchemy.create_engine("sqlite://") + engine = sqlalchemy.create_engine(sqlite_str, poolclass=sqlalchemy.pool.NullPool) yield engine engine.dispose() @@ -447,6 +466,15 @@ def sqlite_conn(sqlite_engine): yield sqlite_engine.connect() +@pytest.fixture +def sqlite_iris_str(sqlite_str, iris_path): + sqlalchemy = pytest.importorskip("sqlalchemy") + engine = sqlalchemy.create_engine(sqlite_str) + create_and_load_iris(engine, iris_path, "sqlite") + engine.dispose() + return sqlite_str + + @pytest.fixture def sqlite_iris_engine(sqlite_engine, iris_path): create_and_load_iris(sqlite_engine, iris_path, "sqlite") @@ -485,11 +513,13 @@ def sqlite_buildin_iris(sqlite_buildin, iris_path): sqlite_connectable = [ "sqlite_engine", "sqlite_conn", + "sqlite_str", ] sqlite_iris_connectable = [ "sqlite_iris_engine", "sqlite_iris_conn", + "sqlite_iris_str", ] sqlalchemy_connectable = mysql_connectable + postgresql_connectable + sqlite_connectable @@ -541,10 +571,47 @@ def test_to_sql_exist_fail(conn, test_frame1, request): @pytest.mark.db @pytest.mark.parametrize("conn", all_connectable_iris) -def test_read_iris(conn, request): +def test_read_iris_query(conn, request): conn = request.getfixturevalue(conn) - with pandasSQL_builder(conn) as pandasSQL: - iris_frame = pandasSQL.read_query("SELECT * FROM iris") + iris_frame = read_sql_query("SELECT * FROM iris", conn) + check_iris_frame(iris_frame) + iris_frame = pd.read_sql("SELECT * FROM iris", conn) + check_iris_frame(iris_frame) + iris_frame = pd.read_sql("SELECT * FROM iris where 0=1", conn) + assert iris_frame.shape == (0, 5) + assert "SepalWidth" in iris_frame.columns + + +@pytest.mark.db +@pytest.mark.parametrize("conn", all_connectable_iris) +def test_read_iris_query_chunksize(conn, request): + conn = request.getfixturevalue(conn) + iris_frame = concat(read_sql_query("SELECT * FROM iris", conn, chunksize=7)) + check_iris_frame(iris_frame) + iris_frame = concat(pd.read_sql("SELECT * FROM iris", conn, chunksize=7)) + check_iris_frame(iris_frame) + iris_frame = concat(pd.read_sql("SELECT * FROM iris where 0=1", conn, chunksize=7)) + assert iris_frame.shape == (0, 5) + assert "SepalWidth" in iris_frame.columns + + +@pytest.mark.db +@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris) +def test_read_iris_table(conn, request): + conn = request.getfixturevalue(conn) + iris_frame = read_sql_table("iris", conn) + check_iris_frame(iris_frame) + iris_frame = pd.read_sql("iris", conn) + check_iris_frame(iris_frame) + + +@pytest.mark.db +@pytest.mark.parametrize("conn", sqlalchemy_connectable_iris) +def test_read_iris_table_chunksize(conn, request): + conn = request.getfixturevalue(conn) + iris_frame = concat(read_sql_table("iris", conn, chunksize=7)) + check_iris_frame(iris_frame) + iris_frame = concat(pd.read_sql("iris", conn, chunksize=7)) check_iris_frame(iris_frame)
- [X] closes #50199 - [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. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This fixes a bug which I introduced in #49531. That PR refactored code so that `SQLDatabase` only accepts a sqlalchemy `Connection` and not an `Engine`. I used a context manager to handle cleanup. However, this can break `read_sql` with `chunksize`, because the caller might be iterating over the chunks after the connection is closed. I added tests with chunksize, and I use `NullPool` with `create_engine`, because this is more likely to cause the connection to close. I also created a new string connectable to test with.
https://api.github.com/repos/pandas-dev/pandas/pulls/49967
2022-11-30T00:57:53Z
2023-01-31T21:23:32Z
2023-01-31T21:23:32Z
2023-02-02T09:28:35Z
REF: reverse dispatch in factorize
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 381f76c4502d6..65691e6f46eb5 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -73,7 +73,6 @@ ABCExtensionArray, ABCIndex, ABCMultiIndex, - ABCRangeIndex, ABCSeries, ABCTimedeltaArray, ) @@ -738,13 +737,11 @@ def factorize( # Step 2 is dispatched to extension types (like Categorical). They are # responsible only for factorization. All data coercion, sorting and boxing # should happen here. - if isinstance(values, ABCRangeIndex): - return values.factorize(sort=sort) + if isinstance(values, (ABCIndex, ABCSeries)): + return values.factorize(sort=sort, use_na_sentinel=use_na_sentinel) values = _ensure_arraylike(values) original = values - if not isinstance(values, ABCMultiIndex): - values = extract_array(values, extract_numpy=True) if ( isinstance(values, (ABCDatetimeArray, ABCTimedeltaArray)) @@ -753,7 +750,7 @@ def factorize( # The presence of 'freq' means we can fast-path sorting and know there # aren't NAs codes, uniques = values.factorize(sort=sort) - return _re_wrap_factorize(original, uniques, codes) + return codes, uniques elif not isinstance(values.dtype, np.dtype): codes, uniques = values.factorize(use_na_sentinel=use_na_sentinel) @@ -789,21 +786,6 @@ def factorize( uniques = _reconstruct_data(uniques, original.dtype, original) - return _re_wrap_factorize(original, uniques, codes) - - -def _re_wrap_factorize(original, uniques, codes: np.ndarray): - """ - Wrap factorize results in Series or Index depending on original type. - """ - if isinstance(original, ABCIndex): - uniques = ensure_wrapped_if_datetimelike(uniques) - uniques = original._shallow_copy(uniques, name=None) - elif isinstance(original, ABCSeries): - from pandas import Index - - uniques = Index(uniques) - return codes, uniques diff --git a/pandas/core/base.py b/pandas/core/base.py index fb563fd640cfd..22a4790b32506 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -79,6 +79,7 @@ from pandas import ( Categorical, + Index, Series, ) @@ -1134,8 +1135,20 @@ def factorize( self, sort: bool = False, use_na_sentinel: bool = True, - ): - return algorithms.factorize(self, sort=sort, use_na_sentinel=use_na_sentinel) + ) -> tuple[npt.NDArray[np.intp], Index]: + + codes, uniques = algorithms.factorize( + self._values, sort=sort, use_na_sentinel=use_na_sentinel + ) + + if isinstance(self, ABCIndex): + # preserve e.g. NumericIndex, preserve MultiIndex + uniques = self._constructor(uniques) + else: + from pandas import Index + + uniques = Index(uniques) + return codes, uniques _shared_docs[ "searchsorted"
- [ ] 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. Needed for upcoming removal of DTA/TDA.freq
https://api.github.com/repos/pandas-dev/pandas/pulls/49966
2022-11-30T00:50:25Z
2022-12-01T01:00:37Z
2022-12-01T01:00:37Z
2022-12-01T02:53:28Z
ENH: Add io.nullable_backend=pyarrow support to read_excel
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 541d021791f35..0c3d85cbcb620 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -28,13 +28,26 @@ The available extras, found in the :ref:`installation guide<install.dependencies ``[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.io_readers_nullable_pyarrow: +.. _whatsnew_200.enhancements.io_use_nullable_dtypes_and_nullable_backend: Configuration option, ``io.nullable_backend``, to return pyarrow-backed dtypes from IO functions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -A new global configuration, ``io.nullable_backend`` can now be used in conjunction with the parameter ``use_nullable_dtypes=True`` in :func:`read_parquet`, :func:`read_orc` and :func:`read_csv` (with ``engine="pyarrow"``) -to return pyarrow-backed dtypes when set to ``"pyarrow"`` (:issue:`48957`). +The ``use_nullable_dtypes`` keyword argument has been expanded to the following functions to enable automatic conversion to nullable dtypes (:issue:`36712`) + +* :func:`read_csv` +* :func:`read_excel` + +Additionally a new global configuration, ``io.nullable_backend`` can now be used in conjunction with the parameter ``use_nullable_dtypes=True`` in the following functions +to select the nullable dtypes implementation. + +* :func:`read_csv` (with ``engine="pyarrow"``) +* :func:`read_excel` +* :func:`read_parquet` +* :func:`read_orc` + +By default, ``io.nullable_backend`` is set to ``"pandas"`` to return existing, numpy-backed nullable dtypes, but it can also +be set to ``"pyarrow"`` to return pyarrow-backed, nullable :class:`ArrowDtype` (:issue:`48957`). .. ipython:: python @@ -43,10 +56,15 @@ to return pyarrow-backed dtypes when set to ``"pyarrow"`` (:issue:`48957`). 1,2.5,True,a,,,,, 3,4.5,False,b,6,7.5,True,a, """) - with pd.option_context("io.nullable_backend", "pyarrow"): - df = pd.read_csv(data, use_nullable_dtypes=True, engine="pyarrow") + with pd.option_context("io.nullable_backend", "pandas"): + df = pd.read_csv(data, use_nullable_dtypes=True) df.dtypes + data.seek(0) + with pd.option_context("io.nullable_backend", "pyarrow"): + df_pyarrow = pd.read_csv(data, use_nullable_dtypes=True, engine="pyarrow") + df_pyarrow.dtypes + .. _whatsnew_200.enhancements.other: Other enhancements @@ -55,7 +73,6 @@ Other enhancements - :meth:`.DataFrameGroupBy.quantile` and :meth:`.SeriesGroupBy.quantile` now preserve nullable dtypes instead of casting to numpy dtypes (:issue:`37493`) - :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support an ``axis`` argument. If ``axis`` is set, the default behaviour of which axis to consider can be overwritten (:issue:`47819`) - :func:`assert_frame_equal` now shows the first element where the DataFrames differ, analogously to ``pytest``'s output (:issue:`47910`) -- Added new argument ``use_nullable_dtypes`` to :func:`read_csv` and :func:`read_excel` to enable automatic conversion to nullable dtypes (:issue:`36712`) - Added ``index`` parameter to :meth:`DataFrame.to_dict` (:issue:`46398`) - Added support for extension array dtypes in :func:`merge` (:issue:`44240`) - Added metadata propagation for binary operators on :class:`DataFrame` (:issue:`28283`) diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 7b9794dd434e6..c5fc054952b1f 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -26,6 +26,8 @@ import numpy as np +from pandas._config.config import get_option + from pandas._libs import ( lib, parsers, @@ -39,6 +41,7 @@ DtypeObj, Scalar, ) +from pandas.compat._optional import import_optional_dependency from pandas.errors import ( ParserError, ParserWarning, @@ -71,6 +74,7 @@ from pandas import StringDtype from pandas.core import algorithms from pandas.core.arrays import ( + ArrowExtensionArray, BooleanArray, Categorical, ExtensionArray, @@ -710,6 +714,7 @@ def _infer_types( use_nullable_dtypes: Literal[True] | Literal[False] = ( self.use_nullable_dtypes and no_dtype_specified ) + nullable_backend = get_option("io.nullable_backend") result: ArrayLike if try_num_bool and is_object_dtype(values.dtype): @@ -767,6 +772,16 @@ def _infer_types( if inferred_type != "datetime": result = StringDtype().construct_array_type()._from_sequence(values) + if use_nullable_dtypes and nullable_backend == "pyarrow": + pa = import_optional_dependency("pyarrow") + if isinstance(result, np.ndarray): + result = ArrowExtensionArray(pa.array(result, from_pandas=True)) + else: + # ExtensionArray + result = ArrowExtensionArray( + pa.array(result.to_numpy(), from_pandas=True) + ) + return result, na_count def _cast_types(self, values: ArrayLike, cast_type: DtypeObj, column) -> ArrayLike: diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index bff4c98fe2842..822e24b224052 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -536,7 +536,11 @@ def test_reader_dtype_str(self, read_ext, dtype, expected): actual = pd.read_excel(basename + read_ext, dtype=dtype) tm.assert_frame_equal(actual, expected) - def test_use_nullable_dtypes(self, read_ext): + @pytest.mark.parametrize( + "nullable_backend", + ["pandas", pytest.param("pyarrow", marks=td.skip_if_no("pyarrow"))], + ) + def test_use_nullable_dtypes(self, read_ext, nullable_backend): # GH#36712 if read_ext in (".xlsb", ".xls"): pytest.skip(f"No engine for filetype: '{read_ext}'") @@ -557,10 +561,30 @@ def test_use_nullable_dtypes(self, read_ext): ) with tm.ensure_clean(read_ext) as file_path: df.to_excel(file_path, "test", index=False) - result = pd.read_excel( - file_path, sheet_name="test", use_nullable_dtypes=True + with pd.option_context("io.nullable_backend", nullable_backend): + result = pd.read_excel( + file_path, sheet_name="test", use_nullable_dtypes=True + ) + if nullable_backend == "pyarrow": + import pyarrow as pa + + from pandas.arrays import ArrowExtensionArray + + expected = DataFrame( + { + col: ArrowExtensionArray(pa.array(df[col], from_pandas=True)) + for col in df.columns + } ) - tm.assert_frame_equal(result, df) + # pyarrow by default infers timestamp resolution as us, not ns + expected["i"] = ArrowExtensionArray( + expected["i"].array._data.cast(pa.timestamp(unit="us")) + ) + # pyarrow supports a null type, so don't have to default to Int64 + expected["j"] = ArrowExtensionArray(pa.array([None, None])) + else: + expected = df + tm.assert_frame_equal(result, expected) def test_use_nullabla_dtypes_and_dtype(self, read_ext): # GH#36712
- [x] xref #48957 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49965
2022-11-30T00:16:46Z
2022-12-02T11:13:08Z
2022-12-02T11:13:08Z
2022-12-02T17:56:11Z
TST/CoW: copy-on-write tests for df.head and df.tail
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 0c68f6a866eec..bf65f153b10dd 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -250,3 +250,33 @@ def test_set_index(using_copy_on_write): df2.iloc[0, 1] = 0 assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c")) tm.assert_frame_equal(df, df_orig) + + +@pytest.mark.parametrize( + "method", + [ + lambda df: df.head(), + lambda df: df.head(2), + lambda df: df.tail(), + lambda df: df.tail(3), + ], +) +def test_head_tail(method, using_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]}) + df_orig = df.copy() + df2 = method(df) + df2._mgr._verify_integrity() + + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + + # modify df2 to trigger CoW for that block + df2.iloc[0, 0] = 0 + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + if using_copy_on_write: + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + else: + # without CoW enabled, head and tail return views. Mutating df2 also mutates df. + df2.iloc[0, 0] = 1 + tm.assert_frame_equal(df, df_orig)
- [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). Progress towards #49473 Because `.head()` and `.tail()` use `.iloc` under the hood, copy-on-write is already implemented for them, but this PR adds explicit tests for both methods.
https://api.github.com/repos/pandas-dev/pandas/pulls/49963
2022-11-29T22:35:16Z
2022-12-01T20:41:19Z
2022-12-01T20:41:19Z
2022-12-01T20:41:25Z
STYLE: #49656 - generic.py
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 1b17deb7def90..2de83bb7a4468 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4,7 +4,7 @@ import collections import datetime as dt import gc -import json +from json import loads import operator import pickle import re @@ -134,7 +134,6 @@ algorithms as algos, arraylike, indexing, - missing, nanops, sample, ) @@ -160,7 +159,11 @@ SingleArrayManager, ) from pandas.core.internals.construction import mgr_to_mgr -from pandas.core.missing import find_valid_index +from pandas.core.missing import ( + clean_fill_method, + clean_reindex_fill_method, + find_valid_index, +) from pandas.core.ops import align_method_FRAME from pandas.core.reshape.concat import concat from pandas.core.shared_docs import _shared_docs @@ -2122,7 +2125,7 @@ def _repr_data_resource_(self): as_json = data.to_json(orient="table") as_json = cast(str, as_json) - return json.loads(as_json, object_pairs_hook=collections.OrderedDict) + return loads(as_json, object_pairs_hook=collections.OrderedDict) # ---------------------------------------------------------------------- # I/O Methods @@ -2410,7 +2413,7 @@ def to_json( Examples -------- - >>> import json + >>> from json import loads, dumps >>> df = pd.DataFrame( ... [["a", "b"], ["c", "d"]], ... index=["row 1", "row 2"], @@ -2418,8 +2421,8 @@ def to_json( ... ) >>> result = df.to_json(orient="split") - >>> parsed = json.loads(result) - >>> json.dumps(parsed, indent=4) # doctest: +SKIP + >>> parsed = loads(result) + >>> dumps(parsed, indent=4) # doctest: +SKIP {{ "columns": [ "col 1", @@ -2445,8 +2448,8 @@ def to_json( Note that index labels are not preserved with this encoding. >>> result = df.to_json(orient="records") - >>> parsed = json.loads(result) - >>> json.dumps(parsed, indent=4) # doctest: +SKIP + >>> parsed = loads(result) + >>> dumps(parsed, indent=4) # doctest: +SKIP [ {{ "col 1": "a", @@ -2461,8 +2464,8 @@ def to_json( Encoding/decoding a Dataframe using ``'index'`` formatted JSON: >>> result = df.to_json(orient="index") - >>> parsed = json.loads(result) - >>> json.dumps(parsed, indent=4) # doctest: +SKIP + >>> parsed = loads(result) + >>> dumps(parsed, indent=4) # doctest: +SKIP {{ "row 1": {{ "col 1": "a", @@ -2477,8 +2480,8 @@ def to_json( Encoding/decoding a Dataframe using ``'columns'`` formatted JSON: >>> result = df.to_json(orient="columns") - >>> parsed = json.loads(result) - >>> json.dumps(parsed, indent=4) # doctest: +SKIP + >>> parsed = loads(result) + >>> dumps(parsed, indent=4) # doctest: +SKIP {{ "col 1": {{ "row 1": "a", @@ -2493,8 +2496,8 @@ def to_json( Encoding/decoding a Dataframe using ``'values'`` formatted JSON: >>> result = df.to_json(orient="values") - >>> parsed = json.loads(result) - >>> json.dumps(parsed, indent=4) # doctest: +SKIP + >>> parsed = loads(result) + >>> dumps(parsed, indent=4) # doctest: +SKIP [ [ "a", @@ -2509,8 +2512,8 @@ def to_json( Encoding with Table Schema: >>> result = df.to_json(orient="table") - >>> parsed = json.loads(result) - >>> json.dumps(parsed, indent=4) # doctest: +SKIP + >>> parsed = loads(result) + >>> dumps(parsed, indent=4) # doctest: +SKIP {{ "schema": {{ "fields": [ @@ -5169,7 +5172,7 @@ def reindex(self: NDFrameT, *args, **kwargs) -> NDFrameT: # construct the args axes, kwargs = self._construct_axes_from_arguments(args, kwargs) - method = missing.clean_reindex_fill_method(kwargs.pop("method", None)) + method = clean_reindex_fill_method(kwargs.pop("method", None)) level = kwargs.pop("level", None) copy = kwargs.pop("copy", None) limit = kwargs.pop("limit", None) @@ -9201,7 +9204,7 @@ def align( 4 600.0 700.0 800.0 900.0 NaN """ - method = missing.clean_fill_method(method) + method = clean_fill_method(method) if broadcast_axis == 1 and self.ndim != other.ndim: if isinstance(self, ABCSeries):
- [ ] closes #49656 - [ ] [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/49960
2022-11-29T20:46:18Z
2022-11-29T23:13:04Z
2022-11-29T23:13:04Z
2022-11-29T23:13:04Z
48779-doc-MonthEnd
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 8e022ac662d21..82f134a348fee 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -2412,11 +2412,28 @@ cdef class MonthEnd(MonthOffset): """ DateOffset of one month end. + MonthEnd goes to the next date which is an end of the month. + To get the end of the current month pass the parameter n equals 0. + + See Also + -------- + :class:`~pandas.tseries.offsets.DateOffset` : Standard kind of date increment. + Examples -------- - >>> ts = pd.Timestamp(2022, 1, 1) + >>> ts = pd.Timestamp(2022, 1, 30) >>> ts + pd.offsets.MonthEnd() Timestamp('2022-01-31 00:00:00') + + >>> ts = pd.Timestamp(2022, 1, 31) + >>> ts + pd.offsets.MonthEnd() + Timestamp('2022-02-28 00:00:00') + + If you want to get the end of the current month pass the parameter n equals 0: + + >>> ts = pd.Timestamp(2022, 1, 31) + >>> ts + pd.offsets.MonthEnd(0) + Timestamp('2022-01-31 00:00:00') """ _period_dtype_code = PeriodDtypeCode.M _prefix = "M"
- [x] closes #48779 - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). As proposed by @MarcoGorelli I updated docs for `MonthEnd` and added one more example to highlight “the last day of the month” behavior. I checked that build of documentation shows the new description.
https://api.github.com/repos/pandas-dev/pandas/pulls/49958
2022-11-29T09:40:50Z
2022-11-30T16:31:31Z
2022-11-30T16:31:31Z
2022-11-30T20:41:54Z
Remove defaults channel from conda asv conf
diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json index b1feb1d0af79c..16f8f28b66d31 100644 --- a/asv_bench/asv.conf.json +++ b/asv_bench/asv.conf.json @@ -57,7 +57,7 @@ "odfpy": [], "jinja2": [], }, - "conda_channels": ["defaults", "conda-forge"], + "conda_channels": ["conda-forge"], // Combinations of libraries/python versions can be excluded/included // from the set to test. Each entry is a dictionary containing additional // key-value pairs to include/exclude.
Looks like we only use conda-forge elsewhere so assuming this is an oversight
https://api.github.com/repos/pandas-dev/pandas/pulls/49955
2022-11-29T04:24:17Z
2022-11-29T08:20:11Z
2022-11-29T08:20:11Z
2022-11-29T17:24:49Z
DEPR: Change numeric_only default to False in remaining groupby methods
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 42170aaa09978..9abd08004edaa 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -572,7 +572,7 @@ Removal of prior version deprecations/changes - Changed default of ``numeric_only`` to ``False`` in all DataFrame methods with that argument (:issue:`46096`, :issue:`46906`) - Changed default of ``numeric_only`` to ``False`` in :meth:`Series.rank` (:issue:`47561`) - Enforced deprecation of silently dropping nuisance columns in groupby and resample operations when ``numeric_only=False`` (:issue:`41475`) -- Changed default of ``numeric_only`` to ``False`` in various :class:`.DataFrameGroupBy` methods (:issue:`46072`) +- Changed default of ``numeric_only`` in various :class:`.DataFrameGroupBy` methods; all methods now default to ``numeric_only=False`` (:issue:`46072`) - Changed default of ``numeric_only`` to ``False`` in :class:`.Resampler` methods (:issue:`47177`) - diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 7e9163b87cee6..a80892a145a70 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -87,7 +87,6 @@ _agg_template, _apply_docs, _transform_template, - warn_dropping_nuisance_columns_deprecated, ) from pandas.core.groupby.grouper import get_grouper from pandas.core.indexes.api import ( @@ -438,7 +437,7 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): ) def _cython_transform( - self, how: str, numeric_only: bool = True, axis: AxisInt = 0, **kwargs + self, how: str, numeric_only: bool = False, axis: AxisInt = 0, **kwargs ): assert axis == 0 # handled by caller @@ -1333,13 +1332,12 @@ def _wrap_applied_output_series( def _cython_transform( self, how: str, - numeric_only: bool | lib.NoDefault = lib.no_default, + numeric_only: bool = False, axis: AxisInt = 0, **kwargs, ) -> DataFrame: assert axis == 0 # handled by caller # TODO: no tests with self.ndim == 1 for DataFrameGroupBy - numeric_only_bool = self._resolve_numeric_only(how, numeric_only, axis) # With self.axis == 0, we have multi-block tests # e.g. test_rank_min_int, test_cython_transform_frame @@ -1347,8 +1345,7 @@ def _cython_transform( # With self.axis == 1, _get_data_to_aggregate does a transpose # so we always have a single block. mgr: Manager2D = self._get_data_to_aggregate() - orig_mgr_len = len(mgr) - if numeric_only_bool: + if numeric_only: mgr = mgr.get_numeric_data(copy=False) def arr_func(bvalues: ArrayLike) -> ArrayLike: @@ -1358,12 +1355,9 @@ def arr_func(bvalues: ArrayLike) -> ArrayLike: # We could use `mgr.apply` here and not have to set_axis, but # we would have to do shape gymnastics for ArrayManager compat - res_mgr = mgr.grouped_reduce(arr_func, ignore_failures=False) + res_mgr = mgr.grouped_reduce(arr_func) res_mgr.set_axis(1, mgr.axes[1]) - if len(res_mgr) < orig_mgr_len: - warn_dropping_nuisance_columns_deprecated(type(self), how, numeric_only) - res_df = self.obj._constructor(res_mgr) if self.axis == 1: res_df = res_df.T @@ -1493,15 +1487,8 @@ def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame: output = {} inds = [] for i, (colname, sgb) in enumerate(self._iterate_column_groupbys(obj)): - try: - output[i] = sgb.transform(wrapper) - except TypeError: - # e.g. trying to call nanmean with string values - warn_dropping_nuisance_columns_deprecated( - type(self), "transform", numeric_only=False - ) - else: - inds.append(i) + output[i] = sgb.transform(wrapper) + inds.append(i) if not output: raise TypeError("Transform function invalid for data types") @@ -2243,7 +2230,7 @@ def corr( self, method: str | Callable[[np.ndarray, np.ndarray], float] = "pearson", min_periods: int = 1, - numeric_only: bool | lib.NoDefault = lib.no_default, + numeric_only: bool = False, ) -> DataFrame: result = self._op_via_apply( "corr", method=method, min_periods=min_periods, numeric_only=numeric_only @@ -2255,7 +2242,7 @@ def cov( self, min_periods: int | None = None, ddof: int | None = 1, - numeric_only: bool | lib.NoDefault = lib.no_default, + numeric_only: bool = False, ) -> DataFrame: result = self._op_via_apply( "cov", min_periods=min_periods, ddof=ddof, numeric_only=numeric_only @@ -2316,7 +2303,7 @@ def corrwith( axis: Axis = 0, drop: bool = False, method: CorrelationMethod = "pearson", - numeric_only: bool | lib.NoDefault = lib.no_default, + numeric_only: bool = False, ) -> DataFrame: result = self._op_via_apply( "corrwith", diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index b3f6bb3edb9da..497e0ef724373 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1007,15 +1007,8 @@ def _op_via_apply(self, name: str, *args, **kwargs): if kwargs.get("axis", None) is None or kwargs.get("axis") is lib.no_default: kwargs["axis"] = self.axis - numeric_only = kwargs.get("numeric_only", lib.no_default) - def curried(x): - with warnings.catch_warnings(): - # Catch any warnings from dispatch to DataFrame; we'll emit - # a warning for groupby below - match = "The default value of numeric_only " - warnings.filterwarnings("ignore", match, FutureWarning) - return f(x, *args, **kwargs) + return f(x, *args, **kwargs) # preserve the name so we can detect it when calling plot methods, # to avoid duplicates @@ -1037,13 +1030,6 @@ def curried(x): not_indexed_same=not is_transform, ) - if self._selected_obj.ndim != 1 and self.axis != 1 and result.ndim != 1: - missing = self._obj_with_exclusions.columns.difference(result.columns) - if len(missing) > 0: - warn_dropping_nuisance_columns_deprecated( - type(self), name, numeric_only - ) - if self.grouper.has_dropped_na and is_transform: # result will have dropped rows due to nans, fill with null # and ensure index is ordered same as the input @@ -1308,80 +1294,6 @@ def _wrap_applied_output( ): raise AbstractMethodError(self) - def _resolve_numeric_only( - self, how: str, numeric_only: bool | lib.NoDefault, axis: AxisInt - ) -> bool: - """ - Determine subclass-specific default value for 'numeric_only'. - - For SeriesGroupBy we want the default to be False (to match Series behavior). - For DataFrameGroupBy we want it to be True (for backwards-compat). - - Parameters - ---------- - numeric_only : bool or lib.no_default - axis : int - Axis passed to the groupby op (not self.axis). - - Returns - ------- - bool - """ - # GH#41291 - if numeric_only is lib.no_default: - # i.e. not explicitly passed by user - if self.obj.ndim == 2: - # i.e. DataFrameGroupBy - numeric_only = axis != 1 - # GH#42395 GH#43108 GH#43154 - # Regression from 1.2.5 to 1.3 caused object columns to be dropped - if self.axis: - obj = self._obj_with_exclusions.T - else: - obj = self._obj_with_exclusions - check = obj._get_numeric_data() - if len(obj.columns) and not len(check.columns) and not obj.empty: - numeric_only = False - - else: - numeric_only = False - - if numeric_only and self.obj.ndim == 1 and not is_numeric_dtype(self.obj.dtype): - # GH#47500 - warnings.warn( - f"{type(self).__name__}.{how} called with " - f"numeric_only={numeric_only} and dtype {self.obj.dtype}. This will " - "raise a TypeError in a future version of pandas", - category=FutureWarning, - stacklevel=find_stack_level(), - ) - raise NotImplementedError( - f"{type(self).__name__}.{how} does not implement numeric_only" - ) - - return numeric_only - - def _maybe_warn_numeric_only_depr( - self, how: str, result: DataFrame | Series, numeric_only: bool | lib.NoDefault - ) -> None: - """Emit warning on numeric_only behavior deprecation when appropriate. - - Parameters - ---------- - how : str - Groupby kernel name. - result : - Result of the groupby operation. - numeric_only : bool or lib.no_default - Argument as passed by user. - """ - if ( - self._obj_with_exclusions.ndim != 1 - and result.ndim > 1 - and len(result.columns) < len(self._obj_with_exclusions.columns) - ): - warn_dropping_nuisance_columns_deprecated(type(self), how, numeric_only) - # ----------------------------------------------------------------- # numba @@ -1606,9 +1518,7 @@ def _python_apply_general( ) @final - def _python_agg_general( - self, func, *args, raise_on_typeerror: bool = False, **kwargs - ): + def _python_agg_general(self, func, *args, **kwargs): func = com.is_builtin_func(func) f = lambda x: func(x, *args, **kwargs) @@ -1621,18 +1531,7 @@ def _python_agg_general( for idx, obj in enumerate(self._iterate_slices()): name = obj.name - - try: - # if this function is invalid for this dtype, we will ignore it. - result = self.grouper.agg_series(obj, f) - except TypeError: - if raise_on_typeerror: - raise - warn_dropping_nuisance_columns_deprecated( - type(self), "agg", numeric_only=False - ) - continue - + result = self.grouper.agg_series(obj, f) key = base.OutputKey(label=name, position=idx) output[key] = result @@ -1644,7 +1543,7 @@ def _python_agg_general( @final def _agg_general( self, - numeric_only: bool | lib.NoDefault = True, + numeric_only: bool = False, min_count: int = -1, *, alias: str, @@ -1706,26 +1605,25 @@ def _cython_agg_general( self, how: str, alt: Callable, - numeric_only: bool | lib.NoDefault, + numeric_only: bool = False, min_count: int = -1, **kwargs, ): # Note: we never get here with how="ohlc" for DataFrameGroupBy; # that goes through SeriesGroupBy - numeric_only_bool = self._resolve_numeric_only(how, numeric_only, axis=0) data = self._get_data_to_aggregate() is_ser = data.ndim == 1 - orig_len = len(data) - if numeric_only_bool: + if numeric_only: if is_ser and not is_numeric_dtype(self._selected_obj.dtype): # GH#41291 match Series behavior kwd_name = "numeric_only" if how in ["any", "all"]: kwd_name = "bool_only" - raise NotImplementedError( - f"{type(self).__name__}.{how} does not implement {kwd_name}." + raise TypeError( + f"Cannot use {kwd_name}={numeric_only} with " + f"{type(self).__name__}.{how} and non-numeric types." ) if not is_ser: data = data.get_numeric_data(copy=False) @@ -1751,10 +1649,7 @@ def array_func(values: ArrayLike) -> ArrayLike: # TypeError -> we may have an exception in trying to aggregate # continue and exclude the block - new_mgr = data.grouped_reduce(array_func, ignore_failures=False) - - if not is_ser and len(new_mgr) < orig_len: - warn_dropping_nuisance_columns_deprecated(type(self), how, numeric_only) + new_mgr = data.grouped_reduce(array_func) res = self._wrap_agged_manager(new_mgr) if is_ser: @@ -1764,7 +1659,7 @@ def array_func(values: ArrayLike) -> ArrayLike: return res def _cython_transform( - self, how: str, numeric_only: bool = True, axis: AxisInt = 0, **kwargs + self, how: str, numeric_only: bool = False, axis: AxisInt = 0, **kwargs ): raise AbstractMethodError(self) @@ -2144,23 +2039,21 @@ def median(self, numeric_only: bool = False): Parameters ---------- - numeric_only : bool, default True + numeric_only : bool, default False Include only float, int, boolean columns. .. versionchanged:: 2.0.0 - numeric_only no longer accepts ``None``. + numeric_only no longer accepts ``None`` and defaults to False. Returns ------- Series or DataFrame Median of values within each group. """ - numeric_only_bool = self._resolve_numeric_only("median", numeric_only, axis=0) - result = self._cython_agg_general( "median", - alt=lambda x: Series(x).median(numeric_only=numeric_only_bool), + alt=lambda x: Series(x).median(numeric_only=numeric_only), numeric_only=numeric_only, ) return result.__finalize__(self.obj, method="groupby") @@ -2221,10 +2114,8 @@ def std( return np.sqrt(self._numba_agg_general(sliding_var, engine_kwargs, ddof)) else: - # Resolve numeric_only so that var doesn't warn - numeric_only_bool = self._resolve_numeric_only("std", numeric_only, axis=0) if ( - numeric_only_bool + numeric_only and self.obj.ndim == 1 and not is_numeric_dtype(self.obj.dtype) ): @@ -2235,7 +2126,7 @@ def std( result = self._get_cythonized_result( libgroupby.group_var, cython_dtype=np.dtype(np.float64), - numeric_only=numeric_only_bool, + numeric_only=numeric_only, needs_counts=True, post_processing=lambda vals, inference: np.sqrt(vals), ddof=ddof, @@ -2319,7 +2210,7 @@ def sem(self, ddof: int = 1, numeric_only: bool = False): ddof : int, default 1 Degrees of freedom. - numeric_only : bool, default True + numeric_only : bool, default False Include only `float`, `int` or `boolean` data. .. versionadded:: 1.5.0 @@ -2333,14 +2224,12 @@ def sem(self, ddof: int = 1, numeric_only: bool = False): Series or DataFrame Standard error of the mean of values within each group. """ - # Reolve numeric_only so that std doesn't warn if numeric_only and self.obj.ndim == 1 and not is_numeric_dtype(self.obj.dtype): raise TypeError( f"{type(self).__name__}.sem called with " f"numeric_only={numeric_only} and dtype {self.obj.dtype}" ) result = self.std(ddof=ddof, numeric_only=numeric_only) - self._maybe_warn_numeric_only_depr("sem", result, numeric_only) if result.ndim == 1: result /= np.sqrt(self.count()) @@ -3107,7 +2996,7 @@ def quantile( self, q: float | AnyArrayLike = 0.5, interpolation: str = "linear", - numeric_only: bool | lib.NoDefault = lib.no_default, + numeric_only: bool = False, ): """ Return group values at the given quantile, a la numpy.percentile. @@ -3118,11 +3007,15 @@ def quantile( Value(s) between 0 and 1 providing the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} Method to use when the desired quantile falls between two points. - numeric_only : bool, default True + numeric_only : bool, default False Include only `float`, `int` or `boolean` data. .. versionadded:: 1.5.0 + .. versionchanged:: 2.0.0 + + numeric_only now defaults to ``False``. + Returns ------- Series or DataFrame @@ -3146,12 +3039,7 @@ def quantile( a 2.0 b 3.0 """ - numeric_only_bool = self._resolve_numeric_only("quantile", numeric_only, axis=0) - if ( - numeric_only_bool - and self.obj.ndim == 1 - and not is_numeric_dtype(self.obj.dtype) - ): + if numeric_only and self.obj.ndim == 1 and not is_numeric_dtype(self.obj.dtype): raise TypeError( f"{type(self).__name__}.quantile called with " f"numeric_only={numeric_only} and dtype {self.obj.dtype}" @@ -3296,25 +3184,8 @@ def blk_func(values: ArrayLike) -> ArrayLike: obj = self._obj_with_exclusions is_ser = obj.ndim == 1 mgr = self._get_data_to_aggregate() - data = mgr.get_numeric_data() if numeric_only_bool else mgr - res_mgr = data.grouped_reduce(blk_func, ignore_failures=False) - - if ( - numeric_only is lib.no_default - and not is_ser - and len(res_mgr.items) != len(mgr.items) - ): - warn_dropping_nuisance_columns_deprecated( - type(self), "quantile", numeric_only - ) - - if len(res_mgr.items) == 0: - # re-call grouped_reduce to get the desired exception message - mgr.grouped_reduce(blk_func, ignore_failures=False) - # grouped_reduce _should_ raise, so this should not be reached - raise TypeError( # pragma: no cover - "All columns were dropped in grouped_reduce" - ) + data = mgr.get_numeric_data() if numeric_only else mgr + res_mgr = data.grouped_reduce(blk_func) if is_ser: res = self._wrap_agged_manager(res_mgr) @@ -3613,9 +3484,8 @@ def cummin( skipna = kwargs.get("skipna", True) if axis != 0: f = lambda x: np.minimum.accumulate(x, axis) - numeric_only_bool = self._resolve_numeric_only("cummax", numeric_only, axis) obj = self._selected_obj - if numeric_only_bool: + if numeric_only: obj = obj._get_numeric_data() return self._python_apply_general(f, obj, is_transform=True) @@ -3639,9 +3509,8 @@ def cummax( skipna = kwargs.get("skipna", True) if axis != 0: f = lambda x: np.maximum.accumulate(x, axis) - numeric_only_bool = self._resolve_numeric_only("cummax", numeric_only, axis) obj = self._selected_obj - if numeric_only_bool: + if numeric_only: obj = obj._get_numeric_data() return self._python_apply_general(f, obj, is_transform=True) @@ -3654,7 +3523,7 @@ def _get_cythonized_result( self, base_func: Callable, cython_dtype: np.dtype, - numeric_only: bool | lib.NoDefault = lib.no_default, + numeric_only: bool = False, needs_counts: bool = False, needs_nullable: bool = False, needs_mask: bool = False, @@ -3670,7 +3539,7 @@ def _get_cythonized_result( base_func : callable, Cythonized function to be called cython_dtype : np.dtype Type of the array that will be modified by the Cython call. - numeric_only : bool, default True + numeric_only : bool, default False Whether only numeric datatypes should be computed needs_counts : bool, default False Whether the counts should be a part of the Cython call @@ -3701,9 +3570,6 @@ def _get_cythonized_result( ------- `Series` or `DataFrame` with filled values """ - how = base_func.__name__ - numeric_only_bool = self._resolve_numeric_only(how, numeric_only, axis=0) - if post_processing and not callable(post_processing): raise ValueError("'post_processing' must be a callable!") if pre_processing and not callable(pre_processing): @@ -3772,18 +3638,15 @@ def blk_func(values: ArrayLike) -> ArrayLike: mgr = self._get_data_to_aggregate() orig_mgr_len = len(mgr) - if numeric_only_bool: + if numeric_only: mgr = mgr.get_numeric_data() - res_mgr = mgr.grouped_reduce(blk_func, ignore_failures=False) + res_mgr = mgr.grouped_reduce(blk_func) if not is_ser and len(res_mgr.items) != orig_mgr_len: - howstr = how.replace("group_", "") - warn_dropping_nuisance_columns_deprecated(type(self), howstr, numeric_only) - if len(res_mgr.items) == 0: # We re-call grouped_reduce to get the right exception message - mgr.grouped_reduce(blk_func, ignore_failures=False) + mgr.grouped_reduce(blk_func) # grouped_reduce _should_ raise, so this should not be reached raise TypeError( # pragma: no cover "All columns were dropped in grouped_reduce" @@ -4331,27 +4194,3 @@ def _insert_quantile_level(idx: Index, qs: npt.NDArray[np.float64]) -> MultiInde else: mi = MultiIndex.from_product([idx, qs]) return mi - - -def warn_dropping_nuisance_columns_deprecated(cls, how: str, numeric_only) -> None: - if numeric_only is not lib.no_default and not numeric_only: - # numeric_only was specified and falsey but still dropped nuisance columns - warnings.warn( - "Dropping invalid columns in " - f"{cls.__name__}.{how} is deprecated. " - "In a future version, a TypeError will be raised. " - f"Before calling .{how}, select only columns which " - "should be valid for the function.", - FutureWarning, - stacklevel=find_stack_level(), - ) - elif numeric_only is lib.no_default: - warnings.warn( - "The default value of numeric_only in " - f"{cls.__name__}.{how} is deprecated. " - "In a future version, numeric_only will default to False. " - f"Either specify numeric_only or select only columns which " - "should be valid for the function.", - FutureWarning, - stacklevel=find_stack_level(), - ) diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 37ae9d103c8b5..feca755fd43db 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -213,7 +213,7 @@ def apply( ------- ArrayManager """ - assert "filter" not in kwargs and "ignore_failures" not in kwargs + assert "filter" not in kwargs align_keys = align_keys or [] result_arrays: list[np.ndarray] = [] @@ -923,15 +923,13 @@ def idelete(self, indexer) -> ArrayManager: # -------------------------------------------------------------------- # Array-wise Operation - def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: + def grouped_reduce(self: T, func: Callable) -> T: """ Apply grouped reduction function columnwise, returning a new ArrayManager. Parameters ---------- func : grouped reduction function - ignore_failures : bool, default False - Whether to drop columns where func raises TypeError. Returns ------- @@ -943,13 +941,7 @@ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: for i, arr in enumerate(self.arrays): # grouped_reduce functions all expect 2D arrays arr = ensure_block_shape(arr, ndim=2) - try: - res = func(arr) - except (TypeError, NotImplementedError): - if not ignore_failures: - raise - continue - + res = func(arr) if res.ndim == 2: # reverse of ensure_block_shape assert res.shape[0] == 1 @@ -963,10 +955,7 @@ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: else: index = Index(range(result_arrays[0].shape[0])) - if ignore_failures: - columns = self.items[np.array(result_indices, dtype="int64")] - else: - columns = self.items + columns = self.items # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]"; # expected "List[Union[ndarray, ExtensionArray]]" diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py index 37aa60f1ee52d..8a0f2863d851f 100644 --- a/pandas/core/internals/base.py +++ b/pandas/core/internals/base.py @@ -189,12 +189,7 @@ def setitem_inplace(self, indexer, value) -> None: arr[indexer] = value - def grouped_reduce(self, func, ignore_failures: bool = False): - """ - ignore_failures : bool, default False - Not used; for compatibility with ArrayManager/BlockManager. - """ - + def grouped_reduce(self, func): arr = self.array res = func(arr) index = default_index(len(res)) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 3eca3756e1678..20cc087adab23 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -320,7 +320,7 @@ def apply( ------- BlockManager """ - assert "filter" not in kwargs and "ignore_failures" not in kwargs + assert "filter" not in kwargs align_keys = align_keys or [] result_blocks: list[Block] = [] @@ -1466,44 +1466,29 @@ def idelete(self, indexer) -> BlockManager: # ---------------------------------------------------------------- # Block-wise Operation - def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: + def grouped_reduce(self: T, func: Callable) -> T: """ Apply grouped reduction function blockwise, returning a new BlockManager. Parameters ---------- func : grouped reduction function - ignore_failures : bool, default False - Whether to drop blocks where func raises TypeError. Returns ------- BlockManager """ result_blocks: list[Block] = [] - dropped_any = False for blk in self.blocks: if blk.is_object: # split on object-dtype blocks bc some columns may raise # while others do not. for sb in blk._split(): - try: - applied = sb.apply(func) - except (TypeError, NotImplementedError): - if not ignore_failures: - raise - dropped_any = True - continue + applied = sb.apply(func) result_blocks = extend_blocks(applied, result_blocks) else: - try: - applied = blk.apply(func) - except (TypeError, NotImplementedError): - if not ignore_failures: - raise - dropped_any = True - continue + applied = blk.apply(func) result_blocks = extend_blocks(applied, result_blocks) if len(result_blocks) == 0: @@ -1511,10 +1496,6 @@ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: else: index = Index(range(result_blocks[0].values.shape[-1])) - if dropped_any: - # faster to skip _combine if we haven't dropped any blocks - return self._combine(result_blocks, copy=False, index=index) - return type(self).from_blocks(result_blocks, [self.axes[0], index]) def reduce(self: T, func: Callable) -> T: diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 2d3ff95504371..03b917edd357b 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -301,11 +301,12 @@ def test_wrap_agg_out(three_group): def func(ser): if ser.dtype == object: - raise TypeError + raise TypeError("Test error message") return ser.sum() - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid columns"): - result = grouped.aggregate(func) + with pytest.raises(TypeError, match="Test error message"): + grouped.aggregate(func) + result = grouped[[c for c in three_group if c != "C"]].aggregate(func) exp_grouped = three_group.loc[:, three_group.columns != "C"] expected = exp_grouped.groupby(["A", "B"]).aggregate(func) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index b8d2350cf6267..dc09a2e0ea6ad 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -92,9 +92,8 @@ def test_cython_agg_boolean(): def test_cython_agg_nothing_to_agg(): frame = DataFrame({"a": np.random.randint(0, 5, 50), "b": ["foo", "bar"] * 25}) - with tm.assert_produces_warning(FutureWarning, match="This will raise a TypeError"): - with pytest.raises(NotImplementedError, match="does not implement"): - frame.groupby("a")["b"].mean(numeric_only=True) + with pytest.raises(TypeError, match="Cannot use numeric_only=True"): + frame.groupby("a")["b"].mean(numeric_only=True) with pytest.raises(TypeError, match="Could not convert (foo|bar)*"): frame.groupby("a")["b"].mean() @@ -116,9 +115,8 @@ def test_cython_agg_nothing_to_agg_with_dates(): "dates": pd.date_range("now", periods=50, freq="T"), } ) - with tm.assert_produces_warning(FutureWarning, match="This will raise a TypeError"): - with pytest.raises(NotImplementedError, match="does not implement"): - frame.groupby("b").dates.mean(numeric_only=True) + with pytest.raises(TypeError, match="Cannot use numeric_only=True"): + frame.groupby("b").dates.mean(numeric_only=True) def test_cython_agg_frame_columns(): diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index 9aa58e919ce24..6a89c72354d04 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -293,8 +293,7 @@ def raiseException(df): raise TypeError("test") with pytest.raises(TypeError, match="test"): - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid"): - df.groupby(0).agg(raiseException) + df.groupby(0).agg(raiseException) def test_series_agg_multikey(): diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 5c250618bf3c4..b35c4158bf420 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1842,6 +1842,9 @@ def test_category_order_reducer( ): msg = "GH#10694 - idxmax/min fail with unused categories" request.node.add_marker(pytest.mark.xfail(reason=msg)) + elif reduction_func == "corrwith" and not as_index: + msg = "GH#49950 - corrwith with as_index=False may not have grouping column" + request.node.add_marker(pytest.mark.xfail(reason=msg)) elif index_kind != "range" and not as_index: pytest.skip(reason="Result doesn't have categories, nothing to test") df = DataFrame( diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 0f301e05dc898..ef39aabd83d22 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -263,7 +263,7 @@ def _check(self, df, method, expected_columns, expected_columns_numeric): # have no Python fallback exception = NotImplementedError if method.startswith("cum") else TypeError - if method in ("min", "max", "cummin", "cummax"): + if method in ("min", "max", "cummin", "cummax", "cumsum", "cumprod"): # The methods default to numeric_only=False and raise TypeError msg = "|".join( [ @@ -591,10 +591,8 @@ def test_axis1_numeric_only(request, groupby_func, numeric_only): method(*args, **kwargs) elif groupby_func not in has_axis: msg = "got an unexpected keyword argument 'axis'" - warn = FutureWarning if groupby_func == "skew" and not numeric_only else None - with tm.assert_produces_warning(warn, match="Dropping of nuisance columns"): - with pytest.raises(TypeError, match=msg): - method(*args, **kwargs) + with pytest.raises(TypeError, match=msg): + method(*args, **kwargs) # fillna and shift are successful even on object dtypes elif (numeric_only is None or not numeric_only) and groupby_func not in ( "fillna", @@ -1374,46 +1372,44 @@ def test_groupby_sum_timedelta_with_nat(): @pytest.mark.parametrize( - "kernel, numeric_only_default, has_arg", + "kernel, has_arg", [ - ("all", False, False), - ("any", False, False), - ("bfill", False, False), - ("corr", True, True), - ("corrwith", True, True), - ("cov", True, True), - ("cummax", False, True), - ("cummin", False, True), - ("cumprod", True, True), - ("cumsum", True, True), - ("diff", False, False), - ("ffill", False, False), - ("fillna", False, False), - ("first", False, True), - ("idxmax", True, True), - ("idxmin", True, True), - ("last", False, True), - ("max", False, True), - ("mean", False, True), - ("median", False, True), - ("min", False, True), - ("nth", False, False), - ("nunique", False, False), - ("pct_change", False, False), - ("prod", False, True), - ("quantile", True, True), - ("sem", False, True), - ("skew", False, True), - ("std", False, True), - ("sum", False, True), - ("var", False, True), + ("all", False), + ("any", False), + ("bfill", False), + ("corr", True), + ("corrwith", True), + ("cov", True), + ("cummax", True), + ("cummin", True), + ("cumprod", True), + ("cumsum", True), + ("diff", False), + ("ffill", False), + ("fillna", False), + ("first", True), + ("idxmax", True), + ("idxmin", True), + ("last", True), + ("max", True), + ("mean", True), + ("median", True), + ("min", True), + ("nth", False), + ("nunique", False), + ("pct_change", False), + ("prod", True), + ("quantile", True), + ("sem", True), + ("skew", True), + ("std", True), + ("sum", True), + ("var", True), ], ) @pytest.mark.parametrize("numeric_only", [True, False, lib.no_default]) @pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) -def test_deprecate_numeric_only( - kernel, numeric_only_default, has_arg, numeric_only, keys -): +def test_numeric_only(kernel, has_arg, numeric_only, keys): # GH#46072 # drops_nuisance: Whether the op drops nuisance columns even when numeric_only=False # has_arg: Whether the op has a numeric_only arg @@ -1424,26 +1420,9 @@ def test_deprecate_numeric_only( gb = df.groupby(keys) method = getattr(gb, kernel) - if ( - has_arg - and (kernel not in ("idxmax", "idxmin") or numeric_only is True) - and ( - # Cases where b does not appear in the result - numeric_only is True - or (numeric_only is lib.no_default and numeric_only_default) - ) - ): - if numeric_only is True or not numeric_only_default: - warn = None - else: - warn = FutureWarning - if numeric_only is lib.no_default and numeric_only_default: - msg = f"The default value of numeric_only in DataFrameGroupBy.{kernel}" - else: - msg = f"Dropping invalid columns in DataFrameGroupBy.{kernel}" - with tm.assert_produces_warning(warn, match=msg): - result = method(*args, **kwargs) - + if has_arg and numeric_only is True: + # Cases where b does not appear in the result + result = method(*args, **kwargs) assert "b" not in result.columns elif ( # kernels that work on any dtype and have numeric_only arg @@ -1577,31 +1556,17 @@ def test_deprecate_numeric_only_series(dtype, groupby_func, request): with pytest.raises(TypeError, match=msg): method(*args, numeric_only=True) elif dtype is object: - err_category = NotImplementedError - err_msg = f"{groupby_func} does not implement numeric_only" - if groupby_func.startswith("cum"): - # cum ops already exhibit future behavior - warn_category = None - warn_msg = "" - err_category = TypeError - err_msg = f"{groupby_func} is not supported for object dtype" - elif groupby_func == "skew": - warn_category = None - warn_msg = "" - err_category = TypeError - err_msg = "Series.skew does not allow numeric_only=True with non-numeric" - elif groupby_func == "sem": - warn_category = None - warn_msg = "" - err_category = TypeError - err_msg = "called with numeric_only=True and dtype object" - else: - warn_category = FutureWarning - warn_msg = "This will raise a TypeError" - - with tm.assert_produces_warning(warn_category, match=warn_msg): - with pytest.raises(err_category, match=err_msg): - method(*args, numeric_only=True) + msg = "|".join( + [ + "Cannot use numeric_only=True", + "called with numeric_only=True and dtype object", + "Series.skew does not allow numeric_only=True with non-numeric", + "got an unexpected keyword argument 'numeric_only'", + "is not supported for object dtype", + ] + ) + with pytest.raises(TypeError, match=msg): + method(*args, numeric_only=True) else: result = method(*args, numeric_only=True) expected = method(*args, numeric_only=False) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index c35930ed43607..a7104c2e21049 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -996,12 +996,11 @@ def test_wrap_aggregated_output_multindex(mframe): def aggfun(ser): if ser.name == ("foo", "one"): - raise TypeError + raise TypeError("Test error message") return ser.sum() - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid columns"): - agged2 = df.groupby(keys).aggregate(aggfun) - assert len(agged2.columns) + 1 == len(df.columns) + with pytest.raises(TypeError, match="Test error message"): + df.groupby(keys).aggregate(aggfun) def test_groupby_level_apply(mframe): diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py index 5b0c0f671ae7c..56b9b35f1f688 100644 --- a/pandas/tests/groupby/test_quantile.py +++ b/pandas/tests/groupby/test_quantile.py @@ -1,8 +1,6 @@ import numpy as np import pytest -from pandas._libs import lib - import pandas as pd from pandas import ( DataFrame, @@ -160,10 +158,7 @@ def test_quantile_raises(): df = DataFrame([["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"]) with pytest.raises(TypeError, match="cannot be performed against 'object' dtypes"): - with tm.assert_produces_warning( - FutureWarning, match="Dropping invalid columns" - ): - df.groupby("key").quantile() + df.groupby("key").quantile() def test_quantile_out_of_bounds_q_raises(): @@ -242,16 +237,11 @@ def test_groupby_quantile_nullable_array(values, q): @pytest.mark.parametrize("q", [0.5, [0.0, 0.5, 1.0]]) -@pytest.mark.parametrize("numeric_only", [lib.no_default, True, False]) -def test_groupby_quantile_skips_invalid_dtype(q, numeric_only): +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_groupby_quantile_raises_on_invalid_dtype(q, numeric_only): df = DataFrame({"a": [1], "b": [2.0], "c": ["x"]}) - - if numeric_only is lib.no_default or numeric_only: - warn = FutureWarning if numeric_only is lib.no_default else None - msg = "The default value of numeric_only in DataFrameGroupBy.quantile" - with tm.assert_produces_warning(warn, match=msg): - result = df.groupby("a").quantile(q, numeric_only=numeric_only) - + if numeric_only: + result = df.groupby("a").quantile(q, numeric_only=numeric_only) expected = df.groupby("a")[["b"]].quantile(q) tm.assert_frame_equal(result, expected) else: diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 23005f291970b..8bdbc86d8659c 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -20,7 +20,6 @@ date_range, ) import pandas._testing as tm -from pandas.core.groupby.generic import DataFrameGroupBy from pandas.tests.groupby import get_groupby_method_args @@ -409,31 +408,21 @@ def test_transform_select_columns(df): tm.assert_frame_equal(result, expected) -def test_transform_exclude_nuisance(df): +def test_transform_nuisance_raises(df): # case that goes through _transform_item_by_item df.columns = ["A", "B", "B", "D"] # this also tests orderings in transform between # series/frame to make sure it's consistent - expected = {} grouped = df.groupby("A") gbc = grouped["B"] - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid columns"): - expected["B"] = gbc.transform(lambda x: np.mean(x)) - # squeeze 1-column DataFrame down to Series - expected["B"] = expected["B"]["B"] - - assert isinstance(gbc.obj, DataFrame) - assert isinstance(gbc, DataFrameGroupBy) - - expected["D"] = grouped["D"].transform(np.mean) - expected = DataFrame(expected) - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid columns"): - result = df.groupby("A").transform(lambda x: np.mean(x)) + with pytest.raises(TypeError, match="Could not convert"): + gbc.transform(lambda x: np.mean(x)) - tm.assert_frame_equal(result, expected) + with pytest.raises(TypeError, match="Could not convert"): + df.groupby("A").transform(lambda x: np.mean(x)) def test_transform_function_aliases(df): @@ -519,10 +508,11 @@ def test_groupby_transform_with_int(): } ) with np.errstate(all="ignore"): - with tm.assert_produces_warning( - FutureWarning, match="Dropping invalid columns" - ): - result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + with pytest.raises(TypeError, match="Could not convert"): + df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + result = df.groupby("A")[["B", "C"]].transform( + lambda x: (x - x.mean()) / x.std() + ) expected = DataFrame( {"B": np.nan, "C": Series([-1, 0, 1, -1, 0, 1], dtype="float64")} ) @@ -538,10 +528,11 @@ def test_groupby_transform_with_int(): } ) with np.errstate(all="ignore"): - with tm.assert_produces_warning( - FutureWarning, match="Dropping invalid columns" - ): - result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + with pytest.raises(TypeError, match="Could not convert"): + df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + result = df.groupby("A")[["B", "C"]].transform( + lambda x: (x - x.mean()) / x.std() + ) expected = DataFrame({"B": np.nan, "C": [-1.0, 0.0, 1.0, -1.0, 0.0, 1.0]}) tm.assert_frame_equal(result, expected) @@ -549,10 +540,11 @@ def test_groupby_transform_with_int(): s = Series([2, 3, 4, 10, 5, -1]) df = DataFrame({"A": [1, 1, 1, 2, 2, 2], "B": 1, "C": s, "D": "foo"}) with np.errstate(all="ignore"): - with tm.assert_produces_warning( - FutureWarning, match="Dropping invalid columns" - ): - result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + with pytest.raises(TypeError, match="Could not convert"): + df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) + result = df.groupby("A")[["B", "C"]].transform( + lambda x: (x - x.mean()) / x.std() + ) s1 = s.iloc[0:3] s1 = (s1 - s1.mean()) / s1.std() @@ -562,8 +554,9 @@ def test_groupby_transform_with_int(): tm.assert_frame_equal(result, expected) # int doesn't get downcasted - with tm.assert_produces_warning(FutureWarning, match="Dropping invalid columns"): - result = df.groupby("A").transform(lambda x: x * 2 / 2) + with pytest.raises(TypeError, match="unsupported operand type"): + df.groupby("A").transform(lambda x: x * 2 / 2) + result = df.groupby("A")[["B", "C"]].transform(lambda x: x * 2 / 2) expected = DataFrame({"B": 1.0, "C": [2.0, 3.0, 4.0, 10.0, 5.0, -1.0]}) tm.assert_frame_equal(result, expected) @@ -755,13 +748,15 @@ def test_cython_transform_frame(op, args, targop): expected = expected.sort_index(axis=1) - warn = None if op == "shift" else FutureWarning - msg = "The default value of numeric_only" - with tm.assert_produces_warning(warn, match=msg): - result = gb.transform(op, *args).sort_index(axis=1) + if op != "shift": + with pytest.raises(TypeError, match="datetime64 type does not support"): + gb.transform(op, *args).sort_index(axis=1) + result = gb[expected.columns].transform(op, *args).sort_index(axis=1) tm.assert_frame_equal(result, expected) - with tm.assert_produces_warning(warn, match=msg): - result = getattr(gb, op)(*args).sort_index(axis=1) + if op != "shift": + with pytest.raises(TypeError, match="datetime64 type does not support"): + getattr(gb, op)(*args).sort_index(axis=1) + result = getattr(gb[expected.columns], op)(*args).sort_index(axis=1) tm.assert_frame_equal(result, expected) # individual columns for c in df: diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index e256b957699b7..5f1e0904b8c3c 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -903,18 +903,16 @@ def test_series_downsample_method(method, numeric_only, expected_data): expected_index = date_range("2018-12-31", periods=1, freq="Y") df = Series(["cat_1", "cat_2"], index=index) resampled = df.resample("Y") + kwargs = {} if numeric_only is lib.no_default else {"numeric_only": numeric_only} func = getattr(resampled, method) if numeric_only and numeric_only is not lib.no_default: - with tm.assert_produces_warning( - FutureWarning, match="This will raise a TypeError" - ): - with pytest.raises(NotImplementedError, match="not implement numeric_only"): - func(numeric_only=numeric_only) + with pytest.raises(TypeError, match="Cannot use numeric_only=True"): + func(**kwargs) elif method == "prod": with pytest.raises(TypeError, match="can't multiply sequence by non-int"): - func(numeric_only=numeric_only) + func(**kwargs) else: - result = func(numeric_only=numeric_only) + result = func(**kwargs) expected = Series(expected_data, index=expected_index) tm.assert_series_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/49951
2022-11-29T00:35:14Z
2022-11-29T18:02:18Z
2022-11-29T18:02:18Z
2022-11-29T22:40:17Z
ASV: Fix asv after versioneer change
diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json index 4a0c882640eb6..b1feb1d0af79c 100644 --- a/asv_bench/asv.conf.json +++ b/asv_bench/asv.conf.json @@ -125,6 +125,7 @@ "regression_thresholds": { }, "build_command": - ["python setup.py build -j4", + ["python -m pip install versioneer[toml]", + "python setup.py build -j4", "PIP_NO_BUILD_ISOLATION=false python -mpip wheel --no-deps --no-index -w {build_cache_dir} {build_dir}"], }
- [ ] 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. #49924 broke the local ci workflow. We have to install versioner before building. Adding it to the other dependencies did not work
https://api.github.com/repos/pandas-dev/pandas/pulls/49948
2022-11-28T23:48:01Z
2022-11-29T03:18:39Z
2022-11-29T03:18:39Z
2023-01-21T01:33:39Z
STYLE make black local hook run twice as fast
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml index 7a90e1bec7783..540e9481befd6 100644 --- a/.github/workflows/code-checks.yml +++ b/.github/workflows/code-checks.yml @@ -36,6 +36,8 @@ jobs: - name: Run pre-commit uses: pre-commit/action@v2.0.3 + with: + extra_args: --verbose --all-files docstring_typing_pylint: name: Docstring validation, typing, and pylint @@ -93,7 +95,7 @@ jobs: - name: Typing + pylint uses: pre-commit/action@v2.0.3 with: - extra_args: --hook-stage manual --all-files + extra_args: --verbose --hook-stage manual --all-files if: ${{ steps.build.outcome == 'success' && always() }} - name: Run docstring validation script tests diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cc6875589c691..869dbd2d67e8b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,10 +17,6 @@ repos: entry: python scripts/run_vulture.py pass_filenames: true require_serial: false -- repo: https://github.com/python/black - rev: 22.10.0 - hooks: - - id: black - repo: https://github.com/codespell-project/codespell rev: v2.2.2 hooks: @@ -114,6 +110,16 @@ repos: additional_dependencies: *flake8_dependencies - repo: local hooks: + # NOTE: we make `black` a local hook because if it's installed from + # PyPI (rather than from source) then it'll run twice as fast thanks to mypyc + - id: black + name: black + description: "Black: The uncompromising Python code formatter" + entry: black + language: python + require_serial: true + types_or: [python, pyi] + additional_dependencies: [black==22.10.0] - id: pyright # note: assumes python env is setup and activated name: pyright diff --git a/environment.yml b/environment.yml index 7cd8859825453..e7430d7a4084f 100644 --- a/environment.yml +++ b/environment.yml @@ -85,7 +85,7 @@ dependencies: - cxx-compiler # code checks - - black=22.3.0 + - black=22.10.0 - cpplint - flake8=5.0.4 - flake8-bugbear=22.7.1 # used by flake8, find likely bugs diff --git a/requirements-dev.txt b/requirements-dev.txt index 78dddbe607084..c17915db60ca7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -62,7 +62,7 @@ py moto flask asv -black==22.3.0 +black==22.10.0 cpplint flake8==5.0.4 flake8-bugbear==22.7.1
- [ ] 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. Since https://ichard26.github.io/blog/2022/05/compiling-black-with-mypyc-part-1/ , `black` runs twice as fast when the wheels are installed, compared with when it's built from source in the pre-commit hook --- EDIT: CI timings show 53.84s vs 131.85s, so this is more than a 2x improvement
https://api.github.com/repos/pandas-dev/pandas/pulls/49947
2022-11-28T23:16:05Z
2022-11-29T17:51:16Z
2022-11-29T17:51:16Z
2022-11-29T17:51:26Z
DEPR: enforce not-automatically aligning in DataFrame comparisons
diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index 496db66c78569..4f84e0a562687 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -106,6 +106,10 @@ def time_frame_op_with_series_axis0(self, opname): def time_frame_op_with_series_axis1(self, opname): getattr(operator, opname)(self.df, self.ser) + # exclude comparisons from the params for time_frame_op_with_series_axis1 + # since they do not do alignment so raise + time_frame_op_with_series_axis1.params = [params[0][6:]] + class FrameWithFrameWide: # Many-columns, mixed dtypes diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 1fb9a81e85a83..03ea1aa5b8f9f 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -569,6 +569,7 @@ Removal of prior version deprecations/changes - Enforced deprecation of calling numpy "ufunc"s on :class:`DataFrame` with ``method="outer"``; this now raises ``NotImplementedError`` (:issue:`36955`) - Enforced deprecation disallowing passing ``numeric_only=True`` to :class:`Series` reductions (``rank``, ``any``, ``all``, ...) with non-numeric dtype (:issue:`47500`) - Changed behavior of :meth:`DataFrameGroupBy.apply` and :meth:`SeriesGroupBy.apply` so that ``group_keys`` is respected even if a transformer is detected (:issue:`34998`) +- Comparisons between a :class:`DataFrame` and a :class:`Series` where the frame's columns do not match the series's index raise ``ValueError`` instead of automatically aligning, do ``left, right = left.align(right, axis=1, copy=False)`` before comparing (:issue:`36795`) - Enforced deprecation ``numeric_only=None`` (the default) in DataFrame reductions that would silently drop columns that raised; ``numeric_only`` now defaults to ``False`` (:issue:`41480`) - Changed default of ``numeric_only`` to ``False`` in all DataFrame methods with that argument (:issue:`46096`, :issue:`46906`) - Changed default of ``numeric_only`` to ``False`` in :meth:`Series.rank` (:issue:`47561`) diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index af27ff67599ac..bfedaca093a8e 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -7,7 +7,6 @@ import operator from typing import TYPE_CHECKING -import warnings import numpy as np @@ -18,7 +17,6 @@ Level, ) from pandas.util._decorators import Appender -from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_array_like, @@ -299,13 +297,10 @@ def to_series(right): if not flex: if not left.axes[axis].equals(right.index): - warnings.warn( - "Automatic reindexing on DataFrame vs Series comparisons " - "is deprecated and will raise ValueError in a future version. " - "Do `left, right = left.align(right, axis=1, copy=False)` " - "before e.g. `left == right`", - FutureWarning, - stacklevel=find_stack_level(), + raise ValueError( + "Operands are not aligned. Do " + "`left, right = left.align(right, axis=1, copy=False)` " + "before operating." ) left, right = left.align( diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index bad5335ad2d58..b4f1c5404d178 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -307,43 +307,60 @@ def test_timestamp_compare_series(self, left, right): def test_dt64arr_timestamp_equality(self, box_with_array): # GH#11034 + box = box_with_array ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), NaT]) - ser = tm.box_expected(ser, box_with_array) + ser = tm.box_expected(ser, box) xbox = get_upcast_box(ser, ser, True) result = ser != ser expected = tm.box_expected([False, False, True], xbox) tm.assert_equal(result, expected) - warn = FutureWarning if box_with_array is pd.DataFrame else None - with tm.assert_produces_warning(warn): + if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated + # in GH#46795 enforced 2.0 + with pytest.raises(ValueError, match="not aligned"): + ser != ser[0] + + else: result = ser != ser[0] - expected = tm.box_expected([False, True, True], xbox) - tm.assert_equal(result, expected) + expected = tm.box_expected([False, True, True], xbox) + tm.assert_equal(result, expected) - with tm.assert_produces_warning(warn): + if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated + # in GH#46795 enforced 2.0 + with pytest.raises(ValueError, match="not aligned"): + ser != ser[2] + else: result = ser != ser[2] - expected = tm.box_expected([True, True, True], xbox) - tm.assert_equal(result, expected) + expected = tm.box_expected([True, True, True], xbox) + tm.assert_equal(result, expected) result = ser == ser expected = tm.box_expected([True, True, False], xbox) tm.assert_equal(result, expected) - with tm.assert_produces_warning(warn): + if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated + # in GH#46795 enforced 2.0 + with pytest.raises(ValueError, match="not aligned"): + ser == ser[0] + else: result = ser == ser[0] - expected = tm.box_expected([True, False, False], xbox) - tm.assert_equal(result, expected) + expected = tm.box_expected([True, False, False], xbox) + tm.assert_equal(result, expected) - with tm.assert_produces_warning(warn): + if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated + # in GH#46795 enforced 2.0 + with pytest.raises(ValueError, match="not aligned"): + ser == ser[2] + else: result = ser == ser[2] - expected = tm.box_expected([False, False, False], xbox) - tm.assert_equal(result, expected) + expected = tm.box_expected([False, False, False], xbox) + tm.assert_equal(result, expected) @pytest.mark.parametrize( "datetimelike", diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 545482e6d3dad..8aedac036c2c9 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1164,19 +1164,15 @@ def test_frame_with_zero_len_series_corner_cases(): expected = DataFrame(df.values * np.nan, columns=df.columns) tm.assert_frame_equal(result, expected) - with tm.assert_produces_warning(FutureWarning): - # Automatic alignment for comparisons deprecated - result = df == ser - expected = DataFrame(False, index=df.index, columns=df.columns) - tm.assert_frame_equal(result, expected) + with pytest.raises(ValueError, match="not aligned"): + # Automatic alignment for comparisons deprecated GH#36795, enforced 2.0 + df == ser - # non-float case should not raise on comparison + # non-float case should not raise TypeError on comparison df2 = DataFrame(df.values.view("M8[ns]"), columns=df.columns) - with tm.assert_produces_warning(FutureWarning): + with pytest.raises(ValueError, match="not aligned"): # Automatic alignment for comparisons deprecated - result = df2 == ser - expected = DataFrame(False, index=df.index, columns=df.columns) - tm.assert_frame_equal(result, expected) + df2 == ser def test_zero_len_frame_with_series_corner_cases(): diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index a7551af68bc2b..c39973d7649e8 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -476,9 +476,6 @@ def test_finalize_called_eval_numexpr(): # Binary operations -@pytest.mark.filterwarnings( - "ignore:Automatic reindexing on DataFrame vs Series:FutureWarning" -) @pytest.mark.parametrize("annotate", ["left", "right", "both"]) @pytest.mark.parametrize( "args", @@ -504,6 +501,20 @@ def test_binops(request, args, annotate, all_binary_operators): if annotate in {"left", "both"} and not isinstance(right, int): right.attrs = {"a": 1} + is_cmp = all_binary_operators in [ + operator.eq, + operator.ne, + operator.gt, + operator.ge, + operator.lt, + operator.le, + ] + if is_cmp and isinstance(left, pd.DataFrame) and isinstance(right, pd.Series): + # in 2.0 silent alignment on comparisons was removed xref GH#28759 + left, right = left.align(right, axis=1, copy=False) + elif is_cmp and isinstance(left, pd.Series) and isinstance(right, pd.DataFrame): + right, left = right.align(left, axis=1, copy=False) + result = all_binary_operators(left, right) assert result.attrs == {"a": 1}
- [ ] 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/49946
2022-11-28T22:52:54Z
2022-12-01T22:06:38Z
2022-12-01T22:06:38Z
2022-12-01T22:06:45Z
STYLE pre-commit autoupdate
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cc6875589c691..9a10d48cf3e27 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,11 +28,11 @@ repos: types_or: [python, rst, markdown] additional_dependencies: [tomli] - repo: https://github.com/MarcoGorelli/cython-lint - rev: v0.2.1 + rev: v0.9.1 hooks: - id: cython-lint - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.3.0 + rev: v4.4.0 hooks: - id: debug-statements - id: end-of-file-fixer @@ -51,22 +51,22 @@ repos: exclude: ^pandas/_libs/src/(klib|headers)/ args: [--quiet, '--extensions=c,h', '--headers=h', --recursive, '--filter=-readability/casting,-runtime/int,-build/include_subdir'] - repo: https://github.com/PyCQA/flake8 - rev: 5.0.4 + rev: 6.0.0 hooks: - id: flake8 # Need to patch os.remove rule in pandas-dev-flaker exclude: ^ci/fix_wheels.py additional_dependencies: &flake8_dependencies - - flake8==5.0.4 + - flake8==6.0.0 - flake8-bugbear==22.7.1 - pandas-dev-flaker==0.5.0 - repo: https://github.com/pycqa/pylint - rev: v2.15.5 + rev: v2.15.6 hooks: - id: pylint stages: [manual] - repo: https://github.com/pycqa/pylint - rev: v2.15.5 + rev: v2.15.6 hooks: - id: pylint alias: redefined-outer-name @@ -89,7 +89,7 @@ repos: hooks: - id: isort - repo: https://github.com/asottile/pyupgrade - rev: v3.2.0 + rev: v3.2.2 hooks: - id: pyupgrade args: [--py38-plus] diff --git a/environment.yml b/environment.yml index 7cd8859825453..eae8abd1f4b11 100644 --- a/environment.yml +++ b/environment.yml @@ -87,7 +87,7 @@ dependencies: # code checks - black=22.3.0 - cpplint - - flake8=5.0.4 + - flake8=6.0.0 - flake8-bugbear=22.7.1 # used by flake8, find likely bugs - isort>=5.2.1 # check that imports are in the right order - mypy=0.990 diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index a5b07d46bfeef..92874ef201246 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -1,14 +1,11 @@ # Copyright (c) 2012, Lambda Foundry, Inc. # See LICENSE for the license -from base64 import decode from collections import defaultdict from csv import ( QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC, ) -from errno import ENOENT -import inspect import sys import time import warnings @@ -24,10 +21,7 @@ from pandas.core.arrays import ( ) cimport cython -from cpython.bytes cimport ( - PyBytes_AsString, - PyBytes_FromString, -) +from cpython.bytes cimport PyBytes_AsString from cpython.exc cimport ( PyErr_Fetch, PyErr_Occurred, @@ -631,7 +625,7 @@ cdef class TextReader: cdef: Py_ssize_t i, start, field_count, passed_count, unnamed_count, level char *word - str name, old_name + str name uint64_t hr, data_line = 0 list header = [] set unnamed_cols = set() @@ -939,7 +933,7 @@ cdef class TextReader: object name, na_flist, col_dtype = None bint na_filter = 0 int64_t num_cols - dict result + dict results bint use_nullable_dtypes start = self.parser_start @@ -1461,7 +1455,7 @@ cdef _string_box_utf8(parser_t *parser, int64_t col, bint na_filter, kh_str_starts_t *na_hashset, const char *encoding_errors): cdef: - int error, na_count = 0 + int na_count = 0 Py_ssize_t i, lines coliter_t it const char *word = NULL @@ -1517,7 +1511,7 @@ cdef _categorical_convert(parser_t *parser, int64_t col, "Convert column data into codes, categories" cdef: int na_count = 0 - Py_ssize_t i, size, lines + Py_ssize_t i, lines coliter_t it const char *word = NULL @@ -1525,8 +1519,6 @@ cdef _categorical_convert(parser_t *parser, int64_t col, int64_t[::1] codes int64_t current_category = 0 - char *errors = "strict" - int ret = 0 kh_str_t *table khiter_t k @@ -1972,7 +1964,6 @@ cdef kh_str_starts_t* kset_from_list(list values) except NULL: cdef kh_float64_t* kset_float64_from_list(values) except NULL: # caller takes responsibility for freeing the hash table cdef: - khiter_t k kh_float64_t *table int ret = 0 float64_t val @@ -1983,7 +1974,7 @@ cdef kh_float64_t* kset_float64_from_list(values) except NULL: for value in values: val = float(value) - k = kh_put_float64(table, val, &ret) + kh_put_float64(table, val, &ret) if table.n_buckets <= 128: # See reasoning in kset_from_list diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index b0208f9ca3296..c40712251ae5b 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -28,7 +28,7 @@ from cpython.datetime cimport ( # alias bc `tzinfo` is a kwarg below PyTZInfo_Check, datetime, import_datetime, - time, + time as dt_time, tzinfo as tzinfo_type, ) from cpython.object cimport ( @@ -120,7 +120,7 @@ from pandas._libs.tslibs.tzconversion cimport ( # ---------------------------------------------------------------------- # Constants -_zero_time = time(0, 0) +_zero_time = dt_time(0, 0) _no_input = object() # ---------------------------------------------------------------------- diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py index f17e2a197a82b..6427c68dc76b5 100644 --- a/pandas/tests/frame/indexing/test_getitem.py +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -115,8 +115,8 @@ def test_getitem_dupe_cols(self): iter, Index, set, - lambda l: dict(zip(l, range(len(l)))), - lambda l: dict(zip(l, range(len(l)))).keys(), + lambda keys: dict(zip(keys, range(len(keys)))), + lambda keys: dict(zip(keys, range(len(keys)))).keys(), ], ids=["list", "iter", "Index", "set", "dict", "dict_keys"], ) diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index ccd59172bc741..1a414ebf73abe 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -207,7 +207,7 @@ def test_readjson_chunks_multiple_empty_lines(chunksize): def test_readjson_unicode(monkeypatch): with tm.ensure_clean("test.json") as path: - monkeypatch.setattr("locale.getpreferredencoding", lambda l: "cp949") + monkeypatch.setattr("locale.getpreferredencoding", lambda do_setlocale: "cp949") with open(path, "w", encoding="utf-8") as f: f.write('{"£©µÀÆÖÞßéöÿ":["АБВГДабвгд가"]}') diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index ce71e9e990364..e76f85c0c69d0 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -302,7 +302,7 @@ def test_index_types(setup_path): with catch_warnings(record=True): values = np.random.randn(2) - func = lambda l, r: tm.assert_series_equal(l, r, check_index_type=True) + func = lambda lhs, rhs: tm.assert_series_equal(lhs, rhs, check_index_type=True) with catch_warnings(record=True): ser = Series(values, [0, "y"]) diff --git a/requirements-dev.txt b/requirements-dev.txt index 78dddbe607084..f7d474e2b16dc 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -64,7 +64,7 @@ flask asv black==22.3.0 cpplint -flake8==5.0.4 +flake8==6.0.0 flake8-bugbear==22.7.1 isort>=5.2.1 mypy==0.990
- [ ] 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/49943
2022-11-28T21:32:14Z
2022-11-29T01:34:31Z
2022-11-29T01:34:31Z
2022-11-29T01:34:43Z
PERF: read_html: Reading one HTML file with multiple tables is much slower than loading each table separatly
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index e657a98f6358f..baed1750c0f9b 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -613,6 +613,7 @@ Performance improvements - Performance improvement in :func:`read_stata` with parameter ``index_col`` set to ``None`` (the default). Now the index will be a :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`49745`) - Performance improvement in :func:`merge` when not merging on the index - the new index will now be :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`49478`) - Performance improvement in :meth:`DataFrame.to_dict` and :meth:`Series.to_dict` when using any non-object dtypes (:issue:`46470`) +- Performance improvement in :func:`read_html` when there are multiple tables (:issue:`49929`) .. --------------------------------------------------------------------------- .. _whatsnew_200.bug_fixes: diff --git a/pandas/io/html.py b/pandas/io/html.py index eceff2d2ec1f3..4f6e43a1639a5 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -744,8 +744,8 @@ def _parse_tables(self, doc, match, kwargs): pattern = match.pattern # 1. check all descendants for the given pattern and only search tables - # 2. go up the tree until we find a table - xpath_expr = f"//table//*[re:test(text(), {repr(pattern)})]/ancestor::table" + # GH 49929 + xpath_expr = f"//table[.//text()[re:test(., {repr(pattern)})]]" # if any table attributes were given build an xpath expression to # search for them
- [x] closes #49929 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. ```py # setup from referenced issue In [2]: %timeit combined = pd.read_html(StringIO(combined_html)) 324 ms ± 1.79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- PR In [3]: %timeit combined = pd.read_html(StringIO(combined_html)) # <- main 44.3 s ± 4.28 s per loop (mean ± std. dev. of 7 runs, 1 loop each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/49942
2022-11-28T20:34:33Z
2022-11-29T17:30:36Z
2022-11-29T17:30:36Z
2022-12-13T00:23:20Z
REF: simplify DTI/PI.get_loc
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 5709f94e2ccd5..1b9291a19d32c 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -526,29 +526,35 @@ def _parsed_string_to_bounds(self, reso: Resolution, parsed: dt.datetime): "The index must be timezone aware when indexing " "with a date string with a UTC offset" ) - start = self._maybe_cast_for_get_loc(start) - end = self._maybe_cast_for_get_loc(end) + # The flipped case with parsed.tz is None and self.tz is not None + # is ruled out bc parsed and reso are produced by _parse_with_reso, + # which localizes parsed. return start, end - def _disallow_mismatched_indexing(self, key, one_way: bool = False) -> None: + def _parse_with_reso(self, label: str): + parsed, reso = super()._parse_with_reso(label) + + parsed = Timestamp(parsed) + + if self.tz is not None and parsed.tzinfo is None: + # we special-case timezone-naive strings and timezone-aware + # DatetimeIndex + # https://github.com/pandas-dev/pandas/pull/36148#issuecomment-687883081 + parsed = parsed.tz_localize(self.tz) + + return parsed, reso + + def _disallow_mismatched_indexing(self, key) -> None: """ Check for mismatched-tzawareness indexing and re-raise as KeyError. """ + # we get here with isinstance(key, self._data._recognized_scalars) try: - self._deprecate_mismatched_indexing(key, one_way=one_way) + # GH#36148 + self._data._assert_tzawareness_compat(key) except TypeError as err: raise KeyError(key) from err - def _deprecate_mismatched_indexing(self, key, one_way: bool = False) -> None: - # GH#36148 - # we get here with isinstance(key, self._data._recognized_scalars) - if self.tz is not None and one_way: - # we special-case timezone-naive strings and timezone-aware - # DatetimeIndex - return - - self._data._assert_tzawareness_compat(key) - def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label @@ -566,7 +572,7 @@ def get_loc(self, key, method=None, tolerance=None): if isinstance(key, self._data._recognized_scalars): # needed to localize naive datetimes self._disallow_mismatched_indexing(key) - key = self._maybe_cast_for_get_loc(key) + key = Timestamp(key) elif isinstance(key, str): @@ -574,7 +580,7 @@ def get_loc(self, key, method=None, tolerance=None): parsed, reso = self._parse_with_reso(key) except ValueError as err: raise KeyError(key) from err - self._disallow_mismatched_indexing(parsed, one_way=True) + self._disallow_mismatched_indexing(parsed) if self._can_partial_date_slice(reso): try: @@ -583,7 +589,7 @@ def get_loc(self, key, method=None, tolerance=None): if method is None: raise KeyError(key) from err - key = self._maybe_cast_for_get_loc(key) + key = parsed elif isinstance(key, dt.timedelta): # GH#20464 @@ -607,24 +613,6 @@ def get_loc(self, key, method=None, tolerance=None): except KeyError as err: raise KeyError(orig_key) from err - def _maybe_cast_for_get_loc(self, key) -> Timestamp: - # needed to localize naive datetimes or dates (GH 35690) - try: - key = Timestamp(key) - except ValueError as err: - # FIXME(dateutil#1180): we get here because parse_with_reso - # doesn't raise on "t2m" - if not isinstance(key, str): - # Not expected to be reached, but check to be sure - raise # pragma: no cover - raise KeyError(key) from err - - if key.tzinfo is None: - key = key.tz_localize(self.tz) - else: - key = key.tz_convert(self.tz) - return key - @doc(DatetimeTimedeltaMixin._maybe_cast_slice_bound) def _maybe_cast_slice_bound(self, label, side: str): @@ -635,8 +623,8 @@ def _maybe_cast_slice_bound(self, label, side: str): label = Timestamp(label).to_pydatetime() label = super()._maybe_cast_slice_bound(label, side) - self._deprecate_mismatched_indexing(label) - return self._maybe_cast_for_get_loc(label) + self._data._assert_tzawareness_compat(label) + return Timestamp(label) def slice_indexer(self, start=None, end=None, step=None): """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index e8a734864a9c8..ef47cb9bf1070 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -420,18 +420,14 @@ def get_loc(self, key, method=None, tolerance=None): if reso == self._resolution_obj: # the reso < self._resolution_obj case goes # through _get_string_slice - key = self._cast_partial_indexing_scalar(key) - loc = self.get_loc(key, method=method, tolerance=tolerance) - # Recursing instead of falling through matters for the exception - # message in test_get_loc3 (though not clear if that really matters) - return loc + key = self._cast_partial_indexing_scalar(parsed) elif method is None: raise KeyError(key) else: key = self._cast_partial_indexing_scalar(parsed) elif isinstance(key, Period): - key = self._maybe_cast_for_get_loc(key) + self._disallow_mismatched_indexing(key) elif isinstance(key, datetime): key = self._cast_partial_indexing_scalar(key) @@ -445,8 +441,7 @@ def get_loc(self, key, method=None, tolerance=None): except KeyError as err: raise KeyError(orig_key) from err - def _maybe_cast_for_get_loc(self, key: Period) -> Period: - # name is a misnomer, chosen for compat with DatetimeIndex + def _disallow_mismatched_indexing(self, key: Period) -> None: sfreq = self.freq kfreq = key.freq if not ( @@ -460,15 +455,14 @@ def _maybe_cast_for_get_loc(self, key: Period) -> Period: # checking these two attributes is sufficient to check equality, # and much more performant than `self.freq == key.freq` raise KeyError(key) - return key - def _cast_partial_indexing_scalar(self, label): + def _cast_partial_indexing_scalar(self, label: datetime) -> Period: try: - key = Period(label, freq=self.freq) + period = Period(label, freq=self.freq) except ValueError as err: # we cannot construct the Period raise KeyError(label) from err - return key + return period @doc(DatetimeIndexOpsMixin._maybe_cast_slice_bound) def _maybe_cast_slice_bound(self, label, side: str): diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index fcc7fa083691e..58b77ce50293d 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -373,7 +373,7 @@ def test_get_loc3(self): msg = "Input has different freq=None from PeriodArray\\(freq=D\\)" with pytest.raises(ValueError, match=msg): idx.get_loc("2000-01-10", method="nearest", tolerance="1 hour") - with pytest.raises(KeyError, match=r"^Period\('2000-01-10', 'D'\)$"): + with pytest.raises(KeyError, match=r"^'2000-01-10'$"): idx.get_loc("2000-01-10", method="nearest", tolerance="1 day") with pytest.raises( ValueError, match="list-like tolerance size must match target index size"
- [ ] 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/49941
2022-11-28T18:41:25Z
2022-11-28T22:58:14Z
2022-11-28T22:58:14Z
2022-11-29T00:29:12Z
STYLE #49656: fixed redefined-outer-name linting issue to format.py
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cc6875589c691..97a9748de8513 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -79,8 +79,6 @@ repos: |^pandas/util/_test_decorators\.py # keep excluded |^pandas/_version\.py # keep excluded |^pandas/conftest\.py # keep excluded - |^pandas/core/tools/datetimes\.py - |^pandas/io/formats/format\.py |^pandas/core/generic\.py args: [--disable=all, --enable=redefined-outer-name] stages: [manual] diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 5709f94e2ccd5..9f17bf6858d30 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -384,7 +384,7 @@ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: def _formatter_func(self): from pandas.io.formats.format import get_format_datetime64 - formatter = get_format_datetime64(is_dates_only=self._is_dates_only) + formatter = get_format_datetime64(is_dates_only_=self._is_dates_only) return lambda x: f"'{formatter(x)}'" # -------------------------------------------------------------------- diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index cdc21f04da43a..61c12f5011886 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -9,7 +9,7 @@ QUOTE_NONE, QUOTE_NONNUMERIC, ) -import decimal +from decimal import Decimal from functools import partial from io import StringIO import math @@ -106,11 +106,7 @@ check_parent_directory, stringify_path, ) -from pandas.io.formats.printing import ( - adjoin, - justify, - pprint_thing, -) +from pandas.io.formats import printing if TYPE_CHECKING: from pandas import ( @@ -339,7 +335,7 @@ def _get_footer(self) -> str: if footer: footer += ", " - series_name = pprint_thing(name, escape_chars=("\t", "\r", "\n")) + series_name = printing.pprint_thing(name, escape_chars=("\t", "\r", "\n")) footer += f"Name: {series_name}" if self.length is True or ( @@ -354,7 +350,7 @@ def _get_footer(self) -> str: if dtype_name: if footer: footer += ", " - footer += f"dtype: {pprint_thing(dtype_name)}" + footer += f"dtype: {printing.pprint_thing(dtype_name)}" # level infos are added to the end and in a new line, like it is done # for Categoricals @@ -433,10 +429,12 @@ def len(self, text: str) -> int: return len(text) def justify(self, texts: Any, max_len: int, mode: str = "right") -> list[str]: - return justify(texts, max_len, mode=mode) + return printing.justify(texts, max_len, mode=mode) def adjoin(self, space: int, *lists, **kwargs) -> str: - return adjoin(space, *lists, strlen=self.len, justfunc=self.justify, **kwargs) + return printing.adjoin( + space, *lists, strlen=self.len, justfunc=self.justify, **kwargs + ) class EastAsianTextAdjustment(TextAdjustment): @@ -1375,7 +1373,7 @@ def _format_strings(self) -> list[str]: else: quote_strings = self.quoting is not None and self.quoting != QUOTE_NONE formatter = partial( - pprint_thing, + printing.pprint_thing, escape_chars=("\t", "\r", "\n"), quote_strings=quote_strings, ) @@ -1794,12 +1792,12 @@ def _format_datetime64_dateonly( def get_format_datetime64( - is_dates_only: bool, nat_rep: str = "NaT", date_format: str | None = None + is_dates_only_: bool, nat_rep: str = "NaT", date_format: str | None = None ) -> Callable: """Return a formatter callable taking a datetime64 as input and providing a string as output""" - if is_dates_only: + if is_dates_only_: return lambda x: _format_datetime64_dateonly( x, nat_rep=nat_rep, date_format=date_format ) @@ -2071,12 +2069,12 @@ def __call__(self, num: float) -> str: @return: engineering formatted string """ - dnum = decimal.Decimal(str(num)) + dnum = Decimal(str(num)) - if decimal.Decimal.is_nan(dnum): + if Decimal.is_nan(dnum): return "NaN" - if decimal.Decimal.is_infinite(dnum): + if Decimal.is_infinite(dnum): return "inf" sign = 1 @@ -2086,9 +2084,9 @@ def __call__(self, num: float) -> str: dnum = -dnum if dnum != 0: - pow10 = decimal.Decimal(int(math.floor(dnum.log10() / 3) * 3)) + pow10 = Decimal(int(math.floor(dnum.log10() / 3) * 3)) else: - pow10 = decimal.Decimal(0) + pow10 = Decimal(0) pow10 = pow10.min(max(self.ENG_PREFIXES.keys())) pow10 = pow10.max(min(self.ENG_PREFIXES.keys()))
Fixed redefined-outer-name issue in: - pandas/io/formats/format.py redefined-outer-name t issues raised for: - justify function (import from pandas.io.formats.printing) - decimal (changed to from decimal import Decimal) - is_dates_only parameter conflict with function name - updated get_format_datetime64 function with renamed parameter - passed related tests in pytest pandas - running: pylint --disable=all --enable=redefined-outer-name pandas/io/ -- > Results in 10.00/10 rating
https://api.github.com/repos/pandas-dev/pandas/pulls/49937
2022-11-28T04:28:25Z
2022-11-29T19:06:21Z
2022-11-29T19:06:21Z
2022-11-29T19:06:28Z
BUG: avoid segfault in tz_localize with ZoneInfo
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 99855b36e8676..afdf6d3d9b001 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -233,6 +233,7 @@ timedelta-like} int64_t shift_delta = 0 ndarray[int64_t] result_a, result_b, dst_hours int64_t[::1] result + bint is_zi = False bint infer_dst = False, is_dst = False, fill = False bint shift_forward = False, shift_backward = False bint fill_nonexist = False @@ -304,6 +305,7 @@ timedelta-like} # Determine whether each date lies left of the DST transition (store in # result_a) or right of the DST transition (store in result_b) if is_zoneinfo(tz): + is_zi = True result_a, result_b =_get_utc_bounds_zoneinfo( vals, tz, creso=creso ) @@ -385,6 +387,11 @@ timedelta-like} # nonexistent times new_local = val - remaining_mins - 1 + if is_zi: + raise NotImplementedError( + "nonexistent shifting is not implemented with ZoneInfo tzinfos" + ) + delta_idx = bisect_right_i8(info.tdata, new_local, info.ntrans) delta_idx = delta_idx - delta_idx_offset diff --git a/pandas/conftest.py b/pandas/conftest.py index 30ff8306a03b2..6959fe6a7fb66 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1895,3 +1895,16 @@ def using_copy_on_write() -> bool: Fixture to check if Copy-on-Write is enabled. """ return pd.options.mode.copy_on_write and pd.options.mode.data_manager == "block" + + +warsaws = ["Europe/Warsaw", "dateutil/Europe/Warsaw"] +if zoneinfo is not None: + warsaws.append(zoneinfo.ZoneInfo("Europe/Warsaw")) + + +@pytest.fixture(params=warsaws) +def warsaw(request): + """ + tzinfo for Europe/Warsaw using pytz, dateutil, or zoneinfo. + """ + return request.param diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index d67bc8a132c0c..f8e826d2ac053 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -872,10 +872,16 @@ def test_constructor_with_ambiguous_keyword_arg(self): result = date_range(end=end, periods=2, ambiguous=False) tm.assert_index_equal(result, expected) - def test_constructor_with_nonexistent_keyword_arg(self): + def test_constructor_with_nonexistent_keyword_arg(self, warsaw, request): # GH 35297 + if type(warsaw).__name__ == "ZoneInfo": + mark = pytest.mark.xfail( + reason="nonexistent-shift not yet implemented for ZoneInfo", + raises=NotImplementedError, + ) + request.node.add_marker(mark) - timezone = "Europe/Warsaw" + timezone = warsaw # nonexistent keyword in start start = Timestamp("2015-03-29 02:30:00").tz_localize( diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 8d651efe336e8..877a7dca42620 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -649,30 +649,6 @@ def test_dti_tz_localize_bdate_range(self): localized = dr.tz_localize(pytz.utc) tm.assert_index_equal(dr_utc, localized) - @pytest.mark.parametrize("tz", ["Europe/Warsaw", "dateutil/Europe/Warsaw"]) - @pytest.mark.parametrize( - "method, exp", [["NaT", pd.NaT], ["raise", None], ["foo", "invalid"]] - ) - def test_dti_tz_localize_nonexistent(self, tz, method, exp): - # GH 8917 - n = 60 - dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min") - if method == "raise": - with pytest.raises(pytz.NonExistentTimeError, match="2015-03-29 02:00:00"): - dti.tz_localize(tz, nonexistent=method) - elif exp == "invalid": - msg = ( - "The nonexistent argument must be one of " - "'raise', 'NaT', 'shift_forward', 'shift_backward' " - "or a timedelta object" - ) - with pytest.raises(ValueError, match=msg): - dti.tz_localize(tz, nonexistent=method) - else: - result = dti.tz_localize(tz, nonexistent=method) - expected = DatetimeIndex([exp] * n, tz=tz) - tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( "start_ts, tz, end_ts, shift", [ @@ -730,10 +706,9 @@ def test_dti_tz_localize_nonexistent_shift( tm.assert_index_equal(result, expected) @pytest.mark.parametrize("offset", [-1, 1]) - @pytest.mark.parametrize("tz_type", ["", "dateutil/"]) - def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, tz_type): + def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, warsaw): # GH 8917 - tz = tz_type + "Europe/Warsaw" + tz = warsaw dti = DatetimeIndex([Timestamp("2015-03-29 02:20:00")]) msg = "The provided timedelta will relocalize on a nonexistent time" with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py index 3e02ab208c502..3ebffaad23910 100644 --- a/pandas/tests/scalar/timestamp/test_timezones.py +++ b/pandas/tests/scalar/timestamp/test_timezones.py @@ -141,9 +141,9 @@ def test_tz_localize_ambiguous_raise(self): with pytest.raises(AmbiguousTimeError, match=msg): ts.tz_localize("US/Pacific", ambiguous="raise") - def test_tz_localize_nonexistent_invalid_arg(self): + def test_tz_localize_nonexistent_invalid_arg(self, warsaw): # GH 22644 - tz = "Europe/Warsaw" + tz = warsaw ts = Timestamp("2015-03-29 02:00:00") msg = ( "The nonexistent argument must be one of 'raise', 'NaT', " @@ -291,27 +291,26 @@ def test_timestamp_tz_localize_nonexistent_shift( assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value @pytest.mark.parametrize("offset", [-1, 1]) - @pytest.mark.parametrize("tz_type", ["", "dateutil/"]) - def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset, tz_type): + def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset, warsaw): # GH 8917, 24466 - tz = tz_type + "Europe/Warsaw" + tz = warsaw ts = Timestamp("2015-03-29 02:20:00") msg = "The provided timedelta will relocalize on a nonexistent time" with pytest.raises(ValueError, match=msg): ts.tz_localize(tz, nonexistent=timedelta(seconds=offset)) - @pytest.mark.parametrize("tz", ["Europe/Warsaw", "dateutil/Europe/Warsaw"]) @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) - def test_timestamp_tz_localize_nonexistent_NaT(self, tz, unit): + def test_timestamp_tz_localize_nonexistent_NaT(self, warsaw, unit): # GH 8917 + tz = warsaw ts = Timestamp("2015-03-29 02:20:00").as_unit(unit) result = ts.tz_localize(tz, nonexistent="NaT") assert result is NaT - @pytest.mark.parametrize("tz", ["Europe/Warsaw", "dateutil/Europe/Warsaw"]) @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) - def test_timestamp_tz_localize_nonexistent_raise(self, tz, unit): + def test_timestamp_tz_localize_nonexistent_raise(self, warsaw, unit): # GH 8917 + tz = warsaw ts = Timestamp("2015-03-29 02:20:00").as_unit(unit) msg = "2015-03-29 02:20:00" with pytest.raises(pytz.NonExistentTimeError, match=msg): diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index b8a1ea55db4fe..a9e28bfeeb76b 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -58,7 +58,6 @@ def test_series_tz_localize_matching_index(self): ) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("tz", ["Europe/Warsaw", "dateutil/Europe/Warsaw"]) @pytest.mark.parametrize( "method, exp", [ @@ -68,8 +67,9 @@ def test_series_tz_localize_matching_index(self): ["foo", "invalid"], ], ) - def test_tz_localize_nonexistent(self, tz, method, exp): + def test_tz_localize_nonexistent(self, warsaw, method, exp): # GH 8917 + tz = warsaw n = 60 dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min") ser = Series(1, index=dti) @@ -85,13 +85,27 @@ def test_tz_localize_nonexistent(self, tz, method, exp): df.tz_localize(tz, nonexistent=method) elif exp == "invalid": - with pytest.raises(ValueError, match="argument must be one of"): + msg = ( + "The nonexistent argument must be one of " + "'raise', 'NaT', 'shift_forward', 'shift_backward' " + "or a timedelta object" + ) + with pytest.raises(ValueError, match=msg): dti.tz_localize(tz, nonexistent=method) - with pytest.raises(ValueError, match="argument must be one of"): + with pytest.raises(ValueError, match=msg): ser.tz_localize(tz, nonexistent=method) - with pytest.raises(ValueError, match="argument must be one of"): + with pytest.raises(ValueError, match=msg): df.tz_localize(tz, nonexistent=method) + elif method == "shift_forward" and type(tz).__name__ == "ZoneInfo": + msg = "nonexistent shifting is not implemented with ZoneInfo tzinfos" + with pytest.raises(NotImplementedError, match=msg): + ser.tz_localize(tz, nonexistent=method) + with pytest.raises(NotImplementedError, match=msg): + df.tz_localize(tz, nonexistent=method) + with pytest.raises(NotImplementedError, match=msg): + dti.tz_localize(tz, nonexistent=method) + else: result = ser.tz_localize(tz, nonexistent=method) expected = Series(1, index=DatetimeIndex([exp] * n, tz=tz)) @@ -101,6 +115,9 @@ def test_tz_localize_nonexistent(self, tz, method, exp): expected = expected.to_frame() tm.assert_frame_equal(result, expected) + res_index = dti.tz_localize(tz, nonexistent=method) + tm.assert_index_equal(res_index, expected.index) + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_series_tz_localize_empty(self, tzstr): # GH#2248
- [ ] 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/49936
2022-11-27T22:46:37Z
2022-11-28T18:17:46Z
2022-11-28T18:17:45Z
2022-11-28T18:30:22Z
CI_check_correctness_notebooks
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml index 66bc7cd917b31..7a90e1bec7783 100644 --- a/.github/workflows/code-checks.yml +++ b/.github/workflows/code-checks.yml @@ -79,6 +79,10 @@ jobs: run: ci/code_checks.sh docstrings if: ${{ steps.build.outcome == 'success' && always() }} + - name: Run check of documentation notebooks + run: ci/code_checks.sh notebooks + if: ${{ steps.build.outcome == 'success' && always() }} + - name: Use existing environment for type checking run: | echo $PATH >> $GITHUB_PATH diff --git a/ci/code_checks.sh b/ci/code_checks.sh index c6067faf92d37..3c1362b1ac83e 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -12,9 +12,10 @@ # $ ./ci/code_checks.sh doctests # run doctests # $ ./ci/code_checks.sh docstrings # validate docstring errors # $ ./ci/code_checks.sh single-docs # check single-page docs build warning-free +# $ ./ci/code_checks.sh notebooks # check execution of documentation notebooks -[[ -z "$1" || "$1" == "code" || "$1" == "doctests" || "$1" == "docstrings" || "$1" == "single-docs" ]] || \ - { echo "Unknown command $1. Usage: $0 [code|doctests|docstrings]"; exit 9999; } +[[ -z "$1" || "$1" == "code" || "$1" == "doctests" || "$1" == "docstrings" || "$1" == "single-docs" || "$1" == "notebooks" ]] || \ + { echo "Unknown command $1. Usage: $0 [code|doctests|docstrings|single-docs|notebooks]"; exit 9999; } BASE_DIR="$(dirname $0)/.." RET=0 @@ -84,6 +85,15 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then fi +### DOCUMENTATION NOTEBOOKS ### +if [[ -z "$CHECK" || "$CHECK" == "notebooks" ]]; then + + MSG='Notebooks' ; echo $MSG + jupyter nbconvert --execute $(find doc/source -name '*.ipynb') --to notebook + RET=$(($RET + $?)) ; echo $MSG "DONE" + +fi + ### SINGLE-PAGE DOCS ### if [[ -z "$CHECK" || "$CHECK" == "single-docs" ]]; then python doc/make.py --warnings-are-errors --single pandas.Series.value_counts
This PR is related to the PR #49874. Creating new PR, that checks correctness notebooks, as was discussed with @MarcoGorelli . - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). CI didn't fail when documentation notebook executed with an error. I added new notebooks section in `ci/code_checks.sh` to check if the notebook execution passes.
https://api.github.com/repos/pandas-dev/pandas/pulls/49935
2022-11-27T22:29:57Z
2022-11-28T17:45:03Z
2022-11-28T17:45:03Z
2022-11-28T17:45:14Z
Bug: Incorrect IntervalIndex.is_overlapping
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index d8609737b8c7a..451cba732ff60 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -698,7 +698,7 @@ Strings Interval ^^^^^^^^ -- +- Bug in :meth:`IntervalIndex.is_overlapping` incorrect output if interval has duplicate left boundaries (:issue:`49581`) - Indexing diff --git a/pandas/_libs/intervaltree.pxi.in b/pandas/_libs/intervaltree.pxi.in index e7a310513d2fa..0d7c96a6f2f2b 100644 --- a/pandas/_libs/intervaltree.pxi.in +++ b/pandas/_libs/intervaltree.pxi.in @@ -81,7 +81,8 @@ cdef class IntervalTree(IntervalMixin): """How to sort the left labels; this is used for binary search """ if self._left_sorter is None: - self._left_sorter = np.argsort(self.left) + values = [self.right, self.left] + self._left_sorter = np.lexsort(values) return self._left_sorter @property diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index c8d7470032e5f..98c21fad1f8c2 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -791,6 +791,13 @@ def test_is_overlapping(self, start, shift, na_value, closed): result = index.is_overlapping assert result is expected + # intervals with duplicate left values + a = [10, 15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85] + b = [15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90] + index = IntervalIndex.from_arrays(a, b, closed="right") + result = index.is_overlapping + assert result is False + @pytest.mark.parametrize( "tuples", [
- [x] closes #49581 - [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/49933
2022-11-27T20:58:42Z
2022-12-05T20:07:59Z
2022-12-05T20:07:59Z
2022-12-07T00:17:48Z
CLN: clean core.construction._extract_index
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 8e186b1f4a034..563011abe2c41 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -580,63 +580,59 @@ def _extract_index(data) -> Index: """ Try to infer an Index from the passed data, raise ValueError on failure. """ - index = None + index: Index if len(data) == 0: - index = Index([]) - else: - raw_lengths = [] - indexes: list[list[Hashable] | Index] = [] - - have_raw_arrays = False - have_series = False - have_dicts = False - - for val in data: - if isinstance(val, ABCSeries): - have_series = True - indexes.append(val.index) - elif isinstance(val, dict): - have_dicts = True - indexes.append(list(val.keys())) - elif is_list_like(val) and getattr(val, "ndim", 1) == 1: - have_raw_arrays = True - raw_lengths.append(len(val)) - elif isinstance(val, np.ndarray) and val.ndim > 1: - raise ValueError("Per-column arrays must each be 1-dimensional") - - if not indexes and not raw_lengths: - raise ValueError("If using all scalar values, you must pass an index") + return Index([]) - if have_series: - index = union_indexes(indexes) - elif have_dicts: - index = union_indexes(indexes, sort=False) + raw_lengths = [] + indexes: list[list[Hashable] | Index] = [] - if have_raw_arrays: - lengths = list(set(raw_lengths)) - if len(lengths) > 1: - raise ValueError("All arrays must be of the same length") + have_raw_arrays = False + have_series = False + have_dicts = False - if have_dicts: - raise ValueError( - "Mixing dicts with non-Series may lead to ambiguous ordering." - ) + for val in data: + if isinstance(val, ABCSeries): + have_series = True + indexes.append(val.index) + elif isinstance(val, dict): + have_dicts = True + indexes.append(list(val.keys())) + elif is_list_like(val) and getattr(val, "ndim", 1) == 1: + have_raw_arrays = True + raw_lengths.append(len(val)) + elif isinstance(val, np.ndarray) and val.ndim > 1: + raise ValueError("Per-column arrays must each be 1-dimensional") + + if not indexes and not raw_lengths: + raise ValueError("If using all scalar values, you must pass an index") + + if have_series: + index = union_indexes(indexes) + elif have_dicts: + index = union_indexes(indexes, sort=False) + + if have_raw_arrays: + lengths = list(set(raw_lengths)) + if len(lengths) > 1: + raise ValueError("All arrays must be of the same length") + + if have_dicts: + raise ValueError( + "Mixing dicts with non-Series may lead to ambiguous ordering." + ) - if have_series: - assert index is not None # for mypy - if lengths[0] != len(index): - msg = ( - f"array length {lengths[0]} does not match index " - f"length {len(index)}" - ) - raise ValueError(msg) - else: - index = default_index(lengths[0]) + if have_series: + if lengths[0] != len(index): + msg = ( + f"array length {lengths[0]} does not match index " + f"length {len(index)}" + ) + raise ValueError(msg) + else: + index = default_index(lengths[0]) - # error: Argument 1 to "ensure_index" has incompatible type "Optional[Index]"; - # expected "Union[Union[Union[ExtensionArray, ndarray], Index, Series], - # Sequence[Any]]" - return ensure_index(index) # type: ignore[arg-type] + return ensure_index(index) def reorder_arrays(
Return early in the case of len(data) == 0, thereby avoiding needing a long `else` clause. Also clean type hints. EDIT: The PR looks a bit messy at first sight, but it's mostly just dedenting stuff. Checking "Hide whitespace" makes the PR much clearer, as suggested by @MarcoGorelli in #49921.
https://api.github.com/repos/pandas-dev/pandas/pulls/49930
2022-11-27T18:16:01Z
2022-11-28T08:57:27Z
2022-11-28T08:57:27Z
2022-11-28T09:12:31Z
Backport PR #49908 on branch 1.5.x ( BUG: SeriesGroupBy.apply sets name attribute if result is DataFrame)
diff --git a/doc/source/whatsnew/v1.5.3.rst b/doc/source/whatsnew/v1.5.3.rst index e7428956c50b5..e0bcd81805cc1 100644 --- a/doc/source/whatsnew/v1.5.3.rst +++ b/doc/source/whatsnew/v1.5.3.rst @@ -16,6 +16,7 @@ Fixed regressions - Fixed performance regression in :meth:`Series.isin` when ``values`` is empty (:issue:`49839`) - Fixed regression in :meth:`DataFrameGroupBy.transform` when used with ``as_index=False`` (:issue:`49834`) - Enforced reversion of ``color`` as an alias for ``c`` and ``size`` as an alias for ``s`` in function :meth:`DataFrame.plot.scatter` (:issue:`49732`) +- Fixed regression in :meth:`SeriesGroupBy.apply` setting a ``name`` attribute on the result if the result was a :class:`DataFrame` (:issue:`49907`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 97d332394e045..7e6e138fa8fe6 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -411,7 +411,8 @@ def _wrap_applied_output( not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) - result.name = self.obj.name + if isinstance(result, Series): + result.name = self.obj.name return result else: # GH #6265 #24880 diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 47ea6a99ffea9..dfd62394c840e 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -335,6 +335,7 @@ def f(piece): result = grouped.apply(f) assert isinstance(result, DataFrame) + assert not hasattr(result, "name") # GH49907 tm.assert_index_equal(result.index, ts.index)
Backport PR #49908: BUG: SeriesGroupBy.apply sets name attribute if result is DataFrame
https://api.github.com/repos/pandas-dev/pandas/pulls/49928
2022-11-27T16:05:53Z
2022-11-27T19:05:23Z
2022-11-27T19:05:23Z
2022-11-27T19:05:24Z
TST: added test for pd.where overflow error GH31687
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 501822f856a63..2a283f719ec0d 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -1017,3 +1017,15 @@ def test_where_producing_ea_cond_for_np_dtype(): {"a": Series([pd.NA, pd.NA, 2], dtype="Int64"), "b": [np.nan, 2, 3]} ) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "replacement", [0.001, True, "snake", None, datetime(2022, 5, 4)] +) +def test_where_int_overflow(replacement): + # GH 31687 + df = DataFrame([[1.0, 2e25, "nine"], [np.nan, 0.1, None]]) + result = df.where(pd.notnull(df), replacement) + expected = DataFrame([[1.0, 2e25, "nine"], [replacement, 0.1, replacement]]) + + tm.assert_frame_equal(result, expected)
Added a test for pd.where to /indexing/test_where.py - [x] closes #31687 - [x] tests added / passed - [x] passes all pre-commit code checks - [ ] 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/49926
2022-11-27T06:46:26Z
2022-11-28T09:08:18Z
2022-11-28T09:08:18Z
2022-11-29T01:14:06Z
BLD: use nonvendor versioneer
diff --git a/.github/workflows/32-bit-linux.yml b/.github/workflows/32-bit-linux.yml index cf8a0fe0da91c..806742c99abac 100644 --- a/.github/workflows/32-bit-linux.yml +++ b/.github/workflows/32-bit-linux.yml @@ -38,7 +38,8 @@ jobs: /opt/python/cp38-cp38/bin/python -m venv ~/virtualenvs/pandas-dev && \ . ~/virtualenvs/pandas-dev/bin/activate && \ python -m pip install --no-deps -U pip wheel 'setuptools<60.0.0' && \ - pip install cython numpy python-dateutil pytz pytest pytest-xdist pytest-asyncio>=0.17 hypothesis && \ + python -m pip install versioneer[toml] && \ + python -m pip install cython numpy python-dateutil pytz pytest pytest-xdist pytest-asyncio>=0.17 hypothesis && \ python setup.py build_ext -q -j1 && \ python -m pip install --no-build-isolation --no-use-pep517 -e . && \ python -m pip list && \ diff --git a/.github/workflows/package-checks.yml b/.github/workflows/package-checks.yml index 87f40270d8774..08fc3fe4c50a4 100644 --- a/.github/workflows/package-checks.yml +++ b/.github/workflows/package-checks.yml @@ -43,6 +43,7 @@ jobs: - name: Install required dependencies run: | python -m pip install --upgrade pip setuptools wheel python-dateutil pytz numpy cython + python -m pip install versioneer[toml] shell: bash -el {0} - name: Pip install with extra diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 7c4b36dab109d..88f3d16a73a1a 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -75,6 +75,7 @@ jobs: python -m pip install --upgrade pip setuptools wheel python -m pip install -i https://pypi.anaconda.org/scipy-wheels-nightly/simple numpy python -m pip install git+https://github.com/nedbat/coveragepy.git + python -m pip install versioneer[toml] python -m pip install python-dateutil pytz cython hypothesis==6.52.1 pytest>=6.2.5 pytest-xdist pytest-cov pytest-asyncio>=0.17 python -m pip list diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml index 9957fc72e9f51..c9ac218bff935 100644 --- a/.github/workflows/sdist.yml +++ b/.github/workflows/sdist.yml @@ -47,6 +47,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip setuptools wheel + python -m pip install versioneer[toml] # GH 39416 pip install numpy diff --git a/ci/deps/actions-310-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml index ef20c2aa889b9..44acae877bdf8 100644 --- a/ci/deps/actions-310-numpydev.yaml +++ b/ci/deps/actions-310-numpydev.yaml @@ -4,7 +4,10 @@ channels: dependencies: - python=3.10 - # tools + # build dependencies + - versioneer[toml] + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index 9ebc305a0cb0c..1f6f73f3c963f 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -4,8 +4,11 @@ channels: dependencies: - python=3.10 - # test dependencies + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml index b167d992a7c1a..1c59b9db9b1fa 100644 --- a/ci/deps/actions-38-downstream_compat.yaml +++ b/ci/deps/actions-38-downstream_compat.yaml @@ -5,8 +5,11 @@ channels: dependencies: - python=3.8 - # test dependencies + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml index 8e0ccd77b19a6..512aa13c6899a 100644 --- a/ci/deps/actions-38-minimum_versions.yaml +++ b/ci/deps/actions-38-minimum_versions.yaml @@ -6,8 +6,11 @@ channels: dependencies: - python=3.8.0 - # test dependencies + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml index 825b8aeebfc2f..48b9d18771afb 100644 --- a/ci/deps/actions-38.yaml +++ b/ci/deps/actions-38.yaml @@ -4,8 +4,11 @@ channels: dependencies: - python=3.8 - # test dependencies + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index 1ee96878dbe34..59191ad107d12 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -4,8 +4,11 @@ channels: dependencies: - python=3.9 - # test dependencies + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/ci/deps/actions-pypy-38.yaml b/ci/deps/actions-pypy-38.yaml index e06b992acc191..17d39a4c53ac3 100644 --- a/ci/deps/actions-pypy-38.yaml +++ b/ci/deps/actions-pypy-38.yaml @@ -7,8 +7,11 @@ dependencies: # with base pandas has been dealt with - python=3.8[build=*_pypy] # TODO: use this once pypy3.8 is available - # tools + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-asyncio diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml index ae4a82d016131..63547d3521489 100644 --- a/ci/deps/circle-38-arm64.yaml +++ b/ci/deps/circle-38-arm64.yaml @@ -4,8 +4,11 @@ channels: dependencies: - python=3.8 - # test dependencies + # build dependencies + - versioneer[toml] - cython>=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/environment.yml b/environment.yml index be7a57d615ed0..7cd8859825453 100644 --- a/environment.yml +++ b/environment.yml @@ -6,8 +6,11 @@ dependencies: - python=3.8 - pip - # test dependencies + # build dependencies + - versioneer[toml] - cython=0.29.32 + + # test dependencies - pytest>=6.0 - pytest-cov - pytest-xdist>=1.31 diff --git a/pandas/_version.py b/pandas/_version.py index 4877bdff3eb3a..6705b8505f7e2 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -1,20 +1,25 @@ -# pylint: disable=consider-using-f-string # This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by GitHub's download-from-tag +# git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. -# This file is released into the public domain. Generated by -# versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) +# This file is released into the public domain. +# Generated by versioneer-0.28 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" import errno +import functools import os import re import subprocess import sys +from typing import ( + Callable, + Dict, +) def get_keywords(): @@ -52,7 +57,8 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator @@ -71,17 +77,26 @@ def decorate(f): def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: - dispcmd = str([c] + args) + process = None + + popen_kwargs = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: + dispcmd = str([command] + args) try: # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, + process = subprocess.Popen( + [command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, ) break except OSError: @@ -89,20 +104,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= if e.errno == errno.ENOENT: continue if verbose: - print("unable to run %s" % dispcmd) + print(f"unable to run {dispcmd}") print(e) return None, None else: if verbose: print(f"unable to find command, tried {commands}") return None, None - stdout = p.communicate()[0].strip().decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + print(f"unable to run {dispcmd} (error)") + print(f"stdout was {stdout}") + return None, process.returncode + return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): @@ -114,7 +129,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return { @@ -124,14 +139,13 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): "error": None, "date": None, } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print( - "Tried directories %s but none started with prefix %s" - % (str(rootdirs), parentdir_prefix) + f"Tried directories {str(rootdirs)} \ + but none started with prefix {parentdir_prefix}" ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -145,21 +159,20 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs) - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() + with open(versionfile_abs) as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) except OSError: pass return keywords @@ -168,8 +181,8 @@ def git_get_keywords(versionfile_abs): @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature @@ -200,18 +213,23 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "main". + # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r"\d", r)} if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) + print(f"discarding '{','.join(refs - tags)}', no digits") if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) + print(f"likely tags: {','.join(sorted(tags))}") for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix) :] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r"\d", r): + continue if verbose: - print("picking %s" % r) + print(f"picking {r}") return { "version": r, "full-revisionid": keywords["full"].strip(), @@ -232,7 +250,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -243,15 +261,22 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose) if rc != 0: if verbose: - print("Directory %s not under git control" % root) + print(f"Directory {root} not under git control") raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( + describe_out, rc = runner( GITS, [ "describe", @@ -260,7 +285,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): "--always", "--long", "--match", - "%s*" % tag_prefix, + f"{tag_prefix}[[:digit:]]*", ], cwd=root, ) @@ -268,7 +293,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() @@ -278,6 +303,38 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -295,7 +352,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out + pieces["error"] = f"unable to parse git-describe output: '{describe_out}'" return pieces # tag @@ -304,10 +361,9 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format( - full_tag, - tag_prefix, - ) + pieces[ + "error" + ] = f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'" return pieces pieces["closest-tag"] = full_tag[len(tag_prefix) :] @@ -320,13 +376,11 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] @@ -335,7 +389,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): return pieces -def plus_or_dot(pieces) -> str: +def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." @@ -355,30 +409,77 @@ def render_pep440(pieces): rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + rendered += f"{pieces['distance']}.g{pieces['short']}" + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = f"0+untagged.{pieces['distance']}.g{pieces['short']}" + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_branch(pieces): + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). + + Exceptions: + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += f"{pieces['distance']}.g{pieces['short']}" if pieces["dirty"]: rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += f"+untagged.{pieces['distance']}.g{pieces['short']}" if pieces["dirty"]: rendered += ".dirty" return rendered +def pep440_split_post(ver): + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + def render_pep440_pre(pieces): - """TAG[.post0.devDISTANCE] -- No -dirty. + """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: - rendered = pieces["closest-tag"] if pieces["distance"]: - rendered += ".post0.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += f".post{post_version + 1}.dev{pieces['distance']}" + else: + rendered += f".post0.dev{pieces['distance']}" + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] + rendered = f"0.post0.dev{pieces['distance']}" return rendered @@ -395,17 +496,46 @@ def render_pep440_post(pieces): if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] + rendered += f".post{pieces['distance']}" if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] + rendered += f"g{pieces['short']}" else: # exception #1 - rendered = "0.post%d" % pieces["distance"] + rendered = f"0.post{pieces['distance']}" if pieces["dirty"]: rendered += ".dev0" - rendered += "+g%s" % pieces["short"] + rendered += f"+g{pieces['short']}" + return rendered + + +def render_pep440_post_branch(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += f".post{pieces['distance']}" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += f"g{pieces['short']}" + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = f"0.post{pieces['distance']}" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += f"+g{pieces['short']}" + if pieces["dirty"]: + rendered += ".dirty" return rendered @@ -420,12 +550,12 @@ def render_pep440_old(pieces): if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] + rendered += f"0.post{pieces['distance']}" if pieces["dirty"]: rendered += ".dev0" else: # exception #1 - rendered = "0.post%d" % pieces["distance"] + rendered = f"0.post{pieces['distance']}" if pieces["dirty"]: rendered += ".dev0" return rendered @@ -442,7 +572,7 @@ def render_git_describe(pieces): if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + rendered += f"-{pieces['distance']}-g{pieces['short']}" else: # exception #1 rendered = pieces["short"] @@ -462,7 +592,7 @@ def render_git_describe_long(pieces): """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + rendered += f"-{pieces['distance']}-g{pieces['short']}" else: # exception #1 rendered = pieces["short"] @@ -487,10 +617,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -498,7 +632,7 @@ def render(pieces, style): elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: - raise ValueError("unknown style '%s'" % style) + raise ValueError(f"unknown style '{style}'") return { "version": rendered, @@ -529,7 +663,7 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split("/"): + for _ in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: return { diff --git a/pyproject.toml b/pyproject.toml index 6ce05ce5d679e..f14bad44a889f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,12 +5,19 @@ requires = [ "setuptools>=51.0.0", "wheel", "Cython>=0.29.32,<3", # Note: sync with setup.py, environment.yml and asv.conf.json - "oldest-supported-numpy>=2022.8.16" + "oldest-supported-numpy>=2022.8.16", + "versioneer[toml]" ] -# uncomment to enable pep517 after versioneer problem is fixed. -# https://github.com/python-versioneer/python-versioneer/issues/193 # build-backend = "setuptools.build_meta" +[tool.versioneer] +VCS = "git" +style = "pep440" +versionfile_source = "pandas/_version.py" +versionfile_build = "pandas/_version.py" +tag_prefix = "v" +parentdir_prefix = "pandas-" + [tool.cibuildwheel] skip = "cp36-* cp37-* pp37-* *-manylinux_i686 *_ppc64le *_s390x *-musllinux*" build-verbosity = "3" diff --git a/requirements-dev.txt b/requirements-dev.txt index 5c90e5908ece8..78dddbe607084 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -2,6 +2,7 @@ # See that file for comments about the need/usage of each dependency. pip +versioneer[toml] cython==0.29.32 pytest>=6.0 pytest-cov diff --git a/setup.cfg b/setup.cfg index 6de5bf2173a70..c3aaf7cf4e9ae 100644 --- a/setup.cfg +++ b/setup.cfg @@ -167,17 +167,6 @@ inplace = True [options.packages.find] include = pandas, pandas.* -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. -[versioneer] -VCS = git -style = pep440 -versionfile_source = pandas/_version.py -versionfile_build = pandas/_version.py -tag_prefix = v -parentdir_prefix = pandas- - [flake8] max-line-length = 88 ignore = diff --git a/setup.py b/setup.py index 02b91cbb0d9b4..f8fa048757289 100755 --- a/setup.py +++ b/setup.py @@ -23,7 +23,6 @@ setup, ) from setuptools.command.build_ext import build_ext as _build_ext - import versioneer cmdclass = versioneer.get_cmdclass() diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 5dd66e4df6c36..0000000000000 --- a/versioneer.py +++ /dev/null @@ -1,1915 +0,0 @@ -# Version: 0.19 -# pylint: disable=consider-using-f-string - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3 -* [![Latest Version][pypi-image]][pypi-url] -* [![Build Status][travis-image]][travis-url] - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere in your $PATH -* add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) -* run `versioneer install` in your source tree, commit the results -* Verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like GitHub's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on GitHub -[issues page](https://github.com/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other languages) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - -## Similar projects - -* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time - dependency -* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of - versioneer - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg -[pypi-url]: https://pypi.python.org/pypi/versioneer/ -[travis-image]: -https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg -[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer - -""" - -import configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ( - "Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND')." - ) - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print( - "Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py) - ) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.ConfigParser() - with open(setup_cfg) as f: - parser.read_file(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - dispcmd = str([c] + args) - try: - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, - cwd=cwd, - env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr else None), - ) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print(f"unable to find command, tried {commands}") - return None, None - stdout = p.communicate()[0].strip().decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -LONG_VERSION_PY[ - "git" -] = r''' -# pylint: disable=consider-using-f-string -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by GitHub's download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = p.communicate()[0].strip().decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post0.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post0.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs) - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r"\d", r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix) :] - if verbose: - print("picking %s" % r) - return { - "version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": None, - "date": date, - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return { - "version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": "no suitable tags", - "date": None, - } - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( - GITS, - [ - "describe", - "--tags", - "--dirty", - "--always", - "--long", - "--match", - "%s*" % tag_prefix, - ], - cwd=root, - ) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[: git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format( - full_tag, - tag_prefix, - ) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix) :] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except OSError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return { - "version": dirname[len(parentdir_prefix) :], - "full-revisionid": None, - "dirty": False, - "error": None, - "date": None, - } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print( - "Tried directories %s but none started with prefix %s" - % (str(rootdirs), parentdir_prefix) - ) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.19) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except OSError: - raise NotThisMethod("unable to read _version.py") - mo = re.search( - r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S - ) - if not mo: - mo = re.search( - r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S - ) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set {} to '{}'".format(filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post0.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post0.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return { - "version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None, - } - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return { - "version": rendered, - "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], - "error": None, - "date": pieces.get("date"), - } - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert ( - cfg.versionfile_source is not None - ), "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or GitHub's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print(f"got version from file {versionfile_abs} {ver}") - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", - "date": None, - } - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools/distutils subclasses used by Versioneer. - - If the package uses a different cmdclass (e.g. one from numpy), it - should be provide as an argument. - """ - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to its pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if "build_py" in cmds: - _build_py = cmds["build_py"] - elif "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - cmds["build_py"] = cmd_build_py - - if "setuptools" in sys.modules: - from setuptools.command.build_ext import build_ext as _build_ext - else: - from distutils.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_ext.run(self) - if self.inplace: - # build_ext --inplace will only build extensions in - # build/lib<..> dir with no _version.py to write to. - # As in place builds will already have a _version.py - # in the module dir, we do not need to write one. - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - target_versionfile = os.path.join(self.build_lib, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - cmds["build_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if "py2exe" in sys.modules: # py2exe enabled? - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if "sdist" in cmds: - _sdist = cmds["sdist"] - elif "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file( - target_versionfile, self._versioneer_generated_versions - ) - - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from pandas._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy) as f: - old = f.read() - except OSError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in) as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except OSError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print( - " appending versionfile_source ('%s') to MANIFEST.in" - % cfg.versionfile_source - ) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1)
This PR: 1. move versioneer config to pyproject.toml 2. use nonvendored version of versioneer After this, we could enable PEP 517.
https://api.github.com/repos/pandas-dev/pandas/pulls/49924
2022-11-27T01:11:21Z
2022-11-28T20:14:11Z
2022-11-28T20:14:11Z
2023-04-03T23:20:05Z
CLN: move codespell config to pyproject.toml
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6b74dd057e865..cc6875589c691 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,7 @@ repos: hooks: - id: codespell types_or: [python, rst, markdown] + additional_dependencies: [tomli] - repo: https://github.com/MarcoGorelli/cython-lint rev: v0.2.1 hooks: diff --git a/pyproject.toml b/pyproject.toml index d3065ae7b129a..6ce05ce5d679e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -334,3 +334,7 @@ exclude_lines = [ [tool.coverage.html] directory = "coverage_html_report" + +[tool.codespell] +ignore-words-list = "blocs, coo, hist, nd, sav, ser, recuse" +ignore-regex = 'https://([\w/\.])+' diff --git a/setup.cfg b/setup.cfg index dbd7cce1874c8..6de5bf2173a70 100644 --- a/setup.cfg +++ b/setup.cfg @@ -283,7 +283,3 @@ exclude = # work around issue of undefined variable warnings # https://github.com/pandas-dev/pandas/pull/38837#issuecomment-752884156 doc/source/getting_started/comparison/includes/*.rst - -[codespell] -ignore-words-list = blocs,coo,hist,nd,sav,ser,recuse -ignore-regex = https://([\w/\.])+
null
https://api.github.com/repos/pandas-dev/pandas/pulls/49923
2022-11-27T00:37:03Z
2022-11-27T08:45:49Z
2022-11-27T08:45:49Z
2022-11-27T08:45:50Z
API: ensure read_json closes file handle
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index f1ee96ddc3c16..dd46cd533bb80 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -349,6 +349,7 @@ Other API changes - :func:`read_stata` with parameter ``index_col`` set to ``None`` (the default) will now set the index on the returned :class:`DataFrame` to a :class:`RangeIndex` instead of a :class:`Int64Index` (:issue:`49745`) - Changed behavior of :class:`Index` constructor with an object-dtype ``numpy.ndarray`` containing all-``bool`` values or all-complex values, this will now retain object dtype, consistent with the :class:`Series` behavior (:issue:`49594`) - Changed behavior of :meth:`DataFrame.shift` with ``axis=1``, an integer ``fill_value``, and homogeneous datetime-like dtype, this now fills new columns with integer dtypes instead of casting to datetimelike (:issue:`49842`) +- Files are now closed when encountering an exception in :func:`read_json` (:issue:`49921`) - :meth:`DataFrame.values`, :meth:`DataFrame.to_numpy`, :meth:`DataFrame.xs`, :meth:`DataFrame.reindex`, :meth:`DataFrame.fillna`, and :meth:`DataFrame.replace` no longer silently consolidate the underlying arrays; do ``df = df.copy()`` to ensure consolidation (:issue:`49356`) - diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 3020731b77a3c..5f02822b68d6d 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -750,8 +750,7 @@ def read_json( if chunksize: return json_reader - - with json_reader: + else: return json_reader.read() @@ -896,20 +895,20 @@ def read(self) -> DataFrame | Series: Read the whole JSON input into a pandas object. """ obj: DataFrame | Series - if self.lines: - if self.chunksize: - obj = concat(self) - elif self.nrows: - lines = list(islice(self.data, self.nrows)) - lines_json = self._combine_lines(lines) - obj = self._get_object_parser(lines_json) + with self: + if self.lines: + if self.chunksize: + obj = concat(self) + elif self.nrows: + lines = list(islice(self.data, self.nrows)) + lines_json = self._combine_lines(lines) + obj = self._get_object_parser(lines_json) + else: + data = ensure_str(self.data) + data_lines = data.split("\n") + obj = self._get_object_parser(self._combine_lines(data_lines)) else: - data = ensure_str(self.data) - data_lines = data.split("\n") - obj = self._get_object_parser(self._combine_lines(data_lines)) - else: - obj = self._get_object_parser(self.data) - self.close() + obj = self._get_object_parser(self.data) return obj def _get_object_parser(self, json) -> DataFrame | Series: @@ -964,24 +963,27 @@ def __next__(self: JsonReader[Literal["frame", "series"]]) -> DataFrame | Series ... def __next__(self) -> DataFrame | Series: - if self.nrows: - if self.nrows_seen >= self.nrows: - self.close() - raise StopIteration + if self.nrows and self.nrows_seen >= self.nrows: + self.close() + raise StopIteration lines = list(islice(self.data, self.chunksize)) - if lines: + if not lines: + self.close() + raise StopIteration + + try: lines_json = self._combine_lines(lines) obj = self._get_object_parser(lines_json) # Make sure that the returned objects have the right index. obj.index = range(self.nrows_seen, self.nrows_seen + len(obj)) self.nrows_seen += len(obj) + except Exception as ex: + self.close() + raise ex - return obj - - self.close() - raise StopIteration + return obj def __enter__(self) -> JsonReader[FrameSeriesStrT]: return self
Use context manager instead of closing manually with `self.close` to ensure file always closes. Not sure if this should have a whatsnew entry and where.
https://api.github.com/repos/pandas-dev/pandas/pulls/49921
2022-11-26T23:40:51Z
2022-12-02T00:31:10Z
2022-12-02T00:31:10Z
2022-12-05T09:27:37Z
Json fix normalize
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 97ee96d8be25d..e657a98f6358f 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -717,6 +717,7 @@ I/O - Bug in :func:`read_csv` for a single-line csv with fewer columns than ``names`` raised :class:`.errors.ParserError` with ``engine="c"`` (:issue:`47566`) - Bug in :func:`DataFrame.to_string` with ``header=False`` that printed the index name on the same line as the first row of the data (:issue:`49230`) - Fixed memory leak which stemmed from the initialization of the internal JSON module (:issue:`49222`) +- Fixed issue where :func:`json_normalize` would incorrectly remove leading characters from column names that matched the ``sep`` argument (:issue:`49861`) - Period diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index 3791dba6e36e3..4b2d0d9beea3f 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -7,6 +7,7 @@ defaultdict, ) import copy +import sys from typing import ( Any, DefaultDict, @@ -148,13 +149,18 @@ def _normalise_json( if isinstance(data, dict): for key, value in data.items(): new_key = f"{key_string}{separator}{key}" + + if not key_string: + if sys.version_info < (3, 9): + from pandas.util._str_methods import removeprefix + + new_key = removeprefix(new_key, separator) + else: + new_key = new_key.removeprefix(separator) + _normalise_json( data=value, - # to avoid adding the separator to the start of every key - # GH#43831 avoid adding key if key_string blank - key_string=new_key - if new_key[: len(separator)] != separator - else new_key[len(separator) :], + key_string=new_key, normalized_dict=normalized_dict, separator=separator, ) diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 986c0039715a6..86059c24b1e48 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -561,6 +561,14 @@ def generator_data(): tm.assert_frame_equal(result, expected) + def test_top_column_with_leading_underscore(self): + # 49861 + data = {"_id": {"a1": 10, "l2": {"l3": 0}}, "gg": 4} + result = json_normalize(data, sep="_") + expected = DataFrame([[4, 10, 0]], columns=["gg", "_id_a1", "_id_l2_l3"]) + + tm.assert_frame_equal(result, expected) + class TestNestedToRecord: def test_flat_stays_flat(self):
closes #49861
https://api.github.com/repos/pandas-dev/pandas/pulls/49920
2022-11-26T20:01:42Z
2022-11-28T20:04:06Z
2022-11-28T20:04:06Z
2023-01-03T18:19:16Z
BUG: GH11206 where pd.isnull did not consider numpy NaT null
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 2c07c28066faf..9367c42f8d39a 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -582,7 +582,7 @@ def time_frame_interpolate_some_good_infer(self): self.df.interpolate(downcast='infer') -class frame_isnull(object): +class frame_isnull_floats_no_null(object): goal_time = 0.2 def setup(self): @@ -593,6 +593,33 @@ def time_frame_isnull(self): isnull(self.df) +class frame_isnull_floats(object): + goal_time = 0.2 + + def setup(self): + np.random.seed(1234) + self.sample = np.array([np.nan, 1.0]) + self.data = np.random.choice(self.sample, (1000, 1000)) + self.df = DataFrame(self.data) + + def time_frame_isnull(self): + isnull(self.df) + + +class frame_isnull_obj(object): + goal_time = 0.2 + + def setup(self): + np.random.seed(1234) + self.sample = np.array([NaT, np.nan, None, np.datetime64('NaT'), + np.timedelta64('NaT'), 0, 1, 2.0, '', 'abcd']) + self.data = np.random.choice(self.sample, (1000, 1000)) + self.df = DataFrame(self.data) + + def time_frame_isnull(self): + isnull(self.df) + + class frame_iteritems(object): goal_time = 0.2 diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index f2008727017f8..f8801cfdf9785 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -156,6 +156,7 @@ Bug Fixes - Bug in output formatting when using an index of ambiguous times (:issue:`11619`) - Bug in comparisons of Series vs list-likes (:issue:`11339`) - Bug in ``DataFrame.replace`` with a ``datetime64[ns, tz]`` and a non-compat to_replace (:issue:`11326`, :issue:`11153`) +- Bug in ``isnull`` where ``numpy.datetime64('NaT')`` in a ``numpy.array`` was not determined to be null(:issue:`11206`) - Bug in list-like indexing with a mixed-integer Index (:issue:`11320`) - Bug in ``pivot_table`` with ``margins=True`` when indexes are of ``Categorical`` dtype (:issue:`10993`) - Bug in ``DataFrame.plot`` cannot use hex strings colors (:issue:`10299`) diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 1a1f04cba1cb9..f7978c4791538 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -1,3 +1,4 @@ +# cython: profile=False cimport numpy as np cimport cython import numpy as np @@ -54,7 +55,8 @@ from datetime import datetime as pydatetime # this is our tseries.pxd from datetime cimport * -from tslib cimport convert_to_tsobject, convert_to_timedelta64 +from tslib cimport (convert_to_tsobject, convert_to_timedelta64, + _check_all_nulls) import tslib from tslib import NaT, Timestamp, Timedelta @@ -245,8 +247,6 @@ def time64_to_datetime(ndarray[int64_t, ndim=1] arr): return result -cdef inline int64_t get_timedelta64_value(val): - return val.view('i8') #---------------------------------------------------------------------- # isnull / notnull related @@ -346,10 +346,10 @@ def isnullobj(ndarray[object] arr): cdef ndarray[uint8_t] result n = len(arr) - result = np.zeros(n, dtype=np.uint8) + result = np.empty(n, dtype=np.uint8) for i from 0 <= i < n: val = arr[i] - result[i] = val is NaT or _checknull(val) + result[i] = _check_all_nulls(val) return result.view(np.bool_) @cython.wraparound(False) diff --git a/pandas/src/datetime.pxd b/pandas/src/datetime.pxd index f2f764c785894..5f7de8244d17e 100644 --- a/pandas/src/datetime.pxd +++ b/pandas/src/datetime.pxd @@ -1,3 +1,4 @@ +# cython: profile=False from numpy cimport int64_t, int32_t, npy_int64, npy_int32, ndarray from cpython cimport PyObject @@ -59,6 +60,7 @@ cdef extern from "numpy/ndarrayobject.h": cdef extern from "numpy_helper.h": npy_datetime get_datetime64_value(object o) + npy_timedelta get_timedelta64_value(object o) cdef extern from "numpy/npy_common.h": diff --git a/pandas/src/numpy_helper.h b/pandas/src/numpy_helper.h index 8b79bbe79ff2f..9f406890c4e68 100644 --- a/pandas/src/numpy_helper.h +++ b/pandas/src/numpy_helper.h @@ -40,7 +40,11 @@ get_nat(void) { PANDAS_INLINE npy_datetime get_datetime64_value(PyObject* obj) { return ((PyDatetimeScalarObject*) obj)->obval; +} +PANDAS_INLINE npy_timedelta +get_timedelta64_value(PyObject* obj) { + return ((PyTimedeltaScalarObject*) obj)->obval; } PANDAS_INLINE int diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 89826209fa46d..57448e2d018dc 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -179,6 +179,13 @@ def test_isnull_nat(): exp = np.array([True]) assert(np.array_equal(result, exp)) +def test_isnull_numpy_nat(): + arr = np.array([NaT, np.datetime64('NaT'), np.timedelta64('NaT'), + np.datetime64('NaT', 's')]) + result = isnull(arr) + expected = np.array([True] * 4) + tm.assert_numpy_array_equal(result, expected) + def test_isnull_datetime(): assert (not isnull(datetime.now())) assert notnull(datetime.now()) diff --git a/pandas/tslib.pxd b/pandas/tslib.pxd index 3cb7e94c65100..5e0c88604206c 100644 --- a/pandas/tslib.pxd +++ b/pandas/tslib.pxd @@ -7,3 +7,4 @@ cdef bint _is_utc(object) cdef bint _is_tzlocal(object) cdef object _get_dst_info(object) cdef bint _nat_scalar_rules[6] +cdef bint _check_all_nulls(obj) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 0d47c2526df14..713cf08bfc3e2 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -3,6 +3,7 @@ cimport numpy as np from numpy cimport (int8_t, int32_t, int64_t, import_array, ndarray, NPY_INT64, NPY_DATETIME, NPY_TIMEDELTA) +from datetime cimport get_datetime64_value, get_timedelta64_value import numpy as np # GH3363 @@ -707,12 +708,28 @@ NaT = NaTType() iNaT = util.get_nat() - cdef inline bint _checknull_with_nat(object val): """ utility to check if a value is a nat or not """ return val is None or ( PyFloat_Check(val) and val != val) or val is NaT +cdef inline bint _check_all_nulls(object val): + """ utility to check if a value is any type of null """ + cdef bint res + if PyFloat_Check(val): + res = val != val + elif val is NaT: + res = 1 + elif val is None: + res = 1 + elif is_datetime64_object(val): + res = get_datetime64_value(val) == NPY_NAT + elif is_timedelta64_object(val): + res = get_timedelta64_value(val) == NPY_NAT + else: + res = 0 + return res + cdef inline bint _cmp_nat_dt(_NaT lhs, _Timestamp rhs, int op) except -1: return _nat_scalar_rules[op]
closes #11206
https://api.github.com/repos/pandas-dev/pandas/pulls/11212
2015-09-30T23:23:51Z
2015-11-20T14:51:21Z
2015-11-20T14:51:21Z
2015-11-20T14:51:30Z
PERF: vectorized DateOffset with months
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 03cac12436898..79d0788efad82 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1056,6 +1056,7 @@ Performance Improvements - 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`) - Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`) - Regression from 0.16.1 in constructing ``DataFrame`` from nested dictionary (:issue:`11084`) +- Performance improvements in addition/subtraction operations for ``DateOffset`` with ``Series`` or ``DatetimeIndex`` (issue:`10744`, :issue:`11205`) .. _whatsnew_0170.bug_fixes: diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index e15be45ef305a..0dac09a243d36 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -261,16 +261,12 @@ def apply_index(self, i): # relativedelta/_offset path only valid for base DateOffset if (self._use_relativedelta and set(self.kwds).issubset(relativedelta_fast)): + months = ((self.kwds.get('years', 0) * 12 + self.kwds.get('months', 0)) * self.n) if months: - base = (i.to_period('M') + months).to_timestamp() - time = i.to_perioddelta('D') - days = i.to_perioddelta('M') - time - # minimum prevents month-end from wrapping - day_offset = np.minimum(days, - to_timedelta(base.days_in_month - 1, unit='D')) - i = base + day_offset + time + shifted = tslib.shift_months(i.asi8, months) + i = i._shallow_copy(shifted) weeks = (self.kwds.get('weeks', 0)) * self.n if weeks: @@ -1081,7 +1077,9 @@ def apply(self, other): @apply_index_wraps def apply_index(self, i): - return self._end_apply_index(i, 'M') + months = self.n - 1 if self.n >= 0 else self.n + shifted = tslib.shift_months(i.asi8, months, 'end') + return i._shallow_copy(shifted) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): @@ -1106,7 +1104,9 @@ def apply(self, other): @apply_index_wraps def apply_index(self, i): - return self._beg_apply_index(i, 'M') + months = self.n + 1 if self.n < 0 else self.n + shifted = tslib.shift_months(i.asi8, months, 'start') + return i._shallow_copy(shifted) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 957cdcc009e1c..ed174bc285e4f 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -2565,32 +2565,32 @@ def test_datetime64_with_DateOffset(self): for klass, assert_func in zip([Series, DatetimeIndex], [self.assert_series_equal, tm.assert_index_equal]): - s = klass(date_range('2000-01-01', '2000-01-31')) + s = klass(date_range('2000-01-01', '2000-01-31'), name='a') result = s + pd.DateOffset(years=1) result2 = pd.DateOffset(years=1) + s - exp = klass(date_range('2001-01-01', '2001-01-31')) + exp = klass(date_range('2001-01-01', '2001-01-31'), name='a') assert_func(result, exp) assert_func(result2, exp) result = s - pd.DateOffset(years=1) - exp = klass(date_range('1999-01-01', '1999-01-31')) + exp = klass(date_range('1999-01-01', '1999-01-31'), name='a') assert_func(result, exp) s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'), - pd.Timestamp('2000-02-15', tz='US/Central')]) + pd.Timestamp('2000-02-15', tz='US/Central')], name='a') result = s + pd.offsets.Day() result2 = pd.offsets.Day() + s exp = klass([Timestamp('2000-01-16 00:15:00', tz='US/Central'), - Timestamp('2000-02-16', tz='US/Central')]) + Timestamp('2000-02-16', tz='US/Central')], name='a') assert_func(result, exp) assert_func(result2, exp) s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'), - pd.Timestamp('2000-02-15', tz='US/Central')]) + pd.Timestamp('2000-02-15', tz='US/Central')], name='a') result = s + pd.offsets.MonthEnd() result2 = pd.offsets.MonthEnd() + s exp = klass([Timestamp('2000-01-31 00:15:00', tz='US/Central'), - Timestamp('2000-02-29', tz='US/Central')]) + Timestamp('2000-02-29', tz='US/Central')], name='a') assert_func(result, exp) assert_func(result2, exp) diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index fadad91e6842a..f618b2593597e 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -949,6 +949,17 @@ def compare_local_to_utc(tz_didx, utc_didx): tslib.maybe_get_tz('Asia/Tokyo')) self.assert_numpy_array_equal(result, np.array([tslib.iNaT], dtype=np.int64)) + def test_shift_months(self): + s = DatetimeIndex([Timestamp('2000-01-05 00:15:00'), Timestamp('2000-01-31 00:23:00'), + Timestamp('2000-01-01'), Timestamp('2000-02-29'), Timestamp('2000-12-31')]) + for years in [-1, 0, 1]: + for months in [-2, 0, 2]: + actual = DatetimeIndex(tslib.shift_months(s.asi8, years * 12 + months)) + expected = DatetimeIndex([x + offsets.DateOffset(years=years, months=months) for x in s]) + tm.assert_index_equal(actual, expected) + + + class TestTimestampOps(tm.TestCase): def test_timestamp_and_datetime(self): self.assertEqual((Timestamp(datetime.datetime(2013, 10, 13)) - datetime.datetime(2013, 10, 12)).days, 1) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 7b3e404f7504c..398c5f0232de1 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -3847,6 +3847,7 @@ def get_time_micros(ndarray[int64_t] dtindex): return micros + @cython.wraparound(False) def get_date_field(ndarray[int64_t] dtindex, object field): ''' @@ -4386,6 +4387,75 @@ cpdef normalize_date(object dt): raise TypeError('Unrecognized type: %s' % type(dt)) +cdef inline int _year_add_months(pandas_datetimestruct dts, + int months): + '''new year number after shifting pandas_datetimestruct number of months''' + return dts.year + (dts.month + months - 1) / 12 + +cdef inline int _month_add_months(pandas_datetimestruct dts, + int months): + '''new month number after shifting pandas_datetimestruct number of months''' + cdef int new_month = (dts.month + months) % 12 + return 12 if new_month == 0 else new_month + +@cython.wraparound(False) +def shift_months(int64_t[:] dtindex, int months, object day=None): + ''' + Given an int64-based datetime index, shift all elements + specified number of months using DateOffset semantics + + day: {None, 'start', 'end'} + * None: day of month + * 'start' 1st day of month + * 'end' last day of month + ''' + cdef: + Py_ssize_t i + int days_in_month + pandas_datetimestruct dts + int count = len(dtindex) + int64_t[:] out = np.empty(count, dtype='int64') + + for i in range(count): + if dtindex[i] == NPY_NAT: + out[i] = NPY_NAT + else: + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + + if day is None: + dts.year = _year_add_months(dts, months) + dts.month = _month_add_months(dts, months) + #prevent day from wrapping around month end + days_in_month = days_per_month_table[is_leapyear(dts.year)][dts.month-1] + dts.day = min(dts.day, days_in_month) + elif day == 'start': + dts.year = _year_add_months(dts, months) + dts.month = _month_add_months(dts, months) + + # offset semantics - when subtracting if at the start anchor + # point, shift back by one more month + if months <= 0 and dts.day == 1: + dts.year = _year_add_months(dts, -1) + dts.month = _month_add_months(dts, -1) + else: + dts.day = 1 + elif day == 'end': + days_in_month = days_per_month_table[is_leapyear(dts.year)][dts.month-1] + dts.year = _year_add_months(dts, months) + dts.month = _month_add_months(dts, months) + + # similar semantics - when adding shift forward by one + # month if already at an end of month + if months >= 0 and dts.day == days_in_month: + dts.year = _year_add_months(dts, 1) + dts.month = _month_add_months(dts, 1) + + days_in_month = days_per_month_table[is_leapyear(dts.year)][dts.month-1] + dts.day = days_in_month + + out[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) + return np.asarray(out) + #---------------------------------------------------------------------- # Don't even ask
This is a follow-up to https://github.com/pydata/pandas/pull/10744. In that, vectorized versions of some offsets were implemented, mostly by changing to periods and back. The case of shifting by years/months (which is actually most useful to me) required some extra hoops and had poorer performance - this PR implements a special cython routine for that, for about a 10x improvement. ``` In [3]: s = pd.Series(pd.date_range('1900-1-1', periods=100000)) # Master In [4]: %timeit s + pd.DateOffset(months=1) 1 loops, best of 3: 140 ms per loop # PR In [2]: %timeit s + pd.DateOffset(months=1) 100 loops, best of 3: 14.2 ms per loo ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11205
2015-09-30T00:03:30Z
2015-10-02T02:15:07Z
2015-10-02T02:15:07Z
2015-10-04T17:01:51Z
BUG: groupby list of keys with same length as index
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index c8ab9599cd92a..11596fe5d4ee3 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1184,3 +1184,4 @@ Bug Fixes - Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`) - Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`) - Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`) +- Bug in ``.groupby`` when number of keys to group by is same as length of index (:issue:`11185`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 9748a594a9b6f..e837445e9e348 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2111,6 +2111,7 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True): # what are we after, exactly? match_axis_length = len(keys) == len(group_axis) any_callable = any(callable(g) or isinstance(g, dict) for g in keys) + any_groupers = any(isinstance(g, Grouper) for g in keys) any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray)) for g in keys) @@ -2123,7 +2124,8 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True): all_in_columns = False if (not any_callable and not all_in_columns - and not any_arraylike and match_axis_length + and not any_arraylike and not any_groupers + and match_axis_length and level is None): keys = [com._asarray_tuplesafe(keys)] diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 42d5af587a859..8eb641ce8f494 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -2989,6 +2989,18 @@ def test_groupby_list_infer_array_like(self): result = df.groupby(['foo', 'bar']).mean() expected = df.groupby([df['foo'], df['bar']]).mean()[['val']] + def test_groupby_keys_same_size_as_index(self): + # GH 11185 + freq = 's' + index = pd.date_range(start=np.datetime64( + '2015-09-29T11:34:44-0700'), periods=2, freq=freq) + df = pd.DataFrame([['A', 10], ['B', 15]], columns=[ + 'metric', 'values'], index=index) + result = df.groupby([pd.Grouper(level=0, freq=freq), 'metric']).mean() + expected = df.set_index([df.index, 'metric']) + + assert_frame_equal(result, expected) + def test_groupby_nat_exclude(self): # GH 6992 df = pd.DataFrame({'values': np.random.randn(8),
Fixes issue #11185
https://api.github.com/repos/pandas-dev/pandas/pulls/11202
2015-09-29T19:06:15Z
2015-10-01T10:45:44Z
2015-10-01T10:45:44Z
2015-10-01T10:45:52Z
CLN: GH11170, * import is removed from test_internals.py
diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 61966674bc104..00553102e172f 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -7,10 +7,13 @@ import numpy as np import re +import itertools from pandas import Index, MultiIndex, DataFrame, DatetimeIndex, Series, Categorical from pandas.compat import OrderedDict, lrange from pandas.sparse.array import SparseArray -from pandas.core.internals import * +from pandas.core.internals import (BlockPlacement, SingleBlockManager, make_block, + BlockManager) +import pandas.core.common as com import pandas.core.internals as internals import pandas.util.testing as tm import pandas as pd @@ -664,8 +667,8 @@ def test_interleave(self): def test_interleave_non_unique_cols(self): df = DataFrame([ - [Timestamp('20130101'), 3.5], - [Timestamp('20130102'), 4.5]], + [pd.Timestamp('20130101'), 3.5], + [pd.Timestamp('20130102'), 4.5]], columns=['x', 'x'], index=[1, 2])
closes #11170
https://api.github.com/repos/pandas-dev/pandas/pulls/11197
2015-09-27T13:11:46Z
2015-09-27T14:28:49Z
2015-09-27T14:28:49Z
2015-09-27T14:28:49Z
PERF: compare freq strings (timeseries plotting perf)
diff --git a/pandas/src/period.pyx b/pandas/src/period.pyx index 1dbf469a946b5..2a7c2135f8045 100644 --- a/pandas/src/period.pyx +++ b/pandas/src/period.pyx @@ -439,10 +439,12 @@ def extract_ordinals(ndarray[object] values, freq): ndarray[int64_t] ordinals = np.empty(n, dtype=np.int64) object p + freqstr = Period._maybe_convert_freq(freq).freqstr + for i in range(n): p = values[i] ordinals[i] = p.ordinal - if p.freq != freq: + if p.freqstr != freqstr: raise ValueError("%s is wrong freq" % p) return ordinals
See overview in #11084
https://api.github.com/repos/pandas-dev/pandas/pulls/11194
2015-09-26T13:25:31Z
2015-10-01T11:20:29Z
2015-10-01T11:20:29Z
2015-10-01T11:20:29Z
COMPAT: platform_int fixes in groupby ops, #11189
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index e72f7c6c6a6bf..9748a594a9b6f 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1379,8 +1379,9 @@ def size(self): """ ids, _, ngroup = self.group_info + ids = com._ensure_platform_int(ids) out = np.bincount(ids[ids != -1], minlength=ngroup) - return Series(out, index=self.result_index) + return Series(out, index=self.result_index, dtype='int64') @cache_readonly def _max_groupsize(self): @@ -1808,15 +1809,17 @@ def indices(self): @cache_readonly def group_info(self): ngroups = self.ngroups - obs_group_ids = np.arange(ngroups, dtype='int64') + obs_group_ids = np.arange(ngroups) rep = np.diff(np.r_[0, self.bins]) + rep = com._ensure_platform_int(rep) if ngroups == len(self.bins): - comp_ids = np.repeat(np.arange(ngroups, dtype='int64'), rep) + comp_ids = np.repeat(np.arange(ngroups), rep) else: - comp_ids = np.repeat(np.r_[-1, np.arange(ngroups, dtype='int64')], rep) + comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep) - return comp_ids, obs_group_ids, ngroups + return comp_ids.astype('int64', copy=False), \ + obs_group_ids.astype('int64', copy=False), ngroups @cache_readonly def ngroups(self): @@ -2565,8 +2568,8 @@ def nunique(self, dropna=True): # group boundries are where group ids change # unique observations are where sorted values change - idx = com._ensure_int64(np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]]) - inc = com._ensure_int64(np.r_[1, val[1:] != val[:-1]]) + idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] + inc = np.r_[1, val[1:] != val[:-1]] # 1st item of each group is a new unique observation mask = isnull(val) @@ -2577,7 +2580,7 @@ def nunique(self, dropna=True): inc[mask & np.r_[False, mask[:-1]]] = 0 inc[idx] = 1 - out = np.add.reduceat(inc, idx) + out = np.add.reduceat(inc, idx).astype('int64', copy=False) return Series(out if ids[0] != -1 else out[1:], index=self.grouper.result_index, name=self.name) @@ -2666,6 +2669,8 @@ def value_counts(self, normalize=False, sort=True, ascending=False, mi = MultiIndex(levels=levels, labels=labels, names=names, verify_integrity=False) + if com.is_integer_dtype(out): + out = com._ensure_int64(out) return Series(out, index=mi) # for compat. with algos.value_counts need to ensure every @@ -2695,6 +2700,8 @@ def value_counts(self, normalize=False, sort=True, ascending=False, mi = MultiIndex(levels=levels, labels=labels, names=names, verify_integrity=False) + if com.is_integer_dtype(out): + out = com._ensure_int64(out) return Series(out, index=mi) def count(self): @@ -2703,9 +2710,10 @@ def count(self): val = self.obj.get_values() mask = (ids != -1) & ~isnull(val) + ids = com._ensure_platform_int(ids) out = np.bincount(ids[mask], minlength=ngroups) if ngroups != 0 else [] - return Series(out, index=self.grouper.result_index, name=self.name) + return Series(out, index=self.grouper.result_index, name=self.name, dtype='int64') def _apply_to_column_groupbys(self, func): """ return a pass thru """ diff --git a/pandas/core/series.py b/pandas/core/series.py index 03b2ea5597ab6..11645311467d5 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1137,7 +1137,7 @@ def count(self, level=None): lev = lev.insert(cnt, _get_na_value(lev.dtype.type)) out = np.bincount(lab[notnull(self.values)], minlength=len(lev)) - return self._constructor(out, index=lev).__finalize__(self) + return self._constructor(out, index=lev, dtype='int64').__finalize__(self) def mode(self): """Returns the mode(s) of the dataset. diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index 2e7fb2adf2fd4..b94c91f72802a 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -9,6 +9,7 @@ import pandas.lib as lib import pandas._period as period import pandas.algos as algos +from pandas.core import common as com from pandas.tseries.holiday import Holiday, SA, next_monday,USMartinLutherKingJr,USMemorialDay,AbstractHolidayCalendar import datetime from pandas import DateOffset @@ -480,10 +481,10 @@ def test_group_ohlc(): def _check(dtype): obj = np.array(np.random.randn(20),dtype=dtype) - bins = np.array([6, 12, 20], dtype=np.int64) + bins = np.array([6, 12, 20]) out = np.zeros((3, 4), dtype) counts = np.zeros(len(out), dtype=np.int64) - labels = np.repeat(np.arange(3, dtype='int64'), np.diff(np.r_[0, bins])) + labels = com._ensure_int64(np.repeat(np.arange(3), np.diff(np.r_[0, bins]))) func = getattr(algos,'group_ohlc_%s' % dtype) func(out, counts, obj[:, None], labels) diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index 7052348e2e6a4..b48f077bd6f6d 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -936,7 +936,7 @@ def test_resample_group_info(self): # GH10914 mask = np.r_[True, vals[1:] != vals[:-1]] mask |= np.r_[True, bins[1:] != bins[:-1]] - arr = np.bincount(bins[mask] - 1, minlength=len(ix)) + arr = np.bincount(bins[mask] - 1, minlength=len(ix)).astype('int64',copy=False) right = Series(arr, index=ix) assert_series_equal(left, right) @@ -950,7 +950,7 @@ def test_resample_size(self): ix = date_range(start=left.index.min(), end=ts.index.max(), freq='7T') bins = np.searchsorted(ix.values, ts.index.values, side='right') - val = np.bincount(bins, minlength=len(ix) + 1)[1:] + val = np.bincount(bins, minlength=len(ix) + 1)[1:].astype('int64',copy=False) right = Series(val, index=ix) assert_series_equal(left, right)
closes #11189
https://api.github.com/repos/pandas-dev/pandas/pulls/11191
2015-09-25T22:57:53Z
2015-09-25T23:51:09Z
2015-09-25T23:51:09Z
2015-09-25T23:51:09Z
DOC: fix bunch of doc build warnings
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index bc4b463e52302..14d712c822bdb 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -1090,7 +1090,7 @@ decreasing. Note that the same result could have been achieved using :ref:`fillna <missing_data.fillna>` (except for ``method='nearest'``) or -:ref:`interpolate <missing_data.interpolation>`: +:ref:`interpolate <missing_data.interpolate>`: .. ipython:: python diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst index 2b3a1b927cbbf..f51603750d61b 100644 --- a/doc/source/comparison_with_sas.rst +++ b/doc/source/comparison_with_sas.rst @@ -34,7 +34,7 @@ Data Structures --------------- General Terminology Translation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. csv-table:: :header: "pandas", "SAS" diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 5d26ca2414690..3e8e866c057e4 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -154,8 +154,8 @@ Creating a Development Environment An easy way to create a *pandas* development environment is as follows. -- Install either :ref:`Install Anaconda <install-anaconda>` or :ref:`Install miniconda <install-miniconda>` -- Make sure that you have :ref:`cloned the repository <contributing-forking>` +- Install either :ref:`Install Anaconda <install.anaconda>` or :ref:`Install miniconda <install.miniconda>` +- Make sure that you have :ref:`cloned the repository <contributing.forking>` - ``cd`` to the pandas source directory Tell ``conda`` to create a new environment, named ``pandas_dev``, or any name you would like for this environment by running: @@ -339,7 +339,7 @@ follow the Numpy Docstring Standard (see above), but you don't need to install this because a local copy of ``numpydoc`` is included in the *pandas* source code. -It is easiest to :ref:`create a development environment <contributing-dev_env>`, then install: +It is easiest to :ref:`create a development environment <contributing.dev_env>`, then install: :: @@ -567,7 +567,7 @@ It is also useful to run tests in your current environment. You can simply do it which would be equivalent to ``asv run --quick --show-stderr --python=same``. This will launch every test only once, display stderr from the benchmarks and use your -local ``python'' that comes from your $PATH. +local ``python`` that comes from your $PATH. Information on how to write a benchmark can be found in `*asv*'s documentation http://asv.readthedocs.org/en/latest/writing_benchmarks.html`. diff --git a/doc/source/install.rst b/doc/source/install.rst index 5c5f6bdcf0ddf..3c624a9d25a0c 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -179,7 +179,7 @@ To install pandas for Python 3 you may need to use the package ``python3-pandas` Installing from source ~~~~~~~~~~~~~~~~~~~~~~ -See the :ref:`contributing documentation <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a devevlopment environment <contributing-dev_env>` if you wish to create a *pandas* development environment. +See the :ref:`contributing documentation <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a development environment <contributing.dev_env>` if you wish to create a *pandas* development environment. Running the test suite ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/io.rst b/doc/source/io.rst index 6affbedad3ae2..ceebef187fe7f 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2075,11 +2075,11 @@ Equivalent class and function approaches to read multiple sheets: # For when Sheet1's format is identical to Sheet2 data = read_excel('path_to_file.xls', ['Sheet1','Sheet2'], index_col=None, na_values=['NA']) +.. _io.excel.specifying_sheets: + Specifying Sheets +++++++++++++++++ -.. _io.specifying_sheets: - .. note :: The second argument is ``sheetname``, not to be confused with ``ExcelFile.sheet_names`` .. note :: An ExcelFile's attribute ``sheet_names`` provides access to a list of sheets. @@ -3924,7 +3924,7 @@ For more information see the examples the SQLAlchemy `documentation <http://docs Advanced SQLAlchemy queries -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +''''''''''''''''''''''''''' You can use SQLAlchemy constructs to describe your query. diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index 150f728871ef3..2b1e77653a415 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -1768,7 +1768,6 @@ TZ aware Dtypes s_aware Both of these ``Series`` can be manipulated via the ``.dt`` accessor, see :ref:`here <basics.dt_accessors>`. -See the :ref:`docs <timeseries.dtypes>` for more details. For example, to localize and convert a naive stamp to timezone aware. diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index f9bef3d9c7f4a..a78d776403528 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -179,7 +179,7 @@ Other enhancements This method is also exposed by the lower level ``Index.get_indexer`` and ``Index.get_loc`` methods. -- The ``read_excel()`` function's :ref:`sheetname <_io.specifying_sheets>` argument now accepts a list and ``None``, to get multiple or all sheets respectively. If more than one sheet is specified, a dictionary is returned. (:issue:`9450`) +- The ``read_excel()`` function's :ref:`sheetname <io.excel.specifying_sheets>` argument now accepts a list and ``None``, to get multiple or all sheets respectively. If more than one sheet is specified, a dictionary is returned. (:issue:`9450`) .. code-block:: python diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index 79a0c48238be7..e1a58a443aa55 100755 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -97,7 +97,7 @@ values NOT in the categories, similarly to how you can reindex ANY pandas index. df2.reindex(pd.Categorical(['a','e'],categories=list('abcde'))) df2.reindex(pd.Categorical(['a','e'],categories=list('abcde'))).index -See the :ref:`documentation <advanced.categoricalindex>` for more. (:issue:`7629`, :issue:`10038`, :issue:`10039`) +See the :ref:`documentation <indexing.categoricalindex>` for more. (:issue:`7629`, :issue:`10038`, :issue:`10039`) .. _whatsnew_0161.enhancements.sample: diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 6be913e1e5f51..08b453eccd380 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -453,7 +453,7 @@ Other enhancements - Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`) -- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`) +- Enable writing Excel files in :ref:`memory <io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`) - Enable serialization of lists and dicts to strings in ``ExcelWriter`` (:issue:`8188`) @@ -967,7 +967,7 @@ Deprecations ``DataFrame.add(other, fill_value=0)`` and ``DataFrame.mul(other, fill_value=1.)`` (:issue:`10735`). - ``TimeSeries`` deprecated in favor of ``Series`` (note that this has been alias since 0.13.0), (:issue:`10890`) -- ``SparsePanel`` deprecated and will be removed in a future version (:issue:``) +- ``SparsePanel`` deprecated and will be removed in a future version (:issue:`11157`). - ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`) - Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`) - ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`)
Fixes mainly some linking errors
https://api.github.com/repos/pandas-dev/pandas/pulls/11184
2015-09-24T09:33:39Z
2015-09-24T21:58:27Z
2015-09-24T21:58:27Z
2015-09-24T21:58:27Z
DOC: XportReader not top-level API
diff --git a/doc/source/api.rst b/doc/source/api.rst index b1fe77c298d71..77c59ec70e8df 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -89,7 +89,6 @@ SAS :toctree: generated/ read_sas - XportReader SQL ~~~
@kshedden `XportReader` is not top-level API, so it was erroring in the doc build. I now removed it from api.rst (the `TextFileReader` what you get back with chunksize for read_csv is also not included), but I can also adapt it to use `.. currentmodule:: pandas.io.sas` so it builds correctly if you want.
https://api.github.com/repos/pandas-dev/pandas/pulls/11183
2015-09-24T08:54:12Z
2015-09-25T12:11:12Z
2015-09-25T12:11:12Z
2015-09-25T12:11:12Z
API: raise on header=bool in parsers
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 6be913e1e5f51..3d4d113940dec 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -907,6 +907,23 @@ Changes to ``Categorical.unique`` cat cat.unique() +Changes to ``bool`` passed as ``header`` in Parsers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In earlier versions of pandas, if a bool was passed the ``header`` argument of +``read_csv``, ``read_excel``, or ``read_html`` it was implicitly converted to +an integer, resulting in ``header=0`` for ``False`` and ``header=1`` for ``True`` +(:issue:`6113`) + +A ``bool`` input to ``header`` will now raise a ``TypeError`` + +.. code-block :: python + + In [29]: df = pd.read_csv('data.csv', header=False) + TypeError: Passing a bool to header is invalid. Use header=None for no header or + header=int or list-like of ints to specify the row(s) making up the column names + + .. _whatsnew_0170.api_breaking.other: Other API Changes diff --git a/pandas/io/common.py b/pandas/io/common.py index e13c402b454d1..b9cdd44e52555 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -194,6 +194,12 @@ def _expand_user(filepath_or_buffer): return os.path.expanduser(filepath_or_buffer) return filepath_or_buffer +def _validate_header_arg(header): + if isinstance(header, bool): + raise TypeError("Passing a bool to header is invalid. " + "Use header=None for no header or " + "header=int or list-like of ints to specify " + "the row(s) making up the column names") def get_filepath_or_buffer(filepath_or_buffer, encoding=None, compression=None): diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 5767af1ad3862..d90a8b8e90a93 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -11,7 +11,7 @@ from pandas.core.frame import DataFrame from pandas.io.parsers import TextParser -from pandas.io.common import _is_url, _urlopen +from pandas.io.common import _is_url, _urlopen, _validate_header_arg from pandas.tseries.period import Period from pandas import json from pandas.compat import (map, zip, reduce, range, lrange, u, add_metaclass, @@ -217,6 +217,7 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0, if skipfooter is not None: skip_footer = skipfooter + _validate_header_arg(header) if has_index_names is not None: warn("\nThe has_index_names argument is deprecated; index names " "will be automatically inferred based on index_col.\n" diff --git a/pandas/io/html.py b/pandas/io/html.py index cb2ee7b1c1e3f..f175702dedabc 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -13,7 +13,7 @@ import numpy as np -from pandas.io.common import _is_url, urlopen, parse_url +from pandas.io.common import _is_url, urlopen, parse_url, _validate_header_arg from pandas.io.parsers import TextParser from pandas.compat import (lrange, lmap, u, string_types, iteritems, raise_with_traceback, binary_type) @@ -861,5 +861,6 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, if isinstance(skiprows, numbers.Integral) and skiprows < 0: raise ValueError('cannot skip rows starting from the end of the ' 'data (you passed a negative value)') + _validate_header_arg(header) return _parse(flavor, io, match, header, index_col, skiprows, parse_dates, tupleize_cols, thousands, attrs, encoding) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 15e11193fd1b7..8ac1aed9d9af7 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -17,7 +17,7 @@ from pandas.core.common import AbstractMethodError from pandas.core.config import get_option from pandas.io.date_converters import generic_parser -from pandas.io.common import get_filepath_or_buffer +from pandas.io.common import get_filepath_or_buffer, _validate_header_arg from pandas.tseries import tools from pandas.util.decorators import Appender @@ -673,6 +673,8 @@ def _clean_options(self, options, engine): # really delete this one keep_default_na = result.pop('keep_default_na') + _validate_header_arg(options['header']) + if index_col is True: raise ValueError("The value of index_col couldn't be 'True'") if _is_index_col(index_col): diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 657789fe8ce9b..e20703398b5f6 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -384,6 +384,8 @@ def test_read_excel_blank_with_header(self): tm.assert_frame_equal(actual, expected) + + class XlrdTests(ReadingTestsBase): """ This is the base class for the xlrd tests, and 3 different file formats @@ -641,7 +643,12 @@ def test_excel_oldindex_format(self): has_index_names=False) tm.assert_frame_equal(actual, expected, check_names=False) - + def test_read_excel_bool_header_arg(self): + #GH 6114 + for arg in [True, False]: + with tm.assertRaises(TypeError): + pd.read_excel(os.path.join(self.dirpath, 'test1' + self.ext), + header=arg) class XlsReaderTests(XlrdTests, tm.TestCase): ext = '.xls' diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py index c00517ab92f96..5c8c15c7c2ae0 100644 --- a/pandas/io/tests/test_html.py +++ b/pandas/io/tests/test_html.py @@ -637,6 +637,11 @@ def test_wikipedia_states_table(self): result = self.read_html(data, 'Arizona', header=1)[0] nose.tools.assert_equal(result['sq mi'].dtype, np.dtype('float64')) + def test_bool_header_arg(self): + #GH 6114 + for arg in [True, False]: + with tm.assertRaises(TypeError): + read_html(self.spam_data, header=arg) def _lang_enc(filename): return os.path.splitext(os.path.basename(filename))[0].split('_') diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index c9ae2f6029530..799c573b13c8b 100755 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -4117,6 +4117,22 @@ def test_single_char_leading_whitespace(self): skipinitialspace=True) tm.assert_frame_equal(result, expected) + def test_bool_header_arg(self): + # GH 6114 + data = """\ +MyColumn + a + b + a + b""" + for arg in [True, False]: + with tm.assertRaises(TypeError): + pd.read_csv(StringIO(data), header=arg) + with tm.assertRaises(TypeError): + pd.read_table(StringIO(data), header=arg) + with tm.assertRaises(TypeError): + pd.read_fwf(StringIO(data), header=arg) + class TestMiscellaneous(tm.TestCase): # for tests that don't fit into any of the other classes, e.g. those that
closes #6113 Passing `header=True|False` to `read_csv` (and brethren), `read_excel`, and `read_html` will now raise a `TypeError`, rather than being coerced to an int. I had thought about converting `False` to `None` but thought that could break someone's code in a very subtle way if they were somehow depending on the old behavior. But happy to change that if it seems better. If you want to push this in for 0.17 I can add a doc-note or this could easily wait.
https://api.github.com/repos/pandas-dev/pandas/pulls/11182
2015-09-24T00:13:08Z
2015-09-24T11:32:00Z
2015-09-24T11:32:00Z
2015-09-26T15:17:44Z
Update 10min.rst
diff --git a/doc/source/10min.rst b/doc/source/10min.rst index 359ec76533520..91e607757e4f1 100644 --- a/doc/source/10min.rst +++ b/doc/source/10min.rst @@ -30,7 +30,7 @@ This is a short introduction to pandas, geared mainly for new users. You can see more complex recipes in the :ref:`Cookbook<cookbook>` -Customarily, we import as follows +Customarily, we import as follows: .. ipython:: python
https://api.github.com/repos/pandas-dev/pandas/pulls/11177
2015-09-23T15:02:30Z
2015-09-24T01:14:58Z
2015-09-24T01:14:58Z
2015-09-24T01:15:01Z
DOC: header=None in SAS docs
diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst index fd42c97c9cbc0..2b3a1b927cbbf 100644 --- a/doc/source/comparison_with_sas.rst +++ b/doc/source/comparison_with_sas.rst @@ -142,10 +142,10 @@ and did not have column names, the pandas command would be: .. code-block:: python - tips = pd.read_csv('tips.csv', sep='\t', header=False) + tips = pd.read_csv('tips.csv', sep='\t', header=None) # alternatively, read_table is an alias to read_csv with tab delimiter - tips = pd.read_table('tips.csv', header=False) + tips = pd.read_table('tips.csv', header=None) In addition to text/csv, pandas supports a variety of other data formats such as Excel, HDF5, and SQL databases. These are all read via a ``pd.read_*``
Fixed a typo where I had `header=False` Side note, it might be nice to change the actual behavior, not the first time it's tripped me up. I guess there already is an issue, #6113
https://api.github.com/repos/pandas-dev/pandas/pulls/11176
2015-09-23T11:35:04Z
2015-09-23T11:53:01Z
2015-09-23T11:53:01Z
2015-09-23T23:19:53Z
ENH: Restore original convert_objects and add _convert
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index 14d712c822bdb..e11c612a510db 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -1711,36 +1711,26 @@ then the more *general* one will be used as the result of the operation. object conversion ~~~~~~~~~~~~~~~~~ -.. note:: - - The syntax of :meth:`~DataFrame.convert_objects` changed in 0.17.0. See - :ref:`API changes <whatsnew_0170.api_breaking.convert_objects>` - for more details. - -:meth:`~DataFrame.convert_objects` is a method that converts columns from -the ``object`` dtype to datetimes, timedeltas or floats. For example, to -attempt conversion of object data that are *number like*, e.g. could be a -string that represents a number, pass ``numeric=True``. By default, this will -attempt a soft conversion and so will only succeed if the entire column is -convertible. To force the conversion, add the keyword argument ``coerce=True``. -This will force strings and number-like objects to be numbers if -possible, and other values will be set to ``np.nan``. +:meth:`~DataFrame.convert_objects` is a method to try to force conversion of types from the ``object`` dtype to other types. +To force conversion of specific types that are *number like*, e.g. could be a string that represents a number, +pass ``convert_numeric=True``. This will force strings and numbers alike to be numbers if possible, otherwise +they will be set to ``np.nan``. .. ipython:: python df3['D'] = '1.' df3['E'] = '1' - df3.convert_objects(numeric=True).dtypes + df3.convert_objects(convert_numeric=True).dtypes # same, but specific dtype conversion df3['D'] = df3['D'].astype('float16') df3['E'] = df3['E'].astype('int32') df3.dtypes -To force conversion to ``datetime64[ns]``, pass ``datetime=True`` and ``coerce=True``. +To force conversion to ``datetime64[ns]``, pass ``convert_dates='coerce'``. This will convert any datetime-like object to dates, forcing other values to ``NaT``. This might be useful if you are reading in data which is mostly dates, -but occasionally contains non-dates that you wish to represent as missing. +but occasionally has non-dates intermixed and you want to represent as missing. .. ipython:: python @@ -1749,15 +1739,10 @@ but occasionally contains non-dates that you wish to represent as missing. 'foo', 1.0, 1, pd.Timestamp('20010104'), '20010105'], dtype='O') s - s.convert_objects(datetime=True, coerce=True) + s.convert_objects(convert_dates='coerce') -Without passing ``coerce=True``, :meth:`~DataFrame.convert_objects` will attempt -*soft* conversion of any *object* dtypes, meaning that if all +In addition, :meth:`~DataFrame.convert_objects` will attempt the *soft* conversion of any *object* dtypes, meaning that if all the objects in a Series are of the same type, the Series will have that dtype. -Note that setting ``coerce=True`` does not *convert* arbitrary types to either -``datetime64[ns]`` or ``timedelta64[ns]``. For example, a series containing string -dates will not be converted to a series of datetimes. To convert between types, -see :ref:`converting to timestamps <timeseries.converting>`. gotchas ~~~~~~~ diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 61c34fc071282..79ca3f369d2ad 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -640,71 +640,6 @@ New Behavior: Timestamp.now() Timestamp.now() + offsets.DateOffset(years=1) -.. _whatsnew_0170.api_breaking.convert_objects: - -Changes to convert_objects -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -``DataFrame.convert_objects`` keyword arguments have been shortened. (:issue:`10265`) - -===================== ============= -Previous Replacement -===================== ============= -``convert_dates`` ``datetime`` -``convert_numeric`` ``numeric`` -``convert_timedelta`` ``timedelta`` -===================== ============= - -Coercing types with ``DataFrame.convert_objects`` is now implemented using the -keyword argument ``coerce=True``. Previously types were coerced by setting a -keyword argument to ``'coerce'`` instead of ``True``, as in ``convert_dates='coerce'``. - -.. ipython:: python - - df = pd.DataFrame({'i': ['1','2'], - 'f': ['apple', '4.2'], - 's': ['apple','banana']}) - df - -The old usage of ``DataFrame.convert_objects`` used ``'coerce'`` along with the -type. - -.. code-block:: python - - In [2]: df.convert_objects(convert_numeric='coerce') - -Now the ``coerce`` keyword must be explicitly used. - -.. ipython:: python - - df.convert_objects(numeric=True, coerce=True) - -In earlier versions of pandas, ``DataFrame.convert_objects`` would not coerce -numeric types when there were no values convertible to a numeric type. This returns -the original DataFrame with no conversion. - -.. code-block:: python - - In [1]: df = pd.DataFrame({'s': ['a','b']}) - In [2]: df.convert_objects(convert_numeric='coerce') - Out[2]: - s - 0 a - 1 b - -The new behavior will convert all non-number-like strings to ``NaN``, -when ``coerce=True`` is passed explicity. - -.. ipython:: python - - pd.DataFrame({'s': ['a','b']}) - df.convert_objects(numeric=True, coerce=True) - -In earlier versions of pandas, the default behavior was to try and convert -datetimes and timestamps. The new default is for ``DataFrame.convert_objects`` -to do nothing, and so it is necessary to pass at least one conversion target -in the method call. - Changes to Index Comparisons ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -992,6 +927,7 @@ Deprecations - ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`) - Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`) - ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`) +- ``DataFrame.convert_objects`` has been deprecated in favor of type-specific function ``pd.to_datetime``, ``pd.to_timestamp`` and ``pd.to_numeric`` (:issue:`11133`). .. _whatsnew_0170.prior_deprecations: @@ -1187,3 +1123,5 @@ Bug Fixes - Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`) - Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`) - Bug in ``.groupby`` when number of keys to group by is same as length of index (:issue:`11185`) +- Bug in ``convert_objects`` where converted values might not be returned if all null and ``coerce`` (:issue:`9589`) +- Bug in ``convert_objects`` where ``copy`` keyword was not respected (:issue:`9589`) diff --git a/pandas/__init__.py b/pandas/__init__.py index dbc697410da80..68a90394cacf1 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -52,6 +52,7 @@ from pandas.tools.pivot import pivot_table, crosstab from pandas.tools.plotting import scatter_matrix, plot_params from pandas.tools.tile import cut, qcut +from pandas.tools.util import to_numeric from pandas.core.reshape import melt from pandas.util.print_versions import show_versions import pandas.util.testing diff --git a/pandas/core/common.py b/pandas/core/common.py index 77e58b4f56c32..2d403f904a446 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -1858,71 +1858,6 @@ def _maybe_box_datetimelike(value): _values_from_object = lib.values_from_object -def _possibly_convert_objects(values, - datetime=True, - numeric=True, - timedelta=True, - coerce=False, - copy=True): - """ if we have an object dtype, try to coerce dates and/or numbers """ - - conversion_count = sum((datetime, numeric, timedelta)) - if conversion_count == 0: - import warnings - warnings.warn('Must explicitly pass type for conversion. Defaulting to ' - 'pre-0.17 behavior where datetime=True, numeric=True, ' - 'timedelta=True and coerce=False', DeprecationWarning) - datetime = numeric = timedelta = True - coerce = False - - if isinstance(values, (list, tuple)): - # List or scalar - values = np.array(values, dtype=np.object_) - elif not hasattr(values, 'dtype'): - values = np.array([values], dtype=np.object_) - elif not is_object_dtype(values.dtype): - # If not object, do not attempt conversion - values = values.copy() if copy else values - return values - - # If 1 flag is coerce, ensure 2 others are False - if coerce: - if conversion_count > 1: - raise ValueError("Only one of 'datetime', 'numeric' or " - "'timedelta' can be True when when coerce=True.") - - # Immediate return if coerce - if datetime: - return pd.to_datetime(values, errors='coerce', box=False) - elif timedelta: - return pd.to_timedelta(values, errors='coerce', box=False) - elif numeric: - return lib.maybe_convert_numeric(values, set(), coerce_numeric=True) - - # Soft conversions - if datetime: - values = lib.maybe_convert_objects(values, - convert_datetime=datetime) - - if timedelta and is_object_dtype(values.dtype): - # Object check to ensure only run if previous did not convert - values = lib.maybe_convert_objects(values, - convert_timedelta=timedelta) - - if numeric and is_object_dtype(values.dtype): - try: - converted = lib.maybe_convert_numeric(values, - set(), - coerce_numeric=True) - # If all NaNs, then do not-alter - values = converted if not isnull(converted).all() else values - values = values.copy() if copy else values - except: - pass - - return values - - def _possibly_castable(arr): # return False to force a non-fastpath diff --git a/pandas/core/convert.py b/pandas/core/convert.py new file mode 100644 index 0000000000000..3745d4f5f6914 --- /dev/null +++ b/pandas/core/convert.py @@ -0,0 +1,132 @@ +""" +Functions for converting object to other types +""" + +import numpy as np + +import pandas as pd +from pandas.core.common import (_possibly_cast_to_datetime, is_object_dtype, + isnull) +import pandas.lib as lib + +# TODO: Remove in 0.18 or 2017, which ever is sooner +def _possibly_convert_objects(values, convert_dates=True, + convert_numeric=True, + convert_timedeltas=True, + copy=True): + """ if we have an object dtype, try to coerce dates and/or numbers """ + + # if we have passed in a list or scalar + if isinstance(values, (list, tuple)): + values = np.array(values, dtype=np.object_) + if not hasattr(values, 'dtype'): + values = np.array([values], dtype=np.object_) + + # convert dates + if convert_dates and values.dtype == np.object_: + + # we take an aggressive stance and convert to datetime64[ns] + if convert_dates == 'coerce': + new_values = _possibly_cast_to_datetime( + values, 'M8[ns]', errors='coerce') + + # if we are all nans then leave me alone + if not isnull(new_values).all(): + values = new_values + + else: + values = lib.maybe_convert_objects( + values, convert_datetime=convert_dates) + + # convert timedeltas + if convert_timedeltas and values.dtype == np.object_: + + if convert_timedeltas == 'coerce': + from pandas.tseries.timedeltas import to_timedelta + new_values = to_timedelta(values, coerce=True) + + # if we are all nans then leave me alone + if not isnull(new_values).all(): + values = new_values + + else: + values = lib.maybe_convert_objects( + values, convert_timedelta=convert_timedeltas) + + # convert to numeric + if values.dtype == np.object_: + if convert_numeric: + try: + new_values = lib.maybe_convert_numeric( + values, set(), coerce_numeric=True) + + # if we are all nans then leave me alone + if not isnull(new_values).all(): + values = new_values + + except: + pass + else: + # soft-conversion + values = lib.maybe_convert_objects(values) + + values = values.copy() if copy else values + + return values + + +def _soft_convert_objects(values, datetime=True, numeric=True, timedelta=True, + coerce=False, copy=True): + """ if we have an object dtype, try to coerce dates and/or numbers """ + + conversion_count = sum((datetime, numeric, timedelta)) + if conversion_count == 0: + raise ValueError('At least one of datetime, numeric or timedelta must ' + 'be True.') + elif conversion_count > 1 and coerce: + raise ValueError("Only one of 'datetime', 'numeric' or " + "'timedelta' can be True when when coerce=True.") + + + if isinstance(values, (list, tuple)): + # List or scalar + values = np.array(values, dtype=np.object_) + elif not hasattr(values, 'dtype'): + values = np.array([values], dtype=np.object_) + elif not is_object_dtype(values.dtype): + # If not object, do not attempt conversion + values = values.copy() if copy else values + return values + + # If 1 flag is coerce, ensure 2 others are False + if coerce: + # Immediate return if coerce + if datetime: + return pd.to_datetime(values, errors='coerce', box=False) + elif timedelta: + return pd.to_timedelta(values, errors='coerce', box=False) + elif numeric: + return pd.to_numeric(values, errors='coerce') + + # Soft conversions + if datetime: + values = lib.maybe_convert_objects(values, + convert_datetime=datetime) + + if timedelta and is_object_dtype(values.dtype): + # Object check to ensure only run if previous did not convert + values = lib.maybe_convert_objects(values, + convert_timedelta=timedelta) + + if numeric and is_object_dtype(values.dtype): + try: + converted = lib.maybe_convert_numeric(values, + set(), + coerce_numeric=True) + # If all NaNs, then do not-alter + values = converted if not isnull(converted).all() else values + values = values.copy() if copy else values + except: + pass + + return values diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9e1eda4714734..08dfe315c4cb2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3543,9 +3543,8 @@ def combine(self, other, func, fill_value=None, overwrite=True): # convert_objects just in case return self._constructor(result, index=new_index, - columns=new_columns).convert_objects( - datetime=True, - copy=False) + columns=new_columns)._convert(datetime=True, + copy=False) def combine_first(self, other): """ @@ -4026,9 +4025,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True): if axis == 1: result = result.T - result = result.convert_objects(datetime=True, - timedelta=True, - copy=False) + result = result._convert(datetime=True, timedelta=True, copy=False) else: @@ -4158,7 +4155,7 @@ def append(self, other, ignore_index=False, verify_integrity=False): other = DataFrame(other.values.reshape((1, len(other))), index=index, columns=combined_columns) - other = other.convert_objects(datetime=True, timedelta=True) + other = other._convert(datetime=True, timedelta=True) if not self.columns.equals(combined_columns): self = self.reindex(columns=combined_columns) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6aec297c31d2b..3473dd0f7cd88 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2534,11 +2534,8 @@ def copy(self, deep=True): data = self._data.copy(deep=deep) return self._constructor(data).__finalize__(self) - @deprecate_kwarg(old_arg_name='convert_dates', new_arg_name='datetime') - @deprecate_kwarg(old_arg_name='convert_numeric', new_arg_name='numeric') - @deprecate_kwarg(old_arg_name='convert_timedeltas', new_arg_name='timedelta') - def convert_objects(self, datetime=False, numeric=False, - timedelta=False, coerce=False, copy=True): + def _convert(self, datetime=False, numeric=False, timedelta=False, + coerce=False, copy=True): """ Attempt to infer better dtype for object columns @@ -2563,31 +2560,48 @@ def convert_objects(self, datetime=False, numeric=False, ------- converted : same as input object """ + return self._constructor( + self._data.convert(datetime=datetime, + numeric=numeric, + timedelta=timedelta, + coerce=coerce, + copy=copy)).__finalize__(self) + + # TODO: Remove in 0.18 or 2017, which ever is sooner + def convert_objects(self, convert_dates=True, convert_numeric=False, + convert_timedeltas=True, copy=True): + """ + Attempt to infer better dtype for object columns + + Parameters + ---------- + convert_dates : boolean, default True + If True, convert to date where possible. If 'coerce', force + conversion, with unconvertible values becoming NaT. + convert_numeric : boolean, default False + If True, attempt to coerce to numbers (including strings), with + unconvertible values becoming NaN. + convert_timedeltas : boolean, default True + If True, convert to timedelta where possible. If 'coerce', force + conversion, with unconvertible values becoming NaT. + copy : boolean, default True + If True, return a copy even if no copy is necessary (e.g. no + conversion was done). Note: This is meant for internal use, and + should not be confused with inplace. - # Deprecation code to handle usage change - issue_warning = False - if datetime == 'coerce': - datetime = coerce = True - numeric = timedelta = False - issue_warning = True - elif numeric == 'coerce': - numeric = coerce = True - datetime = timedelta = False - issue_warning = True - elif timedelta == 'coerce': - timedelta = coerce = True - datetime = numeric = False - issue_warning = True - if issue_warning: - warnings.warn("The use of 'coerce' as an input is deprecated. " - "Instead set coerce=True.", - FutureWarning) + Returns + ------- + converted : same as input object + """ + from warnings import warn + warn("convert_objects is deprecated. Use the data-type specific " + "converters pd.to_datetime, pd.to_timestamp and pd.to_numeric.", + FutureWarning, stacklevel=2) return self._constructor( - self._data.convert(datetime=datetime, - numeric=numeric, - timedelta=timedelta, - coerce=coerce, + self._data.convert(convert_dates=convert_dates, + convert_numeric=convert_numeric, + convert_timedeltas=convert_timedeltas, copy=copy)).__finalize__(self) #---------------------------------------------------------------------- diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index e837445e9e348..40f078a1bbcfe 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -112,7 +112,7 @@ def f(self): except Exception: result = self.aggregate(lambda x: npfunc(x, axis=self.axis)) if _convert: - result = result.convert_objects(datetime=True) + result = result._convert(datetime=True) return result f.__doc__ = "Compute %s of group values" % name @@ -2882,7 +2882,7 @@ def aggregate(self, arg, *args, **kwargs): self._insert_inaxis_grouper_inplace(result) result.index = np.arange(len(result)) - return result.convert_objects(datetime=True) + return result._convert(datetime=True) def _aggregate_multiple_funcs(self, arg): from pandas.tools.merge import concat @@ -3123,14 +3123,14 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): # as we are stacking can easily have object dtypes here if (self._selected_obj.ndim == 2 and self._selected_obj.dtypes.isin(_DATELIKE_DTYPES).any()): - result = result.convert_objects(numeric=True) + result = result._convert(numeric=True) date_cols = self._selected_obj.select_dtypes( include=list(_DATELIKE_DTYPES)).columns result[date_cols] = (result[date_cols] - .convert_objects(datetime=True, + ._convert(datetime=True, coerce=True)) else: - result = result.convert_objects(datetime=True) + result = result._convert(datetime=True) return self._reindex_output(result) @@ -3138,7 +3138,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): # only coerce dates if we find at least 1 datetime coerce = True if any([ isinstance(v,Timestamp) for v in values ]) else False return (Series(values, index=key_index) - .convert_objects(datetime=True, + ._convert(datetime=True, coerce=coerce)) else: @@ -3243,7 +3243,7 @@ def transform(self, func, *args, **kwargs): results = self._try_cast(results, obj[result.columns]) return (DataFrame(results,columns=result.columns,index=obj.index) - .convert_objects(datetime=True)) + ._convert(datetime=True)) def _define_paths(self, func, *args, **kwargs): if isinstance(func, compat.string_types): @@ -3436,7 +3436,7 @@ def _wrap_aggregated_output(self, output, names=None): if self.axis == 1: result = result.T - return self._reindex_output(result).convert_objects(datetime=True) + return self._reindex_output(result)._convert(datetime=True) def _wrap_agged_blocks(self, items, blocks): if not self.as_index: @@ -3454,7 +3454,7 @@ def _wrap_agged_blocks(self, items, blocks): if self.axis == 1: result = result.T - return self._reindex_output(result).convert_objects(datetime=True) + return self._reindex_output(result)._convert(datetime=True) def _reindex_output(self, result): """ diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 97b54d4ef6ebe..4790f3aa3841e 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -25,6 +25,7 @@ from pandas.core.categorical import Categorical, maybe_to_categorical from pandas.tseries.index import DatetimeIndex import pandas.core.common as com +import pandas.core.convert as convert from pandas.sparse.array import _maybe_to_sparse, SparseArray import pandas.lib as lib import pandas.tslib as tslib @@ -1517,14 +1518,35 @@ def is_bool(self): """ return lib.is_bool_array(self.values.ravel()) - def convert(self, datetime=True, numeric=True, timedelta=True, coerce=False, - copy=True, by_item=True): + # TODO: Refactor when convert_objects is removed since there will be 1 path + def convert(self, *args, **kwargs): """ attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we ARE an ObjectBlock!!!!! can return multiple blocks! """ + if args: + raise NotImplementedError + by_item = True if 'by_item' not in kwargs else kwargs['by_item'] + + new_inputs = ['coerce','datetime','numeric','timedelta'] + new_style = False + for kw in new_inputs: + new_style |= kw in kwargs + + if new_style: + fn = convert._soft_convert_objects + fn_inputs = new_inputs + else: + fn = convert._possibly_convert_objects + fn_inputs = ['convert_dates','convert_numeric','convert_timedeltas'] + fn_inputs += ['copy'] + + fn_kwargs = {} + for key in fn_inputs: + if key in kwargs: + fn_kwargs[key] = kwargs[key] # attempt to create new type blocks blocks = [] @@ -1533,30 +1555,14 @@ def convert(self, datetime=True, numeric=True, timedelta=True, coerce=False, for i, rl in enumerate(self.mgr_locs): values = self.iget(i) - values = com._possibly_convert_objects( - values.ravel(), - datetime=datetime, - numeric=numeric, - timedelta=timedelta, - coerce=coerce, - copy=copy - ).reshape(values.shape) + values = fn(values.ravel(), **fn_kwargs).reshape(values.shape) values = _block_shape(values, ndim=self.ndim) - newb = self.make_block(values, - placement=[rl]) + newb = make_block(values, ndim=self.ndim, placement=[rl]) blocks.append(newb) else: - - values = com._possibly_convert_objects( - self.values.ravel(), - datetime=datetime, - numeric=numeric, - timedelta=timedelta, - coerce=coerce, - copy=copy - ).reshape(self.values.shape) - blocks.append(self.make_block(values)) + values = fn(self.values.ravel(), **fn_kwargs).reshape(self.values.shape) + blocks.append(make_block(values, ndim=self.ndim, placement=self.mgr_locs)) return blocks @@ -1597,8 +1603,7 @@ def _maybe_downcast(self, blocks, downcast=None): # split and convert the blocks result_blocks = [] for blk in blocks: - result_blocks.extend(blk.convert(datetime=True, - numeric=False)) + result_blocks.extend(blk.convert(datetime=True, numeric=False)) return result_blocks def _can_hold_element(self, element): diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py index 5c8c15c7c2ae0..141533a131e42 100644 --- a/pandas/io/tests/test_html.py +++ b/pandas/io/tests/test_html.py @@ -527,10 +527,10 @@ def try_remove_ws(x): 'Hamilton Bank, NA', 'The Citizens Savings Bank'] dfnew = df.applymap(try_remove_ws).replace(old, new) gtnew = ground_truth.applymap(try_remove_ws) - converted = dfnew.convert_objects(datetime=True, numeric=True) + converted = dfnew._convert(datetime=True, numeric=True) date_cols = ['Closing Date','Updated Date'] - converted[date_cols] = converted[date_cols].convert_objects(datetime=True, - coerce=True) + converted[date_cols] = converted[date_cols]._convert(datetime=True, + coerce=True) tm.assert_frame_equal(converted,gtnew) @slow diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index adef470965f21..df2a659100305 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -408,7 +408,7 @@ def test_repr(self): df['datetime1'] = datetime.datetime(2001,1,2,0,0) df['datetime2'] = datetime.datetime(2001,1,3,0,0) df.ix[3:6,['obj1']] = np.nan - df = df.consolidate().convert_objects(datetime=True) + df = df.consolidate()._convert(datetime=True) warnings.filterwarnings('ignore', category=PerformanceWarning) store['df'] = df @@ -736,7 +736,7 @@ def test_put_mixed_type(self): df['datetime1'] = datetime.datetime(2001, 1, 2, 0, 0) df['datetime2'] = datetime.datetime(2001, 1, 3, 0, 0) df.ix[3:6, ['obj1']] = np.nan - df = df.consolidate().convert_objects(datetime=True) + df = df.consolidate()._convert(datetime=True) with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df') @@ -1456,7 +1456,7 @@ def check_col(key,name,size): df_dc.ix[7:9, 'string'] = 'bar' df_dc['string2'] = 'cool' df_dc['datetime'] = Timestamp('20010102') - df_dc = df_dc.convert_objects(datetime=True) + df_dc = df_dc._convert(datetime=True) df_dc.ix[3:5, ['A', 'B', 'datetime']] = np.nan _maybe_remove(store, 'df_dc') @@ -1918,7 +1918,7 @@ def test_table_mixed_dtypes(self): df['datetime1'] = datetime.datetime(2001, 1, 2, 0, 0) df['datetime2'] = datetime.datetime(2001, 1, 3, 0, 0) df.ix[3:6, ['obj1']] = np.nan - df = df.consolidate().convert_objects(datetime=True) + df = df.consolidate()._convert(datetime=True) with ensure_clean_store(self.path) as store: store.append('df1_mixed', df) @@ -1974,7 +1974,7 @@ def test_unimplemented_dtypes_table_columns(self): df['obj1'] = 'foo' df['obj2'] = 'bar' df['datetime1'] = datetime.date(2001, 1, 2) - df = df.consolidate().convert_objects(datetime=True) + df = df.consolidate()._convert(datetime=True) with ensure_clean_store(self.path) as store: # this fails because we have a date in the object block...... diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index 8505150932c90..aff9cd6c558e2 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -417,7 +417,7 @@ def test_read_write_reread_dta14(self): expected = self.read_csv(self.csv14) cols = ['byte_', 'int_', 'long_', 'float_', 'double_'] for col in cols: - expected[col] = expected[col].convert_objects(datetime=True, numeric=True) + expected[col] = expected[col]._convert(datetime=True, numeric=True) expected['float_'] = expected['float_'].astype(np.float32) expected['date_td'] = pd.to_datetime(expected['date_td'], errors='coerce') diff --git a/pandas/io/wb.py b/pandas/io/wb.py index 99b14be0b0b6b..e617a01b73bfd 100644 --- a/pandas/io/wb.py +++ b/pandas/io/wb.py @@ -165,7 +165,7 @@ def download(country=['MX', 'CA', 'US'], indicator=['NY.GDP.MKTP.CD', 'NY.GNS.IC out = reduce(lambda x, y: x.merge(y, how='outer'), data) out = out.drop('iso_code', axis=1) out = out.set_index(['country', 'year']) - out = out.convert_objects(datetime=True, numeric=True) + out = out._convert(datetime=True, numeric=True) return out else: msg = "No indicators returned data." diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index b234773359f8c..c488d22da7dfe 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -13,6 +13,7 @@ from pandas.compat import range, long, lrange, lmap, u from pandas.core.common import notnull, isnull, array_equivalent import pandas.core.common as com +import pandas.core.convert as convert import pandas.util.testing as tm import pandas.core.config as cf @@ -1051,33 +1052,32 @@ def test_maybe_convert_string_to_array(self): tm.assert_numpy_array_equal(result, np.array(['x', 2], dtype=object)) self.assertTrue(result.dtype == object) - -def test_dict_compat(): - data_datetime64 = {np.datetime64('1990-03-15'): 1, - np.datetime64('2015-03-15'): 2} - data_unchanged = {1: 2, 3: 4, 5: 6} - expected = {Timestamp('1990-3-15'): 1, Timestamp('2015-03-15'): 2} - assert(com._dict_compat(data_datetime64) == expected) - assert(com._dict_compat(expected) == expected) - assert(com._dict_compat(data_unchanged) == data_unchanged) - - def test_possibly_convert_objects_copy(): values = np.array([1, 2]) - out = com._possibly_convert_objects(values, copy=False) + out = convert._possibly_convert_objects(values, copy=False) assert_true(values is out) - out = com._possibly_convert_objects(values, copy=True) + out = convert._possibly_convert_objects(values, copy=True) assert_true(values is not out) values = np.array(['apply','banana']) - out = com._possibly_convert_objects(values, copy=False) + out = convert._possibly_convert_objects(values, copy=False) assert_true(values is out) - out = com._possibly_convert_objects(values, copy=True) + out = convert._possibly_convert_objects(values, copy=True) assert_true(values is not out) - + + +def test_dict_compat(): + data_datetime64 = {np.datetime64('1990-03-15'): 1, + np.datetime64('2015-03-15'): 2} + data_unchanged = {1: 2, 3: 4, 5: 6} + expected = {Timestamp('1990-3-15'): 1, Timestamp('2015-03-15'): 2} + assert(com._dict_compat(data_datetime64) == expected) + assert(com._dict_compat(expected) == expected) + assert(com._dict_compat(data_unchanged) == data_unchanged) + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index c963222cf4ad9..5acc858840dfa 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -6805,7 +6805,7 @@ def make_dtnat_arr(n,nnat=None): with ensure_clean('.csv') as pth: df=DataFrame(dict(a=s1,b=s2)) df.to_csv(pth,chunksize=chunksize) - recons = DataFrame.from_csv(pth).convert_objects(datetime=True, + recons = DataFrame.from_csv(pth)._convert(datetime=True, coerce=True) assert_frame_equal(df, recons,check_names=False,check_less_precise=True) @@ -7516,7 +7516,7 @@ def test_dtypes(self): def test_convert_objects(self): oops = self.mixed_frame.T.T - converted = oops.convert_objects(datetime=True) + converted = oops._convert(datetime=True) assert_frame_equal(converted, self.mixed_frame) self.assertEqual(converted['A'].dtype, np.float64) @@ -7529,8 +7529,7 @@ def test_convert_objects(self): self.mixed_frame['J'] = '1.' self.mixed_frame['K'] = '1' self.mixed_frame.ix[0:5,['J','K']] = 'garbled' - converted = self.mixed_frame.convert_objects(datetime=True, - numeric=True) + converted = self.mixed_frame._convert(datetime=True, numeric=True) self.assertEqual(converted['H'].dtype, 'float64') self.assertEqual(converted['I'].dtype, 'int64') self.assertEqual(converted['J'].dtype, 'float64') @@ -7552,14 +7551,14 @@ def test_convert_objects(self): # mixed in a single column df = DataFrame(dict(s = Series([1, 'na', 3 ,4]))) - result = df.convert_objects(datetime=True, numeric=True) + result = df._convert(datetime=True, numeric=True) expected = DataFrame(dict(s = Series([1, np.nan, 3 ,4]))) assert_frame_equal(result, expected) def test_convert_objects_no_conversion(self): mixed1 = DataFrame( {'a': [1, 2, 3], 'b': [4.0, 5, 6], 'c': ['x', 'y', 'z']}) - mixed2 = mixed1.convert_objects(datetime=True) + mixed2 = mixed1._convert(datetime=True) assert_frame_equal(mixed1, mixed2) def test_append_series_dict(self): @@ -11551,7 +11550,7 @@ def test_apply_convert_objects(self): 'F': np.random.randn(11)}) result = data.apply(lambda x: x, axis=1) - assert_frame_equal(result.convert_objects(datetime=True), data) + assert_frame_equal(result._convert(datetime=True), data) def test_apply_attach_name(self): result = self.frame.apply(lambda x: x.name) diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 1e707264edebe..35467c6abb9b4 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -3138,8 +3138,7 @@ def test_astype_assignment(self): assert_frame_equal(df,expected) df = df_orig.copy() - df.iloc[:,0:2] = df.iloc[:,0:2].convert_objects(datetime=True, - numeric=True) + df.iloc[:,0:2] = df.iloc[:,0:2]._convert(datetime=True, numeric=True) expected = DataFrame([[1,2,'3','.4',5,6.,'foo']],columns=list('ABCDEFG')) assert_frame_equal(df,expected) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index bd27d11ef14c1..0dad55a9133b6 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1145,7 +1145,7 @@ def test_convert_objects(self): # GH 4937 p = Panel(dict(A = dict(a = ['1','1.0']))) expected = Panel(dict(A = dict(a = [1,1.0]))) - result = p.convert_objects(numeric=True, coerce=True) + result = p._convert(numeric=True, coerce=True) assert_panel_equal(result, expected) def test_dtypes(self): diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index a6d7e63656d68..79de22b507e2a 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -6449,21 +6449,138 @@ def test_apply_dont_convert_dtype(self): result = s.apply(f, convert_dtype=False) self.assertEqual(result.dtype, object) - # GH 10265 def test_convert_objects(self): + + s = Series([1., 2, 3], index=['a', 'b', 'c']) + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates=False, convert_numeric=True) + assert_series_equal(result, s) + + # force numeric conversion + r = s.copy().astype('O') + r['a'] = '1' + with tm.assert_produces_warning(FutureWarning): + result = r.convert_objects(convert_dates=False, convert_numeric=True) + assert_series_equal(result, s) + + r = s.copy().astype('O') + r['a'] = '1.' + with tm.assert_produces_warning(FutureWarning): + result = r.convert_objects(convert_dates=False, convert_numeric=True) + assert_series_equal(result, s) + + r = s.copy().astype('O') + r['a'] = 'garbled' + expected = s.copy() + expected['a'] = np.nan + with tm.assert_produces_warning(FutureWarning): + result = r.convert_objects(convert_dates=False, convert_numeric=True) + assert_series_equal(result, expected) + + # GH 4119, not converting a mixed type (e.g.floats and object) + s = Series([1, 'na', 3, 4]) + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_numeric=True) + expected = Series([1, np.nan, 3, 4]) + assert_series_equal(result, expected) + + s = Series([1, '', 3, 4]) + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_numeric=True) + expected = Series([1, np.nan, 3, 4]) + assert_series_equal(result, expected) + + # dates + s = Series( + [datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime(2001, 1, 3, 0, 0)]) + s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime( + 2001, 1, 3, 0, 0), 'foo', 1.0, 1, Timestamp('20010104'), '20010105'], dtype='O') + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates=True, convert_numeric=False) + expected = Series( + [Timestamp('20010101'), Timestamp('20010102'), Timestamp('20010103')], dtype='M8[ns]') + assert_series_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates='coerce', + convert_numeric=False) + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates='coerce', + convert_numeric=True) + assert_series_equal(result, expected) + + expected = Series( + [Timestamp( + '20010101'), Timestamp('20010102'), Timestamp('20010103'), + lib.NaT, lib.NaT, lib.NaT, Timestamp('20010104'), Timestamp('20010105')], dtype='M8[ns]') + with tm.assert_produces_warning(FutureWarning): + result = s2.convert_objects(convert_dates='coerce', + convert_numeric=False) + assert_series_equal(result, expected) + with tm.assert_produces_warning(FutureWarning): + result = s2.convert_objects(convert_dates='coerce', + convert_numeric=True) + assert_series_equal(result, expected) + + # preserver all-nans (if convert_dates='coerce') + s = Series(['foo', 'bar', 1, 1.0], dtype='O') + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates='coerce', + convert_numeric=False) + assert_series_equal(result, s) + + # preserver if non-object + s = Series([1], dtype='float32') + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates='coerce', + convert_numeric=False) + assert_series_equal(result, s) + + #r = s.copy() + #r[0] = np.nan + #result = r.convert_objects(convert_dates=True,convert_numeric=False) + #self.assertEqual(result.dtype, 'M8[ns]') + + # dateutil parses some single letters into today's value as a date + for x in 'abcdefghijklmnopqrstuvwxyz': + s = Series([x]) + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates='coerce') + assert_series_equal(result, s) + s = Series([x.upper()]) + with tm.assert_produces_warning(FutureWarning): + result = s.convert_objects(convert_dates='coerce') + assert_series_equal(result, s) + + def test_convert_objects_preserve_bool(self): + s = Series([1, True, 3, 5], dtype=object) + with tm.assert_produces_warning(FutureWarning): + r = s.convert_objects(convert_numeric=True) + e = Series([1, 1, 3, 5], dtype='i8') + tm.assert_series_equal(r, e) + + def test_convert_objects_preserve_all_bool(self): + s = Series([False, True, False, False], dtype=object) + with tm.assert_produces_warning(FutureWarning): + r = s.convert_objects(convert_numeric=True) + e = Series([False, True, False, False], dtype=bool) + tm.assert_series_equal(r, e) + + # GH 10265 + def test_convert(self): # Tests: All to nans, coerce, true # Test coercion returns correct type s = Series(['a', 'b', 'c']) - results = s.convert_objects(datetime=True, coerce=True) + results = s._convert(datetime=True, coerce=True) expected = Series([lib.NaT] * 3) assert_series_equal(results, expected) - results = s.convert_objects(numeric=True, coerce=True) + results = s._convert(numeric=True, coerce=True) expected = Series([np.nan] * 3) assert_series_equal(results, expected) expected = Series([lib.NaT] * 3, dtype=np.dtype('m8[ns]')) - results = s.convert_objects(timedelta=True, coerce=True) + results = s._convert(timedelta=True, coerce=True) assert_series_equal(results, expected) dt = datetime(2001, 1, 1, 0, 0) @@ -6471,83 +6588,83 @@ def test_convert_objects(self): # Test coercion with mixed types s = Series(['a', '3.1415', dt, td]) - results = s.convert_objects(datetime=True, coerce=True) + results = s._convert(datetime=True, coerce=True) expected = Series([lib.NaT, lib.NaT, dt, lib.NaT]) assert_series_equal(results, expected) - results = s.convert_objects(numeric=True, coerce=True) + results = s._convert(numeric=True, coerce=True) expected = Series([nan, 3.1415, nan, nan]) assert_series_equal(results, expected) - results = s.convert_objects(timedelta=True, coerce=True) + results = s._convert(timedelta=True, coerce=True) expected = Series([lib.NaT, lib.NaT, lib.NaT, td], dtype=np.dtype('m8[ns]')) assert_series_equal(results, expected) # Test standard conversion returns original - results = s.convert_objects(datetime=True) + results = s._convert(datetime=True) assert_series_equal(results, s) - results = s.convert_objects(numeric=True) + results = s._convert(numeric=True) expected = Series([nan, 3.1415, nan, nan]) assert_series_equal(results, expected) - results = s.convert_objects(timedelta=True) + results = s._convert(timedelta=True) assert_series_equal(results, s) # test pass-through and non-conversion when other types selected s = Series(['1.0','2.0','3.0']) - results = s.convert_objects(datetime=True, numeric=True, timedelta=True) + results = s._convert(datetime=True, numeric=True, timedelta=True) expected = Series([1.0,2.0,3.0]) assert_series_equal(results, expected) - results = s.convert_objects(True,False,True) + results = s._convert(True,False,True) assert_series_equal(results, s) s = Series([datetime(2001, 1, 1, 0, 0),datetime(2001, 1, 1, 0, 0)], dtype='O') - results = s.convert_objects(datetime=True, numeric=True, timedelta=True) + results = s._convert(datetime=True, numeric=True, timedelta=True) expected = Series([datetime(2001, 1, 1, 0, 0),datetime(2001, 1, 1, 0, 0)]) assert_series_equal(results, expected) - results = s.convert_objects(datetime=False,numeric=True,timedelta=True) + results = s._convert(datetime=False,numeric=True,timedelta=True) assert_series_equal(results, s) td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0) s = Series([td, td], dtype='O') - results = s.convert_objects(datetime=True, numeric=True, timedelta=True) + results = s._convert(datetime=True, numeric=True, timedelta=True) expected = Series([td, td]) assert_series_equal(results, expected) - results = s.convert_objects(True,True,False) + results = s._convert(True,True,False) assert_series_equal(results, s) s = Series([1., 2, 3], index=['a', 'b', 'c']) - result = s.convert_objects(numeric=True) + result = s._convert(numeric=True) assert_series_equal(result, s) # force numeric conversion r = s.copy().astype('O') r['a'] = '1' - result = r.convert_objects(numeric=True) + result = r._convert(numeric=True) assert_series_equal(result, s) r = s.copy().astype('O') r['a'] = '1.' - result = r.convert_objects(numeric=True) + result = r._convert(numeric=True) assert_series_equal(result, s) r = s.copy().astype('O') r['a'] = 'garbled' - result = r.convert_objects(numeric=True) + result = r._convert(numeric=True) expected = s.copy() expected['a'] = nan assert_series_equal(result, expected) # GH 4119, not converting a mixed type (e.g.floats and object) s = Series([1, 'na', 3, 4]) - result = s.convert_objects(datetime=True, numeric=True) + result = s._convert(datetime=True, numeric=True) expected = Series([1, nan, 3, 4]) assert_series_equal(result, expected) s = Series([1, '', 3, 4]) - result = s.convert_objects(datetime=True, numeric=True) + result = s._convert(datetime=True, numeric=True) assert_series_equal(result, expected) # dates @@ -6556,95 +6673,64 @@ def test_convert_objects(self): s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime( 2001, 1, 3, 0, 0), 'foo', 1.0, 1, Timestamp('20010104'), '20010105'], dtype='O') - result = s.convert_objects(datetime=True) + result = s._convert(datetime=True) expected = Series( [Timestamp('20010101'), Timestamp('20010102'), Timestamp('20010103')], dtype='M8[ns]') assert_series_equal(result, expected) - result = s.convert_objects(datetime=True, coerce=True) + result = s._convert(datetime=True, coerce=True) assert_series_equal(result, expected) expected = Series( [Timestamp( '20010101'), Timestamp('20010102'), Timestamp('20010103'), lib.NaT, lib.NaT, lib.NaT, Timestamp('20010104'), Timestamp('20010105')], dtype='M8[ns]') - result = s2.convert_objects(datetime=True, + result = s2._convert(datetime=True, numeric=False, timedelta=False, coerce=True) assert_series_equal(result, expected) - result = s2.convert_objects(datetime=True, coerce=True) + result = s2._convert(datetime=True, coerce=True) assert_series_equal(result, expected) s = Series(['foo', 'bar', 1, 1.0], dtype='O') - result = s.convert_objects(datetime=True, coerce=True) + result = s._convert(datetime=True, coerce=True) expected = Series([lib.NaT]*4) assert_series_equal(result, expected) # preserver if non-object s = Series([1], dtype='float32') - result = s.convert_objects(datetime=True, coerce=True) + result = s._convert(datetime=True, coerce=True) assert_series_equal(result, s) #r = s.copy() #r[0] = np.nan - #result = r.convert_objects(convert_dates=True,convert_numeric=False) + #result = r._convert(convert_dates=True,convert_numeric=False) #self.assertEqual(result.dtype, 'M8[ns]') # dateutil parses some single letters into today's value as a date expected = Series([lib.NaT]) for x in 'abcdefghijklmnopqrstuvwxyz': s = Series([x]) - result = s.convert_objects(datetime=True, coerce=True) + result = s._convert(datetime=True, coerce=True) assert_series_equal(result, expected) s = Series([x.upper()]) - result = s.convert_objects(datetime=True, coerce=True) + result = s._convert(datetime=True, coerce=True) assert_series_equal(result, expected) - # GH 10601 - # Remove test after deprecation to convert_objects is final - def test_convert_objects_old_style_deprecation(self): - s = Series(['foo', 'bar', 1, 1.0], dtype='O') - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always', FutureWarning) - new_style = s.convert_objects(datetime=True, coerce=True) - old_style = s.convert_objects(convert_dates='coerce') - self.assertEqual(len(w), 2) - assert_series_equal(new_style, old_style) - - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always', FutureWarning) - new_style = s.convert_objects(numeric=True, coerce=True) - old_style = s.convert_objects(convert_numeric='coerce') - self.assertEqual(len(w), 2) - assert_series_equal(new_style, old_style) - - dt = datetime(2001, 1, 1, 0, 0) - td = dt - datetime(2000, 1, 1, 0, 0) - s = Series(['a', '3.1415', dt, td]) - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always', FutureWarning) - new_style = s.convert_objects(timedelta=True, coerce=True) - old_style = s.convert_objects(convert_timedeltas='coerce') - self.assertEqual(len(w), 2) - assert_series_equal(new_style, old_style) - - def test_convert_objects_no_arg_warning(self): + def test_convert_no_arg_error(self): s = Series(['1.0','2']) - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always', DeprecationWarning) - s.convert_objects() - self.assertEqual(len(w), 1) + self.assertRaises(ValueError, s._convert) - def test_convert_objects_preserve_bool(self): + def test_convert_preserve_bool(self): s = Series([1, True, 3, 5], dtype=object) - r = s.convert_objects(datetime=True, numeric=True) + r = s._convert(datetime=True, numeric=True) e = Series([1, 1, 3, 5], dtype='i8') tm.assert_series_equal(r, e) - def test_convert_objects_preserve_all_bool(self): + def test_convert_preserve_all_bool(self): s = Series([False, True, False, False], dtype=object) - r = s.convert_objects(datetime=True, numeric=True) + r = s._convert(datetime=True, numeric=True) e = Series([False, True, False, False], dtype=bool) tm.assert_series_equal(r, e) diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py index fb334cf9912f3..427c96a839c26 100644 --- a/pandas/tests/test_util.py +++ b/pandas/tests/test_util.py @@ -1,13 +1,11 @@ # -*- coding: utf-8 -*- -import warnings - import nose -import sys -import pandas.util from pandas.util.decorators import deprecate_kwarg import pandas.util.testing as tm + + class TestDecorators(tm.TestCase): def setUp(self): @deprecate_kwarg('old', 'new') @@ -75,7 +73,6 @@ def test_rands_array(): assert(arr.shape == (10, 10)) assert(len(arr[1, 1]) == 7) - if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False) diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 55464a7f1d23e..98d6f5e8eb797 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1079,7 +1079,7 @@ def _compute_plot_data(self): label = 'None' data = data.to_frame(name=label) - numeric_data = data.convert_objects(datetime=True)._get_numeric_data() + numeric_data = data._convert(datetime=True)._get_numeric_data() try: is_empty = numeric_data.empty @@ -1972,8 +1972,7 @@ def __init__(self, data, bins=10, bottom=0, **kwargs): def _args_adjust(self): if com.is_integer(self.bins): # create common bin edge - values = (self.data.convert_objects(datetime=True) - ._get_numeric_data()) + values = (self.data._convert(datetime=True)._get_numeric_data()) values = np.ravel(values) values = values[~com.isnull(values)] diff --git a/pandas/tools/tests/test_util.py b/pandas/tools/tests/test_util.py index 1adf47e946a96..72ce7d8659157 100644 --- a/pandas/tools/tests/test_util.py +++ b/pandas/tools/tests/test_util.py @@ -2,14 +2,15 @@ import locale import codecs import nose +from nose.tools import assert_raises, assert_true import numpy as np from numpy.testing import assert_equal +import pandas as pd from pandas import date_range, Index import pandas.util.testing as tm -from pandas.tools.util import cartesian_product - +from pandas.tools.util import cartesian_product, to_numeric CURRENT_LOCALE = locale.getlocale() LOCALE_OVERRIDE = os.environ.get('LOCALE_OVERRIDE', None) @@ -89,6 +90,54 @@ def test_set_locale(self): self.assertEqual(current_locale, CURRENT_LOCALE) +class TestToNumeric(tm.TestCase): + def test_series(self): + s = pd.Series(['1', '-3.14', '7']) + res = to_numeric(s) + expected = pd.Series([1, -3.14, 7]) + tm.assert_series_equal(res, expected) + + s = pd.Series(['1', '-3.14', 7]) + res = to_numeric(s) + tm.assert_series_equal(res, expected) + + def test_error(self): + s = pd.Series([1, -3.14, 'apple']) + assert_raises(ValueError, to_numeric, s, errors='raise') + + res = to_numeric(s, errors='ignore') + expected = pd.Series([1, -3.14, 'apple']) + tm.assert_series_equal(res, expected) + + res = to_numeric(s, errors='coerce') + expected = pd.Series([1, -3.14, np.nan]) + tm.assert_series_equal(res, expected) + + + def test_list(self): + s = ['1', '-3.14', '7'] + res = to_numeric(s) + expected = np.array([1, -3.14, 7]) + tm.assert_numpy_array_equal(res, expected) + + def test_numeric(self): + s = pd.Series([1, -3.14, 7], dtype='O') + res = to_numeric(s) + expected = pd.Series([1, -3.14, 7]) + tm.assert_series_equal(res, expected) + + s = pd.Series([1, -3.14, 7]) + res = to_numeric(s) + tm.assert_series_equal(res, expected) + + def test_all_nan(self): + s = pd.Series(['a','b','c']) + res = to_numeric(s, errors='coerce') + expected = pd.Series([np.nan, np.nan, np.nan]) + tm.assert_series_equal(res, expected) + + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False) + diff --git a/pandas/tools/util.py b/pandas/tools/util.py index 0bb6b4b7f7892..925c23255b5f5 100644 --- a/pandas/tools/util.py +++ b/pandas/tools/util.py @@ -1,9 +1,9 @@ -import operator -import warnings +import numpy as np +import pandas.lib as lib + +import pandas as pd from pandas.compat import reduce from pandas.core.index import Index -import numpy as np -from pandas import algos from pandas.core import common as com @@ -48,3 +48,57 @@ def compose(*funcs): """Compose 2 or more callables""" assert len(funcs) > 1, 'At least 2 callables must be passed to compose' return reduce(_compose2, funcs) + + +def to_numeric(arg, errors='raise'): + """ + Convert argument to a numeric type. + + Parameters + ---------- + arg : list, tuple or array of objects, or Series + errors : {'ignore', 'raise', 'coerce'}, default 'raise' + - If 'raise', then invalid parsing will raise an exception + - If 'coerce', then invalid parsing will be set as NaN + - If 'ignore', then invalid parsing will return the input + + Returns + ------- + ret : numeric if parsing succeeded. + Return type depends on input. Series if Series, otherwise ndarray + + Examples + -------- + Take separate series and convert to numeric, coercing when told to + + >>> import pandas as pd + >>> s = pd.Series(['1.0', '2', -3]) + >>> pd.to_numeric(s) + >>> s = pd.Series(['apple', '1.0', '2', -3]) + >>> pd.to_numeric(s, errors='ignore') + >>> pd.to_numeric(s, errors='coerce') + """ + + index = name = None + if isinstance(arg, pd.Series): + index, name = arg.index, arg.name + elif isinstance(arg, (list, tuple)): + arg = np.array(arg, dtype='O') + + conv = arg + arg = com._ensure_object(arg) + + coerce_numeric = False if errors in ('ignore', 'raise') else True + + try: + conv = lib.maybe_convert_numeric(arg, + set(), + coerce_numeric=coerce_numeric) + except: + if errors == 'raise': + raise + + if index is not None: + return pd.Series(conv, index=index, name=name) + else: + return conv
Restores the v0.16 behavior of convert_objects and moves the new version of _convert Adds to_numeric for directly converting numeric data closes #11116 closes #11133
https://api.github.com/repos/pandas-dev/pandas/pulls/11173
2015-09-22T21:28:43Z
2015-10-02T14:13:52Z
2015-10-02T14:13:52Z
2016-02-16T16:29:59Z
ENH: make Series.ptp ignore NaN values (GH11163)
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 0b2bb0b5a475c..9f943fa68e639 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -527,6 +527,7 @@ Other enhancements - ``pd.read_csv`` is now able to infer compression type for files read from AWS S3 storage (:issue:`11070`, :issue:`11074`). + .. _whatsnew_0170.api: .. _whatsnew_0170.api_breaking: diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 3d10566e47075..67c3ef39a8cb5 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -60,6 +60,7 @@ API changes - ``Series.sort_index()`` now correctly handles the ``inplace`` option (:issue:`11402`) - ``DataFrame.itertuples()`` now returns ``namedtuple`` objects, when possible. (:issue:`11269`) +- ``Series.ptp`` will now ignore missing values by default (:issue:`11163`) .. _whatsnew_0171.deprecations: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 605c95bfb0ba2..4cc1cac65243c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4701,6 +4701,17 @@ def stat_func(self, axis=None, skipna=None, level=None, want the *index* of the minimum, use ``idxmin``. This is the equivalent of the ``numpy.ndarray`` method ``argmin``.""", nanops.nanmin) + if cls.__name__ == 'Series': + def nanptp(values, axis=0, skipna=True): + nmax = nanops.nanmax(values, axis, skipna) + nmin = nanops.nanmin(values, axis, skipna) + return nmax - nmin + + cls.ptp = _make_stat_function('ptp', """ +Returns the difference between the maximum value and the minimum +value in the object. This is the equivalent of the ``numpy.ndarray`` +method ``ptp``.""", nanptp) + def _make_logical_function(name, desc, f): @Substitution(outname=name, desc=desc) diff --git a/pandas/core/series.py b/pandas/core/series.py index 5106225cdd3c9..9b498bb969cbc 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1277,9 +1277,6 @@ def multi(values, qs): return self._maybe_box(lambda values: multi(values, q), dropna=True) - def ptp(self, axis=None, out=None): - return _values_from_object(self).ptp(axis, out) - def corr(self, other, method='pearson', min_periods=None): """ diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 1c8cbac60e7c7..f8f065f3371ab 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -5949,6 +5949,31 @@ def test_ptp(self): ser = Series(arr) self.assertEqual(np.ptp(ser), np.ptp(arr)) + # GH11163 + s = Series([3, 5, np.nan, -3, 10]) + self.assertEqual(s.ptp(), 13) + self.assertTrue(pd.isnull(s.ptp(skipna=False))) + + mi = pd.MultiIndex.from_product([['a','b'], [1,2,3]]) + s = pd.Series([1, np.nan, 7, 3, 5, np.nan], index=mi) + + expected = pd.Series([6, 2], index=['a', 'b'], dtype=np.float64) + self.assert_series_equal(s.ptp(level=0), expected) + + expected = pd.Series([np.nan, np.nan], index=['a', 'b']) + self.assert_series_equal(s.ptp(level=0, skipna=False), expected) + + with self.assertRaises(ValueError): + s.ptp(axis=1) + + s = pd.Series(['a', 'b', 'c', 'd', 'e']) + with self.assertRaises(TypeError): + s.ptp() + + with self.assertRaises(NotImplementedError): + s.ptp(numeric_only=True) + + def test_asof(self): # array or list or dates N = 50
Closes [GH11163](https://github.com/pydata/pandas/issues/11163). `Series.ptp` will now ignore missing values when calculating the peak to peak difference.
https://api.github.com/repos/pandas-dev/pandas/pulls/11172
2015-09-22T20:31:53Z
2015-11-14T15:04:01Z
2015-11-14T15:04:01Z
2015-11-14T23:16:58Z
BF: for version comparison first arg should be the LooseVersion
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 657789fe8ce9b..d44ce24cbefbc 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -1478,8 +1478,8 @@ def setUpClass(cls): _skip_if_no_openpyxl() import openpyxl ver = openpyxl.__version__ - if not (ver >= LooseVersion('2.0.0') and ver < LooseVersion('2.2.0')): - raise nose.SkipTest("openpyxl >= 2.2") + if not (LooseVersion(ver) >= LooseVersion('2.0.0') and LooseVersion(ver) < LooseVersion('2.2.0')): + raise nose.SkipTest("openpyxl %s >= 2.2" % str(ver)) cls.setUpClass = setUpClass return cls @@ -1593,8 +1593,8 @@ def setUpClass(cls): _skip_if_no_openpyxl() import openpyxl ver = openpyxl.__version__ - if ver < LooseVersion('2.2.0'): - raise nose.SkipTest("openpyxl < 2.2") + if LooseVersion(ver) < LooseVersion('2.2.0'): + raise nose.SkipTest("openpyxl %s < 2.2" % str(ver)) cls.setUpClass = setUpClass return cls
also enhanced skip test msg a bit
https://api.github.com/repos/pandas-dev/pandas/pulls/11168
2015-09-22T16:25:27Z
2015-09-24T01:20:47Z
2015-09-24T01:20:47Z
2015-09-24T01:20:51Z
DOC: minor doc formatting fixes
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9d40cf3921b98..b513b767693bf 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -597,7 +597,7 @@ def iterrows(self): Notes ----- - 1. Because ``iterrows` returns a Series for each row, + 1. Because ``iterrows`` returns a Series for each row, it does **not** preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). For example, diff --git a/pandas/core/series.py b/pandas/core/series.py index 4afaae0fd25df..03b2ea5597ab6 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -333,7 +333,8 @@ def values(self): [a, a, b, c] Categories (3, object): [a, b, c] - # this is converted to UTC + Timezone aware datetime data is converted to UTC: + >>> pd.Series(pd.date_range('20130101',periods=3,tz='US/Eastern')).values array(['2013-01-01T00:00:00.000000000-0500', '2013-01-02T00:00:00.000000000-0500', diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 3337a978961c4..cd2297d6018ca 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -3674,10 +3674,10 @@ def box(self, by=None, **kwds): .. versionadded:: 0.17.0 Parameters - --------- + ---------- by : string or sequence Column in the DataFrame to group by. - **kwds : optional + \*\*kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns
Removes some warnings
https://api.github.com/repos/pandas-dev/pandas/pulls/11161
2015-09-21T12:22:23Z
2015-09-21T12:22:28Z
2015-09-21T12:22:27Z
2015-09-21T12:22:28Z
PERF: Series.dropna with non-nan dtype blocks
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 37969a6949157..a40ed3f1d6482 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -71,3 +71,23 @@ def setup(self): def time_series_nsmallest2(self): self.s2.nsmallest(3, take_last=True) self.s2.nsmallest(3, take_last=False) + + +class series_dropna_int64(object): + goal_time = 0.2 + + def setup(self): + self.s = Series(np.random.randint(1, 10, 1000000)) + + def time_series_dropna_int64(self): + self.s.dropna() + +class series_dropna_datetime(object): + goal_time = 0.2 + + def setup(self): + self.s = Series(pd.date_range('2000-01-01', freq='S', periods=1000000)) + self.s[np.random.randint(1, 1000000, 100)] = pd.NaT + + def time_series_dropna_datetime(self): + self.s.dropna() diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 25b22230e5f3d..5b2b128186bf5 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -53,6 +53,7 @@ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Checking monotonic-ness before sorting on an index (:issue:`11080`) +- ``Series.dropna`` performance improvement when its dtype can't contain ``NaN`` (:issue:`11159`) .. _whatsnew_0171.bug_fixes: diff --git a/pandas/core/series.py b/pandas/core/series.py index f4e3374626011..2fc90ef8596f1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2501,11 +2501,19 @@ def dropna(self, axis=0, inplace=False, **kwargs): 'argument "{0}"'.format(list(kwargs.keys())[0])) axis = self._get_axis_number(axis or 0) - result = remove_na(self) - if inplace: - self._update_inplace(result) + + if self._can_hold_na: + result = remove_na(self) + if inplace: + self._update_inplace(result) + else: + return result else: - return result + if inplace: + # do nothing + pass + else: + return self.copy() valid = lambda self, inplace=False, **kwargs: self.dropna(inplace=inplace, **kwargs) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 9c86c3f894c67..f33adc1cd08b7 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -5117,7 +5117,6 @@ def test_dropna_empty(self): # invalid axis self.assertRaises(ValueError, s.dropna, axis=1) - def test_datetime64_tz_dropna(self): # DatetimeBlock s = Series([Timestamp('2011-01-01 10:00'), pd.NaT, @@ -5140,6 +5139,18 @@ def test_datetime64_tz_dropna(self): self.assertEqual(result.dtype, 'datetime64[ns, Asia/Tokyo]') self.assert_series_equal(result, expected) + def test_dropna_no_nan(self): + for s in [Series([1, 2, 3], name='x'), + Series([False, True, False], name='x')]: + + result = s.dropna() + self.assert_series_equal(result, s) + self.assertFalse(result is s) + + s2 = s.copy() + s2.dropna(inplace=True) + self.assert_series_equal(s2, s) + def test_axis_alias(self): s = Series([1, 2, np.nan]) assert_series_equal(s.dropna(axis='rows'), s.dropna(axis='index'))
Minor improvement when `dropna` actually does nothing. If OK for 0.17, I'll add a release note. ``` import numpy as np import pandas as pd s = pd.Series(np.random.randint(0, 1000, 50000000)) # before %timeit s.dropna() #1 loops, best of 3: 1.58 s per loop # after %timeit s.dropna() #1 loops, best of 3: 568 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11159
2015-09-21T00:17:25Z
2015-10-18T13:46:13Z
2015-10-18T13:46:13Z
2015-11-07T03:42:03Z
PERF: nested dict DataFrame construction
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index f8efa8ec23300..22ab5c0236dca 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1032,6 +1032,7 @@ Performance Improvements - Improved performance of ``to_datetime`` when specified format string is ISO8601 (:issue:`10178`) - 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`) - Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`) +- Regression from 0.16.1 in constructing ``DataFrame`` from nested dictionary (:issue:`11084`) .. _whatsnew_0170.bug_fixes: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9d40cf3921b98..86c382efa8a64 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -52,6 +52,8 @@ from pandas.tseries.period import PeriodIndex from pandas.tseries.index import DatetimeIndex +from pandas.tseries.tdi import TimedeltaIndex + import pandas.core.algorithms as algos import pandas.core.base as base @@ -5400,8 +5402,13 @@ def _homogenize(data, index, dtype=None): v = v.reindex(index, copy=False) else: if isinstance(v, dict): - v = _dict_compat(v) - oindex = index.astype('O') + if oindex is None: + oindex = index.astype('O') + + if isinstance(index, (DatetimeIndex, TimedeltaIndex)): + v = _dict_compat(v) + else: + v = dict(v) v = lib.fast_multiget(v, oindex.values, default=NA) v = _sanitize_array(v, index, dtype=dtype, copy=False, raise_cast_failure=False) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 533f8df1d4599..c963222cf4ad9 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -34,7 +34,7 @@ from pandas import (DataFrame, Index, Series, Panel, notnull, isnull, MultiIndex, DatetimeIndex, Timestamp, date_range, read_csv, timedelta_range, Timedelta, CategoricalIndex, - option_context) + option_context, period_range) from pandas.core.dtypes import DatetimeTZDtype import pandas as pd from pandas.parser import CParserError @@ -3061,6 +3061,27 @@ def create_data(constructor): assert_frame_equal(result_timedelta, expected) assert_frame_equal(result_Timedelta, expected) + def test_nested_dict_frame_constructor(self): + rng = period_range('1/1/2000', periods=5) + df = DataFrame(randn(10, 5), columns=rng) + + data = {} + for col in df.columns: + for row in df.index: + data.setdefault(col, {})[row] = df.get_value(row, col) + + result = DataFrame(data, columns=rng) + tm.assert_frame_equal(result, df) + + data = {} + for col in df.columns: + for row in df.index: + data.setdefault(row, {})[col] = df.get_value(row, col) + + result = DataFrame(data, index=rng).T + tm.assert_frame_equal(result, df) + + def _check_basic_constructor(self, empty): "mat: 2d matrix with shpae (3, 2) to input. empty - makes sized objects" mat = empty((2, 3), dtype=float) diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index 951bb803ef793..c6fb54ceec644 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -2075,26 +2075,6 @@ def test_period_set_index_reindex(self): df = df.set_index(idx2) self.assertTrue(df.index.equals(idx2)) - def test_nested_dict_frame_constructor(self): - rng = period_range('1/1/2000', periods=5) - df = DataFrame(randn(10, 5), columns=rng) - - data = {} - for col in df.columns: - for row in df.index: - data.setdefault(col, {})[row] = df.get_value(row, col) - - result = DataFrame(data, columns=rng) - tm.assert_frame_equal(result, df) - - data = {} - for col in df.columns: - for row in df.index: - data.setdefault(row, {})[col] = df.get_value(row, col) - - result = DataFrame(data, index=rng).T - tm.assert_frame_equal(result, df) - def test_frame_to_time_stamp(self): K = 5 index = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
Part of #11084 http://pydata.github.io/pandas/#frame_ctor.frame_ctor_nested_dict_int64.time_frame_ctor_nested_dict_int64 ``` before after ratio [d28fd70 ] [48c588 ] - 325.06ms 72.25ms 0.22 frame_ctor.frame_ctor_nested_dict.time_frame_ctor_nested_dict - 364.35ms 106.67ms 0.29 frame_ctor.frame_ctor_nested_dict_int64.time_frame_ctor_nested_dict_int64 ``` Two changes to get back to the old performance: - skip attempting to box `Timedeltas`/`Timestamps` if not a `DatetimeIndex`/`TimedeltaIndex` - only convert index to object once
https://api.github.com/repos/pandas-dev/pandas/pulls/11158
2015-09-21T00:13:11Z
2015-09-21T14:17:23Z
2015-09-21T14:17:23Z
2015-09-24T02:16:41Z
DEPR: deprecate SparsePanel
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index f8efa8ec23300..c2c7ca2410068 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -964,6 +964,7 @@ Deprecations ``DataFrame.add(other, fill_value=0)`` and ``DataFrame.mul(other, fill_value=1.)`` (:issue:`10735`). - ``TimeSeries`` deprecated in favor of ``Series`` (note that this has been alias since 0.13.0), (:issue:`10890`) +- ``SparsePanel`` deprecated and will be removed in a future version (:issue:``) - ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`) - Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`) - ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`) diff --git a/pandas/core/series.py b/pandas/core/series.py index 05a2ff6840d62..4afaae0fd25df 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2566,7 +2566,7 @@ def last_valid_index(self): def asof(self, where): """ - Return last good (non-NaN) value in TimeSeries if value is NaN for + Return last good (non-NaN) value in Series if value is NaN for requested date. If there is no good value, NaN is returned. @@ -2624,7 +2624,7 @@ def to_timestamp(self, freq=None, how='start', copy=True): Returns ------- - ts : TimeSeries with DatetimeIndex + ts : Series with DatetimeIndex """ new_values = self._values if copy: @@ -2636,7 +2636,7 @@ def to_timestamp(self, freq=None, how='start', copy=True): def to_period(self, freq=None, copy=True): """ - Convert TimeSeries from DatetimeIndex to PeriodIndex with desired + Convert Series from DatetimeIndex to PeriodIndex with desired frequency (inferred from index if not passed) Parameters @@ -2645,7 +2645,7 @@ def to_period(self, freq=None, copy=True): Returns ------- - ts : TimeSeries with PeriodIndex + ts : Series with PeriodIndex """ new_values = self._values if copy: diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py index 34256acfb0e60..f57339fea0a7f 100644 --- a/pandas/sparse/panel.py +++ b/pandas/sparse/panel.py @@ -5,6 +5,7 @@ # pylint: disable=E1101,E1103,W0231 +import warnings from pandas.compat import range, lrange, zip from pandas import compat import numpy as np @@ -69,6 +70,10 @@ def __init__(self, frames=None, items=None, major_axis=None, minor_axis=None, default_fill_value=np.nan, default_kind='block', copy=False): + # deprecation #11157 + warnings.warn("SparsePanel is deprecated and will be removed in a future version", + FutureWarning, stacklevel=2) + if frames is None: frames = {} diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index 3c42467c20838..a86942718091c 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -1793,6 +1793,11 @@ def test_constructor(self): "input must be a dict, a 'list' was passed"): SparsePanel(['a', 'b', 'c']) + # deprecation GH11157 + def test_deprecation(self): + with tm.assert_produces_warning(FutureWarning): + SparsePanel() + # GH 9272 def test_constructor_empty(self): sp = SparsePanel()
does not fit the current implementation; in theory a `Panel` could actually do this, but very little support (or issues related).
https://api.github.com/repos/pandas-dev/pandas/pulls/11157
2015-09-20T21:13:13Z
2015-09-20T23:19:08Z
2015-09-20T23:19:08Z
2015-09-20T23:19:08Z
BLD: use python-dateutil in conda recipe
diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml index 95c4aa084230d..e3495bc5bd04a 100644 --- a/conda.recipe/meta.yaml +++ b/conda.recipe/meta.yaml @@ -16,12 +16,12 @@ requirements: - libpython # [py2k and win] - setuptools - pytz - - dateutil + - python-dateutil run: - python - numpy - - dateutil + - python-dateutil - pytz test:
https://api.github.com/repos/pandas-dev/pandas/pulls/11156
2015-09-20T21:12:11Z
2015-09-20T23:18:11Z
2015-09-20T23:18:11Z
2015-09-20T23:18:11Z
BUG/API: GH11086 where freq is not inferred if both freq is None
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 2be7194af34b0..96a95bc03711d 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -916,7 +916,7 @@ Other API Changes - When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`) - some numeric reduction operators would return ``ValueError``, rather than ``TypeError`` on object types that includes strings and numbers (:issue:`11131`) - +- ``DatetimeIndex.union`` does not infer ``freq`` if ``self`` and the input have ``None`` as ``freq`` (:issue:`11086`) - ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`) =============================== =============================================================== diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 5fdc0ce86a0b4..ac2358cb3d231 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -51,7 +51,7 @@ _default_encoding = 'UTF-8' def _ensure_decoded(s): - """ if we have bytes, decode them to unicde """ + """ if we have bytes, decode them to unicode """ if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index c2dc625bd6ece..8f6b924ebd850 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -895,7 +895,8 @@ def union(self, other): result = Index.union(this, other) if isinstance(result, DatetimeIndex): result.tz = this.tz - if result.freq is None: + if (result.freq is None and + (this.freq is not None or other.freq is not None)): result.offset = to_offset(result.inferred_freq) return result diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index a02edf32cfcb0..0883eb72a73fe 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -2551,6 +2551,15 @@ def test_intersection_bug_1708(self): result = index_1 & index_2 self.assertEqual(len(result), 0) + def test_union_freq_both_none(self): + #GH11086 + expected = bdate_range('20150101', periods=10) + expected.freq = None + + result = expected.union(expected) + tm.assert_index_equal(result, expected) + self.assertIsNone(result.freq) + # GH 10699 def test_datetime64_with_DateOffset(self): for klass, assert_func in zip([Series, DatetimeIndex],
closes #11086, and a typo
https://api.github.com/repos/pandas-dev/pandas/pulls/11155
2015-09-20T16:39:58Z
2015-09-21T02:35:53Z
2015-09-21T02:35:53Z
2015-09-21T02:35:57Z
ENH: add merge indicator to DataFrame.merge
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 50fecf9b2886c..9d40cf3921b98 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4265,12 +4265,12 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='', @Appender(_merge_doc, indents=2) def merge(self, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, - suffixes=('_x', '_y'), copy=True): + suffixes=('_x', '_y'), copy=True, indicator=False): from pandas.tools.merge import merge return merge(self, right, how=how, on=on, left_on=left_on, right_on=right_on, left_index=left_index, right_index=right_index, sort=sort, - suffixes=suffixes, copy=copy) + suffixes=suffixes, copy=copy, indicator=indicator) def round(self, decimals=0, out=None): """ diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index 24b5feb21f5ac..929a72cfd4adc 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -951,25 +951,27 @@ def test_indicator(self): df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b'], 'col_conflict':[1,2]}) df1_copy = df1.copy() - df2 = pd.DataFrame({'col1':[1,2,3,4,5],'col_right':[2,2,2,2,2], + df2 = pd.DataFrame({'col1':[1,2,3,4,5],'col_right':[2,2,2,2,2], 'col_conflict':[1,2,3,4,5]}) df2_copy = df2.copy() - - df_result = pd.DataFrame({'col1':[0,1,2,3,4,5], + + df_result = pd.DataFrame({'col1':[0,1,2,3,4,5], 'col_conflict_x':[1,2,np.nan,np.nan,np.nan,np.nan], - 'col_left':['a','b', np.nan,np.nan,np.nan,np.nan], - 'col_conflict_y':[np.nan,1,2,3,4,5], + 'col_left':['a','b', np.nan,np.nan,np.nan,np.nan], + 'col_conflict_y':[np.nan,1,2,3,4,5], 'col_right':[np.nan, 2,2,2,2,2]}, dtype='float64') df_result['_merge'] = pd.Categorical(['left_only','both','right_only', 'right_only','right_only','right_only'] , categories=['left_only', 'right_only', 'both']) - df_result = df_result[['col1', 'col_conflict_x', 'col_left', + df_result = df_result[['col1', 'col_conflict_x', 'col_left', 'col_conflict_y', 'col_right', '_merge' ]] test = pd.merge(df1, df2, on='col1', how='outer', indicator=True) assert_frame_equal(test, df_result) + test = df1.merge(df2, on='col1', how='outer', indicator=True) + assert_frame_equal(test, df_result) # No side effects assert_frame_equal(df1, df1_copy) @@ -981,49 +983,65 @@ def test_indicator(self): test_custom_name = pd.merge(df1, df2, on='col1', how='outer', indicator='custom_name') assert_frame_equal(test_custom_name, df_result_custom_name) + test_custom_name = df1.merge(df2, on='col1', how='outer', indicator='custom_name') + assert_frame_equal(test_custom_name, df_result_custom_name) # Check only accepts strings and booleans with tm.assertRaises(ValueError): pd.merge(df1, df2, on='col1', how='outer', indicator=5) + with tm.assertRaises(ValueError): + df1.merge(df2, on='col1', how='outer', indicator=5) # Check result integrity - + test2 = pd.merge(df1, df2, on='col1', how='left', indicator=True) self.assertTrue((test2._merge != 'right_only').all()) + test2 = df1.merge(df2, on='col1', how='left', indicator=True) + self.assertTrue((test2._merge != 'right_only').all()) test3 = pd.merge(df1, df2, on='col1', how='right', indicator=True) self.assertTrue((test3._merge != 'left_only').all()) + test3 = df1.merge(df2, on='col1', how='right', indicator=True) + self.assertTrue((test3._merge != 'left_only').all()) test4 = pd.merge(df1, df2, on='col1', how='inner', indicator=True) self.assertTrue((test4._merge == 'both').all()) + test4 = df1.merge(df2, on='col1', how='inner', indicator=True) + self.assertTrue((test4._merge == 'both').all()) # Check if working name in df for i in ['_right_indicator', '_left_indicator', '_merge']: df_badcolumn = pd.DataFrame({'col1':[1,2], i:[2,2]}) - + with tm.assertRaises(ValueError): pd.merge(df1, df_badcolumn, on='col1', how='outer', indicator=True) + with tm.assertRaises(ValueError): + df1.merge(df_badcolumn, on='col1', how='outer', indicator=True) # Check for name conflict with custom name df_badcolumn = pd.DataFrame({'col1':[1,2], 'custom_column_name':[2,2]}) - + with tm.assertRaises(ValueError): pd.merge(df1, df_badcolumn, on='col1', how='outer', indicator='custom_column_name') + with tm.assertRaises(ValueError): + df1.merge(df_badcolumn, on='col1', how='outer', indicator='custom_column_name') # Merge on multiple columns df3 = pd.DataFrame({'col1':[0,1], 'col2':['a','b']}) df4 = pd.DataFrame({'col1':[1,1,3], 'col2':['b','x','y']}) - hand_coded_result = pd.DataFrame({'col1':[0,1,1,3.0], + hand_coded_result = pd.DataFrame({'col1':[0,1,1,3.0], 'col2':['a','b','x','y']}) hand_coded_result['_merge'] = pd.Categorical( ['left_only','both','right_only','right_only'] , categories=['left_only', 'right_only', 'both']) - + test5 = pd.merge(df3, df4, on=['col1', 'col2'], how='outer', indicator=True) assert_frame_equal(test5, hand_coded_result) - + test5 = df3.merge(df4, on=['col1', 'col2'], how='outer', indicator=True) + assert_frame_equal(test5, hand_coded_result) + def _check_merge(x, y): for how in ['inner', 'left', 'outer']:
Follow-up to https://github.com/pydata/pandas/pull/10054 xref #8790 Adds new `indicator` keyword to `DataFrame.merge` as well
https://api.github.com/repos/pandas-dev/pandas/pulls/11154
2015-09-20T13:38:25Z
2015-09-20T19:07:28Z
2015-09-20T19:07:28Z
2015-09-20T19:10:54Z
(WIP) BUG: DatetimeTZBlock.fillna raises TypeError
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 2be7194af34b0..27c8a66575747 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1157,3 +1157,4 @@ Bug Fixes - Bug in ``Index`` dtype may not applied properly (:issue:`11017`) - Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`) - Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`) +- Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`) diff --git a/pandas/core/dtypes.py b/pandas/core/dtypes.py index 68d72fdd80554..ce345738d9efc 100644 --- a/pandas/core/dtypes.py +++ b/pandas/core/dtypes.py @@ -181,7 +181,7 @@ def construct_from_string(cls, string): def __unicode__(self): # format the tz - return "datetime64[{unit}, {tz}]".format(unit=self.unit,tz=self.tz) + return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz) @property def name(self): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 94eccad8e0185..97b54d4ef6ebe 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1947,20 +1947,42 @@ def _try_fill(self, value): def fillna(self, value, limit=None, inplace=False, downcast=None): - # straight putmask here - values = self.values if inplace else self.values.copy() mask = isnull(self.values) value = self._try_fill(value) + if limit is not None: if self.ndim > 2: raise NotImplementedError("number of dimensions for 'fillna' " "is currently limited to 2") mask[mask.cumsum(self.ndim-1)>limit]=False - np.putmask(values, mask, value) - return [self if inplace else - self.make_block(values, - fastpath=True)] + if mask.any(): + try: + return self._fillna_mask(mask, value, inplace=inplace) + except TypeError: + pass + # _fillna_mask raises TypeError when it fails + # cannot perform inplace op because of object coercion + values = self.get_values(dtype=object) + np.putmask(values, mask, value) + return [self.make_block(values, fastpath=True)] + else: + return [self if inplace else self.copy()] + + def _fillna_mask(self, mask, value, inplace=False): + if getattr(value, 'tzinfo', None) is None: + # Series comes to this path + values = self.values + if not inplace: + values = values.copy() + try: + np.putmask(values, mask, value) + return [self if inplace else + self.make_block(values, fastpath=True)] + except (ValueError, TypeError): + # scalar causes ValueError, and array causes TypeError + pass + raise TypeError def to_native_types(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs): @@ -2033,6 +2055,29 @@ def get_values(self, dtype=None): .reshape(self.values.shape) return self.values + def _fillna_mask(self, mask, value, inplace=False): + # cannot perform inplace op for internal DatetimeIndex + my_tz = tslib.get_timezone(self.values.tz) + value_tz = tslib.get_timezone(getattr(value, 'tzinfo', None)) + + if (my_tz == value_tz or self.dtype == getattr(value, 'dtype', None)): + if my_tz == value_tz: + # hack for PY2.6 / numpy 1.7.1. + # Other versions can directly use self.values.putmask + # -------------------------------------- + try: + value = value.asm8 + except AttributeError: + value = tslib.Timestamp(value).asm8 + ### ------------------------------------ + + try: + values = self.values.putmask(mask, value) + return [self.make_block(values, fastpath=True)] + except ValueError: + pass + raise TypeError + def _slice(self, slicer): """ return a slice of my values """ if isinstance(slicer, tuple): diff --git a/pandas/tests/test_dtypes.py b/pandas/tests/test_dtypes.py index 54a49de582e56..e6df9c894c219 100644 --- a/pandas/tests/test_dtypes.py +++ b/pandas/tests/test_dtypes.py @@ -137,6 +137,20 @@ def test_basic(self): self.assertFalse(is_datetimetz(np.dtype('float64'))) self.assertFalse(is_datetimetz(1.0)) + def test_dst(self): + + dr1 = date_range('2013-01-01', periods=3, tz='US/Eastern') + s1 = Series(dr1, name='A') + self.assertTrue(is_datetimetz(s1)) + + dr2 = date_range('2013-08-01', periods=3, tz='US/Eastern') + s2 = Series(dr2, name='A') + self.assertTrue(is_datetimetz(s2)) + self.assertEqual(s1.dtype, s2.dtype) + + + + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index c1185f9455284..533f8df1d4599 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -8740,6 +8740,34 @@ def test_fillna_dtype_conversion(self): result = df.fillna(v) assert_frame_equal(result, expected) + def test_fillna_datetime_columns(self): + # GH 7095 + df = pd.DataFrame({'A': [-1, -2, np.nan], + 'B': date_range('20130101', periods=3), + 'C': ['foo', 'bar', None], + 'D': ['foo2', 'bar2', None]}, + index=date_range('20130110', periods=3)) + result = df.fillna('?') + expected = pd.DataFrame({'A': [-1, -2, '?'], + 'B': date_range('20130101', periods=3), + 'C': ['foo', 'bar', '?'], + 'D': ['foo2', 'bar2', '?']}, + index=date_range('20130110', periods=3)) + self.assert_frame_equal(result, expected) + + df = pd.DataFrame({'A': [-1, -2, np.nan], + 'B': [pd.Timestamp('2013-01-01'), pd.Timestamp('2013-01-02'), pd.NaT], + 'C': ['foo', 'bar', None], + 'D': ['foo2', 'bar2', None]}, + index=date_range('20130110', periods=3)) + result = df.fillna('?') + expected = pd.DataFrame({'A': [-1, -2, '?'], + 'B': [pd.Timestamp('2013-01-01'), pd.Timestamp('2013-01-02'), '?'], + 'C': ['foo', 'bar', '?'], + 'D': ['foo2', 'bar2', '?']}, + index=date_range('20130110', periods=3)) + self.assert_frame_equal(result, expected) + def test_ffill(self): self.tsframe['A'][:5] = nan self.tsframe['A'][-5:] = nan diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 2060b31511ead..a6d7e63656d68 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -3937,6 +3937,89 @@ def test_datetime64_fillna(self): result = s.fillna(method='backfill') assert_series_equal(result, expected) + def test_datetime64_tz_fillna(self): + for tz in ['US/Eastern', 'Asia/Tokyo']: + # DatetimeBlock + s = Series([Timestamp('2011-01-01 10:00'), pd.NaT, + Timestamp('2011-01-03 10:00'), pd.NaT]) + result = s.fillna(pd.Timestamp('2011-01-02 10:00')) + expected = Series([Timestamp('2011-01-01 10:00'), Timestamp('2011-01-02 10:00'), + Timestamp('2011-01-03 10:00'), Timestamp('2011-01-02 10:00')]) + self.assert_series_equal(expected, result) + + result = s.fillna(pd.Timestamp('2011-01-02 10:00', tz=tz)) + expected = Series([Timestamp('2011-01-01 10:00'), + Timestamp('2011-01-02 10:00', tz=tz), + Timestamp('2011-01-03 10:00'), + Timestamp('2011-01-02 10:00', tz=tz)]) + self.assert_series_equal(expected, result) + + result = s.fillna('AAA') + expected = Series([Timestamp('2011-01-01 10:00'), 'AAA', + Timestamp('2011-01-03 10:00'), 'AAA'], dtype=object) + self.assert_series_equal(expected, result) + + result = s.fillna({1: pd.Timestamp('2011-01-02 10:00', tz=tz), + 3: pd.Timestamp('2011-01-04 10:00')}) + expected = Series([Timestamp('2011-01-01 10:00'), + Timestamp('2011-01-02 10:00', tz=tz), + Timestamp('2011-01-03 10:00'), + Timestamp('2011-01-04 10:00')]) + self.assert_series_equal(expected, result) + + result = s.fillna({1: pd.Timestamp('2011-01-02 10:00'), + 3: pd.Timestamp('2011-01-04 10:00')}) + expected = Series([Timestamp('2011-01-01 10:00'), Timestamp('2011-01-02 10:00'), + Timestamp('2011-01-03 10:00'), Timestamp('2011-01-04 10:00')]) + self.assert_series_equal(expected, result) + + # DatetimeBlockTZ + idx = pd.DatetimeIndex(['2011-01-01 10:00', pd.NaT, + '2011-01-03 10:00', pd.NaT], tz=tz) + s = pd.Series(idx) + result = s.fillna(pd.Timestamp('2011-01-02 10:00')) + expected = Series([Timestamp('2011-01-01 10:00', tz=tz), + Timestamp('2011-01-02 10:00'), + Timestamp('2011-01-03 10:00', tz=tz), + Timestamp('2011-01-02 10:00')]) + self.assert_series_equal(expected, result) + + result = s.fillna(pd.Timestamp('2011-01-02 10:00', tz=tz)) + idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-02 10:00', + '2011-01-03 10:00', '2011-01-02 10:00'], + tz=tz) + expected = Series(idx) + self.assert_series_equal(expected, result) + + result = s.fillna(pd.Timestamp('2011-01-02 10:00', tz=tz).to_pydatetime()) + idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-02 10:00', + '2011-01-03 10:00', '2011-01-02 10:00'], + tz=tz) + expected = Series(idx) + self.assert_series_equal(expected, result) + + result = s.fillna('AAA') + expected = Series([Timestamp('2011-01-01 10:00', tz=tz), 'AAA', + Timestamp('2011-01-03 10:00', tz=tz), 'AAA'], + dtype=object) + self.assert_series_equal(expected, result) + + result = s.fillna({1: pd.Timestamp('2011-01-02 10:00', tz=tz), + 3: pd.Timestamp('2011-01-04 10:00')}) + expected = Series([Timestamp('2011-01-01 10:00', tz=tz), + Timestamp('2011-01-02 10:00', tz=tz), + Timestamp('2011-01-03 10:00', tz=tz), + Timestamp('2011-01-04 10:00')]) + self.assert_series_equal(expected, result) + + result = s.fillna({1: pd.Timestamp('2011-01-02 10:00', tz=tz), + 3: pd.Timestamp('2011-01-04 10:00', tz=tz)}) + expected = Series([Timestamp('2011-01-01 10:00', tz=tz), + Timestamp('2011-01-02 10:00', tz=tz), + Timestamp('2011-01-03 10:00', tz=tz), + Timestamp('2011-01-04 10:00', tz=tz)]) + self.assert_series_equal(expected, result) + def test_fillna_int(self): s = Series(np.random.randint(-100, 100, 50)) s.fillna(method='ffill', inplace=True) @@ -5022,6 +5105,29 @@ def test_dropna_empty(self): # invalid axis self.assertRaises(ValueError, s.dropna, axis=1) + + def test_datetime64_tz_dropna(self): + # DatetimeBlock + s = Series([Timestamp('2011-01-01 10:00'), pd.NaT, + Timestamp('2011-01-03 10:00'), pd.NaT]) + result = s.dropna() + expected = Series([Timestamp('2011-01-01 10:00'), + Timestamp('2011-01-03 10:00')], index=[0, 2]) + self.assert_series_equal(result, expected) + + # DatetimeBlockTZ + idx = pd.DatetimeIndex(['2011-01-01 10:00', pd.NaT, + '2011-01-03 10:00', pd.NaT], + tz='Asia/Tokyo') + s = pd.Series(idx) + self.assertEqual(s.dtype, 'datetime64[ns, Asia/Tokyo]') + result = s.dropna() + expected = Series([Timestamp('2011-01-01 10:00', tz='Asia/Tokyo'), + Timestamp('2011-01-03 10:00', tz='Asia/Tokyo')], + index=[0, 2]) + self.assertEqual(result.dtype, 'datetime64[ns, Asia/Tokyo]') + self.assert_series_equal(result, expected) + def test_axis_alias(self): s = Series([1, 2, np.nan]) assert_series_equal(s.dropna(axis='rows'), s.dropna(axis='index'))
``` import pandas as pd idx = pd.DatetimeIndex(['2011-01-01', pd.NaT, '2011-01-03'], tz='Asia/Tokyo') s = pd.Series(idx) s #0 2011-01-01 00:00:00+09:00 #1 NaT #2 2011-01-03 00:00:00+09:00 # dtype: datetime64[ns, Asia/Tokyo] # NG, the result must be DatetimeTZBlock s.fillna(pd.Timestamp('2011-01-02', tz='Asia/Tokyo')) # TypeError: putmask() argument 1 must be numpy.ndarray, not DatetimeIndex # NG, it should be object dtype, as the same as when Series creation with mixed tz s.fillna(pd.Timestamp('2011-01-02')) # TypeError: putmask() argument 1 must be numpy.ndarray, not DatetimeIndex ``` Also, found existing `DatetimeBlock` doesn't handle tz properly. Closes #7095. ``` idx = pd.DatetimeIndex(['2011-01-01', pd.NaT, '2011-01-03']) s = pd.Series(idx) # OK, result must be DatetimeBlock s.fillna(pd.Timestamp('2011-01-02')) #0 2011-01-01 #1 2011-01-02 #2 2011-01-03 # dtype: datetime64[ns] # NG, it should be object dtype, as the same as when Series creation with mixed tz s.fillna(pd.Timestamp('2011-01-02', tz='Asia/Tokyo')) #0 2011-01-01 00:00:00 #1 2011-01-01 15:00:00 #2 2011-01-03 00:00:00 # dtype: datetime64[ns] # NG, unable to fill different dtypes s.fillna('AAA') # ValueError: Error parsing datetime string "AAA" at position 0 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11153
2015-09-19T23:01:47Z
2015-09-20T18:52:13Z
2015-09-20T18:52:13Z
2015-09-26T00:27:01Z
PERF: improves performance in groupby.size
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 8e44480c0c09b..20c1140bbd80e 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1378,12 +1378,9 @@ def size(self): Compute group sizes """ - # TODO: better impl - labels, _, ngroups = self.group_info - bin_counts = algos.value_counts(labels, sort=False) - bin_counts = bin_counts.reindex(np.arange(ngroups)) - bin_counts.index = self.result_index - return bin_counts + ids, _, ngroup = self.group_info + out = np.bincount(ids[ids != -1], minlength=ngroup) + return Series(out, index=self.result_index) @cache_readonly def _max_groupsize(self): @@ -1845,24 +1842,6 @@ def groupings(self): # for compat return None - def size(self): - """ - Compute group sizes - - """ - index = self.result_index - base = Series(np.zeros(len(index), dtype=np.int64), index=index) - indices = self.indices - for k, v in compat.iteritems(indices): - indices[k] = len(v) - bin_counts = Series(indices, dtype=np.int64) - # make bin_counts.index to have same name to preserve it - bin_counts.index.name = index.name - result = base.add(bin_counts, fill_value=0) - # addition with fill_value changes dtype to float64 - result = result.astype(np.int64) - return result - #---------------------------------------------------------------------- # cython aggregation diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 0336ee2e9b50e..42d5af587a859 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -2485,6 +2485,12 @@ def test_size(self): for key, group in grouped: self.assertEqual(result[key], len(group)) + df = DataFrame(np.random.choice(20, (1000, 3)), columns=list('abc')) + for sort, key in cart_product((False, True), ('a', 'b', ['a', 'b'])): + left = df.groupby(key, sort=sort).size() + right = df.groupby(key, sort=sort)['c'].apply(lambda a: a.shape[0]) + assert_series_equal(left, right, check_names=False) + def test_count(self): from string import ascii_lowercase n = 1 << 15 diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index ec03d558e45b8..7052348e2e6a4 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -941,6 +941,20 @@ def test_resample_group_info(self): # GH10914 assert_series_equal(left, right) + def test_resample_size(self): + n = 10000 + dr = date_range('2015-09-19', periods=n, freq='T') + ts = Series(np.random.randn(n), index=np.random.choice(dr, n)) + + left = ts.resample('7T', how='size') + ix = date_range(start=left.index.min(), end=ts.index.max(), freq='7T') + + bins = np.searchsorted(ix.values, ts.index.values, side='right') + val = np.bincount(bins, minlength=len(ix) + 1)[1:] + + right = Series(val, index=ix) + assert_series_equal(left, right) + def test_resmaple_dst_anchor(self): # 5172 dti = DatetimeIndex([datetime(2012, 11, 4, 23)], tz='US/Eastern')
on master: ``` python In [1]: n = 100000 In [2]: np.random.seed(2718281) In [3]: dr = date_range('2015-09-19', periods=n, freq='T') In [4]: ts = Series(np.random.choice(n, n), index=np.random.choice(dr, n)) In [5]: %timeit ts.resample('5T', how='size') 1 loops, best of 3: 538 ms per loop ``` on branch: ``` python In [5]: %timeit ts.resample('5T', how='size') 10 loops, best of 3: 27.6 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11152
2015-09-19T22:57:21Z
2015-09-20T18:54:14Z
2015-09-20T18:54:14Z
2015-09-20T19:03:47Z
BUG: astype(str) on datetimelike index #10442
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 25b22230e5f3d..64d04df06851f 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -17,6 +17,7 @@ Highlights include: Enhancements ~~~~~~~~~~~~ +- ``DatetimeIndex`` now supports conversion to strings with astype(str)(:issue:`10442`) - Support for ``compression`` (gzip/bz2) in :method:`DataFrame.to_csv` (:issue:`7615`) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 814a9ccc45582..868057c675594 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -756,6 +756,8 @@ def astype(self, dtype): return self.asi8.copy() elif dtype == _NS_DTYPE and self.tz is not None: return self.tz_convert('UTC').tz_localize(None) + elif dtype == str: + return self._shallow_copy(values=self.format(), infer=True) else: # pragma: no cover raise ValueError('Cannot cast DatetimeIndex to dtype %s' % dtype) diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py index 24edc54582ec1..4d353eccba972 100644 --- a/pandas/tseries/tests/test_base.py +++ b/pandas/tseries/tests/test_base.py @@ -45,6 +45,32 @@ def test_ops_properties_basic(self): self.assertEqual(s.day,10) self.assertRaises(AttributeError, lambda : s.weekday) + def test_astype_str(self): + # test astype string - #10442 + result = date_range('2012-01-01', periods=4, name='test_name').astype(str) + expected = Index(['2012-01-01', '2012-01-02', '2012-01-03','2012-01-04'], + name='test_name', dtype=object) + tm.assert_index_equal(result, expected) + + # test astype string with tz and name + result = date_range('2012-01-01', periods=3, name='test_name', tz='US/Eastern').astype(str) + expected = Index(['2012-01-01 00:00:00-05:00', '2012-01-02 00:00:00-05:00', + '2012-01-03 00:00:00-05:00'], name='test_name', dtype=object) + tm.assert_index_equal(result, expected) + + # test astype string with freqH and name + result = date_range('1/1/2011', periods=3, freq='H', name='test_name').astype(str) + expected = Index(['2011-01-01 00:00:00', '2011-01-01 01:00:00', '2011-01-01 02:00:00'], + name='test_name', dtype=object) + tm.assert_index_equal(result, expected) + + # test astype string with freqH and timezone + result = date_range('3/6/2012 00:00', periods=2, freq='H', + tz='Europe/London', name='test_name').astype(str) + expected = Index(['2012-03-06 00:00:00+00:00', '2012-03-06 01:00:00+00:00'], + dtype=object, name='test_name') + tm.assert_index_equal(result, expected) + def test_asobject_tolist(self): idx = pd.date_range(start='2013-01-01', periods=4, freq='M', name='idx') expected_list = [pd.Timestamp('2013-01-31'), pd.Timestamp('2013-02-28'), @@ -503,7 +529,6 @@ def test_infer_freq(self): tm.assert_index_equal(idx, result) self.assertEqual(result.freq, freq) - class TestTimedeltaIndexOps(Ops): def setUp(self): diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index a80bdf970cccb..230016f00374f 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -2223,6 +2223,7 @@ def test_append_join_nondatetimeindex(self): # it works rng.join(idx, how='outer') + def test_astype(self): rng = date_range('1/1/2000', periods=10) @@ -2235,6 +2236,17 @@ def test_astype(self): expected = date_range('1/1/2000', periods=10, tz='US/Eastern').tz_convert('UTC').tz_localize(None) tm.assert_index_equal(result, expected) + # BUG#10442 : testing astype(str) is correct for Series/DatetimeIndex + result = pd.Series(pd.date_range('2012-01-01', periods=3)).astype(str) + expected = pd.Series(['2012-01-01', '2012-01-02', '2012-01-03'], dtype=object) + tm.assert_series_equal(result, expected) + + result = Series(pd.date_range('2012-01-01', periods=3, tz='US/Eastern')).astype(str) + expected = Series(['2012-01-01 00:00:00-05:00', '2012-01-02 00:00:00-05:00', '2012-01-03 00:00:00-05:00'], + dtype=object) + tm.assert_series_equal(result, expected) + + def test_to_period_nofreq(self): idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04']) self.assertRaises(ValueError, idx.to_period)
closes #10442 fix for the bug: Convert datetimelike index to strings with astype(str) going to send pull request for test
https://api.github.com/repos/pandas-dev/pandas/pulls/11148
2015-09-19T00:31:15Z
2015-10-16T22:07:39Z
2015-10-16T22:07:39Z
2015-10-16T22:07:42Z
PERF: improves performance in SeriesGroupBy.transform
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 2be7194af34b0..6ae67ab6eedb1 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1021,7 +1021,7 @@ Performance Improvements - Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`) - Added vbench benchmarks for alternative ExcelWriter engines and reading Excel files (:issue:`7171`) - Performance improvements in ``Categorical.value_counts`` (:issue:`10804`) -- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` (:issue:`10820`, :issue:`11077`) +- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` and ``SeriesGroupby.transform`` (:issue:`10820`, :issue:`11077`) - Performance improvements in ``DataFrame.drop_duplicates`` with integer dtypes (:issue:`10917`) - 4x improvement in ``timedelta`` string parsing (:issue:`6755`, :issue:`10426`) - 8x improvement in ``timedelta64`` and ``datetime64`` ops (:issue:`6755`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 8e44480c0c09b..35f5b7fadb9db 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2512,13 +2512,19 @@ def _transform_fast(self, func): if isinstance(func, compat.string_types): func = getattr(self,func) - values = func().values - counts = self.size().fillna(0).values - values = np.repeat(values, com._ensure_platform_int(counts)) - if any(counts == 0): - values = self._try_cast(values, self._selected_obj) + ids, _, ngroup = self.grouper.group_info + mask = ids != -1 + + out = func().values[ids] + if not mask.all(): + out = np.where(mask, out, np.nan) + + obs = np.zeros(ngroup, dtype='bool') + obs[ids[mask]] = True + if not obs.all(): + out = self._try_cast(out, self._selected_obj) - return self._set_result_index_ordered(Series(values)) + return Series(out, index=self.obj.index) def filter(self, func, dropna=True, *args, **kwargs): """
``` ------------------------------------------------------------------------------- Test name | head[ms] | base[ms] | ratio | ------------------------------------------------------------------------------- groupby_transform_series2 | 6.3464 | 167.3844 | 0.0379 | groupby_transform_multi_key3 | 99.4797 | 1078.2626 | 0.0923 | groupby_transform_multi_key1 | 10.9547 | 98.5500 | 0.1112 | groupby_transform_multi_key2 | 9.0899 | 67.2680 | 0.1351 | groupby_transform_series | 5.4360 | 30.5537 | 0.1779 | groupby_transform_multi_key4 | 39.9816 | 187.1406 | 0.2136 | ------------------------------------------------------------------------------- Test name | head[ms] | base[ms] | ratio | ------------------------------------------------------------------------------- Ratio < 1.0 means the target commit is faster then the baseline. Seed used: 1234 Target [0470a10] : PERF: improves performance in SeriesGroupBy.transform Base [7b9fe14] : revers import .pandas_vb_common ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11147
2015-09-18T23:07:27Z
2015-09-20T18:53:34Z
2015-09-20T18:53:34Z
2015-09-20T19:03:42Z
PERF: infer_datetime_format without padding #11142
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 2be7194af34b0..120be63edce72 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1031,6 +1031,7 @@ Performance Improvements - 20x improvement in ``concat`` of Categoricals when categories are identical (:issue:`10587`) - Improved performance of ``to_datetime`` when specified format string is ISO8601 (:issue:`10178`) - 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`) +- Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`) .. _whatsnew_0170.bug_fixes: diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index a02edf32cfcb0..c4eb0e0cddfc9 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -4615,6 +4615,24 @@ def test_guess_datetime_format_invalid_inputs(self): for invalid_dt in invalid_dts: self.assertTrue(tools._guess_datetime_format(invalid_dt) is None) + def test_guess_datetime_format_nopadding(self): + # GH 11142 + dt_string_to_format = ( + ('2011-1-1', '%Y-%m-%d'), + ('30-1-2011', '%d-%m-%Y'), + ('1/1/2011', '%m/%d/%Y'), + ('2011-1-1 00:00:00', '%Y-%m-%d %H:%M:%S'), + ('2011-1-1 0:0:0', '%Y-%m-%d %H:%M:%S'), + ('2011-1-3T00:00:0', '%Y-%m-%dT%H:%M:%S') + ) + + for dt_string, dt_format in dt_string_to_format: + self.assertEqual( + tools._guess_datetime_format(dt_string), + dt_format + ) + + 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) diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index bd19b771f30ce..c38878fe398e4 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -86,20 +86,21 @@ def _guess_datetime_format(dt_str, dayfirst=False, if not isinstance(dt_str, compat.string_types): return None - day_attribute_and_format = (('day',), '%d') + day_attribute_and_format = (('day',), '%d', 2) + # attr name, format, padding (if any) datetime_attrs_to_format = [ - (('year', 'month', 'day'), '%Y%m%d'), - (('year',), '%Y'), - (('month',), '%B'), - (('month',), '%b'), - (('month',), '%m'), + (('year', 'month', 'day'), '%Y%m%d', 0), + (('year',), '%Y', 0), + (('month',), '%B', 0), + (('month',), '%b', 0), + (('month',), '%m', 2), day_attribute_and_format, - (('hour',), '%H'), - (('minute',), '%M'), - (('second',), '%S'), - (('microsecond',), '%f'), - (('second', 'microsecond'), '%S.%f'), + (('hour',), '%H', 2), + (('minute',), '%M', 2), + (('second',), '%S', 2), + (('microsecond',), '%f', 6), + (('second', 'microsecond'), '%S.%f', 0), ] if dayfirst: @@ -125,7 +126,7 @@ def _guess_datetime_format(dt_str, dayfirst=False, format_guess = [None] * len(tokens) found_attrs = set() - for attrs, attr_format in datetime_attrs_to_format: + for attrs, attr_format, padding in datetime_attrs_to_format: # If a given attribute has been placed in the format string, skip # over other formats for that same underlying attribute (IE, month # can be represented in multiple different ways) @@ -134,9 +135,11 @@ def _guess_datetime_format(dt_str, dayfirst=False, if all(getattr(parsed_datetime, attr) is not None for attr in attrs): for i, token_format in enumerate(format_guess): + token_filled = tokens[i].zfill(padding) if (token_format is None and - tokens[i] == parsed_datetime.strftime(attr_format)): + token_filled == parsed_datetime.strftime(attr_format)): format_guess[i] = attr_format + tokens[i] = token_filled found_attrs.update(attrs) break @@ -163,6 +166,8 @@ def _guess_datetime_format(dt_str, dayfirst=False, guessed_format = ''.join(output_format) + # rebuild string, capturing any inferred padding + dt_str = ''.join(tokens) if parsed_datetime.strftime(guessed_format) == dt_str: return guessed_format
Closes #11142
https://api.github.com/repos/pandas-dev/pandas/pulls/11146
2015-09-18T22:53:15Z
2015-09-20T19:21:37Z
2015-09-20T19:21:37Z
2015-09-20T20:40:27Z
COMPAT: Support for MPL 1.5
diff --git a/ci/install_conda.sh b/ci/install_conda.sh index c54f5494c12ee..8d99034a86109 100755 --- a/ci/install_conda.sh +++ b/ci/install_conda.sh @@ -72,6 +72,7 @@ bash miniconda.sh -b -p $HOME/miniconda || exit 1 conda config --set always_yes yes --set changeps1 no || exit 1 conda update -q conda || exit 1 +conda config --add channels conda-forge || exit 1 conda config --add channels http://conda.binstar.org/pandas || exit 1 conda config --set ssl_verify false || exit 1 diff --git a/ci/requirements-3.4.run b/ci/requirements-3.4.run index 73209a4623a49..c984036203251 100644 --- a/ci/requirements-3.4.run +++ b/ci/requirements-3.4.run @@ -11,7 +11,6 @@ beautiful-soup scipy numexpr pytables -matplotlib=1.3.1 lxml sqlalchemy bottleneck diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 1a976bf0d921e..4ec5281b5f2ff 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -50,6 +50,7 @@ Highlights include: - Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>` - Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` - Compatibility with Python 3.5 (:issue:`11097`) +- Compatibility with matplotlib 1.5.0 (:issue:`11111`) Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating. diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index ad9518116a066..27069ddfd9c49 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -74,13 +74,22 @@ def setUp(self): 'weight': random.normal(161, 32, size=n), 'category': random.randint(4, size=n)}) - if str(mpl.__version__) >= LooseVersion('1.4'): + self.mpl_le_1_2_1 = plotting._mpl_le_1_2_1() + self.mpl_ge_1_3_1 = plotting._mpl_ge_1_3_1() + self.mpl_ge_1_4_0 = plotting._mpl_ge_1_4_0() + self.mpl_ge_1_5_0 = plotting._mpl_ge_1_5_0() + + if self.mpl_ge_1_4_0: self.bp_n_objects = 7 else: self.bp_n_objects = 8 + if self.mpl_ge_1_5_0: + # 1.5 added PolyCollections to legend handler + # so we have twice as many items. + self.polycollection_factor = 2 + else: + self.polycollection_factor = 1 - self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') - self.mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1') def tearDown(self): tm.close() @@ -183,7 +192,7 @@ def _check_colors(self, collections, linecolors=None, facecolors=None, """ from matplotlib.lines import Line2D - from matplotlib.collections import Collection + from matplotlib.collections import Collection, PolyCollection conv = self.colorconverter if linecolors is not None: @@ -197,6 +206,8 @@ def _check_colors(self, collections, linecolors=None, facecolors=None, result = patch.get_color() # Line2D may contains string color expression result = conv.to_rgba(result) + elif isinstance(patch, PolyCollection): + result = tuple(patch.get_edgecolor()[0]) else: result = patch.get_edgecolor() @@ -472,6 +483,21 @@ def is_grid_on(): obj.plot(kind=kind, grid=True, **kws) self.assertTrue(is_grid_on()) + def _maybe_unpack_cycler(self, rcParams, field='color'): + """ + Compat layer for MPL 1.5 change to color cycle + + Before: plt.rcParams['axes.color_cycle'] -> ['b', 'g', 'r'...] + After : plt.rcParams['axes.prop_cycle'] -> cycler(...) + """ + if self.mpl_ge_1_5_0: + cyl = rcParams['axes.prop_cycle'] + colors = [v[field] for v in cyl] + else: + colors = rcParams['axes.color_cycle'] + return colors + + @tm.mplskip class TestSeriesPlots(TestPlotBase): @@ -536,9 +562,13 @@ def test_plot_figsize_and_title(self): def test_dont_modify_rcParams(self): # GH 8242 - colors = self.plt.rcParams['axes.color_cycle'] + if self.mpl_ge_1_5_0: + key = 'axes.prop_cycle' + else: + key = 'axes.color_cycle' + colors = self.plt.rcParams[key] Series([1, 2, 3]).plot() - self.assertEqual(colors, self.plt.rcParams['axes.color_cycle']) + self.assertEqual(colors, self.plt.rcParams[key]) def test_ts_line_lim(self): ax = self.ts.plot() @@ -770,8 +800,8 @@ def test_hist_legacy(self): _check_plot_works(self.ts.hist) _check_plot_works(self.ts.hist, grid=False) _check_plot_works(self.ts.hist, figsize=(8, 10)) - _check_plot_works(self.ts.hist, by=self.ts.index.month) - _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5) + _check_plot_works(self.ts.hist, filterwarnings='ignore', by=self.ts.index.month) + _check_plot_works(self.ts.hist, filterwarnings='ignore', by=self.ts.index.month, bins=5) fig, ax = self.plt.subplots(1, 1) _check_plot_works(self.ts.hist, ax=ax) @@ -805,25 +835,32 @@ def test_hist_layout(self): def test_hist_layout_with_by(self): df = self.hist_df - axes = _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.gender, layout=(2, 1)) self._check_axes_shape(axes, axes_num=2, layout=(2, 1)) - axes = _check_plot_works(df.height.hist, by=df.gender, layout=(3, -1)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.gender, layout=(3, -1)) self._check_axes_shape(axes, axes_num=2, layout=(3, 1)) - axes = _check_plot_works(df.height.hist, by=df.category, layout=(4, 1)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.category, layout=(4, 1)) self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) - axes = _check_plot_works(df.height.hist, by=df.category, layout=(2, -1)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.category, layout=(2, -1)) self._check_axes_shape(axes, axes_num=4, layout=(2, 2)) - axes = _check_plot_works(df.height.hist, by=df.category, layout=(3, -1)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.category, layout=(3, -1)) self._check_axes_shape(axes, axes_num=4, layout=(3, 2)) - axes = _check_plot_works(df.height.hist, by=df.category, layout=(-1, 4)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.category, layout=(-1, 4)) self._check_axes_shape(axes, axes_num=4, layout=(1, 4)) - axes = _check_plot_works(df.height.hist, by=df.classroom, layout=(2, 2)) + axes = _check_plot_works(df.height.hist, filterwarnings='ignore', + by=df.classroom, layout=(2, 2)) self._check_axes_shape(axes, axes_num=3, layout=(2, 2)) axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7)) @@ -1109,7 +1146,8 @@ def test_errorbar_plot(self): s.plot(yerr=np.arange(11)) s_err = ['zzz']*10 - with tm.assertRaises(TypeError): + # in mpl 1.5+ this is a TypeError + with tm.assertRaises((ValueError, TypeError)): s.plot(yerr=s_err) def test_table(self): @@ -1183,7 +1221,10 @@ def test_time_series_plot_color_kwargs(self): def test_time_series_plot_color_with_empty_kwargs(self): import matplotlib as mpl - def_colors = mpl.rcParams['axes.color_cycle'] + if self.mpl_ge_1_5_0: + def_colors = self._maybe_unpack_cycler(mpl.rcParams) + else: + def_colors = mpl.rcParams['axes.color_cycle'] index = date_range('1/1/2000', periods=12) s = Series(np.arange(1, 13), index=index) @@ -1213,14 +1254,16 @@ def setUp(self): @slow def test_plot(self): df = self.tdf - _check_plot_works(df.plot, grid=False) - axes = _check_plot_works(df.plot, subplots=True) + _check_plot_works(df.plot, filterwarnings='ignore', grid=False) + axes = _check_plot_works(df.plot, filterwarnings='ignore', subplots=True) self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) - axes = _check_plot_works(df.plot, subplots=True, layout=(-1, 2)) + axes = _check_plot_works(df.plot, filterwarnings='ignore', + subplots=True, layout=(-1, 2)) self._check_axes_shape(axes, axes_num=4, layout=(2, 2)) - axes = _check_plot_works(df.plot, subplots=True, use_index=False) + axes = _check_plot_works(df.plot, filterwarnings='ignore', + subplots=True, use_index=False) self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) df = DataFrame({'x': [1, 2], 'y': [3, 4]}) @@ -1229,13 +1272,14 @@ def test_plot(self): df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10])) + _check_plot_works(df.plot, use_index=True) _check_plot_works(df.plot, sort_columns=False) _check_plot_works(df.plot, yticks=[1, 5, 10]) _check_plot_works(df.plot, xticks=[1, 5, 10]) _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100)) - _check_plot_works(df.plot, subplots=True, title='blah') + _check_plot_works(df.plot, filterwarnings='ignore', subplots=True, title='blah') # We have to redo it here because _check_plot_works does two plots, once without an ax # kwarg and once with an ax kwarg and the new sharex behaviour does not remove the # visibility of the latter axis (as ax is present). @@ -1292,7 +1336,11 @@ def test_plot(self): fig, ax = self.plt.subplots() axes = df.plot.bar(subplots=True, ax=ax) self.assertEqual(len(axes), 1) - self.assertIs(ax.get_axes(), axes[0]) + if self.mpl_ge_1_5_0: + result = ax.axes + else: + result = ax.get_axes() # deprecated + self.assertIs(result, axes[0]) def test_color_and_style_arguments(self): df = DataFrame({'x': [1, 2], 'y': [3, 4]}) @@ -1802,8 +1850,7 @@ def test_area_lim(self): @slow def test_bar_colors(self): import matplotlib.pyplot as plt - - default_colors = plt.rcParams.get('axes.color_cycle') + default_colors = self._maybe_unpack_cycler(plt.rcParams) df = DataFrame(randn(5, 5)) ax = df.plot.bar() @@ -2025,6 +2072,19 @@ def test_plot_scatter_with_c(self): float_array = np.array([0.0, 1.0]) df.plot.scatter(x='A', y='B', c=float_array, cmap='spring') + def test_scatter_colors(self): + df = DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}) + with tm.assertRaises(TypeError): + df.plot.scatter(x='a', y='b', c='c', color='green') + + ax = df.plot.scatter(x='a', y='b', c='c') + tm.assert_numpy_array_equal(ax.collections[0].get_facecolor()[0], + (0, 0, 1, 1)) + + ax = df.plot.scatter(x='a', y='b', color='white') + tm.assert_numpy_array_equal(ax.collections[0].get_facecolor()[0], + (1, 1, 1, 1)) + @slow def test_plot_bar(self): df = DataFrame(randn(6, 4), @@ -2033,7 +2093,7 @@ def test_plot_bar(self): _check_plot_works(df.plot.bar) _check_plot_works(df.plot.bar, legend=False) - _check_plot_works(df.plot.bar, subplots=True) + _check_plot_works(df.plot.bar, filterwarnings='ignore', subplots=True) _check_plot_works(df.plot.bar, stacked=True) df = DataFrame(randn(10, 15), @@ -2250,7 +2310,7 @@ def test_boxplot_vertical(self): self._check_text_labels(ax.get_yticklabels(), labels) self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols)) - axes = _check_plot_works(df.plot.box, subplots=True, + axes = _check_plot_works(df.plot.box, filterwarnings='ignore', subplots=True, vert=False, logx=True) self._check_axes_shape(axes, axes_num=3, layout=(1, 3)) self._check_ax_scales(axes, xaxis='log') @@ -2310,7 +2370,7 @@ def test_kde_df(self): ax = df.plot(kind='kde', rot=20, fontsize=5) self._check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5) - axes = _check_plot_works(df.plot, kind='kde', subplots=True) + axes = _check_plot_works(df.plot, filterwarnings='ignore', kind='kde', subplots=True) self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) axes = df.plot(kind='kde', logy=True, subplots=True) @@ -2326,6 +2386,7 @@ def test_kde_missing_vals(self): @slow def test_hist_df(self): + from matplotlib.patches import Rectangle if self.mpl_le_1_2_1: raise nose.SkipTest("not supported in matplotlib <= 1.2.x") @@ -2336,7 +2397,7 @@ def test_hist_df(self): expected = [com.pprint_thing(c) for c in df.columns] self._check_legend_labels(ax, labels=expected) - axes = _check_plot_works(df.plot.hist, subplots=True, logy=True) + axes = _check_plot_works(df.plot.hist, filterwarnings='ignore', subplots=True, logy=True) self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) self._check_ax_scales(axes, yaxis='log') @@ -2346,11 +2407,14 @@ def test_hist_df(self): ax = series.plot.hist(normed=True, cumulative=True, bins=4) # height of last bin (index 5) must be 1.0 - self.assertAlmostEqual(ax.get_children()[5].get_height(), 1.0) + rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] + self.assertAlmostEqual(rects[-1].get_height(), 1.0) tm.close() ax = series.plot.hist(cumulative=True, bins=4) - self.assertAlmostEqual(ax.get_children()[5].get_height(), 100.0) + rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] + + self.assertAlmostEqual(rects[-2].get_height(), 100.0) tm.close() # if horizontal, yticklabels are rotated @@ -2626,7 +2690,7 @@ def test_line_colors(self): def test_line_colors_and_styles_subplots(self): # GH 9894 from matplotlib import cm - default_colors = self.plt.rcParams.get('axes.color_cycle') + default_colors = self._maybe_unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) @@ -2698,7 +2762,8 @@ def test_area_colors(self): handles, labels = ax.get_legend_handles_labels() # legend is stored as Line2D, thus check linecolors - self._check_colors(handles, linecolors=custom_colors) + linehandles = [x for x in handles if not isinstance(x, PolyCollection)] + self._check_colors(linehandles, linecolors=custom_colors) for h in handles: self.assertTrue(h.get_alpha() is None) tm.close() @@ -2710,12 +2775,13 @@ def test_area_colors(self): self._check_colors(poly, facecolors=jet_colors) handles, labels = ax.get_legend_handles_labels() - self._check_colors(handles, linecolors=jet_colors) + linehandles = [x for x in handles if not isinstance(x, PolyCollection)] + self._check_colors(linehandles, linecolors=jet_colors) for h in handles: self.assertTrue(h.get_alpha() is None) tm.close() - # When stacked=True, alpha is set to 0.5 + # When stacked=False, alpha is set to 0.5 ax = df.plot.area(colormap=cm.jet, stacked=False) self._check_colors(ax.get_lines(), linecolors=jet_colors) poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)] @@ -2724,13 +2790,13 @@ def test_area_colors(self): handles, labels = ax.get_legend_handles_labels() # Line2D can't have alpha in its linecolor - self._check_colors(handles, linecolors=jet_colors) + self._check_colors(handles[:len(jet_colors)], linecolors=jet_colors) for h in handles: self.assertEqual(h.get_alpha(), 0.5) @slow def test_hist_colors(self): - default_colors = self.plt.rcParams.get('axes.color_cycle') + default_colors = self._maybe_unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) ax = df.plot.hist() @@ -2791,7 +2857,7 @@ def test_kde_colors_and_styles_subplots(self): _skip_if_no_scipy_gaussian_kde() from matplotlib import cm - default_colors = self.plt.rcParams.get('axes.color_cycle') + default_colors = self._maybe_unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) @@ -2853,7 +2919,7 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c='k', fliers_c='b'): self._check_colors(bp['fliers'], linecolors=[fliers_c] * len(bp['fliers'])) self._check_colors(bp['caps'], linecolors=[caps_c] * len(bp['caps'])) - default_colors = self.plt.rcParams.get('axes.color_cycle') + default_colors = self._maybe_unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) bp = df.plot.box(return_type='dict') @@ -2900,12 +2966,17 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c='k', fliers_c='b'): def test_default_color_cycle(self): import matplotlib.pyplot as plt - plt.rcParams['axes.color_cycle'] = list('rgbk') + colors = list('rgbk') + if self.mpl_ge_1_5_0: + import cycler + plt.rcParams['axes.prop_cycle'] = cycler.cycler('color', colors) + else: + plt.rcParams['axes.color_cycle'] = colors df = DataFrame(randn(5, 3)) ax = df.plot() - expected = plt.rcParams['axes.color_cycle'][:3] + expected = self._maybe_unpack_cycler(plt.rcParams)[:3] self._check_colors(ax.get_lines(), linecolors=expected) def test_unordered_ts(self): @@ -3032,7 +3103,7 @@ def test_pie_df(self): ax = _check_plot_works(df.plot.pie, y=2) self._check_text_labels(ax.texts, df.index) - axes = _check_plot_works(df.plot.pie, subplots=True) + axes = _check_plot_works(df.plot.pie, filterwarnings='ignore', subplots=True) self.assertEqual(len(axes), len(df.columns)) for ax in axes: self._check_text_labels(ax.texts, df.index) @@ -3041,7 +3112,7 @@ def test_pie_df(self): labels = ['A', 'B', 'C', 'D', 'E'] color_args = ['r', 'g', 'b', 'c', 'm'] - axes = _check_plot_works(df.plot.pie, subplots=True, + axes = _check_plot_works(df.plot.pie, filterwarnings='ignore', subplots=True, labels=labels, colors=color_args) self.assertEqual(len(axes), len(df.columns)) @@ -3095,7 +3166,8 @@ def test_errorbar_plot(self): self._check_has_errorbars(ax, xerr=2, yerr=2) ax = _check_plot_works(df.plot, xerr=0.2, yerr=0.2, kind=kind) self._check_has_errorbars(ax, xerr=2, yerr=2) - axes = _check_plot_works(df.plot, yerr=df_err, xerr=df_err, subplots=True, kind=kind) + axes = _check_plot_works(df.plot, filterwarnings='ignore', yerr=df_err, + xerr=df_err, subplots=True, kind=kind) self._check_has_errorbars(axes, xerr=1, yerr=1) ax = _check_plot_works((df+1).plot, yerr=df_err, xerr=df_err, kind='bar', log=True) @@ -3125,7 +3197,7 @@ def test_errorbar_plot(self): df.plot(yerr=np.random.randn(11)) df_err = DataFrame({'x': ['zzz']*12, 'y': ['zzz']*12}) - with tm.assertRaises(TypeError): + with tm.assertRaises((ValueError, TypeError)): df.plot(yerr=df_err) @slow @@ -3184,7 +3256,8 @@ def test_errorbar_timeseries(self): self._check_has_errorbars(ax, xerr=0, yerr=1) ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind) self._check_has_errorbars(ax, xerr=0, yerr=2) - axes = _check_plot_works(tdf.plot, kind=kind, yerr=tdf_err, subplots=True) + axes = _check_plot_works(tdf.plot, filterwarnings='ignore', kind=kind, + yerr=tdf_err, subplots=True) self._check_has_errorbars(axes, xerr=0, yerr=1) def test_errorbar_asymmetrical(self): @@ -3629,37 +3702,38 @@ def assert_is_valid_plot_return_object(objs): ''.format(objs.__class__.__name__)) -def _check_plot_works(f, *args, **kwargs): +def _check_plot_works(f, filterwarnings='always', **kwargs): import matplotlib.pyplot as plt ret = None - - try: + with warnings.catch_warnings(): + warnings.simplefilter(filterwarnings) try: - fig = kwargs['figure'] - except KeyError: - fig = plt.gcf() - - plt.clf() + try: + fig = kwargs['figure'] + except KeyError: + fig = plt.gcf() - ax = kwargs.get('ax', fig.add_subplot(211)) - ret = f(*args, **kwargs) + plt.clf() - assert_is_valid_plot_return_object(ret) + ax = kwargs.get('ax', fig.add_subplot(211)) + ret = f(**kwargs) - try: - kwargs['ax'] = fig.add_subplot(212) - ret = f(*args, **kwargs) - except Exception: - pass - else: assert_is_valid_plot_return_object(ret) - with ensure_clean(return_filelike=True) as path: - plt.savefig(path) - finally: - tm.close(fig) + try: + kwargs['ax'] = fig.add_subplot(212) + ret = f(**kwargs) + except Exception: + pass + else: + assert_is_valid_plot_return_object(ret) + + with ensure_clean(return_filelike=True) as path: + plt.savefig(path) + finally: + tm.close(fig) - return ret + return ret def _generate_4_axes_via_gridspec(): import matplotlib.pyplot as plt diff --git a/pandas/tests/test_graphics_others.py b/pandas/tests/test_graphics_others.py index 641180c8010c0..b18cbae600b43 100644 --- a/pandas/tests/test_graphics_others.py +++ b/pandas/tests/test_graphics_others.py @@ -161,8 +161,8 @@ def test_plot_fails_when_ax_differs_from_figure(self): @slow def test_autocorrelation_plot(self): from pandas.tools.plotting import autocorrelation_plot - _check_plot_works(autocorrelation_plot, self.ts) - _check_plot_works(autocorrelation_plot, self.ts.values) + _check_plot_works(autocorrelation_plot, series=self.ts) + _check_plot_works(autocorrelation_plot, series=self.ts.values) ax = autocorrelation_plot(self.ts, label='Test') self._check_legend_labels(ax, labels=['Test']) @@ -170,13 +170,13 @@ def test_autocorrelation_plot(self): @slow def test_lag_plot(self): from pandas.tools.plotting import lag_plot - _check_plot_works(lag_plot, self.ts) - _check_plot_works(lag_plot, self.ts, lag=5) + _check_plot_works(lag_plot, series=self.ts) + _check_plot_works(lag_plot, series=self.ts, lag=5) @slow def test_bootstrap_plot(self): from pandas.tools.plotting import bootstrap_plot - _check_plot_works(bootstrap_plot, self.ts, size=10) + _check_plot_works(bootstrap_plot, series=self.ts, size=10) @tm.mplskip @@ -210,7 +210,7 @@ def test_boxplot_legacy(self): _check_plot_works(df.boxplot, column='one', by=['indic', 'indic2']) _check_plot_works(df.boxplot, by='indic') _check_plot_works(df.boxplot, by=['indic', 'indic2']) - _check_plot_works(plotting.boxplot, df['one'], return_type='dict') + _check_plot_works(plotting.boxplot, data=df['one'], return_type='dict') _check_plot_works(df.boxplot, notch=1, return_type='dict') _check_plot_works(df.boxplot, by='indic', notch=1) @@ -304,6 +304,7 @@ def test_boxplot_empty_column(self): @slow def test_hist_df_legacy(self): + from matplotlib.patches import Rectangle _check_plot_works(self.hist_df.hist) # make sure layout is handled @@ -347,7 +348,8 @@ def test_hist_df_legacy(self): # make sure kwargs to hist are handled ax = ser.hist(normed=True, cumulative=True, bins=4) # height of last bin (index 5) must be 1.0 - self.assertAlmostEqual(ax.get_children()[5].get_height(), 1.0) + rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] + self.assertAlmostEqual(rects[-1].get_height(), 1.0) tm.close() ax = ser.hist(log=True) @@ -413,9 +415,9 @@ def scat(**kwds): def scat2(x, y, by=None, ax=None, figsize=None): return plotting.scatter_plot(df, x, y, by, ax, figsize=None) - _check_plot_works(scat2, 0, 1) + _check_plot_works(scat2, x=0, y=1) grouper = Series(np.repeat([1, 2, 3, 4, 5], 20), df.index) - _check_plot_works(scat2, 0, 1, by=grouper) + _check_plot_works(scat2, x=0, y=1, by=grouper) def test_scatter_matrix_axis(self): tm._skip_if_no_scipy() @@ -424,7 +426,8 @@ def test_scatter_matrix_axis(self): with tm.RNGContext(42): df = DataFrame(randn(100, 3)) - axes = _check_plot_works(scatter_matrix, df, range_padding=.1) + axes = _check_plot_works(scatter_matrix, filterwarnings='always', frame=df, + range_padding=.1) axes0_labels = axes[0][0].yaxis.get_majorticklabels() # GH 5662 expected = ['-2', '-1', '0', '1', '2'] @@ -432,7 +435,8 @@ def test_scatter_matrix_axis(self): self._check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) df[0] = ((df[0] - 2) / 3) - axes = _check_plot_works(scatter_matrix, df, range_padding=.1) + axes = _check_plot_works(scatter_matrix, filterwarnings='always', frame=df, + range_padding=.1) axes0_labels = axes[0][0].yaxis.get_majorticklabels() expected = ['-1.2', '-1.0', '-0.8', '-0.6', '-0.4', '-0.2', '0.0'] self._check_text_labels(axes0_labels, expected) @@ -445,17 +449,17 @@ def test_andrews_curves(self): df = self.iris - _check_plot_works(andrews_curves, df, 'Name') + _check_plot_works(andrews_curves, frame=df, class_column='Name') rgba = ('#556270', '#4ECDC4', '#C7F464') - ax = _check_plot_works(andrews_curves, df, 'Name', color=rgba) + ax = _check_plot_works(andrews_curves, frame=df, class_column='Name', color=rgba) self._check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df['Name'][:10]) cnames = ['dodgerblue', 'aquamarine', 'seagreen'] - ax = _check_plot_works(andrews_curves, df, 'Name', color=cnames) + ax = _check_plot_works(andrews_curves, frame=df, class_column='Name', color=cnames) self._check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df['Name'][:10]) - ax = _check_plot_works(andrews_curves, df, 'Name', colormap=cm.jet) + ax = _check_plot_works(andrews_curves, frame=df, class_column='Name', colormap=cm.jet) cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique())) self._check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df['Name'][:10]) @@ -478,23 +482,23 @@ def test_parallel_coordinates(self): df = self.iris - ax = _check_plot_works(parallel_coordinates, df, 'Name') + ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name') nlines = len(ax.get_lines()) nxticks = len(ax.xaxis.get_ticklabels()) rgba = ('#556270', '#4ECDC4', '#C7F464') - ax = _check_plot_works(parallel_coordinates, df, 'Name', color=rgba) + ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', color=rgba) self._check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df['Name'][:10]) cnames = ['dodgerblue', 'aquamarine', 'seagreen'] - ax = _check_plot_works(parallel_coordinates, df, 'Name', color=cnames) + ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', color=cnames) self._check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df['Name'][:10]) - ax = _check_plot_works(parallel_coordinates, df, 'Name', colormap=cm.jet) + ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', colormap=cm.jet) cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique())) self._check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df['Name'][:10]) - ax = _check_plot_works(parallel_coordinates, df, 'Name', axvlines=False) + ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', axvlines=False) assert len(ax.get_lines()) == (nlines - nxticks) colors = ['b', 'g', 'r'] @@ -517,20 +521,20 @@ def test_radviz(self): from matplotlib import cm df = self.iris - _check_plot_works(radviz, df, 'Name') + _check_plot_works(radviz, frame=df, class_column='Name') rgba = ('#556270', '#4ECDC4', '#C7F464') - ax = _check_plot_works(radviz, df, 'Name', color=rgba) + ax = _check_plot_works(radviz, frame=df, class_column='Name', color=rgba) # skip Circle drawn as ticks patches = [p for p in ax.patches[:20] if p.get_label() != ''] self._check_colors(patches[:10], facecolors=rgba, mapping=df['Name'][:10]) cnames = ['dodgerblue', 'aquamarine', 'seagreen'] - _check_plot_works(radviz, df, 'Name', color=cnames) + _check_plot_works(radviz, frame=df, class_column='Name', color=cnames) patches = [p for p in ax.patches[:20] if p.get_label() != ''] self._check_colors(patches, facecolors=cnames, mapping=df['Name'][:10]) - _check_plot_works(radviz, df, 'Name', colormap=cm.jet) + _check_plot_works(radviz, frame=df, class_column='Name', colormap=cm.jet) cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique())) patches = [p for p in ax.patches[:20] if p.get_label() != ''] self._check_colors(patches, facecolors=cmaps, mapping=df['Name'][:10]) @@ -607,6 +611,8 @@ def test_grouped_plot_fignums(self): @slow def test_grouped_hist_legacy(self): + from matplotlib.patches import Rectangle + df = DataFrame(randn(500, 2), columns=['A', 'B']) df['C'] = np.random.randint(0, 4, 500) df['D'] = ['X'] * 500 @@ -633,7 +639,8 @@ def test_grouped_hist_legacy(self): xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) # height of last bin (index 5) must be 1.0 for ax in axes.ravel(): - height = ax.get_children()[5].get_height() + rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] + height = rects[-1].get_height() self.assertAlmostEqual(height, 1.0) self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index cd2297d6018ca..55464a7f1d23e 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -24,13 +24,13 @@ from pandas.compat import range, lrange, lmap, map, zip, string_types import pandas.compat as compat from pandas.util.decorators import Appender - try: # mpl optional import pandas.tseries.converter as conv conv.register() # needs to override so set_xlim works with str/number except ImportError: pass + # Extracted from https://gist.github.com/huyng/816622 # this is the rcParams set when setting display.with_mpl_style # to True. @@ -97,6 +97,48 @@ 'ytick.minor.size': 0.0 } + +def _mpl_le_1_2_1(): + try: + import matplotlib as mpl + return (str(mpl.__version__) <= LooseVersion('1.2.1') and + str(mpl.__version__)[0] != '0') + except ImportError: + return False + +def _mpl_ge_1_3_1(): + try: + import matplotlib + # The or v[0] == '0' is because their versioneer is + # messed up on dev + return (matplotlib.__version__ >= LooseVersion('1.3.1') + or matplotlib.__version__[0] == '0') + except ImportError: + return False + +def _mpl_ge_1_4_0(): + try: + import matplotlib + return (matplotlib.__version__ >= LooseVersion('1.4') + or matplotlib.__version__[0] == '0') + except ImportError: + return False + +def _mpl_ge_1_5_0(): + try: + import matplotlib + return (matplotlib.__version__ >= LooseVersion('1.5') + or matplotlib.__version__[0] == '0') + except ImportError: + return False + +if _mpl_ge_1_5_0(): + # Compat with mp 1.5, which uses cycler. + import cycler + colors = mpl_stylesheet.pop('axes.color_cycle') + mpl_stylesheet['axes.prop_cycle'] = cycler.cycler('color_cycle', colors) + + def _get_standard_kind(kind): return {'density': 'kde'}.get(kind, kind) @@ -784,7 +826,6 @@ def _kind(self): _layout_type = 'vertical' _default_rot = 0 orientation = None - _pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog', 'mark_right', 'stacked'] _attr_defaults = {'logy': False, 'logx': False, 'loglog': False, @@ -973,8 +1014,9 @@ def _maybe_right_yaxis(self, ax, axes_num): else: # otherwise, create twin axes orig_ax, new_ax = ax, ax.twinx() - new_ax._get_lines.color_cycle = orig_ax._get_lines.color_cycle - + # TODO: use Matplotlib public API when available + new_ax._get_lines = orig_ax._get_lines + new_ax._get_patches_for_fill = orig_ax._get_patches_for_fill orig_ax.right_ax, new_ax.left_ax = new_ax, orig_ax if not self._has_plotted_object(orig_ax): # no data on left y @@ -1197,6 +1239,14 @@ def plt(self): import matplotlib.pyplot as plt return plt + @staticmethod + def mpl_ge_1_3_1(): + return _mpl_ge_1_3_1() + + @staticmethod + def mpl_ge_1_5_0(): + return _mpl_ge_1_5_0() + _need_to_set_index = False def _get_xticks(self, convert_period=False): @@ -1474,9 +1524,6 @@ def __init__(self, data, x, y, s=None, c=None, **kwargs): self.c = c def _make_plot(self): - import matplotlib as mpl - mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1') - x, y, c, data = self.x, self.y, self.c, self.data ax = self.axes[0] @@ -1488,9 +1535,13 @@ def _make_plot(self): # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'Greys' cmap = self.plt.cm.get_cmap(cmap) - - if c is None: + color = self.kwds.pop("color", None) + if c is not None and color is not None: + raise TypeError('Specify exactly one of `c` and `color`') + elif c is None and color is None: c_values = self.plt.rcParams['patch.facecolor'] + elif color is not None: + c_values = color elif c_is_column: c_values = self.data[c].values else: @@ -1505,7 +1556,7 @@ def _make_plot(self): if cb: img = ax.collections[0] kws = dict(ax=ax) - if mpl_ge_1_3_1: + if self.mpl_ge_1_3_1(): kws['label'] = c if c_is_column else '' self.fig.colorbar(img, **kws) @@ -1636,6 +1687,11 @@ def _ts_plot(cls, ax, x, data, style=None, **kwds): # Set ax with freq info _decorate_axes(ax, freq, kwds) + # digging deeper + if hasattr(ax, 'left_ax'): + _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)) lines = cls._plot(ax, data.index, data.values, style=style, **kwds) @@ -1743,6 +1799,8 @@ def _plot(cls, ax, x, y, style=None, column_num=None, if not 'color' in kwds: kwds['color'] = lines[0].get_color() + if cls.mpl_ge_1_5_0(): # mpl 1.5 added real support for poly legends + kwds.pop('label') ax.fill_between(xdata, start, y_values, **kwds) cls._update_stacker(ax, stacking_id, y) return lines diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index d9b31c0a1d620..bcd1e400d3974 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -483,6 +483,7 @@ def test_gaps(self): ts[5:25] = np.nan ax = ts.plot() lines = ax.get_lines() + tm._skip_if_mpl_1_5() self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() @@ -532,6 +533,9 @@ def test_gap_upsample(self): self.assertEqual(len(ax.right_ax.get_lines()), 1) l = lines[0] data = l.get_xydata() + + tm._skip_if_mpl_1_5() + tm.assertIsInstance(data, np.ma.core.MaskedArray) mask = data.mask self.assertTrue(mask[5:25, 1].all()) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 6d443c8fbc380..d70e6349ddef1 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -196,6 +196,14 @@ def setUpClass(cls): return cls +def _skip_if_mpl_1_5(): + import matplotlib + v = matplotlib.__version__ + if v > LooseVersion('1.4.3') or v[0] == '0': + import nose + raise nose.SkipTest("matplotlib 1.5") + + def _skip_if_no_scipy(): try: import scipy.stats
closes https://github.com/pydata/pandas/issues/11111 (nice issue number) Testing with tox locally I get 1 failure using either matplotlib 1.4 or 1.5. I may have messed up my tox config though. Still need to cleanup a bunch of stuff, I just threw in changes to get each test passing as I went. release notes et. al coming tonight or tomorrow. Are we making any changes to the build matrix to run a matplotlib 1.5?
https://api.github.com/repos/pandas-dev/pandas/pulls/11145
2015-09-18T19:55:26Z
2015-09-22T11:29:59Z
2015-09-22T11:29:59Z
2016-11-03T12:38:24Z
TST: Verify fix for buffer overflow in read_csv with engine='c'
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 6b7132aea3280..c9ae2f6029530 100755 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -2293,6 +2293,13 @@ def test_chunk_begins_with_newline_whitespace(self): result = self.read_csv(StringIO(data), header=None) self.assertEqual(len(result), 2) + # GH 9735 + chunk1 = 'a' * (1024 * 256 - 2) + '\na' + chunk2 = '\n a' + result = pd.read_csv(StringIO(chunk1 + chunk2), header=None) + expected = pd.DataFrame(['a' * (1024 * 256 - 2), 'a', ' a']) + tm.assert_frame_equal(result, expected) + def test_empty_with_index(self): # GH 10184 data = 'x,y'
Tests for the bug in GH #9735, which was previously fixed in GH #10023.
https://api.github.com/repos/pandas-dev/pandas/pulls/11138
2015-09-17T19:55:56Z
2015-09-17T23:45:20Z
2015-09-17T23:45:20Z
2015-09-18T09:14:24Z
DEPR: Series.is_timeseries
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 070d3bff42c92..2be7194af34b0 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -964,6 +964,7 @@ Deprecations ``DataFrame.add(other, fill_value=0)`` and ``DataFrame.mul(other, fill_value=1.)`` (:issue:`10735`). - ``TimeSeries`` deprecated in favor of ``Series`` (note that this has been alias since 0.13.0), (:issue:`10890`) +- ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`) - Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`) - ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`) diff --git a/pandas/core/series.py b/pandas/core/series.py index 7f2573ce5bdde..05a2ff6840d62 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -251,7 +251,11 @@ def _can_hold_na(self): @property def is_time_series(self): - return self._subtyp in ['time_series', 'sparse_time_series'] + msg = "is_time_series is deprecated. Please use Series.index.is_all_dates" + warnings.warn(msg, FutureWarning, stacklevel=2) + # return self._subtyp in ['time_series', 'sparse_time_series'] + return self.index.is_all_dates + _index = None diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 7fb89b30cec97..2060b31511ead 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -703,11 +703,15 @@ def test_TimeSeries_deprecation(self): def test_constructor(self): # Recognize TimeSeries - self.assertTrue(self.ts.is_time_series) + with tm.assert_produces_warning(FutureWarning): + self.assertTrue(self.ts.is_time_series) + self.assertTrue(self.ts.index.is_all_dates) # Pass in Series derived = Series(self.ts) - self.assertTrue(derived.is_time_series) + with tm.assert_produces_warning(FutureWarning): + self.assertTrue(derived.is_time_series) + self.assertTrue(derived.index.is_all_dates) self.assertTrue(tm.equalContents(derived.index, self.ts.index)) # Ensure new index is not created @@ -718,9 +722,12 @@ def test_constructor(self): self.assertEqual(mixed.dtype, np.object_) self.assertIs(mixed[1], np.NaN) - self.assertFalse(self.empty.is_time_series) - self.assertFalse(Series({}).is_time_series) - + with tm.assert_produces_warning(FutureWarning): + self.assertFalse(self.empty.is_time_series) + self.assertFalse(self.empty.index.is_all_dates) + with tm.assert_produces_warning(FutureWarning): + self.assertFalse(Series({}).is_time_series) + self.assertFalse(Series({}).index.is_all_dates) self.assertRaises(Exception, Series, np.random.randn(3, 3), index=np.arange(3)) @@ -7693,12 +7700,16 @@ def test_set_index_makes_timeseries(self): s = Series(lrange(10)) s.index = idx - self.assertTrue(s.is_time_series == True) + with tm.assert_produces_warning(FutureWarning): + self.assertTrue(s.is_time_series == True) + self.assertTrue(s.index.is_all_dates == True) def test_timeseries_coercion(self): idx = tm.makeDateIndex(10000) ser = Series(np.random.randn(len(idx)), idx.astype(object)) - self.assertTrue(ser.is_time_series) + with tm.assert_produces_warning(FutureWarning): + self.assertTrue(ser.is_time_series) + self.assertTrue(ser.index.is_all_dates) self.assertIsInstance(ser.index, DatetimeIndex) def test_replace(self):
Follow-up for #10890. Deprecate `Series.is_timeseries`.
https://api.github.com/repos/pandas-dev/pandas/pulls/11135
2015-09-17T14:35:38Z
2015-09-17T15:36:06Z
2015-09-17T15:36:06Z
2015-09-17T15:36:08Z
BUG: nested construction with timedelta #11129
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 0b4acdc3e89bb..4d020c4fc768f 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1154,3 +1154,4 @@ Bug Fixes - Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`) - Bug in ``Index`` dtype may not applied properly (:issue:`11017`) - Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`) +- Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`) diff --git a/pandas/core/common.py b/pandas/core/common.py index 8ffffae6bd160..0d9baad9f5d5e 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -1851,9 +1851,9 @@ def _maybe_box(indexer, values, obj, key): def _maybe_box_datetimelike(value): # turn a datetime like into a Timestamp/timedelta as needed - if isinstance(value, np.datetime64): + if isinstance(value, (np.datetime64, datetime)): value = tslib.Timestamp(value) - elif isinstance(value, np.timedelta64): + elif isinstance(value, (np.timedelta64, timedelta)): value = tslib.Timedelta(value) return value diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 24de36d95794c..f46918dd88f47 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3037,6 +3037,29 @@ def create_data(constructor): assert_frame_equal(result_datetime, expected) assert_frame_equal(result_Timestamp, expected) + def test_constructor_dict_timedelta64_index(self): + # GH 10160 + td_as_int = [1, 2, 3, 4] + + def create_data(constructor): + return dict((i, {constructor(s): 2*i}) for i, s in enumerate(td_as_int)) + + data_timedelta64 = create_data(lambda x: np.timedelta64(x, 'D')) + data_timedelta = create_data(lambda x: timedelta(days=x)) + data_Timedelta = create_data(lambda x: Timedelta(x, 'D')) + + expected = DataFrame([{0: 0, 1: None, 2: None, 3: None}, + {0: None, 1: 2, 2: None, 3: None}, + {0: None, 1: None, 2: 4, 3: None}, + {0: None, 1: None, 2: None, 3: 6}], + index=[Timedelta(td, 'D') for td in td_as_int]) + + result_timedelta64 = DataFrame(data_timedelta64) + result_timedelta = DataFrame(data_timedelta) + result_Timedelta = DataFrame(data_Timedelta) + assert_frame_equal(result_timedelta64, expected) + assert_frame_equal(result_timedelta, expected) + assert_frame_equal(result_Timedelta, expected) def _check_basic_constructor(self, empty): "mat: 2d matrix with shpae (3, 2) to input. empty - makes sized objects" diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index 69dc70698ca28..45b98b0f85b1c 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -885,6 +885,24 @@ def test_pickle(self): v_p = self.round_trip_pickle(v) self.assertEqual(v,v_p) + def test_timedelta_hash_equality(self): + #GH 11129 + v = Timedelta(1, 'D') + td = timedelta(days=1) + self.assertEqual(hash(v), hash(td)) + + d = {td: 2} + self.assertEqual(d[v], 2) + + tds = timedelta_range('1 second', periods=20) + self.assertTrue( + all(hash(td) == hash(td.to_pytimedelta()) for td in tds)) + + # python timedeltas drop ns resolution + ns_td = Timedelta(1, 'ns') + self.assertNotEqual(hash(ns_td), hash(ns_td.to_pytimedelta())) + + class TestTimedeltaIndex(tm.TestCase): _multiprocess_can_split_ = True diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index def3764c1113c..7b3e404f7504c 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -2061,7 +2061,10 @@ cdef class _Timedelta(timedelta): int64_t _sign, _d, _h, _m, _s, _ms, _us, _ns def __hash__(_Timedelta self): - return hash(self.value) + if self._has_ns(): + return hash(self.value) + else: + return timedelta.__hash__(self) def __richcmp__(_Timedelta self, object other, int op): cdef: @@ -2110,63 +2113,63 @@ cdef class _Timedelta(timedelta): cdef float64_t frac if self.is_populated: - return + return # put frac in seconds - frac = float(ivalue)/1e9 + frac = float(ivalue)/1e9 if frac < 0: - self._sign = -1 - - # even fraction - if int(-frac/86400) != -frac/86400.0: - self._d = int(-frac/86400.0+1) - frac += 86400*self._d - else: - frac = -frac + self._sign = -1 + + # even fraction + if int(-frac/86400) != -frac/86400.0: + self._d = int(-frac/86400.0+1) + frac += 86400*self._d + else: + frac = -frac else: - self._sign = 1 - self._d = 0 + self._sign = 1 + self._d = 0 if frac >= 86400: - self._d += int(frac / 86400) - frac -= self._d * 86400 + self._d += int(frac / 86400) + frac -= self._d * 86400 if frac >= 3600: - self._h = int(frac / 3600) - frac -= self._h * 3600 + self._h = int(frac / 3600) + frac -= self._h * 3600 else: - self._h = 0 + self._h = 0 if frac >= 60: - self._m = int(frac / 60) - frac -= self._m * 60 + self._m = int(frac / 60) + frac -= self._m * 60 else: - self._m = 0 + self._m = 0 if frac >= 0: - self._s = int(frac) - frac -= self._s + self._s = int(frac) + frac -= self._s else: - self._s = 0 + self._s = 0 if frac != 0: - # reset so we don't lose precision - sfrac = int((self._h*3600 + self._m*60 + self._s)*1e9) - if self._sign < 0: - ifrac = ivalue + self._d*DAY_NS - sfrac - else: - ifrac = ivalue - (self._d*DAY_NS + sfrac) - - self._ms = int(ifrac/1e6) - ifrac -= self._ms*1000*1000 - self._us = int(ifrac/1e3) - ifrac -= self._us*1000 - self._ns = ifrac + # reset so we don't lose precision + sfrac = int((self._h*3600 + self._m*60 + self._s)*1e9) + if self._sign < 0: + ifrac = ivalue + self._d*DAY_NS - sfrac + else: + ifrac = ivalue - (self._d*DAY_NS + sfrac) + + self._ms = int(ifrac/1e6) + ifrac -= self._ms*1000*1000 + self._us = int(ifrac/1e3) + ifrac -= self._us*1000 + self._ns = ifrac else: - self._ms = 0 - self._us = 0 - self._ns = 0 + self._ms = 0 + self._us = 0 + self._ns = 0 self.is_populated = 1 @@ -2177,6 +2180,9 @@ cdef class _Timedelta(timedelta): """ return timedelta(microseconds=int(self.value)/1000) + cpdef bint _has_ns(self): + return self.value % 1000 != 0 + # components named tuple Components = collections.namedtuple('Components',['days','hours','minutes','seconds','milliseconds','microseconds','nanoseconds']) @@ -2433,7 +2439,7 @@ class Timedelta(_Timedelta): """ self._ensure_components() return self._ns - + def total_seconds(self): """ Total duration of timedelta in seconds (to ns precision)
Closes #11129 Per discussion in issue this adds similar hash equality to `_Timedelta` / `datetime.timedelta` that exists for `_Timestamp` / `datetime.datime`. I tried inlining `_Timedelta._ensure_components` and it actually hurt performance a bit, so I left it as a plain `def` but did build a seperate `_has_ns` check for hashing. Adds a little overhead to hashing: ``` In [1]: tds = pd.timedelta_range('1 day', periods=100000) # PR In [2]: %timeit [hash(td) for td in tds] 1 loops, best of 3: 810 ms per loop # Master In [2]: %timeit [hash(td) for td in tds] 1 loops, best of 3: 765 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11134
2015-09-17T01:34:38Z
2015-09-17T11:45:05Z
2015-09-17T11:45:05Z
2015-09-17T22:31:12Z
ERR: make sure raising TypeError on invalid nanops reductions xref #10472
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 3d625c0299db5..622324155b551 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -915,6 +915,7 @@ Other API Changes - ``groupby`` using ``Categorical`` follows the same rule as ``Categorical.unique`` described above (:issue:`10508`) - When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`) +- some numeric reduction operators would return ``ValueError``, rather than ``TypeError`` on object types that includes strings and numbers (:issue:`11131`) - ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`) diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 8602fdc26d6f6..1561c0aefbb9b 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -43,7 +43,16 @@ def _f(*args, **kwargs): raise TypeError('reduction operation {0!r} not allowed for ' 'this dtype'.format(f.__name__.replace('nan', ''))) - return f(*args, **kwargs) + try: + return f(*args, **kwargs) + except ValueError as e: + # we want to transform an object array + # ValueError message to the more typical TypeError + # e.g. this is normally a disallowed function on + # object arrays that contain strings + if is_object_dtype(args[0]): + raise TypeError(e) + raise return _f @@ -93,7 +102,17 @@ def f(values, axis=None, skipna=True, **kwds): else: result = alt(values, axis=axis, skipna=skipna, **kwds) except Exception: - result = alt(values, axis=axis, skipna=skipna, **kwds) + try: + result = alt(values, axis=axis, skipna=skipna, **kwds) + except ValueError as e: + # we want to transform an object array + # ValueError message to the more typical TypeError + # e.g. this is normally a disallowed function on + # object arrays that contain strings + + if is_object_dtype(values): + raise TypeError(e) + raise return result @@ -372,7 +391,6 @@ def nanvar(values, axis=None, skipna=True, ddof=1): values = values.copy() np.putmask(values, mask, 0) - # xref GH10242 # Compute variance via two-pass algorithm, which is stable against # cancellation errors and relatively accurate for small numbers of diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 24de36d95794c..01ad4992dd785 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -12792,7 +12792,7 @@ def test_numeric_only_flag(self): # df1 has all numbers, df2 has a letter inside self.assertRaises(TypeError, lambda : getattr(df1, meth)(axis=1, numeric_only=False)) - self.assertRaises(ValueError, lambda : getattr(df2, meth)(axis=1, numeric_only=False)) + self.assertRaises(TypeError, lambda : getattr(df2, meth)(axis=1, numeric_only=False)) def test_sem(self): alt = lambda x: np.std(x, ddof=1)/np.sqrt(len(x)) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index d25009171afdf..7fb89b30cec97 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2912,6 +2912,10 @@ def testit(): exp = alternate(s) self.assertEqual(res, exp) + # check on string data + if name not in ['sum','min','max']: + self.assertRaises(TypeError, f, Series(list('abc'))) + # Invalid axis. self.assertRaises(ValueError, f, self.series, axis=1)
xref #https://github.com/blaze/dask/issues/693
https://api.github.com/repos/pandas-dev/pandas/pulls/11131
2015-09-16T23:46:48Z
2015-09-17T00:28:58Z
2015-09-17T00:28:58Z
2015-09-17T00:28:58Z
BLD: install build deps when building
diff --git a/ci/install_conda.sh b/ci/install_conda.sh index 1db1e7fa6f571..c54f5494c12ee 100755 --- a/ci/install_conda.sh +++ b/ci/install_conda.sh @@ -78,21 +78,13 @@ conda config --set ssl_verify false || exit 1 # Useful for debugging any issues with conda conda info -a || exit 1 -REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.txt" -conda create -n pandas python=$TRAVIS_PYTHON_VERSION || exit 1 -conda install -n pandas --file=${REQ} || exit 1 - -conda install -n pandas pip setuptools nose || exit 1 -conda remove -n pandas pandas +# build deps +REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.build" +time conda create -n pandas python=$TRAVIS_PYTHON_VERSION nose || exit 1 +time conda install -n pandas --file=${REQ} || exit 1 source activate pandas -# we may have additional pip installs -REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.pip" -if [ -e ${REQ} ]; then - pip install -r $REQ -fi - # set the compiler cache to work if [ "$IRON_TOKEN" ]; then export PATH=/usr/lib/ccache:/usr/lib64/ccache:$PATH @@ -104,15 +96,33 @@ if [ "$IRON_TOKEN" ]; then fi if [ "$BUILD_TEST" ]; then + + # build testing pip uninstall --yes cython pip install cython==0.15.1 ( python setup.py build_ext --inplace && python setup.py develop ) || true + else - python setup.py build_ext --inplace && python setup.py develop -fi -for package in beautifulsoup4; do - pip uninstall --yes $package -done + # build but don't install + time python setup.py build_ext --inplace || exit 1 + + # we may have run installations + REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.run" + time conda install -n pandas --file=${REQ} || exit 1 + + # we may have additional pip installs + REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.pip" + if [ -e ${REQ} ]; then + pip install -r $REQ + fi + + # remove any installed pandas package + conda remove pandas + + # install our pandas + python setup.py develop || exit 1 + +fi true diff --git a/ci/install_pydata.sh b/ci/install_pydata.sh index f2ab5af34dc64..667b57897be7e 100755 --- a/ci/install_pydata.sh +++ b/ci/install_pydata.sh @@ -90,7 +90,8 @@ fi # Force virtualenv to accept system_site_packages rm -f $VIRTUAL_ENV/lib/python$TRAVIS_PYTHON_VERSION/no-global-site-packages.txt -time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.txt +# build deps +time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.build # Need to enable for locale testing. The location of the locale file(s) is # distro specific. For example, on Arch Linux all of the locales are in a @@ -147,6 +148,9 @@ else python setup.py develop fi +# install the run libs +time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.run + # restore cython (if not numpy building) if [ -z "$NUMPY_BUILD" ]; then time pip install $PIP_ARGS $(cat ci/requirements-${wheel_box}.txt | grep -i cython) diff --git a/ci/requirements-2.6.build b/ci/requirements-2.6.build new file mode 100644 index 0000000000000..f8cbd8cef3fef --- /dev/null +++ b/ci/requirements-2.6.build @@ -0,0 +1,4 @@ +numpy=1.7.0 +cython=0.19.1 +dateutil=1.5 +pytz=2013b diff --git a/ci/requirements-2.6.txt b/ci/requirements-2.6.run similarity index 93% rename from ci/requirements-2.6.txt rename to ci/requirements-2.6.run index 9b338cee26801..d8ed2a4262cfc 100644 --- a/ci/requirements-2.6.txt +++ b/ci/requirements-2.6.run @@ -1,5 +1,4 @@ numpy=1.7.0 -cython=0.19.1 dateutil=1.5 pytz=2013b scipy=0.11.0 diff --git a/ci/requirements-2.7.build b/ci/requirements-2.7.build new file mode 100644 index 0000000000000..df543aaf40f69 --- /dev/null +++ b/ci/requirements-2.7.build @@ -0,0 +1,4 @@ +dateutil=2.1 +pytz=2013b +numpy=1.7.1 +cython=0.19.1 diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.run similarity index 91% rename from ci/requirements-2.7.txt rename to ci/requirements-2.7.run index 2764e740886da..a740966684ab2 100644 --- a/ci/requirements-2.7.txt +++ b/ci/requirements-2.7.run @@ -1,8 +1,7 @@ dateutil=2.1 pytz=2013b +numpy=1.7.1 xlwt=0.7.5 -numpy=1.7.0 -cython=0.19.1 numexpr=2.2.2 pytables=3.0.0 matplotlib=1.3.1 @@ -12,7 +11,6 @@ sqlalchemy=0.9.6 lxml=3.2.1 scipy xlsxwriter=0.4.6 -statsmodels boto=2.36.0 bottleneck=0.8.0 psycopg2=2.5.2 @@ -20,3 +18,4 @@ patsy pymysql=0.6.3 html5lib=1.0b2 beautiful-soup=4.2.1 +statsmodels diff --git a/ci/requirements-2.7_32.txt b/ci/requirements-2.7_32.txt deleted file mode 100644 index 2e241b1ce45bf..0000000000000 --- a/ci/requirements-2.7_32.txt +++ /dev/null @@ -1,11 +0,0 @@ -python-dateutil -pytz -xlwt -numpy -cython -numexpr -pytables -matplotlib -openpyxl -xlrd -scipy diff --git a/ci/requirements-2.7_64.txt b/ci/requirements-2.7_64.txt deleted file mode 100644 index 2e241b1ce45bf..0000000000000 --- a/ci/requirements-2.7_64.txt +++ /dev/null @@ -1,11 +0,0 @@ -python-dateutil -pytz -xlwt -numpy -cython -numexpr -pytables -matplotlib -openpyxl -xlrd -scipy diff --git a/ci/requirements-2.7_BUILD_TEST.txt b/ci/requirements-2.7_BUILD_TEST.build similarity index 84% rename from ci/requirements-2.7_BUILD_TEST.txt rename to ci/requirements-2.7_BUILD_TEST.build index b273ca043c4a2..faf1e3559f7f1 100644 --- a/ci/requirements-2.7_BUILD_TEST.txt +++ b/ci/requirements-2.7_BUILD_TEST.build @@ -2,4 +2,3 @@ dateutil pytz numpy cython -nose diff --git a/ci/requirements-2.7_LOCALE.build b/ci/requirements-2.7_LOCALE.build new file mode 100644 index 0000000000000..ada6686f599ca --- /dev/null +++ b/ci/requirements-2.7_LOCALE.build @@ -0,0 +1,4 @@ +python-dateutil +pytz=2013b +numpy=1.7.1 +cython=0.19.1 diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.run similarity index 94% rename from ci/requirements-2.7_LOCALE.txt rename to ci/requirements-2.7_LOCALE.run index fc7aceb0dffbb..9bb37ee10f8db 100644 --- a/ci/requirements-2.7_LOCALE.txt +++ b/ci/requirements-2.7_LOCALE.run @@ -1,11 +1,10 @@ python-dateutil pytz=2013b +numpy=1.7.1 xlwt=0.7.5 openpyxl=1.6.2 xlsxwriter=0.4.6 xlrd=0.9.2 -numpy=1.7.1 -cython=0.19.1 bottleneck=0.8.0 matplotlib=1.2.1 patsy=0.1.0 diff --git a/ci/requirements-2.7_NUMPY_DEV_1_8_x.txt b/ci/requirements-2.7_NUMPY_DEV_1_8_x.txt deleted file mode 100644 index 90fa8f11c1cfd..0000000000000 --- a/ci/requirements-2.7_NUMPY_DEV_1_8_x.txt +++ /dev/null @@ -1,3 +0,0 @@ -python-dateutil -pytz==2013b -cython==0.19.1 diff --git a/ci/requirements-2.7_NUMPY_DEV_master.txt b/ci/requirements-2.7_NUMPY_DEV_master.build similarity index 100% rename from ci/requirements-2.7_NUMPY_DEV_master.txt rename to ci/requirements-2.7_NUMPY_DEV_master.build diff --git a/ci/requirements-2.7_NUMPY_DEV_master.run b/ci/requirements-2.7_NUMPY_DEV_master.run new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ci/requirements-2.7_SLOW.build b/ci/requirements-2.7_SLOW.build new file mode 100644 index 0000000000000..9558cf00ddf5c --- /dev/null +++ b/ci/requirements-2.7_SLOW.build @@ -0,0 +1,4 @@ +python-dateutil +pytz +numpy +cython diff --git a/ci/requirements-2.7_SLOW.txt b/ci/requirements-2.7_SLOW.run similarity index 96% rename from ci/requirements-2.7_SLOW.txt rename to ci/requirements-2.7_SLOW.run index 563ce3e1190e6..b6c9250dd775e 100644 --- a/ci/requirements-2.7_SLOW.txt +++ b/ci/requirements-2.7_SLOW.run @@ -1,7 +1,6 @@ python-dateutil pytz numpy -cython matplotlib scipy patsy diff --git a/ci/requirements-3.3.build b/ci/requirements-3.3.build new file mode 100644 index 0000000000000..8dc9b2102596a --- /dev/null +++ b/ci/requirements-3.3.build @@ -0,0 +1,4 @@ +python-dateutil +pytz=2013b +numpy=1.8.0 +cython=0.19.1 diff --git a/ci/requirements-3.3.txt b/ci/requirements-3.3.run similarity index 93% rename from ci/requirements-3.3.txt rename to ci/requirements-3.3.run index cb8c3f7c10127..09d07c1c51f94 100644 --- a/ci/requirements-3.3.txt +++ b/ci/requirements-3.3.run @@ -1,11 +1,10 @@ python-dateutil pytz=2013b +numpy=1.8.0 openpyxl=1.6.2 xlsxwriter=0.4.6 xlrd=0.9.2 html5lib=1.0b2 -numpy=1.8.0 -cython=0.19.1 numexpr pytables bottleneck=0.8.0 diff --git a/ci/requirements-3.4.build b/ci/requirements-3.4.build new file mode 100644 index 0000000000000..9558cf00ddf5c --- /dev/null +++ b/ci/requirements-3.4.build @@ -0,0 +1,4 @@ +python-dateutil +pytz +numpy +cython diff --git a/ci/requirements-3.4_SLOW.txt b/ci/requirements-3.4.run similarity index 91% rename from ci/requirements-3.4_SLOW.txt rename to ci/requirements-3.4.run index ecc31dad78d07..73209a4623a49 100644 --- a/ci/requirements-3.4_SLOW.txt +++ b/ci/requirements-3.4.run @@ -1,5 +1,6 @@ python-dateutil pytz +numpy openpyxl xlsxwriter xlrd @@ -7,8 +8,6 @@ xlwt html5lib patsy beautiful-soup -numpy -cython scipy numexpr pytables @@ -16,5 +15,5 @@ matplotlib=1.3.1 lxml sqlalchemy bottleneck -pymysql +pymysql=0.6.3 psycopg2 diff --git a/ci/requirements-3.4_32.txt b/ci/requirements-3.4_32.txt deleted file mode 100644 index f2a364ed64311..0000000000000 --- a/ci/requirements-3.4_32.txt +++ /dev/null @@ -1,10 +0,0 @@ -python-dateutil -pytz -openpyxl -xlrd -numpy -cython -scipy -numexpr -pytables -matplotlib diff --git a/ci/requirements-3.4_64.txt b/ci/requirements-3.4_64.txt deleted file mode 100644 index f2a364ed64311..0000000000000 --- a/ci/requirements-3.4_64.txt +++ /dev/null @@ -1,10 +0,0 @@ -python-dateutil -pytz -openpyxl -xlrd -numpy -cython -scipy -numexpr -pytables -matplotlib diff --git a/ci/requirements-3.4_SLOW.build b/ci/requirements-3.4_SLOW.build new file mode 100644 index 0000000000000..9558cf00ddf5c --- /dev/null +++ b/ci/requirements-3.4_SLOW.build @@ -0,0 +1,4 @@ +python-dateutil +pytz +numpy +cython diff --git a/ci/requirements-3.4.txt b/ci/requirements-3.4_SLOW.run similarity index 87% rename from ci/requirements-3.4.txt rename to ci/requirements-3.4_SLOW.run index fd0a5bc53dd7e..4c60fb883954f 100644 --- a/ci/requirements-3.4.txt +++ b/ci/requirements-3.4_SLOW.run @@ -1,5 +1,6 @@ python-dateutil pytz +numpy openpyxl xlsxwriter xlrd @@ -7,8 +8,6 @@ xlwt html5lib patsy beautiful-soup -numpy -cython scipy numexpr pytables @@ -16,5 +15,6 @@ matplotlib lxml sqlalchemy bottleneck -pymysql==0.6.3 +pymysql psycopg2 +statsmodels diff --git a/ci/requirements-3.5.build b/ci/requirements-3.5.build new file mode 100644 index 0000000000000..9558cf00ddf5c --- /dev/null +++ b/ci/requirements-3.5.build @@ -0,0 +1,4 @@ +python-dateutil +pytz +numpy +cython diff --git a/ci/requirements-3.5.txt b/ci/requirements-3.5.run similarity index 97% rename from ci/requirements-3.5.txt rename to ci/requirements-3.5.run index 7af2c473bceca..f06cac7b8b9c7 100644 --- a/ci/requirements-3.5.txt +++ b/ci/requirements-3.5.run @@ -1,12 +1,11 @@ python-dateutil pytz +numpy openpyxl xlsxwriter xlrd xlwt patsy -numpy -cython scipy numexpr pytables
closes #11122 dependency resolution in the `pandas` channel is a bit challenging as the current script tries to install all deps up front before building. But `statsmodels` requires pandas, so a current version is installed (e.g. the rc), and several of the deps are changed. So fixed, but installing only the build deps, compiling, then install in the run deps.
https://api.github.com/repos/pandas-dev/pandas/pulls/11127
2015-09-16T21:02:57Z
2015-09-16T23:01:46Z
2015-09-16T23:01:46Z
2015-09-16T23:01:46Z
BUG: Fix computation of invalid NaN indexes for interpolate.
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 0b4acdc3e89bb..3d625c0299db5 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -383,7 +383,7 @@ Other enhancements - ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`) -- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`) +- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218`, :issue:`10420`, :issue:`11115`) .. ipython:: python diff --git a/pandas/core/common.py b/pandas/core/common.py index 8ffffae6bd160..9189b0d89de4f 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -1582,13 +1582,10 @@ def interpolate_1d(xvalues, yvalues, method='linear', limit=None, method = 'values' def _interp_limit(invalid, fw_limit, bw_limit): - "Get idx of values that won't be forward-filled b/c they exceed the limit." - all_nans = np.where(invalid)[0] - if all_nans.size == 0: # no nans anyway - return [] - violate = [invalid[max(0, x - bw_limit):x + fw_limit + 1] for x in all_nans] - violate = np.array([x.all() & (x.size > bw_limit + fw_limit) for x in violate]) - return all_nans[violate] + fw_limit - bw_limit + "Get idx of values that won't be filled b/c they exceed the limits." + for x in np.where(invalid)[0]: + if invalid[max(0, x - fw_limit):x + bw_limit + 1].all(): + yield x valid_limit_directions = ['forward', 'backward', 'both'] limit_direction = limit_direction.lower() @@ -1624,7 +1621,7 @@ def _interp_limit(invalid, fw_limit, bw_limit): if limit_direction == 'backward': violate_limit = sorted(end_nans | set(_interp_limit(invalid, 0, limit))) if limit_direction == 'both': - violate_limit = _interp_limit(invalid, limit, limit) + violate_limit = sorted(_interp_limit(invalid, limit, limit)) xvalues = getattr(xvalues, 'values', xvalues) yvalues = getattr(yvalues, 'values', yvalues) diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index 19989116b26df..3a26be2ca1032 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -878,7 +878,6 @@ def test_interp_limit_forward(self): def test_interp_limit_bad_direction(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - expected = Series([1., 3., 5., 7., 9., 11.]) self.assertRaises(ValueError, s.interpolate, method='linear', limit=2, @@ -930,6 +929,25 @@ def test_interp_limit_to_ends(self): method='linear', limit=2, limit_direction='both') assert_series_equal(result, expected) + def test_interp_limit_before_ends(self): + # These test are for issue #11115 -- limit ends properly. + s = Series([np.nan, np.nan, 5, 7, np.nan, np.nan]) + + expected = Series([np.nan, np.nan, 5., 7., 7., np.nan]) + result = s.interpolate( + method='linear', limit=1, limit_direction='forward') + assert_series_equal(result, expected) + + expected = Series([np.nan, 5., 5., 7., np.nan, np.nan]) + result = s.interpolate( + method='linear', limit=1, limit_direction='backward') + assert_series_equal(result, expected) + + expected = Series([np.nan, 5., 5., 7., 7., np.nan]) + result = s.interpolate( + method='linear', limit=1, limit_direction='both') + assert_series_equal(result, expected) + def test_interp_all_good(self): # scipy tm._skip_if_no_scipy()
Fixes issue #11115. This change fixes up a couple edge cases for the computation of invalid NaN indexes for interpolation limits. I've also added a test explicitly for the reported bug (and similar behaviors at the opposite end of the series) in #11115. /cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/11124
2015-09-16T18:03:12Z
2015-09-16T23:04:10Z
2015-09-16T23:04:10Z
2015-09-16T23:04:13Z
BF: do not assume that expanduser would replace all ~
diff --git a/pandas/io/tests/test_common.py b/pandas/io/tests/test_common.py index 34e7c94b64bcb..03d1e4fb1f365 100644 --- a/pandas/io/tests/test_common.py +++ b/pandas/io/tests/test_common.py @@ -3,6 +3,7 @@ """ from pandas.compat import StringIO import os +from os.path import isabs import pandas.util.testing as tm @@ -16,7 +17,7 @@ def test_expand_user(self): expanded_name = common._expand_user(filename) self.assertNotEqual(expanded_name, filename) - self.assertNotIn('~', expanded_name) + self.assertTrue(isabs(expanded_name)) self.assertEqual(os.path.expanduser(filename), expanded_name) def test_expand_user_normal_path(self): @@ -24,14 +25,13 @@ def test_expand_user_normal_path(self): expanded_name = common._expand_user(filename) self.assertEqual(expanded_name, filename) - self.assertNotIn('~', expanded_name) self.assertEqual(os.path.expanduser(filename), expanded_name) def test_get_filepath_or_buffer_with_path(self): filename = '~/sometest' filepath_or_buffer, _, _ = common.get_filepath_or_buffer(filename) self.assertNotEqual(filepath_or_buffer, filename) - self.assertNotIn('~', filepath_or_buffer) + self.assertTrue(isabs(filepath_or_buffer)) self.assertEqual(os.path.expanduser(filename), filepath_or_buffer) def test_get_filepath_or_buffer_with_buffer(self):
since it must not e.g. if there is ~ in some directory name along the path (awkward but possible/allowed). Better to check either new path is absolute. Removed 1 test which had no value
https://api.github.com/repos/pandas-dev/pandas/pulls/11120
2015-09-16T01:58:17Z
2015-09-17T01:00:29Z
2015-09-17T01:00:29Z
2015-09-22T14:16:59Z
COMPAT: compat for python 3.5, #11097
diff --git a/.travis.yml b/.travis.yml index 6460a9a726b48..4e46fb7ad85ca 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,13 +43,6 @@ matrix: - CLIPBOARD_GUI=gtk2 - BUILD_TYPE=conda - DOC_BUILD=true # if rst files were changed, build docs in parallel with tests - - python: 3.3 - env: - - JOB_NAME: "33_nslow" - - NOSE_ARGS="not slow and not disabled" - - FULL_DEPS=true - - CLIPBOARD=xsel - - BUILD_TYPE=conda - python: 3.4 env: - JOB_NAME: "34_nslow" @@ -64,6 +57,13 @@ matrix: - FULL_DEPS=true - CLIPBOARD=xsel - BUILD_TYPE=conda + - python: 3.3 + env: + - JOB_NAME: "33_nslow" + - NOSE_ARGS="not slow and not disabled" + - FULL_DEPS=true + - CLIPBOARD=xsel + - BUILD_TYPE=conda - python: 2.7 env: - JOB_NAME: "27_slow" @@ -104,10 +104,10 @@ matrix: - BUILD_TYPE=pydata - PANDAS_TESTING_MODE="deprecate" allow_failures: - - python: 3.5 + - python: 3.3 env: - - JOB_NAME: "35_nslow" - - NOSE_ARGS="not slow and not network and not disabled" + - JOB_NAME: "33_nslow" + - NOSE_ARGS="not slow and not disabled" - FULL_DEPS=true - CLIPBOARD=xsel - BUILD_TYPE=conda diff --git a/ci/requirements-3.5.txt b/ci/requirements-3.5.txt index 1e67cefa6c98e..7af2c473bceca 100644 --- a/ci/requirements-3.5.txt +++ b/ci/requirements-3.5.txt @@ -10,3 +10,15 @@ cython scipy numexpr pytables +html5lib +lxml + +# currently causing some warnings +#sqlalchemy +#pymysql +#psycopg2 + +# not available from conda +#beautiful-soup +#bottleneck +#matplotlib diff --git a/doc/source/install.rst b/doc/source/install.rst index 36a6c4038f8be..5c5f6bdcf0ddf 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -18,7 +18,7 @@ Instructions for installing from source, Python version support ---------------------- -Officially Python 2.6, 2.7, 3.3, and 3.4. +Officially Python 2.6, 2.7, 3.3, 3.4, and 3.5 Installing pandas ----------------- diff --git a/doc/source/release.rst b/doc/source/release.rst index 2010939724c5e..4fa8ba06cf8d0 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -64,6 +64,7 @@ Highlights include: - Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` - Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>` - Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` +- Compatibility with Python 3.5 See the :ref:`v0.17.0 Whatsnew <whatsnew_0170>` overview for an extensive list of all enhancements and bugs that have been fixed in 0.17.0. diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 615bfc9e23253..ab0e7a481f031 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -49,6 +49,7 @@ Highlights include: - Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` - Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>` - Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` +- Compatibility with Python 3.5 (:issue:`11097`) Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating. diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 2ac81f15a6d6c..bad7192047e19 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -36,9 +36,9 @@ import sys import types -PY3 = (sys.version_info[0] >= 3) PY2 = sys.version_info[0] == 2 - +PY3 = (sys.version_info[0] >= 3) +PY35 = (sys.version_info >= (3, 5)) try: import __builtin__ as builtins diff --git a/pandas/computation/expr.py b/pandas/computation/expr.py index 123051d802d7d..2ae6f29f74efc 100644 --- a/pandas/computation/expr.py +++ b/pandas/computation/expr.py @@ -516,7 +516,54 @@ def visit_Attribute(self, node, **kwargs): raise ValueError("Invalid Attribute context {0}".format(ctx.__name__)) - def visit_Call(self, node, side=None, **kwargs): + def visit_Call_35(self, node, side=None, **kwargs): + """ in 3.5 the starargs attribute was changed to be more flexible, #11097 """ + + if isinstance(node.func, ast.Attribute): + res = self.visit_Attribute(node.func) + elif not isinstance(node.func, ast.Name): + raise TypeError("Only named functions are supported") + else: + try: + res = self.visit(node.func) + except UndefinedVariableError: + # Check if this is a supported function name + try: + res = FuncNode(node.func.id) + except ValueError: + # Raise original error + raise + + if res is None: + raise ValueError("Invalid function call {0}".format(node.func.id)) + if hasattr(res, 'value'): + res = res.value + + if isinstance(res, FuncNode): + + new_args = [ self.visit(arg) for arg in node.args ] + + if node.keywords: + raise TypeError("Function \"{0}\" does not support keyword " + "arguments".format(res.name)) + + return res(*new_args, **kwargs) + + else: + + new_args = [ self.visit(arg).value for arg in node.args ] + + for key in node.keywords: + if not isinstance(key, ast.keyword): + raise ValueError("keyword error in function call " + "'{0}'".format(node.func.id)) + + if key.arg: + kwargs.append(ast.keyword(keyword.arg, self.visit(keyword.value))) + + return self.const_type(res(*new_args, **kwargs), self.env) + + def visit_Call_legacy(self, node, side=None, **kwargs): # this can happen with: datetime.datetime if isinstance(node.func, ast.Attribute): @@ -607,6 +654,13 @@ def visitor(x, y): operands = node.values return reduce(visitor, operands) +# ast.Call signature changed on 3.5, +# conditionally change which methods is named +# visit_Call depending on Python version, #11097 +if compat.PY35: + BaseExprVisitor.visit_Call = BaseExprVisitor.visit_Call_35 +else: + BaseExprVisitor.visit_Call = BaseExprVisitor.visit_Call_legacy _python_not_supported = frozenset(['Dict', 'BoolOp', 'In', 'NotIn']) _numexpr_supported_calls = frozenset(_reductions + _mathops) diff --git a/pandas/io/tests/__init__.py b/pandas/io/tests/__init__.py index e6089154cd5e5..e69de29bb2d1d 100644 --- a/pandas/io/tests/__init__.py +++ b/pandas/io/tests/__init__.py @@ -1,4 +0,0 @@ - -def setUp(): - import socket - socket.setdefaulttimeout(5) diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 96bac2c45340b..e39e71b474f58 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -27,6 +27,13 @@ def _skip_if_no_lxml(): except ImportError: raise nose.SkipTest("no lxml") +def _skip_if_no_bs(): + try: + import bs4 + import html5lib + except ImportError: + raise nose.SkipTest("no html5lib/bs4") + def assert_n_failed_equals_n_null_columns(wngs, obj, cls=SymbolWarning): all_nan_cols = pd.Series(dict((k, pd.isnull(v).all()) for k, v in @@ -288,6 +295,7 @@ class TestYahooOptions(tm.TestCase): def setUpClass(cls): super(TestYahooOptions, cls).setUpClass() _skip_if_no_lxml() + _skip_if_no_bs() # aapl has monthlies cls.aapl = web.Options('aapl', 'yahoo') diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 5eef48c51d070..06338e576a2b1 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2573,7 +2573,9 @@ def test_tuple_index(self): idx = [(0., 1.), (2., 3.), (4., 5.)] data = np.random.randn(30).reshape((3, 10)) DF = DataFrame(data, index=idx, columns=col) - with tm.assert_produces_warning(expected_warning=PerformanceWarning): + + expected_warning = Warning if compat.PY35 else PerformanceWarning + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): self._check_roundtrip(DF, tm.assert_frame_equal) def test_index_types(self): @@ -2585,23 +2587,25 @@ def test_index_types(self): check_index_type=True, check_series_type=True) - with tm.assert_produces_warning(expected_warning=PerformanceWarning): + # nose has a deprecation warning in 3.5 + expected_warning = Warning if compat.PY35 else PerformanceWarning + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): ser = Series(values, [0, 'y']) self._check_roundtrip(ser, func) - with tm.assert_produces_warning(expected_warning=PerformanceWarning): + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): ser = Series(values, [datetime.datetime.today(), 0]) self._check_roundtrip(ser, func) - with tm.assert_produces_warning(expected_warning=PerformanceWarning): + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): ser = Series(values, ['y', 0]) self._check_roundtrip(ser, func) - with tm.assert_produces_warning(expected_warning=PerformanceWarning): + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): ser = Series(values, [datetime.date.today(), 'a']) self._check_roundtrip(ser, func) - with tm.assert_produces_warning(expected_warning=PerformanceWarning): + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): ser = Series(values, [1.23, 'b']) self._check_roundtrip(ser, func) @@ -3377,7 +3381,8 @@ def test_retain_index_attributes2(self): with ensure_clean_path(self.path) as path: - with tm.assert_produces_warning(expected_warning=AttributeConflictWarning): + expected_warning = Warning if compat.PY35 else AttributeConflictWarning + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): df = DataFrame(dict(A = Series(lrange(3), index=date_range('2000-1-1',periods=3,freq='H')))) df.to_hdf(path,'data',mode='w',append=True) @@ -3391,7 +3396,7 @@ def test_retain_index_attributes2(self): self.assertEqual(read_hdf(path,'data').index.name, 'foo') - with tm.assert_produces_warning(expected_warning=AttributeConflictWarning): + with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False): idx2 = date_range('2001-1-1',periods=3,freq='H') idx2.name = 'bar' diff --git a/setup.py b/setup.py index 370c49a754b95..2d1b9374f6c94 100755 --- a/setup.py +++ b/setup.py @@ -181,6 +181,7 @@ def build_extensions(self): 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', 'Programming Language :: Cython', 'Topic :: Scientific/Engineering', ]
closes #11097 - update install / compat docs for 3.5 - use visit_Call based on the version of python - skip if html5lib is not installed in test_data - bug in nose causes deprecation warning in some pytables tests - remove superfluous socket timeout
https://api.github.com/repos/pandas-dev/pandas/pulls/11114
2015-09-15T16:32:37Z
2015-09-15T23:25:24Z
2015-09-15T23:25:24Z
2015-09-15T23:25:24Z
COMPAT: Add Google BigQuery support for python 3 #11094
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 03cac12436898..c8ab9599cd92a 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -332,6 +332,7 @@ Google BigQuery Enhancements - Added ability to replace an existing table and schema when calling the :func:`pandas.io.gbq.to_gbq` function via the ``if_exists`` argument. See the :ref:`docs <io.bigquery>` for more details (:issue:`8325`). - ``InvalidColumnOrder`` and ``InvalidPageToken`` in the gbq module will raise ``ValueError`` instead of ``IOError``. - The ``generate_bq_schema()`` function is now deprecated and will be removed in a future version (:issue:`11121`) +- Update the gbq module to support Python 3 (:issue:`11094`). .. _whatsnew_0170.enhancements.other: diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index 22500f23f6e07..e9568db06f391 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -13,10 +13,9 @@ from pandas.tools.merge import concat from pandas.core.common import PandasError from pandas.util.decorators import deprecate +from pandas.compat import lzip, bytes_to_str def _check_google_client_version(): - if compat.PY3: - raise NotImplementedError("Google's libraries do not support Python 3 yet") try: import pkg_resources @@ -24,11 +23,16 @@ def _check_google_client_version(): except ImportError: raise ImportError('Could not import pkg_resources (setuptools).') + if compat.PY3: + google_api_minimum_version = '1.4.1' + else: + google_api_minimum_version = '1.2.0' + _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version - if StrictVersion(_GOOGLE_API_CLIENT_VERSION) < StrictVersion('1.2.0'): - raise ImportError("pandas requires google-api-python-client >= 1.2.0 for Google " - "BigQuery support, current version " + _GOOGLE_API_CLIENT_VERSION) + if StrictVersion(_GOOGLE_API_CLIENT_VERSION) < StrictVersion(google_api_minimum_version): + raise ImportError("pandas requires google-api-python-client >= {0} for Google BigQuery support, " + "current version {1}".format(google_api_minimum_version, _GOOGLE_API_CLIENT_VERSION)) logger = logging.getLogger('pandas.io.gbq') logger.setLevel(logging.ERROR) @@ -161,7 +165,7 @@ def get_service(credentials): def process_http_error(ex): # See `BigQuery Troubleshooting Errors <https://cloud.google.com/bigquery/troubleshooting-errors>`__ - status = json.loads(ex.content)['error'] + status = json.loads(bytes_to_str(ex.content))['error'] errors = status.get('errors', None) if errors: @@ -353,10 +357,10 @@ def _parse_data(schema, rows): fields = schema['fields'] col_types = [field['type'] for field in fields] - col_names = [field['name'].encode('ascii', 'ignore') for field in fields] + col_names = [str(field['name']) for field in fields] col_dtypes = [dtype_map.get(field['type'], object) for field in fields] page_array = np.zeros((len(rows),), - dtype=zip(col_names, col_dtypes)) + dtype=lzip(col_names, col_dtypes)) for row_num, raw_row in enumerate(rows): entries = raw_row.get('f', []) diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py index b57530e926a2e..cc1e901d8f119 100644 --- a/pandas/io/tests/test_gbq.py +++ b/pandas/io/tests/test_gbq.py @@ -30,45 +30,44 @@ def _test_imports(): - if not compat.PY3: + global _GOOGLE_API_CLIENT_INSTALLED, _GOOGLE_API_CLIENT_VALID_VERSION, \ + _HTTPLIB2_INSTALLED, _SETUPTOOLS_INSTALLED - global _GOOGLE_API_CLIENT_INSTALLED, _GOOGLE_API_CLIENT_VALID_VERSION, \ - _HTTPLIB2_INSTALLED, _SETUPTOOLS_INSTALLED - - try: - import pkg_resources - _SETUPTOOLS_INSTALLED = True - except ImportError: - _SETUPTOOLS_INSTALLED = False - - if _SETUPTOOLS_INSTALLED: - try: - from apiclient.discovery import build - from apiclient.errors import HttpError + try: + import pkg_resources + _SETUPTOOLS_INSTALLED = True + except ImportError: + _SETUPTOOLS_INSTALLED = False - from oauth2client.client import OAuth2WebServerFlow - from oauth2client.client import AccessTokenRefreshError + if compat.PY3: + google_api_minimum_version = '1.4.1' + else: + google_api_minimum_version = '1.2.0' - from oauth2client.file import Storage - from oauth2client.tools import run_flow - _GOOGLE_API_CLIENT_INSTALLED=True - _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version + if _SETUPTOOLS_INSTALLED: + try: + from apiclient.discovery import build + from apiclient.errors import HttpError - if StrictVersion(_GOOGLE_API_CLIENT_VERSION) >= StrictVersion('1.2.0'): - _GOOGLE_API_CLIENT_VALID_VERSION = True + from oauth2client.client import OAuth2WebServerFlow + from oauth2client.client import AccessTokenRefreshError - except ImportError: - _GOOGLE_API_CLIENT_INSTALLED = False + from oauth2client.file import Storage + from oauth2client.tools import run_flow + _GOOGLE_API_CLIENT_INSTALLED=True + _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version + if StrictVersion(_GOOGLE_API_CLIENT_VERSION) >= StrictVersion(google_api_minimum_version): + _GOOGLE_API_CLIENT_VALID_VERSION = True - try: - import httplib2 - _HTTPLIB2_INSTALLED = True - except ImportError: - _HTTPLIB2_INSTALLED = False + except ImportError: + _GOOGLE_API_CLIENT_INSTALLED = False - if compat.PY3: - raise NotImplementedError("Google's libraries do not support Python 3 yet") + try: + import httplib2 + _HTTPLIB2_INSTALLED = True + except ImportError: + _HTTPLIB2_INSTALLED = False if not _SETUPTOOLS_INSTALLED: raise ImportError('Could not import pkg_resources (setuptools).') @@ -77,8 +76,8 @@ def _test_imports(): raise ImportError('Could not import Google API Client.') if not _GOOGLE_API_CLIENT_VALID_VERSION: - raise ImportError("pandas requires google-api-python-client >= 1.2.0 for Google " - "BigQuery support, current version " + _GOOGLE_API_CLIENT_VERSION) + raise ImportError("pandas requires google-api-python-client >= {0} for Google BigQuery support, " + "current version {1}".format(google_api_minimum_version, _GOOGLE_API_CLIENT_VERSION)) if not _HTTPLIB2_INSTALLED: raise ImportError("pandas requires httplib2 for Google BigQuery support") @@ -299,7 +298,12 @@ def test_unicode_string_conversion_and_normalization(self): {'UNICODE_STRING': [u("\xe9\xfc")]} ) - query = 'SELECT "\xc3\xa9\xc3\xbc" as UNICODE_STRING' + unicode_string = "\xc3\xa9\xc3\xbc" + + if compat.PY3: + unicode_string = unicode_string.encode('latin-1').decode('utf8') + + query = 'SELECT "{0}" as UNICODE_STRING'.format(unicode_string) df = gbq.read_gbq(query, project_id=PROJECT_ID) tm.assert_frame_equal(df, correct_test_datatype)
closes #11094 Adds gbq support for python 3.4
https://api.github.com/repos/pandas-dev/pandas/pulls/11110
2015-09-15T15:32:08Z
2015-09-27T14:10:24Z
2015-09-27T14:10:24Z
2015-09-27T14:19:46Z
DOC: fix ref to template for plot accessor
diff --git a/doc/source/api.rst b/doc/source/api.rst index 01634d7c02481..b1fe77c298d71 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -982,7 +982,7 @@ specific plotting methods of the form ``DataFrame.plot.<kind>``. .. autosummary:: :toctree: generated/ - :template: autosummary/accessor_plot.rst + :template: autosummary/accessor_callable.rst DataFrame.plot
https://api.github.com/repos/pandas-dev/pandas/pulls/11104
2015-09-15T13:55:12Z
2015-09-15T13:55:20Z
2015-09-15T13:55:20Z
2015-09-15T13:58:56Z
ENH: Data formatting with unicode length
diff --git a/doc/source/options.rst b/doc/source/options.rst index fb57175f96eaa..46ff2b6e5c343 100644 --- a/doc/source/options.rst +++ b/doc/source/options.rst @@ -440,3 +440,56 @@ For instance: pd.reset_option('^display\.') To round floats on a case-by-case basis, you can also use :meth:`~pandas.Series.round` and :meth:`~pandas.DataFrame.round`. + +.. _options.east_asian_width: + +Unicode Formatting +------------------ + +.. warning:: + + Enabling this option will affect the performance for printing of DataFrame and Series (about 2 times slower). + Use only when it is actually required. + +Some East Asian countries use Unicode characters its width is corresponding to 2 alphabets. +If DataFrame or Series contains these characters, default output cannot be aligned properly. + +.. ipython:: python + + df = pd.DataFrame({u'国籍': ['UK', u'日本'], u'名前': ['Alice', u'しのぶ']}) + df + +Enable ``display.unicode.east_asian_width`` allows pandas to check each character's "East Asian Width" property. +These characters can be aligned properly by checking this property, but it takes longer time than standard ``len`` function. + +.. ipython:: python + + pd.set_option('display.unicode.east_asian_width', True) + df + +In addition, Unicode contains characters which width is "Ambiguous". These character's width should be either 1 or 2 depending on terminal setting or encoding. Because this cannot be distinguished from Python, ``display.unicode.ambiguous_as_wide`` option is added to handle this. + +By default, "Ambiguous" character's width, "¡" (inverted exclamation) in below example, is regarded as 1. + +.. note:: + + This should be aligned properly in terminal which uses monospaced font. + +.. ipython:: python + + df = pd.DataFrame({'a': ['xxx', u'¡¡'], 'b': ['yyy', u'¡¡']}) + df + +Enabling ``display.unicode.ambiguous_as_wide`` lets pandas to regard these character's width as 2. Note that this option will be effective only when ``display.unicode.east_asian_width`` is enabled. Confirm starting position has been changed, but not aligned properly because the setting is mismatched with this environment. + +.. ipython:: python + + pd.set_option('display.unicode.ambiguous_as_wide', True) + df + +.. ipython:: python + :suppress: + + pd.set_option('display.unicode.east_asian_width', False) + pd.set_option('display.unicode.ambiguous_as_wide', False) + diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 9990d2bd1c78d..59b69d22c3b62 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -49,6 +49,7 @@ Highlights include: - Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` - Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>` - Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` +- Display format with plain text can optionally align with Unicode East Asian Width, see :ref:`here <whatsnew_0170.east_asian_width>` - Compatibility with Python 3.5 (:issue:`11097`) - Compatibility with matplotlib 1.5.0 (:issue:`11111`) @@ -334,6 +335,36 @@ Google BigQuery Enhancements - The ``generate_bq_schema()`` function is now deprecated and will be removed in a future version (:issue:`11121`) - Update the gbq module to support Python 3 (:issue:`11094`). +.. _whatsnew_0170.east_asian_width: + +Display Alignemnt with Unicode East Asian Width +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. warning:: + + Enabling this option will affect the performance for printing of DataFrame and Series (about 2 times slower). + Use only when it is actually required. + +Some East Asian countries use Unicode characters its width is corresponding to 2 alphabets. If DataFrame or Series contains these characters, default output cannot be aligned properly. The following options are added to enable precise handling for these characters. + +- ``display.unicode.east_asian_width``: Whether to use the Unicode East Asian Width to calculate the display text width. (:issue:`2612`) +- ``display.unicode.ambiguous_as_wide``: Whether to handle Unicode characters belong to Ambiguous as Wide. (:issue:`11102`) + +.. ipython:: python + + df = pd.DataFrame({u'国籍': ['UK', u'日本'], u'名前': ['Alice', u'しのぶ']}) + df + + pd.set_option('display.unicode.east_asian_width', True) + df + +For further details, see :ref:`here <options.east_asian_width>` + +.. ipython:: python + :suppress: + + pd.set_option('display.unicode.east_asian_width', False) + .. _whatsnew_0170.enhancements.other: Other enhancements diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index bad7192047e19..ba5114dd7d8ba 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -35,6 +35,7 @@ from itertools import product import sys import types +from unicodedata import east_asian_width PY2 = sys.version_info[0] == 2 PY3 = (sys.version_info[0] >= 3) @@ -90,6 +91,7 @@ def lmap(*args, **kwargs): def lfilter(*args, **kwargs): return list(filter(*args, **kwargs)) + else: # Python 2 import re @@ -176,6 +178,11 @@ class to receive bound method # The license for this library can be found in LICENSES/SIX and the code can be # found at https://bitbucket.org/gutworth/six +# Definition of East Asian Width +# http://unicode.org/reports/tr11/ +# Ambiguous width can be changed by option +_EAW_MAP = {'Na': 1, 'N': 1, 'W': 2, 'F': 2, 'H': 1} + if PY3: string_types = str, integer_types = int, @@ -188,6 +195,20 @@ def u(s): def u_safe(s): return s + + def strlen(data, encoding=None): + # encoding is for compat with PY2 + return len(data) + + def east_asian_len(data, encoding=None, ambiguous_width=1): + """ + Calculate display width considering unicode East Asian Width + """ + if isinstance(data, text_type): + return sum([_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data]) + else: + return len(data) + else: string_types = basestring, integer_types = (int, long) @@ -204,6 +225,25 @@ def u_safe(s): except: return s + def strlen(data, encoding=None): + try: + data = data.decode(encoding) + except UnicodeError: + pass + return len(data) + + def east_asian_len(data, encoding=None, ambiguous_width=1): + """ + Calculate display width considering unicode East Asian Width + """ + if isinstance(data, text_type): + try: + data = data.decode(encoding) + except UnicodeError: + pass + return sum([_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data]) + else: + return len(data) string_and_binary_types = string_types + (binary_type,) diff --git a/pandas/core/common.py b/pandas/core/common.py index 2d403f904a446..2411925207696 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2149,21 +2149,33 @@ def _count_not_none(*args): -def adjoin(space, *lists): +def adjoin(space, *lists, **kwargs): """ Glues together two sets of strings using the amount of space requested. The idea is to prettify. - """ + + ---------- + space : int + number of spaces for padding + lists : str + list of str which being joined + strlen : callable + function used to calculate the length of each str. Needed for unicode + handling. + justfunc : callable + function used to justify str. Needed for unicode handling. + """ + strlen = kwargs.pop('strlen', len) + justfunc = kwargs.pop('justfunc', _justify) + out_lines = [] newLists = [] - lengths = [max(map(len, x)) + space for x in lists[:-1]] - + lengths = [max(map(strlen, x)) + space for x in lists[:-1]] # not the last one lengths.append(max(map(len, lists[-1]))) - maxLen = max(map(len, lists)) for i, lst in enumerate(lists): - nl = [x.ljust(lengths[i]) for x in lst] + nl = justfunc(lst, lengths[i], mode='left') nl.extend([' ' * lengths[i]] * (maxLen - len(lst))) newLists.append(nl) toJoin = zip(*newLists) @@ -2171,6 +2183,16 @@ def adjoin(space, *lists): out_lines.append(_join_unicode(lines)) return _join_unicode(out_lines, sep='\n') +def _justify(texts, max_len, mode='right'): + """ + Perform ljust, center, rjust against string or list-like + """ + if mode == 'left': + return [x.ljust(max_len) for x in texts] + elif mode == 'center': + return [x.center(max_len) for x in texts] + else: + return [x.rjust(max_len) for x in texts] def _join_unicode(lines, sep=''): try: diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 03eaa45582bef..751a530ce73cc 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -144,6 +144,17 @@ Deprecated. """ +pc_east_asian_width_doc = """ +: boolean + Whether to use the Unicode East Asian Width to calculate the display text width + Enabling this may affect to the performance (default: False) +""" +pc_ambiguous_as_wide_doc = """ +: boolean + Whether to handle Unicode characters belong to Ambiguous as Wide (width=2) + (default: False) +""" + pc_line_width_deprecation_warning = """\ line_width has been deprecated, use display.width instead (currently both are identical) @@ -282,6 +293,10 @@ def mpl_style_cb(key): pc_line_width_doc) cf.register_option('memory_usage', True, pc_memory_usage_doc, validator=is_instance_factory([type(None), bool])) + cf.register_option('unicode.east_asian_width', False, + pc_east_asian_width_doc, validator=is_bool) + cf.register_option('unicode.ambiguous_as_wide', False, + pc_east_asian_width_doc, validator=is_bool) cf.deprecate_option('display.line_width', msg=pc_line_width_deprecation_warning, diff --git a/pandas/core/format.py b/pandas/core/format.py index 0c1a3dbadbd86..5f12abb543513 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -138,6 +138,7 @@ def __init__(self, series, buf=None, length=True, header=True, float_format = get_option("display.float_format") self.float_format = float_format self.dtype = dtype + self.adj = _get_adjustment() self._chk_truncate() @@ -221,22 +222,24 @@ def to_string(self): fmt_index, have_header = self._get_formatted_index() fmt_values = self._get_formatted_values() - maxlen = max(len(x) for x in fmt_index) # max index len + maxlen = max(self.adj.len(x) for x in fmt_index) # max index len pad_space = min(maxlen, 60) if self.truncate_v: n_header_rows = 0 row_num = self.tr_row_num - width = len(fmt_values[row_num-1]) + width = self.adj.len(fmt_values[row_num-1]) if width > 3: dot_str = '...' else: dot_str = '..' - dot_str = dot_str.center(width) + # Series uses mode=center because it has single value columns + # DataFrame uses mode=left + dot_str = self.adj.justify([dot_str], width, mode='center')[0] fmt_values.insert(row_num + n_header_rows, dot_str) fmt_index.insert(row_num + 1, '') - result = adjoin(3, *[fmt_index[1:], fmt_values]) + result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values]) if self.header and have_header: result = fmt_index[0] + '\n' + result @@ -247,19 +250,54 @@ def to_string(self): return compat.text_type(u('').join(result)) -def _strlen_func(): - if compat.PY3: # pragma: no cover - _strlen = len - else: - encoding = get_option("display.encoding") +class TextAdjustment(object): + + def __init__(self): + self.encoding = get_option("display.encoding") + + def len(self, text): + return compat.strlen(text, encoding=self.encoding) + + def justify(self, texts, max_len, mode='right'): + return com._justify(texts, max_len, mode=mode) + + def adjoin(self, space, *lists, **kwargs): + return com.adjoin(space, *lists, strlen=self.len, + justfunc=self.justify, **kwargs) + + +class EastAsianTextAdjustment(TextAdjustment): + + def __init__(self): + super(EastAsianTextAdjustment, self).__init__() + if get_option("display.unicode.ambiguous_as_wide"): + self.ambiguous_width = 2 + else: + self.ambiguous_width = 1 + + def len(self, text): + return compat.east_asian_len(text, encoding=self.encoding, + ambiguous_width=self.ambiguous_width) + + def justify(self, texts, max_len, mode='right'): + # re-calculate padding space per str considering East Asian Width + def _get_pad(t): + return max_len - self.len(t) + len(t) + + if mode == 'left': + return [x.ljust(_get_pad(x)) for x in texts] + elif mode == 'center': + return [x.center(_get_pad(x)) for x in texts] + else: + return [x.rjust(_get_pad(x)) for x in texts] - def _strlen(x): - try: - return len(x.decode(encoding)) - except UnicodeError: - return len(x) - return _strlen +def _get_adjustment(): + use_east_asian_width = get_option("display.unicode.east_asian_width") + if use_east_asian_width: + return EastAsianTextAdjustment() + else: + return TextAdjustment() class TableFormatter(object): @@ -338,6 +376,7 @@ def __init__(self, frame, buf=None, columns=None, col_space=None, self.columns = frame.columns self._chk_truncate() + self.adj = _get_adjustment() def _chk_truncate(self): ''' @@ -414,7 +453,6 @@ def _to_str_columns(self): """ Render a DataFrame to a list of columns (as lists of strings). """ - _strlen = _strlen_func() frame = self.tr_frame # may include levels names also @@ -427,27 +465,23 @@ def _to_str_columns(self): for i, c in enumerate(frame): cheader = str_columns[i] max_colwidth = max(self.col_space or 0, - *(_strlen(x) for x in cheader)) - + *(self.adj.len(x) for x in cheader)) fmt_values = self._format_col(i) - fmt_values = _make_fixed_width(fmt_values, self.justify, - minimum=max_colwidth) + minimum=max_colwidth, + adj=self.adj) - max_len = max(np.max([_strlen(x) for x in fmt_values]), + max_len = max(np.max([self.adj.len(x) for x in fmt_values]), max_colwidth) - if self.justify == 'left': - cheader = [x.ljust(max_len) for x in cheader] - else: - cheader = [x.rjust(max_len) for x in cheader] - + cheader = self.adj.justify(cheader, max_len, mode=self.justify) stringified.append(cheader + fmt_values) else: stringified = [] for i, c in enumerate(frame): fmt_values = self._format_col(i) fmt_values = _make_fixed_width(fmt_values, self.justify, - minimum=(self.col_space or 0)) + minimum=(self.col_space or 0), + adj=self.adj) stringified.append(fmt_values) @@ -461,13 +495,13 @@ def _to_str_columns(self): if truncate_h: col_num = self.tr_col_num - col_width = len(strcols[self.tr_size_col][0]) # infer from column header + col_width = self.adj.len(strcols[self.tr_size_col][0]) # infer from column header strcols.insert(self.tr_col_num + 1, ['...'.center(col_width)] * (len(str_index))) if truncate_v: n_header_rows = len(str_index) - len(frame) row_num = self.tr_row_num for ix, col in enumerate(strcols): - cwidth = len(strcols[ix][row_num]) # infer from above row + cwidth = self.adj.len(strcols[ix][row_num]) # infer from above row is_dot_col = False if truncate_h: is_dot_col = ix == col_num + 1 @@ -477,13 +511,13 @@ def _to_str_columns(self): my_str = '..' if ix == 0: - dot_str = my_str.ljust(cwidth) + dot_mode = 'left' elif is_dot_col: - cwidth = len(strcols[self.tr_size_col][0]) - dot_str = my_str.center(cwidth) + cwidth = self.adj.len(strcols[self.tr_size_col][0]) + dot_mode = 'center' else: - dot_str = my_str.rjust(cwidth) - + dot_mode = 'right' + dot_str = self.adj.justify([my_str], cwidth, mode=dot_mode)[0] strcols[ix].insert(row_num + n_header_rows, dot_str) return strcols @@ -492,6 +526,7 @@ def to_string(self): Render a DataFrame to a console-friendly tabular output. """ from pandas import Series + frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: @@ -503,11 +538,11 @@ def to_string(self): else: strcols = self._to_str_columns() if self.line_width is None: # no need to wrap around just print the whole frame - text = adjoin(1, *strcols) + text = self.adj.adjoin(1, *strcols) elif not isinstance(self.max_cols, int) or self.max_cols > 0: # need to wrap around text = self._join_multiline(*strcols) else: # max_cols == 0. Try to fit frame to terminal - text = adjoin(1, *strcols).split('\n') + text = self.adj.adjoin(1, *strcols).split('\n') row_lens = Series(text).apply(len) max_len_col_ix = np.argmax(row_lens) max_len = row_lens[max_len_col_ix] @@ -535,7 +570,7 @@ def to_string(self): # and then generate string representation self._chk_truncate() strcols = self._to_str_columns() - text = adjoin(1, *strcols) + text = self.adj.adjoin(1, *strcols) self.buf.writelines(text) @@ -549,9 +584,9 @@ def _join_multiline(self, *strcols): strcols = list(strcols) if self.index: idx = strcols.pop(0) - lwidth -= np.array([len(x) for x in idx]).max() + adjoin_width + lwidth -= np.array([self.adj.len(x) for x in idx]).max() + adjoin_width - col_widths = [np.array([len(x) for x in col]).max() + col_widths = [np.array([self.adj.len(x) for x in col]).max() if len(col) > 0 else 0 for col in strcols] col_bins = _binify(col_widths, lwidth) @@ -572,8 +607,7 @@ def _join_multiline(self, *strcols): row.append([' \\'] + [' '] * (nrows - 1)) else: row.append([' '] * nrows) - - str_lst.append(adjoin(adjoin_width, *row)) + str_lst.append(self.adj.adjoin(adjoin_width, *row)) st = ed return '\n\n'.join(str_lst) @@ -776,11 +810,12 @@ def _get_formatted_index(self, frame): formatter=fmt) else: fmt_index = [index.format(name=show_index_names, formatter=fmt)] - fmt_index = [tuple(_make_fixed_width( - list(x), justify='left', minimum=(self.col_space or 0))) - for x in fmt_index] + fmt_index = [tuple(_make_fixed_width(list(x), justify='left', + minimum=(self.col_space or 0), + adj=self.adj)) + for x in fmt_index] - adjoined = adjoin(1, *fmt_index).split('\n') + adjoined = self.adj.adjoin(1, *fmt_index).split('\n') # empty space for columns if show_col_names: @@ -2222,13 +2257,16 @@ def _formatter(x): return _formatter -def _make_fixed_width(strings, justify='right', minimum=None): +def _make_fixed_width(strings, justify='right', minimum=None, + adj=None): + if len(strings) == 0 or justify == 'all': return strings - _strlen = _strlen_func() + if adj is None: + adj = _get_adjustment() - max_len = np.max([_strlen(x) for x in strings]) + max_len = np.max([adj.len(x) for x in strings]) if minimum is not None: max_len = max(minimum, max_len) @@ -2237,22 +2275,14 @@ def _make_fixed_width(strings, justify='right', minimum=None): if conf_max is not None and max_len > conf_max: max_len = conf_max - if justify == 'left': - justfunc = lambda self, x: self.ljust(x) - else: - justfunc = lambda self, x: self.rjust(x) - def just(x): - eff_len = max_len - if conf_max is not None: - if (conf_max > 3) & (_strlen(x) > max_len): - x = x[:eff_len - 3] + '...' - - return justfunc(x, eff_len) - - result = [just(x) for x in strings] + if (conf_max > 3) & (adj.len(x) > max_len): + x = x[:max_len - 3] + '...' + return x + strings = [just(x) for x in strings] + result = adj.justify(strings, max_len, mode=justify) return result diff --git a/pandas/core/index.py b/pandas/core/index.py index d64a20fc9563c..1daa0e1b52d02 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -488,7 +488,7 @@ def _format_data(self): """ Return the formatted data as a unicode string """ - from pandas.core.format import get_console_size + from pandas.core.format import get_console_size, _get_adjustment display_width, _ = get_console_size() if display_width is None: display_width = get_option('display.width') or 80 @@ -502,14 +502,19 @@ def _format_data(self): formatter = self._formatter_func # do we want to justify (only do so for non-objects) - is_justify = not (self.inferred_type == 'string' or self.inferred_type == 'categorical' and is_object_dtype(self.categories)) + is_justify = not (self.inferred_type in ('string', 'unicode') or + (self.inferred_type == 'categorical' and + is_object_dtype(self.categories))) # are we a truncated display is_truncated = n > max_seq_items + # adj can optionaly handle unicode eastern asian width + adj = _get_adjustment() + def _extend_line(s, line, value, display_width, next_line_prefix): - if len(line.rstrip()) + len(value.rstrip()) >= display_width: + if adj.len(line.rstrip()) + adj.len(value.rstrip()) >= display_width: s += line.rstrip() line = next_line_prefix line += value @@ -517,7 +522,7 @@ def _extend_line(s, line, value, display_width, next_line_prefix): def best_len(values): if values: - return max([len(x) for x in values]) + return max([adj.len(x) for x in values]) else: return 0 @@ -556,8 +561,10 @@ def best_len(values): word = head[i] + sep + ' ' summary, line = _extend_line(summary, line, word, display_width, space2) + if is_truncated: - summary += line + space2 + '...' + # remove trailing space of last line + summary += line.rstrip() + space2 + '...' line = space2 for i in range(len(tail)-1): @@ -4501,8 +4508,11 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False, start=int(names), sentinel=sentinel) + if adjoin: - return com.adjoin(space, *result_levels).split('\n') + from pandas.core.format import _get_adjustment + adj = _get_adjustment() + return adj.adjoin(space, *result_levels).split('\n') else: return result_levels diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 9173c0a87f6c2..e97010e1cb552 100755 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -2,7 +2,7 @@ # pylint: disable=E1101,E1103,W0232 from datetime import datetime -from pandas.compat import range, lrange, u +from pandas.compat import range, lrange, u, PY3 import os import pickle import re @@ -534,6 +534,33 @@ def test_print_none_width(self): with option_context("display.width", None): self.assertEqual(exp, repr(a)) + def test_unicode_print(self): + if PY3: + _rep = repr + else: + _rep = unicode + + c = pd.Categorical(['aaaaa', 'bb', 'cccc'] * 20) + expected = u"""[aaaaa, bb, cccc, aaaaa, bb, ..., bb, cccc, aaaaa, bb, cccc] +Length: 60 +Categories (3, object): [aaaaa, bb, cccc]""" + self.assertEqual(_rep(c), expected) + + c = pd.Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20) + expected = u"""[ああああ, いいいいい, ううううううう, ああああ, いいいいい, ..., いいいいい, ううううううう, ああああ, いいいいい, ううううううう] +Length: 60 +Categories (3, object): [ああああ, いいいいい, ううううううう]""" + self.assertEqual(_rep(c), expected) + + # unicode option should not affect to Categorical, as it doesn't care the repr width + with option_context('display.unicode.east_asian_width', True): + + c = pd.Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20) + expected = u"""[ああああ, いいいいい, ううううううう, ああああ, いいいいい, ..., いいいいい, ううううううう, ああああ, いいいいい, ううううううう] +Length: 60 +Categories (3, object): [ああああ, いいいいい, ううううううう]""" + self.assertEqual(_rep(c), expected) + def test_periodindex(self): idx1 = PeriodIndex(['2014-01', '2014-01', '2014-02', '2014-02', '2014-03', '2014-03'], freq='M') diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index c488d22da7dfe..003fd134cf210 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -14,6 +14,7 @@ from pandas.core.common import notnull, isnull, array_equivalent import pandas.core.common as com import pandas.core.convert as convert +import pandas.core.format as fmt import pandas.util.testing as tm import pandas.core.config as cf @@ -332,6 +333,99 @@ def test_adjoin(): assert(adjoined == expected) + +class TestFormattBase(tm.TestCase): + + def test_adjoin(self): + data = [['a', 'b', 'c'], + ['dd', 'ee', 'ff'], + ['ggg', 'hhh', 'iii']] + expected = 'a dd ggg\nb ee hhh\nc ff iii' + + adjoined = com.adjoin(2, *data) + + self.assertEqual(adjoined, expected) + + def test_adjoin_unicode(self): + data = [[u'あ', 'b', 'c'], + ['dd', u'ええ', 'ff'], + ['ggg', 'hhh', u'いいい']] + expected = u'あ dd ggg\nb ええ hhh\nc ff いいい' + adjoined = com.adjoin(2, *data) + self.assertEqual(adjoined, expected) + + adj = fmt.EastAsianTextAdjustment() + + expected = u"""あ dd ggg +b ええ hhh +c ff いいい""" + adjoined = adj.adjoin(2, *data) + self.assertEqual(adjoined, expected) + cols = adjoined.split('\n') + self.assertEqual(adj.len(cols[0]), 13) + self.assertEqual(adj.len(cols[1]), 13) + self.assertEqual(adj.len(cols[2]), 16) + + expected = u"""あ dd ggg +b ええ hhh +c ff いいい""" + adjoined = adj.adjoin(7, *data) + self.assertEqual(adjoined, expected) + cols = adjoined.split('\n') + self.assertEqual(adj.len(cols[0]), 23) + self.assertEqual(adj.len(cols[1]), 23) + self.assertEqual(adj.len(cols[2]), 26) + + def test_justify(self): + adj = fmt.EastAsianTextAdjustment() + + def just(x, *args, **kwargs): + # wrapper to test single str + return adj.justify([x], *args, **kwargs)[0] + + self.assertEqual(just('abc', 5, mode='left'), 'abc ') + self.assertEqual(just('abc', 5, mode='center'), ' abc ') + self.assertEqual(just('abc', 5, mode='right'), ' abc') + self.assertEqual(just(u'abc', 5, mode='left'), 'abc ') + self.assertEqual(just(u'abc', 5, mode='center'), ' abc ') + self.assertEqual(just(u'abc', 5, mode='right'), ' abc') + + self.assertEqual(just(u'パンダ', 5, mode='left'), u'パンダ') + self.assertEqual(just(u'パンダ', 5, mode='center'), u'パンダ') + self.assertEqual(just(u'パンダ', 5, mode='right'), u'パンダ') + + self.assertEqual(just(u'パンダ', 10, mode='left'), u'パンダ ') + self.assertEqual(just(u'パンダ', 10, mode='center'), u' パンダ ') + self.assertEqual(just(u'パンダ', 10, mode='right'), u' パンダ') + + def test_east_asian_len(self): + adj = fmt.EastAsianTextAdjustment() + + self.assertEqual(adj.len('abc'), 3) + self.assertEqual(adj.len(u'abc'), 3) + + self.assertEqual(adj.len(u'パンダ'), 6) + self.assertEqual(adj.len(u'パンダ'), 5) + self.assertEqual(adj.len(u'パンダpanda'), 11) + self.assertEqual(adj.len(u'パンダpanda'), 10) + + + def test_ambiguous_width(self): + adj = fmt.EastAsianTextAdjustment() + self.assertEqual(adj.len(u'¡¡ab'), 4) + + with cf.option_context('display.unicode.ambiguous_as_wide', True): + adj = fmt.EastAsianTextAdjustment() + self.assertEqual(adj.len(u'¡¡ab'), 6) + + data = [[u'あ', 'b', 'c'], + ['dd', u'ええ', 'ff'], + ['ggg', u'¡¡ab', u'いいい']] + expected = u'あ dd ggg \nb ええ ¡¡ab\nc ff いいい' + adjoined = adj.adjoin(2, *data) + self.assertEqual(adjoined, expected) + + def test_iterpairs(): data = [1, 2, 3, 4] expected = [(1, 2), diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 58c365029a694..b5220c8cb2706 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -162,10 +162,10 @@ def test_repr_truncation(self): r = repr(df) r = r[r.find('\n') + 1:] - _strlen = fmt._strlen_func() + adj = fmt._get_adjustment() for line, value in lzip(r.split('\n'), df['B']): - if _strlen(value) + 1 > max_len: + if adj.len(value) + 1 > max_len: self.assertIn('...', line) else: self.assertNotIn('...', line) @@ -438,6 +438,209 @@ def test_to_string_with_formatters_unicode(self): self.assertEqual(result, u(' c/\u03c3\n') + '0 1\n1 2\n2 3') + def test_east_asian_unicode_frame(self): + if PY3: + _rep = repr + else: + _rep = unicode + + # not alighned properly because of east asian width + + # mid col + df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'], + 'b': [1, 222, 33333, 4]}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" a b\na あ 1\n" + u"bb いいい 222\nc う 33333\n" + u"ddd ええええええ 4") + self.assertEqual(_rep(df), expected) + + # last col + df = DataFrame({'a': [1, 222, 33333, 4], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" a b\na 1 あ\n" + u"bb 222 いいい\nc 33333 う\n" + u"ddd 4 ええええええ") + self.assertEqual(_rep(df), expected) + + # all col + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" a b\na あああああ あ\n" + u"bb い いいい\nc う う\n" + u"ddd えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # column name + df = DataFrame({u'あああああ': [1, 222, 33333, 4], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" b あああああ\na あ 1\n" + u"bb いいい 222\nc う 33333\n" + u"ddd ええええええ 4") + self.assertEqual(_rep(df), expected) + + # index + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=[u'あああ', u'いいいいいい', u'うう', u'え']) + expected = (u" a b\nあああ あああああ あ\n" + u"いいいいいい い いいい\nうう う う\n" + u"え えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # index name + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=pd.Index([u'あ', u'い', u'うう', u'え'], name=u'おおおお')) + expected = (u" a b\nおおおお \nあ あああああ あ\n" + u"い い いいい\nうう う う\nえ えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # all + df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'], + u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']}, + index=pd.Index([u'あ', u'いいい', u'うう', u'え'], name=u'お')) + expected = (u" あああ いいいいい\nお \nあ あああ あ\n" + u"いいい い いいい\nうう う う\nえ えええええ ええ") + self.assertEqual(_rep(df), expected) + + # MultiIndex + idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), + (u'おおお', u'かかかか'), (u'き', u'くく')]) + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=idx) + expected = (u" a b\nあ いい あああああ あ\n" + u"う え い いいい\nおおお かかかか う う\n" + u"き くく えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # truncate + with option_context('display.max_rows', 3, 'display.max_columns', 3): + df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ'], + 'c': [u'お', u'か', u'ききき', u'くくくくくく'], + u'ああああ': [u'さ', u'し', u'す', u'せ']}, + columns=['a', 'b', 'c', u'ああああ']) + + expected = (u" a ... ああああ\n0 あああああ ... さ\n" + u".. ... ... ...\n3 えええ ... せ\n" + u"\n[4 rows x 4 columns]") + self.assertEqual(_rep(df), expected) + + df.index = [u'あああ', u'いいいい', u'う', 'aaa'] + expected = (u" a ... ああああ\nあああ あああああ ... さ\n" + u".. ... ... ...\naaa えええ ... せ\n" + u"\n[4 rows x 4 columns]") + self.assertEqual(_rep(df), expected) + + # Emable Unicode option ----------------------------------------- + with option_context('display.unicode.east_asian_width', True): + + # mid col + df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'], + 'b': [1, 222, 33333, 4]}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" a b\na あ 1\n" + u"bb いいい 222\nc う 33333\n" + u"ddd ええええええ 4") + self.assertEqual(_rep(df), expected) + + # last col + df = DataFrame({'a': [1, 222, 33333, 4], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" a b\na 1 あ\n" + u"bb 222 いいい\nc 33333 う\n" + u"ddd 4 ええええええ") + self.assertEqual(_rep(df), expected) + + # all col + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" a b\na あああああ あ\n" + u"bb い いいい\nc う う\n" + u"ddd えええ ええええええ""") + self.assertEqual(_rep(df), expected) + + # column name + df = DataFrame({u'あああああ': [1, 222, 33333, 4], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=['a', 'bb', 'c', 'ddd']) + expected = (u" b あああああ\na あ 1\n" + u"bb いいい 222\nc う 33333\n" + u"ddd ええええええ 4") + self.assertEqual(_rep(df), expected) + + # index + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=[u'あああ', u'いいいいいい', u'うう', u'え']) + expected = (u" a b\nあああ あああああ あ\n" + u"いいいいいい い いいい\nうう う う\n" + u"え えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # index name + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, + index=pd.Index([u'あ', u'い', u'うう', u'え'], name=u'おおおお')) + expected = (u" a b\nおおおお \n" + u"あ あああああ あ\nい い いいい\n" + u"うう う う\nえ えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # all + df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'], + u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']}, + index=pd.Index([u'あ', u'いいい', u'うう', u'え'], name=u'お')) + expected = (u" あああ いいいいい\nお \n" + u"あ あああ あ\nいいい い いいい\n" + u"うう う う\nえ えええええ ええ") + self.assertEqual(_rep(df), expected) + + # MultiIndex + idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), + (u'おおお', u'かかかか'), (u'き', u'くく')]) + df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=idx) + expected = (u" a b\nあ いい あああああ あ\n" + u"う え い いいい\nおおお かかかか う う\n" + u"き くく えええ ええええええ") + self.assertEqual(_rep(df), expected) + + # truncate + with option_context('display.max_rows', 3, 'display.max_columns', 3): + + df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], + 'b': [u'あ', u'いいい', u'う', u'ええええええ'], + 'c': [u'お', u'か', u'ききき', u'くくくくくく'], + u'ああああ': [u'さ', u'し', u'す', u'せ']}, + columns=['a', 'b', 'c', u'ああああ']) + + expected = (u" a ... ああああ\n0 あああああ ... さ\n" + u".. ... ... ...\n3 えええ ... せ\n" + u"\n[4 rows x 4 columns]") + self.assertEqual(_rep(df), expected) + + df.index = [u'あああ', u'いいいい', u'う', 'aaa'] + expected = (u" a ... ああああ\nあああ あああああ ... さ\n" + u"... ... ... ...\naaa えええ ... せ\n" + u"\n[4 rows x 4 columns]") + self.assertEqual(_rep(df), expected) + + # ambiguous unicode + df = DataFrame({u'あああああ': [1, 222, 33333, 4], + 'b': [u'あ', u'いいい', u'¡¡', u'ええええええ']}, + index=['a', 'bb', 'c', '¡¡¡']) + expected = (u" b あああああ\na あ 1\n" + u"bb いいい 222\nc ¡¡ 33333\n" + u"¡¡¡ ええええええ 4") + self.assertEqual(_rep(df), expected) + def test_to_string_buffer_all_unicode(self): buf = StringIO() @@ -895,10 +1098,6 @@ def test_to_html_regression_GH6098(self): # it works df.pivot_table(index=[u('clé1')], columns=[u('clé2')])._repr_html_() - - - - def test_to_html_truncate(self): raise nose.SkipTest("unreliable on travis") index = pd.DatetimeIndex(start='20010101',freq='D',periods=20) @@ -2888,6 +3087,148 @@ def test_unicode_name_in_footer(self): sf = fmt.SeriesFormatter(s, name=u('\u05e2\u05d1\u05e8\u05d9\u05ea')) sf._get_footer() # should not raise exception + def test_east_asian_unicode_series(self): + if PY3: + _rep = repr + else: + _rep = unicode + # not alighned properly because of east asian width + + # unicode index + s = Series(['a', 'bb', 'CCC', 'D'], + index=[u'あ', u'いい', u'ううう', u'ええええ']) + expected = (u"あ a\nいい bb\nううう CCC\n" + u"ええええ D\ndtype: object") + self.assertEqual(_rep(s), expected) + + # unicode values + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=['a', 'bb', 'c', 'ddd']) + expected = (u"a あ\nbb いい\nc ううう\n" + u"ddd ええええ\ndtype: object") + self.assertEqual(_rep(s), expected) + + # both + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], + index=[u'ああ', u'いいいい', u'う', u'えええ']) + expected = (u"ああ あ\nいいいい いい\nう ううう\n" + u"えええ ええええ\ndtype: object") + self.assertEqual(_rep(s), expected) + + # unicode footer + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], + index=[u'ああ', u'いいいい', u'う', u'えええ'], + name=u'おおおおおおお') + expected = (u"ああ あ\nいいいい いい\nう ううう\n" + u"えええ ええええ\nName: おおおおおおお, dtype: object") + self.assertEqual(_rep(s), expected) + + # MultiIndex + idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), + (u'おおお', u'かかかか'), (u'き', u'くく')]) + s = Series([1, 22, 3333, 44444], index=idx) + expected = (u"あ いい 1\nう え 22\nおおお かかかか 3333\n" + u"き くく 44444\ndtype: int64") + self.assertEqual(_rep(s), expected) + + # object dtype, shorter than unicode repr + s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ']) + expected = (u"1 1\nAB 22\nNaN 3333\n" + u"あああ 44444\ndtype: int64") + self.assertEqual(_rep(s), expected) + + # object dtype, longer than unicode repr + s = Series([1, 22, 3333, 44444], + index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ']) + expected = (u"1 1\nAB 22\n" + u"2011-01-01 00:00:00 3333\nあああ 44444\ndtype: int64") + self.assertEqual(_rep(s), expected) + + # truncate + with option_context('display.max_rows', 3): + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], + name=u'おおおおおおお') + + expected = (u"0 あ\n ... \n" + u"3 ええええ\nName: おおおおおおお, dtype: object") + self.assertEqual(_rep(s), expected) + + s.index = [u'ああ', u'いいいい', u'う', u'えええ'] + expected = (u"ああ あ\n ... \n" + u"えええ ええええ\nName: おおおおおおお, dtype: object") + self.assertEqual(_rep(s), expected) + + # Emable Unicode option ----------------------------------------- + with option_context('display.unicode.east_asian_width', True): + + # unicode index + s = Series(['a', 'bb', 'CCC', 'D'], + index=[u'あ', u'いい', u'ううう', u'ええええ']) + expected = (u"あ a\nいい bb\nううう CCC\n" + u"ええええ D\ndtype: object") + self.assertEqual(_rep(s), expected) + + # unicode values + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=['a', 'bb', 'c', 'ddd']) + expected = (u"a あ\nbb いい\nc ううう\n" + u"ddd ええええ\ndtype: object") + self.assertEqual(_rep(s), expected) + + # both + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], + index=[u'ああ', u'いいいい', u'う', u'えええ']) + expected = (u"ああ あ\nいいいい いい\nう ううう\n" + u"えええ ええええ\ndtype: object") + self.assertEqual(_rep(s), expected) + + # unicode footer + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], + index=[u'ああ', u'いいいい', u'う', u'えええ'], + name=u'おおおおおおお') + expected = (u"ああ あ\nいいいい いい\nう ううう\n" + u"えええ ええええ\nName: おおおおおおお, dtype: object") + self.assertEqual(_rep(s), expected) + + # MultiIndex + idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), + (u'おおお', u'かかかか'), (u'き', u'くく')]) + s = Series([1, 22, 3333, 44444], index=idx) + expected = (u"あ いい 1\nう え 22\nおおお かかかか 3333\n" + u"き くく 44444\ndtype: int64") + self.assertEqual(_rep(s), expected) + + # object dtype, shorter than unicode repr + s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ']) + expected = (u"1 1\nAB 22\nNaN 3333\n" + u"あああ 44444\ndtype: int64") + self.assertEqual(_rep(s), expected) + + # object dtype, longer than unicode repr + s = Series([1, 22, 3333, 44444], + index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ']) + expected = (u"1 1\nAB 22\n" + u"2011-01-01 00:00:00 3333\nあああ 44444\ndtype: int64") + self.assertEqual(_rep(s), expected) + + # truncate + with option_context('display.max_rows', 3): + s = Series([u'あ', u'いい', u'ううう', u'ええええ'], + name=u'おおおおおおお') + expected = (u"0 あ\n ... \n" + u"3 ええええ\nName: おおおおおおお, dtype: object") + self.assertEqual(_rep(s), expected) + + s.index = [u'ああ', u'いいいい', u'う', u'えええ'] + expected = (u"ああ あ\n ... \n" + u"えええ ええええ\nName: おおおおおおお, dtype: object") + self.assertEqual(_rep(s), expected) + + # ambiguous unicode + s = Series([u'¡¡', u'い¡¡', u'ううう', u'ええええ'], + index=[u'ああ', u'¡¡¡¡いい', u'¡¡', u'えええ']) + expected = (u"ああ ¡¡\n¡¡¡¡いい い¡¡\n¡¡ ううう\n" + u"えええ ええええ\ndtype: object") + self.assertEqual(_rep(s), expected) + def test_float_trim_zeros(self): vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10, 2.03954217305e+10, 5.59897817305e+10] diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 75daabe2dab67..81ebc7efdbdd9 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -2,7 +2,7 @@ # pylint: disable=E1101,E1103,W0232 from datetime import datetime, timedelta, time -from pandas.compat import range, lrange, lzip, u, zip +from pandas.compat import range, lrange, lzip, u, zip, PY3 import operator import re import nose @@ -1842,6 +1842,137 @@ def test_conversion_preserves_name(self): self.assertEqual(i.name, pd.to_datetime(i).name) self.assertEqual(i.name, pd.to_timedelta(i).name) + def test_string_index_repr(self): + # py3/py2 repr can differ because of "u" prefix + # which also affects to displayed element size + + # short + idx = pd.Index(['a', 'bb', 'ccc']) + if PY3: + expected = u"""Index(['a', 'bb', 'ccc'], dtype='object')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'a', u'bb', u'ccc'], dtype='object')""" + self.assertEqual(unicode(idx), expected) + + # multiple lines + idx = pd.Index(['a', 'bb', 'ccc'] * 10) + if PY3: + expected = u"""Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', + 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', + 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], + dtype='object')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', + u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', + u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'], + dtype='object')""" + self.assertEqual(unicode(idx), expected) + + # truncated + idx = pd.Index(['a', 'bb', 'ccc'] * 100) + if PY3: + expected = u"""Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', + ... + 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], + dtype='object', length=300)""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', + ... + u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'], + dtype='object', length=300)""" + self.assertEqual(unicode(idx), expected) + + # short + idx = pd.Index([u'あ', u'いい', u'ううう']) + if PY3: + expected = u"""Index(['あ', 'いい', 'ううう'], dtype='object')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'あ', u'いい', u'ううう'], dtype='object')""" + self.assertEqual(unicode(idx), expected) + + # multiple lines + idx = pd.Index([u'あ', u'いい', u'ううう'] * 10) + if PY3: + expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + dtype='object')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'], + dtype='object')""" + self.assertEqual(unicode(idx), expected) + + # truncated + idx = pd.Index([u'あ', u'いい', u'ううう'] * 100) + if PY3: + expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', + ... + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + dtype='object', length=300)""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + ... + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'], + dtype='object', length=300)""" + self.assertEqual(unicode(idx), expected) + + # Emable Unicode option ----------------------------------------- + with cf.option_context('display.unicode.east_asian_width', True): + + # short + idx = pd.Index([u'あ', u'いい', u'ううう']) + if PY3: + expected = u"""Index(['あ', 'いい', 'ううう'], dtype='object')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'あ', u'いい', u'ううう'], dtype='object')""" + self.assertEqual(unicode(idx), expected) + + # multiple lines + idx = pd.Index([u'あ', u'いい', u'ううう'] * 10) + if PY3: + expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう'], + dtype='object')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'], + dtype='object')""" + self.assertEqual(unicode(idx), expected) + + # truncated + idx = pd.Index([u'あ', u'いい', u'ううう'] * 100) + if PY3: + expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', + ... + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう'], + dtype='object', length=300)""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', + ... + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう'], + dtype='object', length=300)""" + self.assertEqual(unicode(idx), expected) + + class TestCategoricalIndex(Base, tm.TestCase): _holder = CategoricalIndex @@ -2211,6 +2342,180 @@ def test_equals(self): self.assertFalse(CategoricalIndex(list('aabca') + [np.nan],categories=['c','a','b']).equals(list('aabca'))) self.assertTrue(CategoricalIndex(list('aabca') + [np.nan],categories=['c','a','b']).equals(list('aabca') + [np.nan])) + def test_string_categorical_index_repr(self): + # short + idx = pd.CategoricalIndex(['a', 'bb', 'ccc']) + if PY3: + expected = u"""CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'a', u'bb', u'ccc'], categories=[u'a', u'bb', u'ccc'], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # multiple lines + idx = pd.CategoricalIndex(['a', 'bb', 'ccc'] * 10) + if PY3: + expected = u"""CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', + 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', + 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], + categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', + u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', + u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', + u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'], + categories=[u'a', u'bb', u'ccc'], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # truncated + idx = pd.CategoricalIndex(['a', 'bb', 'ccc'] * 100) + if PY3: + expected = u"""CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', + ... + 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], + categories=['a', 'bb', 'ccc'], ordered=False, dtype='category', length=300)""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', + u'ccc', u'a', + ... + u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', + u'bb', u'ccc'], + categories=[u'a', u'bb', u'ccc'], ordered=False, dtype='category', length=300)""" + self.assertEqual(unicode(idx), expected) + + # larger categories + idx = pd.CategoricalIndex(list('abcdefghijklmmo')) + if PY3: + expected = u"""CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'm', 'o'], + categories=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', ...], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j', + u'k', u'l', u'm', u'm', u'o'], + categories=[u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', ...], ordered=False, dtype='category')""" + + self.assertEqual(unicode(idx), expected) + + # short + idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう']) + if PY3: + expected = u"""CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう'], categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # multiple lines + idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 10) + if PY3: + expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', + 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', + u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'], + categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # truncated + idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 100) + if PY3: + expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', + ... + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', + ... + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう'], + categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category', length=300)""" + self.assertEqual(unicode(idx), expected) + + # larger categories + idx = pd.CategoricalIndex(list(u'あいうえおかきくけこさしすせそ')) + if PY3: + expected = u"""CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し', + 'す', 'せ', 'そ'], + categories=['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', ...], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', u'け', u'こ', + u'さ', u'し', u'す', u'せ', u'そ'], + categories=[u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', ...], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # Emable Unicode option ----------------------------------------- + with cf.option_context('display.unicode.east_asian_width', True): + + # short + idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう']) + if PY3: + expected = u"""CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう'], categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # multiple lines + idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 10) + if PY3: + expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', u'いい', u'ううう'], + categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + + # truncated + idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 100) + if PY3: + expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', + 'ううう', 'あ', + ... + 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', + 'あ', 'いい', 'ううう'], + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', + u'いい', u'ううう', u'あ', + ... + u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', + u'ううう', u'あ', u'いい', u'ううう'], + categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category', length=300)""" + self.assertEqual(unicode(idx), expected) + + # larger categories + idx = pd.CategoricalIndex(list(u'あいうえおかきくけこさしすせそ')) + if PY3: + expected = u"""CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', + 'さ', 'し', 'す', 'せ', 'そ'], + categories=['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', ...], ordered=False, dtype='category')""" + self.assertEqual(repr(idx), expected) + else: + expected = u"""CategoricalIndex([u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', + u'け', u'こ', u'さ', u'し', u'す', u'せ', u'そ'], + categories=[u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', ...], ordered=False, dtype='category')""" + self.assertEqual(unicode(idx), expected) + class Numeric(Base):
Closes #2612. Added `display.unicode.east_asian_width` options, which calculate text width considering East Asian Width. Enabling this option affects to a performance as width must be calculated per characters. #### Current results (captured) ![2015-09-15 20 57 27](https://cloud.githubusercontent.com/assets/1696302/9875847/7928d98c-5bec-11e5-98d9-a218c3a6b425.png) - [x] Basic impl and test - [x] Series / DataFrame truncation - [x] Perf test - [x] Doc / Release note
https://api.github.com/repos/pandas-dev/pandas/pulls/11102
2015-09-15T12:38:20Z
2015-10-03T14:41:03Z
2015-10-03T14:41:03Z
2015-10-03T22:24:44Z
DOC: Fixed outdated doc-string, added missing default values, added missing optional parameters for some io classes
diff --git a/pandas/io/data.py b/pandas/io/data.py index 1a4c45628a256..310b165101bdf 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -53,12 +53,17 @@ def DataReader(name, data_source=None, start=None, end=None, name : str or list of strs the name of the dataset. Some data sources (yahoo, google, fred) will accept a list of names. - data_source: str + data_source: str, default: None the data source ("yahoo", "google", "fred", or "ff") - start : {datetime, None} + start : datetime, default: None left boundary for range (defaults to 1/1/2010) - end : {datetime, None} + end : datetime, default: None right boundary for range (defaults to today) + retry_count : int, default 3 + Number of times to retry query request. + pause : numeric, default 0.001 + Time, in seconds, to pause between consecutive queries of chunks. If + single value given for symbol, represents the pause between retries. Examples ---------- @@ -398,28 +403,28 @@ def get_data_yahoo(symbols=None, start=None, end=None, retry_count=3, Parameters ---------- - symbols : string, array-like object (list, tuple, Series), or DataFrame + symbols : string, array-like object (list, tuple, Series), or DataFrame, default: None Single stock symbol (ticker), array-like object of symbols or - DataFrame with index containing stock symbols. + DataFrame with index containing stock symbols start : string, (defaults to '1/1/2010') Starting date, timestamp. Parses many different kind of date representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980') end : string, (defaults to today) Ending date, timestamp. Same format as starting date. - retry_count : int, default 3 + retry_count : int, default: 3 Number of times to retry query request. - pause : int, default 0 + pause : numeric, default: 0.001 Time, in seconds, to pause between consecutive queries of chunks. If single value given for symbol, represents the pause between retries. - adjust_price : bool, default False + adjust_price : bool, default: False If True, adjusts all prices in hist_data ('Open', 'High', 'Low', 'Close') based on 'Adj Close' price. Adds 'Adj_Ratio' column and drops 'Adj Close'. - ret_index : bool, default False + ret_index : bool, default: False If True, includes a simple return index 'Ret_Index' in hist_data. - chunksize : int, default 25 + chunksize : int, default: 25 Number of symbols to download consecutively before intiating pause. - interval : string, default 'd' + interval : string, default: 'd' Time interval code, valid values are 'd' for daily, 'w' for weekly, 'm' for monthly and 'v' for dividend. @@ -451,13 +456,15 @@ def get_data_google(symbols=None, start=None, end=None, retry_count=3, representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980') end : string, (defaults to today) Ending date, timestamp. Same format as starting date. - retry_count : int, default 3 + retry_count : int, default: 3 Number of times to retry query request. - pause : int, default 0 + pause : numeric, default: 0.001 Time, in seconds, to pause between consecutive queries of chunks. If single value given for symbol, represents the pause between retries. - chunksize : int, default 25 + chunksize : int, default: 25 Number of symbols to download consecutively before intiating pause. + ret_index : bool, default: False + If True, includes a simple return index 'Ret_Index' in hist_data. Returns ------- @@ -903,10 +910,10 @@ def get_near_stock_price(self, above_below=2, call=True, put=False, The number of strike prices above and below the stock price that should be taken - call : bool + call : bool, default: True Tells the function whether or not it should be using calls - put : bool + put : bool, default: False Tells the function weather or not it should be using puts month : number, int, optional(default=None) diff --git a/pandas/io/ga.py b/pandas/io/ga.py index 57de5c6f5abb4..b6b4081e3650f 100644 --- a/pandas/io/ga.py +++ b/pandas/io/ga.py @@ -30,10 +30,9 @@ dimensions : list of str Un-prefixed dimension variable names start_date : str/date/datetime -end_date : str/date/datetime, optional - Defaults to today -segment : list of str, optional -filters : list of str, optional +end_date : str/date/datetime, optional, default is None but internally set as today +segment : list of str, optional, default: None +filters : list of str, optional, default: None start_index : int, default 1 max_results : int, default 10000 If >10000, must specify chunksize or ValueError will be raised""" @@ -58,21 +57,21 @@ Sort output by index or list of columns chunksize : int, optional If max_results >10000, specifies the number of rows per iteration -index_col : str/list of str/dict, optional +index_col : str/list of str/dict, optional, default: None If unspecified then dimension variables are set as index -parse_dates : bool/list/dict, default True -keep_date_col : boolean, default False -date_parser : optional -na_values : optional -converters : optional +parse_dates : bool/list/dict, default: True +keep_date_col : boolean, default: False +date_parser : optional, default: None +na_values : optional, default: None +converters : optional, default: None dayfirst : bool, default False Informs date parsing -account_name : str, optional -account_id : str, optional -property_name : str, optional -property_id : str, optional -profile_name : str, optional -profile_id : str, optional +account_name : str, optional, default: None +account_id : str, optional, default: None +property_name : str, optional, default: None +property_id : str, optional, default: None +profile_name : str, optional, default: None +profile_id : str, optional, default: None %%(extras)s Returns ------- @@ -192,8 +191,8 @@ def get_account(self, name=None, id=None, **kwargs): Parameters ---------- - name : str, optional - id : str, optional + name : str, optional, default: None + id : str, optional, default: None """ accounts = self.service.management().accounts().list().execute() return _get_match(accounts, name, id, **kwargs) @@ -205,9 +204,9 @@ def get_web_property(self, account_id=None, name=None, id=None, **kwargs): Parameters ---------- - account_id : str, optional - name : str, optional - id : str, optional + account_id : str, optional, default: None + name : str, optional, default: None + id : str, optional, default: None """ prop_store = self.service.management().webproperties() kwds = {} @@ -225,10 +224,10 @@ def get_profile(self, account_id=None, web_property_id=None, name=None, Parameters ---------- - account_id : str, optional - web_property_id : str, optional - name : str, optional - id : str, optional + account_id : str, optional, default: None + web_property_id : str, optional, default: None + name : str, optional, default: None + id : str, optional, default: None """ profile_store = self.service.management().profiles() kwds = {} diff --git a/pandas/io/json.py b/pandas/io/json.py index d6310d81ab87f..f368f0e6cf28e 100644 --- a/pandas/io/json.py +++ b/pandas/io/json.py @@ -110,12 +110,12 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, Parameters ---------- - filepath_or_buffer : a valid JSON string or file-like + path_or_buf : a valid JSON string or file-like, default: None The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be ``file://localhost/path/to/table.json`` - orient + orient * `Series` @@ -162,13 +162,13 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, * it is ``'date'`` - keep_default_dates : boolean, default True. + keep_default_dates : boolean, default True If parsing dates, then parse the default datelike columns numpy : boolean, default False Direct decoding to numpy arrays. Supports numeric data only, but non-numeric column and index labels are supported. Note also that the JSON ordering MUST be the same for each term if numpy=True. - precise_float : boolean, default False. + precise_float : boolean, default False Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (False) is to use fast but less precise builtin functionality @@ -582,6 +582,8 @@ def nested_to_record(ds, prefix="", level=0): Parameters ---------- ds : dict or list of dicts + prefix: the prefix, optional, default: "" + level: the number of levels in the jason string, optional, default: 0 Returns ------- @@ -646,7 +648,7 @@ def json_normalize(data, record_path=None, meta=None, record_path : string or list of strings, default None Path in each object to list of records. If not passed, data will be assumed to be an array of records - meta : list of paths (string or list of strings) + meta : list of paths (string or list of strings), default None Fields to use as metadata for each record in resulting table record_prefix : string, default None If True, prefix records with dotted (?) path, e.g. foo.bar.field if
Some doc-strings are outdated, in a sense that there are missing newly added optional parameters and default values.
https://api.github.com/repos/pandas-dev/pandas/pulls/11098
2015-09-14T23:54:06Z
2015-09-17T17:27:23Z
2015-09-17T17:27:23Z
2015-09-17T17:34:49Z
TST: More thorough test to check correctness of to_html_unicode
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 6c92bb7095d8b..d6abb00e55e7b 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -521,11 +521,12 @@ def test_to_html_with_empty_string_label(self): self.assertTrue("rowspan" not in res) def test_to_html_unicode(self): - # it works! df = DataFrame({u('\u03c3'): np.arange(10.)}) - df.to_html() + expected = u'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>\u03c3</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9</td>\n </tr>\n </tbody>\n</table>' + self.assertEqual(df.to_html(), expected) df = DataFrame({'A': [u('\u03c3')]}) - df.to_html() + expected = u'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>\u03c3</td>\n </tr>\n </tbody>\n</table>' + self.assertEqual(df.to_html(), expected) def test_to_html_escaped(self): a = 'str<ing1 &amp;'
The current test for `test_to_html_unicode` only checks for whether the function works but does not check for its correctness.
https://api.github.com/repos/pandas-dev/pandas/pulls/11093
2015-09-14T15:25:50Z
2015-09-16T23:02:08Z
2015-09-16T23:02:08Z
2015-09-16T23:02:45Z
DOC: Update "enhancing perf" doc based on #10953
diff --git a/doc/source/enhancingperf.rst b/doc/source/enhancingperf.rst index 855a459f48cf4..028e6d064a561 100644 --- a/doc/source/enhancingperf.rst +++ b/doc/source/enhancingperf.rst @@ -449,12 +449,15 @@ These operations are supported by :func:`pandas.eval`: - Attribute access, e.g., ``df.a`` - Subscript expressions, e.g., ``df[0]`` - Simple variable evaluation, e.g., ``pd.eval('df')`` (this is not very useful) +- Math functions, `sin`, `cos`, `exp`, `log`, `expm1`, `log1p`, + `sqrt`, `sinh`, `cosh`, `tanh`, `arcsin`, `arccos`, `arctan`, `arccosh`, + `arcsinh`, `arctanh`, `abs` and `arctan2`. This Python syntax is **not** allowed: * Expressions - - Function calls + - Function calls other than math functions. - ``is``/``is not`` operations - ``if`` expressions - ``lambda`` expressions
Updated ["enhancing performance"](http://pandas.pydata.org/pandas-docs/stable/enhancingperf.html#enhancingperf-eval) doc based on #10953. CC @sklam
https://api.github.com/repos/pandas-dev/pandas/pulls/11092
2015-09-14T12:21:30Z
2015-09-14T13:10:48Z
2015-09-14T13:10:48Z
2015-09-14T13:10:51Z
TST: Fix skipped unit tests in test_ga. Install python-gflags using p…
diff --git a/ci/requirements-2.7.pip b/ci/requirements-2.7.pip index ff1978a8d45ed..644457d69b37f 100644 --- a/ci/requirements-2.7.pip +++ b/ci/requirements-2.7.pip @@ -1,3 +1,4 @@ blosc httplib2 google-api-python-client == 1.2 +python-gflags == 2.0 diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt index d6a1e2d362330..2764e740886da 100644 --- a/ci/requirements-2.7.txt +++ b/ci/requirements-2.7.txt @@ -20,4 +20,3 @@ patsy pymysql=0.6.3 html5lib=1.0b2 beautiful-soup=4.2.1 -python-gflags=2.0 diff --git a/ci/requirements-2.7_SLOW.txt b/ci/requirements-2.7_SLOW.txt index 1a56434c62f86..563ce3e1190e6 100644 --- a/ci/requirements-2.7_SLOW.txt +++ b/ci/requirements-2.7_SLOW.txt @@ -20,4 +20,3 @@ psycopg2 pymysql html5lib beautiful-soup -python-gflags diff --git a/pandas/io/tests/test_ga.py b/pandas/io/tests/test_ga.py index cc26411e8d364..13d31b43ac39a 100644 --- a/pandas/io/tests/test_ga.py +++ b/pandas/io/tests/test_ga.py @@ -3,11 +3,14 @@ import nose import pandas as pd -from pandas import DataFrame +from pandas import compat from pandas.util.testing import network, assert_frame_equal, with_connectivity_check from numpy.testing.decorators import slow import pandas.util.testing as tm +if compat.PY3: + raise nose.SkipTest("python-gflags does not support Python 3 yet") + try: import httplib2 import pandas.io.ga as ga @@ -17,6 +20,7 @@ except ImportError: raise nose.SkipTest("need httplib2 and auth libs") + class TestGoogle(tm.TestCase): _multiprocess_can_split_ = True @@ -29,8 +33,7 @@ def test_remove_token_store(self): reset_default_token_store() self.assertFalse(os.path.exists(auth.DEFAULT_TOKEN_FILE)) - @slow - @network + @with_connectivity_check("http://www.google.com") def test_getdata(self): try: end_date = datetime.now() @@ -45,18 +48,19 @@ def test_getdata(self): start_date=start_date, end_date=end_date, dimensions=['date', 'hour'], - parse_dates={'ts': ['date', 'hour']}) - - assert isinstance(df, DataFrame) - assert isinstance(df.index, pd.DatetimeIndex) - assert len(df) > 1 - assert 'date' not in df - assert 'hour' not in df - assert df.index.name == 'ts' - assert 'avgTimeOnSite' in df - assert 'visitors' in df - assert 'newVisits' in df - assert 'pageviewsPerVisit' in df + parse_dates={'ts': ['date', 'hour']}, + index_col=0) + + self.assertIsInstance(df, pd.DataFrame) + self.assertIsInstance(df.index, pd.DatetimeIndex) + self.assertGreater(len(df), 1) + self.assertTrue('date' not in df) + self.assertTrue('hour' not in df) + self.assertEqual(df.index.name, 'ts') + self.assertTrue('avgTimeOnSite' in df) + self.assertTrue('visitors' in df) + self.assertTrue('newVisits' in df) + self.assertTrue('pageviewsPerVisit' in df) df2 = read_ga( metrics=['avgTimeOnSite', 'visitors', 'newVisits', @@ -64,14 +68,14 @@ def test_getdata(self): start_date=start_date, end_date=end_date, dimensions=['date', 'hour'], - parse_dates={'ts': ['date', 'hour']}) + parse_dates={'ts': ['date', 'hour']}, + index_col=0) assert_frame_equal(df, df2) except AuthenticationConfigError: raise nose.SkipTest("authentication error") - @slow @with_connectivity_check("http://www.google.com") def test_iterator(self): try: @@ -81,20 +85,21 @@ def test_iterator(self): metrics='visitors', start_date='2005-1-1', dimensions='date', - max_results=10, chunksize=5) + max_results=10, chunksize=5, + index_col=0) df1 = next(it) df2 = next(it) for df in [df1, df2]: - assert isinstance(df, DataFrame) - assert isinstance(df.index, pd.DatetimeIndex) - assert len(df) == 5 - assert 'date' not in df - assert df.index.name == 'date' - assert 'visitors' in df + self.assertIsInstance(df, pd.DataFrame) + self.assertIsInstance(df.index, pd.DatetimeIndex) + self.assertEqual(len(df), 5) + self.assertTrue('date' not in df) + self.assertEqual(df.index.name, 'date') + self.assertTrue('visitors' in df) - assert (df2.index > df1.index).all() + self.assertTrue((df2.index > df1.index).all()) except AuthenticationConfigError: raise nose.SkipTest("authentication error") @@ -102,30 +107,28 @@ def test_iterator(self): def test_v2_advanced_segment_format(self): advanced_segment_id = 1234567 query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id) - assert query['segment'] == 'gaid::' + str(advanced_segment_id), "An integer value should be formatted as an advanced segment." + self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "An integer value should be formatted as an advanced segment.") def test_v2_dynamic_segment_format(self): dynamic_segment_id = 'medium==referral' query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=dynamic_segment_id) - assert query['segment'] == 'dynamic::ga:' + str(dynamic_segment_id), "A string value with more than just letters and numbers should be formatted as a dynamic segment." + self.assertEqual(query['segment'], 'dynamic::ga:' + str(dynamic_segment_id), "A string value with more than just letters and numbers should be formatted as a dynamic segment.") def test_v3_advanced_segment_common_format(self): advanced_segment_id = 'aZwqR234' query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id) - assert query['segment'] == 'gaid::' + str(advanced_segment_id), "A string value with just letters and numbers should be formatted as an advanced segment." + self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "A string value with just letters and numbers should be formatted as an advanced segment.") def test_v3_advanced_segment_weird_format(self): advanced_segment_id = '_aZwqR234-s1' query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id) - assert query['segment'] == 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and hyphens should be formatted as an advanced segment." + self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and hyphens should be formatted as an advanced segment.") def test_v3_advanced_segment_with_underscore_format(self): advanced_segment_id = 'aZwqR234_s1' query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id) - assert query['segment'] == 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and underscores should be formatted as an advanced segment." - + self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and underscores should be formatted as an advanced segment.") - @slow @with_connectivity_check("http://www.google.com") def test_segment(self): try: @@ -142,20 +145,21 @@ def test_segment(self): end_date=end_date, segment=-2, dimensions=['date', 'hour'], - parse_dates={'ts': ['date', 'hour']}) - - assert isinstance(df, DataFrame) - assert isinstance(df.index, pd.DatetimeIndex) - assert len(df) > 1 - assert 'date' not in df - assert 'hour' not in df - assert df.index.name == 'ts' - assert 'avgTimeOnSite' in df - assert 'visitors' in df - assert 'newVisits' in df - assert 'pageviewsPerVisit' in df - - #dynamic + parse_dates={'ts': ['date', 'hour']}, + index_col=0) + + self.assertIsInstance(df, pd.DataFrame) + self.assertIsInstance(df.index, pd.DatetimeIndex) + self.assertGreater(len(df), 1) + self.assertTrue('date' not in df) + self.assertTrue('hour' not in df) + self.assertEqual(df.index.name, 'ts') + self.assertTrue('avgTimeOnSite' in df) + self.assertTrue('visitors' in df) + self.assertTrue('newVisits' in df) + self.assertTrue('pageviewsPerVisit' in df) + + # dynamic df = read_ga( metrics=['avgTimeOnSite', 'visitors', 'newVisits', 'pageviewsPerVisit'], @@ -163,18 +167,19 @@ def test_segment(self): end_date=end_date, segment="source=~twitter", dimensions=['date', 'hour'], - parse_dates={'ts': ['date', 'hour']}) + parse_dates={'ts': ['date', 'hour']}, + index_col=0) - assert isinstance(df, DataFrame) + assert isinstance(df, pd.DataFrame) assert isinstance(df.index, pd.DatetimeIndex) - assert len(df) > 1 - assert 'date' not in df - assert 'hour' not in df - assert df.index.name == 'ts' - assert 'avgTimeOnSite' in df - assert 'visitors' in df - assert 'newVisits' in df - assert 'pageviewsPerVisit' in df + self.assertGreater(len(df), 1) + self.assertTrue('date' not in df) + self.assertTrue('hour' not in df) + self.assertEqual(df.index.name, 'ts') + self.assertTrue('avgTimeOnSite' in df) + self.assertTrue('visitors' in df) + self.assertTrue('newVisits' in df) + self.assertTrue('pageviewsPerVisit' in df) except AuthenticationConfigError: raise nose.SkipTest("authentication error")
closes #11090 This commit should resolve the following error in the travis build log. ``` ------------------------------------------------------------- #15 nose.failure.Failure.runTest: need httplib2 and auth libs ------------------------------------------------------------- ``` Valid Google credentials are required to run the ga unit tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/11091
2015-09-13T20:15:02Z
2015-09-14T19:51:21Z
2015-09-14T19:51:21Z
2015-09-14T20:23:13Z
TST: make sure to close stata readers
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index 29f0422c58ac8..8505150932c90 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -98,19 +98,19 @@ def test_read_empty_dta(self): def test_data_method(self): # Minimal testing of legacy data method - reader_114 = StataReader(self.dta1_114) - with warnings.catch_warnings(record=True) as w: - parsed_114_data = reader_114.data() + with StataReader(self.dta1_114) as rdr: + with warnings.catch_warnings(record=True) as w: + parsed_114_data = rdr.data() - reader_114 = StataReader(self.dta1_114) - parsed_114_read = reader_114.read() + with StataReader(self.dta1_114) as rdr: + parsed_114_read = rdr.read() tm.assert_frame_equal(parsed_114_data, parsed_114_read) def test_read_dta1(self): - reader_114 = StataReader(self.dta1_114) - parsed_114 = reader_114.read() - reader_117 = StataReader(self.dta1_117) - parsed_117 = reader_117.read() + + parsed_114 = self.read_dta(self.dta1_114) + parsed_117 = self.read_dta(self.dta1_117) + # Pandas uses np.nan as missing value. # Thus, all columns will be of type float, regardless of their name. expected = DataFrame([(np.nan, np.nan, np.nan, np.nan, np.nan)], @@ -264,19 +264,18 @@ def test_read_dta18(self): for col in parsed_118.columns: tm.assert_almost_equal(parsed_118[col], expected[col]) - rdr = StataReader(self.dta22_118) - vl = rdr.variable_labels() - vl_expected = {u'Unicode_Cities_Strl': u'Here are some strls with Ünicode chars', - u'Longs': u'long data', - u'Things': u'Here are some things', - u'Bytes': u'byte data', - u'Ints': u'int data', - u'Cities': u'Here are some cities', - u'Floats': u'float data'} - tm.assert_dict_equal(vl, vl_expected) - - self.assertEqual(rdr.data_label, u'This is a Ünicode data label') + with StataReader(self.dta22_118) as rdr: + vl = rdr.variable_labels() + vl_expected = {u'Unicode_Cities_Strl': u'Here are some strls with Ünicode chars', + u'Longs': u'long data', + u'Things': u'Here are some things', + u'Bytes': u'byte data', + u'Ints': u'int data', + u'Cities': u'Here are some cities', + u'Floats': u'float data'} + tm.assert_dict_equal(vl, vl_expected) + self.assertEqual(rdr.data_label, u'This is a Ünicode data label') def test_read_write_dta5(self): original = DataFrame([(np.nan, np.nan, np.nan, np.nan, np.nan)], @@ -610,8 +609,10 @@ def test_bool_uint(self): tm.assert_frame_equal(written_and_read_again, expected) def test_variable_labels(self): - sr_115 = StataReader(self.dta16_115).variable_labels() - sr_117 = StataReader(self.dta16_117).variable_labels() + with StataReader(self.dta16_115) as rdr: + sr_115 = rdr.variable_labels() + with StataReader(self.dta16_117) as rdr: + sr_117 = rdr.variable_labels() keys = ('var1', 'var2', 'var3') labels = ('label1', 'label2', 'label3') for k,v in compat.iteritems(sr_115): @@ -652,7 +653,8 @@ def test_missing_value_generator(self): df = DataFrame([[0.0]],columns=['float_']) with tm.ensure_clean() as path: df.to_stata(path) - valid_range = StataReader(path).VALID_RANGE + with StataReader(path) as rdr: + valid_range = rdr.VALID_RANGE expected_values = ['.' + chr(97 + i) for i in range(26)] expected_values.insert(0, '.') for t in types:
https://api.github.com/repos/pandas-dev/pandas/pulls/11088
2015-09-13T15:27:25Z
2015-09-13T18:27:40Z
2015-09-13T18:27:40Z
2015-09-13T18:27:40Z
DOC: Comparison with SAS
diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst new file mode 100644 index 0000000000000..fd42c97c9cbc0 --- /dev/null +++ b/doc/source/comparison_with_sas.rst @@ -0,0 +1,607 @@ +.. currentmodule:: pandas +.. _compare_with_sas: + +Comparison with SAS +******************** +For potential users coming from `SAS <https://en.wikipedia.org/wiki/SAS_(software)>`__ +this page is meant to demonstrate how different SAS operations would be +performed in pandas. + +If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>` +to familiarize yourself with the library. + +As is customary, we import pandas and numpy as follows: + +.. ipython:: python + + import pandas as pd + import numpy as np + + +.. note:: + + Throughout this tutorial, the pandas ``DataFrame`` will be displayed by calling + ``df.head()``, which displays the first N (default 5) rows of the ``DataFrame``. + This is often used in interactive work (e.g. `Jupyter notebook + <https://jupyter.org/>`_ or terminal) - the equivalent in SAS would be: + + .. code-block:: none + + proc print data=df(obs=5); + run; + +Data Structures +--------------- + +General Terminology Translation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. csv-table:: + :header: "pandas", "SAS" + :widths: 20, 20 + + ``DataFrame``, data set + column, variable + row, observation + groupby, BY-group + ``NaN``, ``.`` + + +``DataFrame`` / ``Series`` +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``DataFrame`` in pandas is analogous to a SAS data set - a two-dimensional +data source with labeled columns that can be of different types. As will be +shown in this document, almost any operation that can be applied to a data set +using SAS's ``DATA`` step, can also be accomplished in pandas. + +A ``Series`` is the data structure that represents one column of a +``DataFrame``. SAS doesn't have a separate data structure for a single column, +but in general, working with a ``Series`` is analogous to referencing a column +in the ``DATA`` step. + +``Index`` +~~~~~~~~~ + +Every ``DataFrame`` and ``Series`` has an ``Index`` - which are labels on the +*rows* of the data. SAS does not have an exactly analogous concept. A data set's +row are essentially unlabeled, other than an implicit integer index that can be +accessed during the ``DATA`` step (``_N_``). + +In pandas, if no index is specified, an integer index is also used by default +(first row = 0, second row = 1, and so on). While using a labeled ``Index`` or +``MultiIndex`` can enable sophisticated analyses and is ultimately an important +part of pandas to understand, for this comparison we will essentially ignore the +``Index`` and just treat the ``DataFrame`` as a collection of columns. Please +see the :ref:`indexing documentation<indexing>` for much more on how to use an +``Index`` effectively. + + +Data Input / Output +------------------- + +Constructing a DataFrame from Values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A SAS data set can be built from specified values by +placing the data after a ``datalines`` statement and +specifying the column names. + +.. code-block:: none + + data df; + input x y; + datalines; + 1 2 + 3 4 + 5 6 + ; + run; + +A pandas ``DataFrame`` can be constructed in many different ways, +but for a small number of values, it is often convenient to specify it as +a python dictionary, where the keys are the column names +and the values are the data. + +.. ipython:: python + + df = pd.DataFrame({ + 'x': [1, 3, 5], + 'y': [2, 4, 6]}) + df + + +Reading External Data +~~~~~~~~~~~~~~~~~~~~~ + +Like SAS, pandas provides utilities for reading in data from +many formats. The ``tips`` dataset, found within the pandas +tests (`csv <https://raw.github.com/pydata/pandas/master/pandas/tests/data/tips.csv>`_) +will be used in many of the following examples. + +SAS provides ``PROC IMPORT`` to read csv data into a data set. + +.. code-block:: none + + proc import datafile='tips.csv' dbms=csv out=tips replace; + getnames=yes; + run; + +The pandas method is :func:`read_csv`, which works similarly. + +.. ipython:: python + + url = 'https://raw.github.com/pydata/pandas/master/pandas/tests/data/tips.csv' + tips = pd.read_csv(url) + tips.head() + + +Like ``PROC IMPORT``, ``read_csv`` can take a number of parameters to specify +how the data should be parsed. For example, if the data was instead tab delimited, +and did not have column names, the pandas command would be: + +.. code-block:: python + + tips = pd.read_csv('tips.csv', sep='\t', header=False) + + # alternatively, read_table is an alias to read_csv with tab delimiter + tips = pd.read_table('tips.csv', header=False) + +In addition to text/csv, pandas supports a variety of other data formats +such as Excel, HDF5, and SQL databases. These are all read via a ``pd.read_*`` +function. See the :ref:`IO documentation<io>` for more details. + +Exporting Data +~~~~~~~~~~~~~~ + +The inverse of ``PROC IMPORT`` in SAS is ``PROC EXPORT`` + +.. code-block:: none + + proc export data=tips outfile='tips2.csv' dbms=csv; + run; + +Similarly in pandas, the opposite of ``read_csv`` is :meth:`~DataFrame.to_csv`, +and other data formats follow a similar api. + +.. code-block:: python + + tips.to_csv('tips2.csv') + + +Data Operations +--------------- + +Operations on Columns +~~~~~~~~~~~~~~~~~~~~~ + +In the ``DATA`` step, arbitrary math expressions can +be used on new or existing columns. + +.. code-block:: none + + data tips; + set tips; + total_bill = total_bill - 2; + new_bill = total_bill / 2; + run; + +pandas provides similar vectorized operations by +specifying the individual ``Series`` in the ``DataFrame``. +New columns can be assigned in the same way. + +.. ipython:: python + + tips['total_bill'] = tips['total_bill'] - 2 + tips['new_bill'] = tips['total_bill'] / 2.0 + tips.head() + +.. ipython:: python + :suppress: + + tips = tips.drop('new_bill', axis=1) + +Filtering +~~~~~~~~~ + +Filtering in SAS is done with an ``if`` or ``where`` statement, on one +or more columns. + +.. code-block:: none + + data tips; + set tips; + if total_bill > 10; + run; + + data tips; + set tips; + where total_bill > 10; + /* equivalent in this case - where happens before the + DATA step begins and can also be used in PROC statements */ + run; + +DataFrames can be filtered in multiple ways; the most intuitive of which is using +:ref:`boolean indexing <indexing.boolean>` + +.. ipython:: python + + tips[tips['total_bill'] > 10].head() + +If/Then Logic +~~~~~~~~~~~~~ + +In SAS, if/then logic can be used to create new columns. + +.. code-block:: none + + data tips; + set tips; + format bucket $4.; + + if total_bill < 10 then bucket = 'low'; + else bucket = 'high'; + run; + +The same operation in pandas can be accomplished using +the ``where`` method from ``numpy``. + +.. ipython:: python + + tips['bucket'] = np.where(tips['total_bill'] < 10, 'low', 'high') + tips.head() + +.. ipython:: python + :suppress: + + tips = tips.drop('bucket', axis=1) + +Date Functionality +~~~~~~~~~~~~~~~~~~ + +SAS provides a variety of functions to do operations on +date/datetime columns. + +.. code-block:: none + + data tips; + set tips; + format date1 date2 date1_plusmonth mmddyy10.; + date1 = mdy(1, 15, 2013); + date2 = mdy(2, 15, 2015); + date1_year = year(date1); + date2_month = month(date2); + * shift date to begninning of next interval; + date1_next = intnx('MONTH', date1, 1); + * count intervals between dates; + months_between = intck('MONTH', date1, date2); + run; + +The equivalent pandas operations are shown below. In addition to these +functions pandas supports other Time Series features +not available in Base SAS (such as resampling and and custom offets) - +see the :ref:`timeseries documentation<timeseries>` for more details. + +.. ipython:: python + + tips['date1'] = pd.Timestamp('2013-01-15') + tips['date2'] = pd.Timestamp('2015-02-15') + tips['date1_year'] = tips['date1'].dt.year + tips['date2_month'] = tips['date2'].dt.month + tips['date1_next'] = tips['date1'] + pd.offsets.MonthBegin() + tips['months_between'] = (tips['date2'].dt.to_period('M') - + tips['date1'].dt.to_period('M')) + + tips[['date1','date2','date1_year','date2_month', + 'date1_next','months_between']].head() + +.. ipython:: python + :suppress: + + tips = tips.drop(['date1','date2','date1_year', + 'date2_month','date1_next','months_between'], axis=1) + +Selection of Columns +~~~~~~~~~~~~~~~~~~~~ + +SAS provides keywords in the ``DATA`` step to select, +drop, and rename columns. + +.. code-block:: none + + data tips; + set tips; + keep sex total_bill tip; + run; + + data tips; + set tips; + drop sex; + run; + + data tips; + set tips; + rename total_bill=total_bill_2; + run; + +The same operations are expressed in pandas below. + +.. ipython:: python + + # keep + tips[['sex', 'total_bill', 'tip']].head() + + # drop + tips.drop('sex', axis=1).head() + + # rename + tips.rename(columns={'total_bill':'total_bill_2'}).head() + + +Sorting by Values +~~~~~~~~~~~~~~~~~ + +Sorting in SAS is accomplished via ``PROC SORT`` + +.. code-block:: none + + proc sort data=tips; + by sex total_bill; + run; + +pandas objects have a :meth:`~DataFrame.sort_values` method, which +takes a list of columnns to sort by. + +.. ipython:: python + + tips = tips.sort_values(['sex', 'total_bill']) + tips.head() + +Merging +------- + +The following tables will be used in the merge examples + +.. ipython:: python + + df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], + 'value': np.random.randn(4)}) + df1 + df2 = pd.DataFrame({'key': ['B', 'D', 'D', 'E'], + 'value': np.random.randn(4)}) + df2 + +In SAS, data must be explicitly sorted before merging. Different +types of joins are accomplished using the ``in=`` dummy +variables to track whether a match was found in one or both +input frames. + +.. code-block:: none + + proc sort data=df1; + by key; + run; + + proc sort data=df2; + by key; + run; + + data left_join inner_join right_join outer_join; + merge df1(in=a) df2(in=b); + + if a and b then output inner_join; + if a then output left_join; + if b then output right_join; + if a or b then output outer_join; + run; + +pandas DataFrames have a :meth:`~DataFrame.merge` method, which provides +similar functionality. Note that the data does not have +to be sorted ahead of time, and different join +types are accomplished via the ``how`` keyword. + +.. ipython:: python + + inner_join = df1.merge(df2, on=['key'], how='inner') + inner_join + + left_join = df1.merge(df2, on=['key'], how='left') + left_join + + right_join = df1.merge(df2, on=['key'], how='right') + right_join + + outer_join = df1.merge(df2, on=['key'], how='outer') + outer_join + + +Missing Data +------------ + +Like SAS, pandas has a representation for missing data - which is the +special float value ``NaN`` (not a number). Many of the semantics +are the same, for example missing data propagates through numeric +operations, and is ignored by default for aggregations. + +.. ipython:: python + + outer_join + outer_join['value_x'] + outer_join['value_y'] + outer_join['value_x'].sum() + +One difference is that missing data cannot be compared to its sentinel value. +For example, in SAS you could do this to filter missing values. + +.. code-block:: none + + data outer_join_nulls; + set outer_join; + if value_x = .; + run; + + data outer_join_no_nulls; + set outer_join; + if value_x ^= .; + run; + +Which doesn't work in in pandas. Instead, the ``pd.isnull`` or ``pd.notnull`` functions +should be used for comparisons. + +.. ipython:: python + + outer_join[pd.isnull(outer_join['value_x'])] + outer_join[pd.notnull(outer_join['value_x'])] + +pandas also provides a variety of methods to work with missing data - some of +which would be challenging to express in SAS. For example, there are methods to +drop all rows with any missing values, replacing missing values with a specified +value, like the mean, or forward filling from previous rows. See the +:ref:`missing data documentation<missing_data>` for more. + +.. ipython:: python + + outer_join.dropna() + outer_join.fillna(method='ffill') + outer_join['value_x'].fillna(outer_join['value_x'].mean()) + + +GroupBy +------- + +Aggregation +~~~~~~~~~~~ + +SAS's PROC SUMMARY can be used to group by one or +more key variables and compute aggregations on +numeric columns. + +.. code-block:: none + + proc summary data=tips nway; + class sex smoker; + var total_bill tip; + output out=tips_summed sum=; + run; + +pandas provides a flexible ``groupby`` mechanism that +allows similar aggregations. See the :ref:`groupby documentation<groupby>` +for more details and examples. + +.. ipython:: python + + tips_summed = tips.groupby(['sex', 'smoker'])['total_bill', 'tip'].sum() + tips_summed.head() + + +Transformation +~~~~~~~~~~~~~~ + +In SAS, if the group aggregations need to be used with +the original frame, it must be merged back together. For +example, to subtract the mean for each observation by smoker group. + +.. code-block:: none + + proc summary data=tips missing nway; + class smoker; + var total_bill; + output out=smoker_means mean(total_bill)=group_bill; + run; + + proc sort data=tips; + by smoker; + run; + + data tips; + merge tips(in=a) smoker_means(in=b); + by smoker; + adj_total_bill = total_bill - group_bill; + if a and b; + run; + + +pandas ``groubpy`` provides a ``transform`` mechanism that allows +these type of operations to be succinctly expressed in one +operation. + +.. ipython:: python + + gb = tips.groupby('smoker')['total_bill'] + tips['adj_total_bill'] = tips['total_bill'] - gb.transform('mean') + tips.head() + + +By Group Processing +~~~~~~~~~~~~~~~~~~~ + +In addition to aggregation, pandas ``groupby`` can be used to +replicate most other by group processing from SAS. For example, +this ``DATA`` step reads the data by sex/smoker group and filters to +the first entry for each. + +.. code-block:: none + + proc sort data=tips; + by sex smoker; + run; + + data tips_first; + set tips; + by sex smoker; + if FIRST.sex or FIRST.smoker then output; + run; + +In pandas this would be written as: + +.. ipython:: python + + tips.groupby(['sex','smoker']).first() + + +Other Considerations +-------------------- + +Disk vs Memory +~~~~~~~~~~~~~~ + +pandas operates exclusively in memory, where a SAS data set exists on disk. +This means that the size of data able to be loaded in pandas is limited by your +machine's memory, but also that the operations on that data may be faster. + +If out of core processing is needed, one possibility is the +`dask.dataframe <http://dask.pydata.org/en/latest/dataframe.html>`_ +library (currently in development) which +provides a subset of pandas functionality for an on-disk ``DataFrame`` + +Data Interop +~~~~~~~~~~~~ + +pandas provides a :func:`read_sas` method that can read SAS data saved in +the XPORT format. The ability to read SAS's binary format is planned for a +future release. + +.. code-block:: none + + libname xportout xport 'transport-file.xpt'; + data xportout.tips; + set tips(rename=(total_bill=tbill)); + * xport variable names limited to 6 characters; + run; + +.. code-block:: python + + df = pd.read_sas('transport-file.xpt') + +XPORT is a relatively limited format and the parsing of it is not as +optimized as some of the other pandas readers. An alternative way +to interop data between SAS and pandas is to serialize to csv. + +.. code-block:: python + + # version 0.17, 10M rows + + In [8]: %time df = pd.read_sas('big.xpt') + Wall time: 14.6 s + + In [9]: %time df = pd.read_csv('big.csv') + Wall time: 4.86 s diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template index f4469482ec290..621bd33ba5a41 100644 --- a/doc/source/index.rst.template +++ b/doc/source/index.rst.template @@ -145,6 +145,7 @@ See the package overview for more detail about what's in the library. ecosystem comparison_with_r comparison_with_sql + comparison_with_sas {% endif -%} {% if api -%} api diff --git a/doc/source/release.rst b/doc/source/release.rst index 6e74e2c68e44e..2010939724c5e 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -62,6 +62,7 @@ Highlights include: - Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`) - Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`) - Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` +- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>` - Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` See the :ref:`v0.17.0 Whatsnew <whatsnew_0170>` overview for an extensive list diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 3f6da20c4a422..cdc5ffb2fa556 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -47,6 +47,7 @@ Highlights include: - Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`) - Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`) - Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` +- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>` - Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating.
closes #11075 xref #4052 There doesn't seem to be a straightforward way to syntax highlight the SAS code, so it will format as generic code blocks.
https://api.github.com/repos/pandas-dev/pandas/pulls/11087
2015-09-13T14:17:11Z
2015-09-13T19:10:41Z
2015-09-13T19:10:41Z
2015-09-13T21:43:33Z
DOC: fix plot submethods whatsnew example
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 914c18a66af61..3f6da20c4a422 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -150,7 +150,7 @@ The Series and DataFrame ``.plot()`` method allows for customizing :ref:`plot ty To alleviate this issue, we have added a new, optional plotting interface, which exposes each kind of plot as a method of the ``.plot`` attribute. Instead of writing ``series.plot(kind=<kind>, ...)``, you can now also use ``series.plot.<kind>(...)``: .. ipython:: - :verbatim: + :verbatim: In [13]: df = pd.DataFrame(np.random.rand(10, 2), columns=['a', 'b'])
This was not building properly.
https://api.github.com/repos/pandas-dev/pandas/pulls/11083
2015-09-12T23:25:09Z
2015-09-12T23:35:09Z
2015-09-12T23:35:09Z
2015-09-13T00:23:54Z
CI: support *.pip for installations
diff --git a/ci/install_conda.sh b/ci/install_conda.sh index 01b89807d164c..1db1e7fa6f571 100755 --- a/ci/install_conda.sh +++ b/ci/install_conda.sh @@ -78,16 +78,20 @@ conda config --set ssl_verify false || exit 1 # Useful for debugging any issues with conda conda info -a || exit 1 +REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.txt" conda create -n pandas python=$TRAVIS_PYTHON_VERSION || exit 1 -conda install -n pandas --file=ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.txt || exit 1 +conda install -n pandas --file=${REQ} || exit 1 conda install -n pandas pip setuptools nose || exit 1 conda remove -n pandas pandas source activate pandas -pip install -U blosc # See https://github.com/pydata/pandas/pull/9783 -python -c 'import blosc; blosc.print_versions()' +# we may have additional pip installs +REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.pip" +if [ -e ${REQ} ]; then + pip install -r $REQ +fi # set the compiler cache to work if [ "$IRON_TOKEN" ]; then diff --git a/ci/requirements-2.6.pip b/ci/requirements-2.6.pip new file mode 100644 index 0000000000000..cf8e6b8b3d3a6 --- /dev/null +++ b/ci/requirements-2.6.pip @@ -0,0 +1 @@ +blosc diff --git a/ci/requirements-2.7.pip b/ci/requirements-2.7.pip new file mode 100644 index 0000000000000..cf8e6b8b3d3a6 --- /dev/null +++ b/ci/requirements-2.7.pip @@ -0,0 +1 @@ +blosc diff --git a/ci/requirements-2.7_LOCALE.pip b/ci/requirements-2.7_LOCALE.pip new file mode 100644 index 0000000000000..cf8e6b8b3d3a6 --- /dev/null +++ b/ci/requirements-2.7_LOCALE.pip @@ -0,0 +1 @@ +blosc diff --git a/ci/requirements-3.3.pip b/ci/requirements-3.3.pip new file mode 100644 index 0000000000000..cf8e6b8b3d3a6 --- /dev/null +++ b/ci/requirements-3.3.pip @@ -0,0 +1 @@ +blosc diff --git a/ci/requirements-3.4.pip b/ci/requirements-3.4.pip new file mode 100644 index 0000000000000..cf8e6b8b3d3a6 --- /dev/null +++ b/ci/requirements-3.4.pip @@ -0,0 +1 @@ +blosc diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py index 88b3c94d3ea18..f0545e9949e24 100644 --- a/pandas/util/print_versions.py +++ b/pandas/util/print_versions.py @@ -72,6 +72,7 @@ def show_versions(as_json=False): ("patsy", lambda mod: mod.__version__), ("dateutil", lambda mod: mod.__version__), ("pytz", lambda mod: mod.VERSION), + ("blosc", lambda mod: mod.__version__), ("bottleneck", lambda mod: mod.__version__), ("tables", lambda mod: mod.__version__), ("numexpr", lambda mod: mod.__version__),
https://api.github.com/repos/pandas-dev/pandas/pulls/11081
2015-09-12T22:46:57Z
2015-09-12T23:36:12Z
2015-09-12T23:36:12Z
2015-09-12T23:36:12Z
BUG: Fix Series nunique groupby with object dtype
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 9d8532aa3649a..7fe92b580536a 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1014,7 +1014,7 @@ Performance Improvements - Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`) - Added vbench benchmarks for alternative ExcelWriter engines and reading Excel files (:issue:`7171`) - Performance improvements in ``Categorical.value_counts`` (:issue:`10804`) -- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` (:issue:`10820`) +- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` (:issue:`10820`, :issue:`11077`) - Performance improvements in ``DataFrame.drop_duplicates`` with integer dtypes (:issue:`10917`) - 4x improvement in ``timedelta`` string parsing (:issue:`6755`, :issue:`10426`) - 8x improvement in ``timedelta64`` and ``datetime64`` ops (:issue:`6755`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index f34fd6e3d2575..8e44480c0c09b 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2565,7 +2565,17 @@ def nunique(self, dropna=True): ids, _, _ = self.grouper.group_info val = self.obj.get_values() - sorter = np.lexsort((val, ids)) + try: + sorter = np.lexsort((val, ids)) + except TypeError: # catches object dtypes + assert val.dtype == object, \ + 'val.dtype must be object, got %s' % val.dtype + val, _ = algos.factorize(val, sort=False) + sorter = np.lexsort((val, ids)) + isnull = lambda a: a == -1 + else: + isnull = com.isnull + ids, val = ids[sorter], val[sorter] # group boundries are where group ids change diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 97b57690ccc49..0336ee2e9b50e 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -5511,6 +5511,22 @@ def test_sort(x): g.apply(test_sort) + def test_nunique_with_object(self): + # GH 11077 + data = pd.DataFrame( + [[100, 1, 'Alice'], + [200, 2, 'Bob'], + [300, 3, 'Charlie'], + [-400, 4, 'Dan'], + [500, 5, 'Edith']], + columns=['amount', 'id', 'name'] + ) + + result = data.groupby(['id', 'amount'])['name'].nunique() + index = MultiIndex.from_arrays([data.id, data.amount]) + expected = pd.Series([1] * 5, name='name', index=index) + tm.assert_series_equal(result, expected) + def assert_fp_equal(a, b): assert (np.abs(a - b) < 1e-12).all()
closes #11077
https://api.github.com/repos/pandas-dev/pandas/pulls/11079
2015-09-12T18:31:35Z
2015-09-14T22:09:02Z
2015-09-14T22:09:01Z
2015-09-14T22:11:28Z
ENH Add check for inferred compression before `get_filepath_or_buffer`
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 615bfc9e23253..a6e6c9f2f2b3c 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -481,6 +481,8 @@ Other enhancements - Read CSV files from AWS S3 incrementally, instead of first downloading the entire file. (Full file download still required for compressed files in Python 2.) (:issue:`11070`, :issue:`11073`) +- ``pd.read_csv`` is now able to infer compression type for files read from AWS S3 storage (:issue:`11070`, :issue:`11074`). + .. _whatsnew_0170.api: .. _whatsnew_0170.api_breaking: diff --git a/pandas/io/common.py b/pandas/io/common.py index 7095a0fd60f2a..e13c402b454d1 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -217,6 +217,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None, content_encoding = req.headers.get('Content-Encoding', None) if content_encoding == 'gzip': compression = 'gzip' + else: + compression = None # cat on the compression to the tuple returned by the function to_return = list(maybe_read_encoded_stream(req, encoding, compression)) + \ [compression] @@ -237,7 +239,9 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None, conn = boto.connect_s3(anon=True) b = conn.get_bucket(parsed_url.netloc, validate=False) - if compat.PY2 and compression == 'gzip': + if compat.PY2 and (compression == 'gzip' or + (compression == 'infer' and + filepath_or_buffer.endswith(".gz"))): k = boto.s3.key.Key(b, parsed_url.path) filepath_or_buffer = BytesIO(k.get_contents_as_string( encoding=encoding)) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 736c08f72dee8..15e11193fd1b7 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -235,10 +235,25 @@ def _read(filepath_or_buffer, kwds): if skipfooter is not None: kwds['skip_footer'] = skipfooter + # If the input could be a filename, check for a recognizable compression extension. + # If we're reading from a URL, the `get_filepath_or_buffer` will use header info + # to determine compression, so use what it finds in that case. + inferred_compression = kwds.get('compression') + if inferred_compression == 'infer': + if isinstance(filepath_or_buffer, compat.string_types): + if filepath_or_buffer.endswith('.gz'): + inferred_compression = 'gzip' + elif filepath_or_buffer.endswith('.bz2'): + inferred_compression = 'bz2' + else: + inferred_compression = None + else: + inferred_compression = None + filepath_or_buffer, _, compression = get_filepath_or_buffer(filepath_or_buffer, encoding, compression=kwds.get('compression', None)) - kwds['compression'] = compression + kwds['compression'] = inferred_compression if compression == 'infer' else compression if kwds.get('date_parser', None) is not None: if isinstance(kwds['parse_dates'], bool): @@ -301,7 +316,7 @@ def _read(filepath_or_buffer, kwds): 'verbose': False, 'encoding': None, 'squeeze': False, - 'compression': 'infer', + 'compression': None, 'mangle_dupe_cols': True, 'tupleize_cols': False, 'infer_datetime_format': False, @@ -1402,17 +1417,6 @@ def __init__(self, f, **kwds): self.comment = kwds['comment'] self._comment_lines = [] - if self.compression == 'infer': - if isinstance(f, compat.string_types): - if f.endswith('.gz'): - self.compression = 'gzip' - elif f.endswith('.bz2'): - self.compression = 'bz2' - else: - self.compression = None - else: - self.compression = None - if isinstance(f, compat.string_types): f = com._get_handle(f, 'r', encoding=self.encoding, compression=self.compression) diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 70a49e6bd6782..6b7132aea3280 100755 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -4341,6 +4341,15 @@ def test_parse_public_s3_bucket_python(self): self.assertFalse(df.empty) tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) + @tm.network + def test_infer_s3_compression(self): + for ext in ['', '.gz', '.bz2']: + df = pd.read_csv('s3://pandas-test/tips.csv' + ext, + engine='python', compression='infer') + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) + @tm.network def test_parse_public_s3_bucket_nrows_python(self): for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: diff --git a/pandas/parser.pyx b/pandas/parser.pyx index 647e8e72414e9..8ac1f64f2d50e 100644 --- a/pandas/parser.pyx +++ b/pandas/parser.pyx @@ -541,17 +541,6 @@ cdef class TextReader: self.parser.cb_io = NULL self.parser.cb_cleanup = NULL - if self.compression == 'infer': - if isinstance(source, basestring): - if source.endswith('.gz'): - self.compression = 'gzip' - elif source.endswith('.bz2'): - self.compression = 'bz2' - else: - self.compression = None - else: - self.compression = None - if self.compression: if self.compression == 'gzip': import gzip
When reading CSVs, if `compression='infer'`, check the input before calling `get_filepath_or_buffer` in the `_read` function. This way we can catch compresion extensions on S3 files. Partially resolves issue #11070 . Checking for the file extension in the `_read` function should make the checks inside the parsers redundant. When I tried to remove them, however, I discovered that there's tests which assume the parsers can take an "infer" compression, so I left their checks. I also discovered that the URL-reading code has a test which reads a URL ending in "gz" but which appears not to be gzip encoded, so this PR attempts to preserve its verdict in that case.
https://api.github.com/repos/pandas-dev/pandas/pulls/11074
2015-09-12T16:09:22Z
2015-09-15T13:23:42Z
2015-09-15T13:23:42Z
2015-09-15T13:29:18Z
ENH Enable streaming from S3
diff --git a/asv_bench/benchmarks/io_bench.py b/asv_bench/benchmarks/io_bench.py index a171641502d3c..0f15ab6e5e142 100644 --- a/asv_bench/benchmarks/io_bench.py +++ b/asv_bench/benchmarks/io_bench.py @@ -1,9 +1,10 @@ from .pandas_vb_common import * -from pandas import concat, Timestamp +from pandas import concat, Timestamp, compat try: from StringIO import StringIO except ImportError: from io import StringIO +import timeit class frame_to_csv(object): @@ -135,4 +136,36 @@ def setup(self): self.df = DataFrame({'float1': randn(10000), 'float2': randn(10000), 'string1': (['foo'] * 10000), 'bool1': ([True] * 10000), 'int1': np.random.randint(0, 100000, size=10000), }, index=self.index) def time_write_csv_standard(self): - self.df.to_csv('__test__.csv') \ No newline at end of file + self.df.to_csv('__test__.csv') + + +class read_csv_from_s3(object): + # Make sure that we can read part of a file from S3 without + # needing to download the entire thing. Use the timeit.default_timer + # to measure wall time instead of CPU time -- we want to see + # how long it takes to download the data. + timer = timeit.default_timer + params = ([None, "gzip", "bz2"], ["python", "c"]) + param_names = ["compression", "engine"] + + def setup(self, compression, engine): + if compression == "bz2" and engine == "c" and compat.PY2: + # The Python 2 C parser can't read bz2 from open files. + raise NotImplementedError + try: + import boto + except ImportError: + # Skip these benchmarks if `boto` is not installed. + raise NotImplementedError + + self.big_fname = "s3://pandas-test/large_random.csv" + + def time_read_nrows(self, compression, engine): + # Read a small number of rows from a huge (100,000 x 50) table. + ext = "" + if compression == "gzip": + ext = ".gz" + elif compression == "bz2": + ext = ".bz2" + pd.read_csv(self.big_fname + ext, nrows=10, + compression=compression, engine=engine) diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 9d8532aa3649a..5f9f7574a282b 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -479,6 +479,8 @@ Other enhancements - In ``pd.read_csv``, recognize "s3n://" and "s3a://" URLs as designating S3 file storage (:issue:`11070`, :issue:`11071`). +- Read CSV files from AWS S3 incrementally, instead of first downloading the entire file. (Full file download still required for compressed files in Python 2.) (:issue:`11070`, :issue:`11073`) + .. _whatsnew_0170.api: .. _whatsnew_0170.api_breaking: diff --git a/pandas/io/common.py b/pandas/io/common.py index 5ab5640ca12c0..7095a0fd60f2a 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -47,6 +47,77 @@ class DtypeWarning(Warning): pass +try: + from boto.s3 import key + class BotoFileLikeReader(key.Key): + """boto Key modified to be more file-like + + This modification of the boto Key will read through a supplied + S3 key once, then stop. The unmodified boto Key object will repeatedly + cycle through a file in S3: after reaching the end of the file, + boto will close the file. Then the next call to `read` or `next` will + re-open the file and start reading from the beginning. + + Also adds a `readline` function which will split the returned + values by the `\n` character. + """ + def __init__(self, *args, **kwargs): + encoding = kwargs.pop("encoding", None) # Python 2 compat + super(BotoFileLikeReader, self).__init__(*args, **kwargs) + self.finished_read = False # Add a flag to mark the end of the read. + self.buffer = "" + self.lines = [] + if encoding is None and compat.PY3: + encoding = "utf-8" + self.encoding = encoding + self.lines = [] + + def next(self): + return self.readline() + + __next__ = next + + def read(self, *args, **kwargs): + if self.finished_read: + return b'' if compat.PY3 else '' + return super(BotoFileLikeReader, self).read(*args, **kwargs) + + def close(self, *args, **kwargs): + self.finished_read = True + return super(BotoFileLikeReader, self).close(*args, **kwargs) + + def seekable(self): + """Needed for reading by bz2""" + return False + + def readline(self): + """Split the contents of the Key by '\n' characters.""" + if self.lines: + retval = self.lines[0] + self.lines = self.lines[1:] + return retval + if self.finished_read: + if self.buffer: + retval, self.buffer = self.buffer, "" + return retval + else: + raise StopIteration + + if self.encoding: + self.buffer = "{}{}".format(self.buffer, self.read(8192).decode(self.encoding)) + else: + self.buffer = "{}{}".format(self.buffer, self.read(8192)) + + split_buffer = self.buffer.split("\n") + self.lines.extend(split_buffer[:-1]) + self.buffer = split_buffer[-1] + + return self.readline() +except ImportError: + # boto is only needed for reading from S3. + pass + + def _is_url(url): """Check to see if a URL has a valid protocol. @@ -166,10 +237,14 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None, conn = boto.connect_s3(anon=True) b = conn.get_bucket(parsed_url.netloc, validate=False) - k = boto.s3.key.Key(b) - k.key = parsed_url.path - filepath_or_buffer = BytesIO(k.get_contents_as_string( - encoding=encoding)) + if compat.PY2 and compression == 'gzip': + k = boto.s3.key.Key(b, parsed_url.path) + filepath_or_buffer = BytesIO(k.get_contents_as_string( + encoding=encoding)) + else: + k = BotoFileLikeReader(b, parsed_url.path, encoding=encoding) + k.open('r') # Expose read errors immediately + filepath_or_buffer = k return filepath_or_buffer, None, compression return _expand_user(filepath_or_buffer), None, compression diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 205140e02a8ea..70a49e6bd6782 100755 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -4241,16 +4241,22 @@ def setUp(self): @tm.network def test_parse_public_s3_bucket(self): - import nose.tools as nt - df = pd.read_csv('s3://nyqpug/tips.csv') - nt.assert_true(isinstance(df, pd.DataFrame)) - nt.assert_false(df.empty) - tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) + for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: + if comp == 'bz2' and compat.PY2: + # The Python 2 C parser can't read bz2 from S3. + self.assertRaises(ValueError, pd.read_csv, + 's3://pandas-test/tips.csv' + ext, + compression=comp) + else: + df = pd.read_csv('s3://pandas-test/tips.csv' + ext, compression=comp) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) # Read public file from bucket with not-public contents df = pd.read_csv('s3://cant_get_it/tips.csv') - nt.assert_true(isinstance(df, pd.DataFrame)) - nt.assert_false(df.empty) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) @tm.network @@ -4269,6 +4275,81 @@ def test_parse_public_s3a_bucket(self): self.assertFalse(df.empty) tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df) + @tm.network + def test_parse_public_s3_bucket_nrows(self): + for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: + if comp == 'bz2' and compat.PY2: + # The Python 2 C parser can't read bz2 from S3. + self.assertRaises(ValueError, pd.read_csv, + 's3://pandas-test/tips.csv' + ext, + compression=comp) + else: + df = pd.read_csv('s3://pandas-test/tips.csv' + ext, nrows=10, compression=comp) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df) + + @tm.network + def test_parse_public_s3_bucket_chunked(self): + # Read with a chunksize + chunksize = 5 + local_tips = pd.read_csv(tm.get_data_path('tips.csv')) + for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: + if comp == 'bz2' and compat.PY2: + # The Python 2 C parser can't read bz2 from S3. + self.assertRaises(ValueError, pd.read_csv, + 's3://pandas-test/tips.csv' + ext, + compression=comp) + else: + df_reader = pd.read_csv('s3://pandas-test/tips.csv' + ext, + chunksize=chunksize, compression=comp) + self.assertEqual(df_reader.chunksize, chunksize) + for i_chunk in [0, 1, 2]: + # Read a couple of chunks and make sure we see them properly. + df = df_reader.get_chunk() + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + true_df = local_tips.iloc[chunksize * i_chunk: chunksize * (i_chunk + 1)] + true_df = true_df.reset_index().drop('index', axis=1) # Chunking doesn't preserve row numbering + tm.assert_frame_equal(true_df, df) + + @tm.network + def test_parse_public_s3_bucket_chunked_python(self): + # Read with a chunksize using the Python parser + chunksize = 5 + local_tips = pd.read_csv(tm.get_data_path('tips.csv')) + for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: + df_reader = pd.read_csv('s3://pandas-test/tips.csv' + ext, + chunksize=chunksize, compression=comp, + engine='python') + self.assertEqual(df_reader.chunksize, chunksize) + for i_chunk in [0, 1, 2]: + # Read a couple of chunks and make sure we see them properly. + df = df_reader.get_chunk() + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + true_df = local_tips.iloc[chunksize * i_chunk: chunksize * (i_chunk + 1)] + true_df = true_df.reset_index().drop('index', axis=1) # Chunking doesn't preserve row numbering + tm.assert_frame_equal(true_df, df) + + @tm.network + def test_parse_public_s3_bucket_python(self): + for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: + df = pd.read_csv('s3://pandas-test/tips.csv' + ext, engine='python', + compression=comp) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) + + @tm.network + def test_parse_public_s3_bucket_nrows_python(self): + for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: + df = pd.read_csv('s3://pandas-test/tips.csv' + ext, engine='python', + nrows=10, compression=comp) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df) + @tm.network def test_s3_fails(self): import boto
File reading from AWS S3: Modify the `get_filepath_or_buffer` function such that it only opens the connection to S3, rather than reading the entire file at once. This allows partial reads (e.g. through the `nrows` argument) or chunked reading (e.g. through the `chunksize` argument) without needing to download the entire file first. I wasn't sure what the best place was to put the `OnceThroughKey`. (Suggestions for better names welcome.) I don't like putting an entire class inside a function like that, but this keeps the `boto` dependency contained. The `readline` function, and modifying `next` such that it returns lines, was necessary to allow the Python engine to read uncompressed CSVs. The Python 2 standard library's `gzip` module needs a `seek` and `tell` function on its inputs, so I reverted to the old behavior there. Partially addresses #11070 .
https://api.github.com/repos/pandas-dev/pandas/pulls/11073
2015-09-12T13:51:09Z
2015-09-14T22:24:49Z
2015-09-14T22:24:49Z
2015-09-14T22:32:55Z
ENH Enable bzip2 streaming for Python 3
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 914c18a66af61..986af61414587 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -465,6 +465,8 @@ Other enhancements - Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`) +- ``pd.read_csv`` can now read bz2-compressed files incrementally, and the C parser can read bz2-compressed files from AWS S3 (:issue:`11070`, :issue:`11072`). + .. _whatsnew_0170.api: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index f0c994ba17e27..736c08f72dee8 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1344,12 +1344,13 @@ def _wrap_compressed(f, compression, encoding=None): elif compression == 'bz2': import bz2 - # bz2 module can't take file objects, so have to run through decompress - # manually - data = bz2.decompress(f.read()) if compat.PY3: - data = data.decode(encoding) - f = StringIO(data) + f = bz2.open(f, 'rt', encoding=encoding) + else: + # Python 2's bz2 module can't take file objects, so have to + # run through decompress manually + data = bz2.decompress(f.read()) + f = StringIO(data) return f else: raise ValueError('do not recognize compression method %s' diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index ed261edad4f20..fabe4ce40b22f 100755 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -3836,6 +3836,14 @@ def test_decompression(self): self.assertRaises(ValueError, self.read_csv, path, compression='bz3') + with open(path, 'rb') as fin: + if compat.PY3: + result = self.read_csv(fin, compression='bz2') + tm.assert_frame_equal(result, expected) + else: + self.assertRaises(ValueError, self.read_csv, + fin, compression='bz2') + def test_decompression_regex_sep(self): try: import gzip diff --git a/pandas/parser.pyx b/pandas/parser.pyx index c2916f2c0cfb8..647e8e72414e9 100644 --- a/pandas/parser.pyx +++ b/pandas/parser.pyx @@ -561,10 +561,10 @@ cdef class TextReader: source = gzip.GzipFile(fileobj=source) elif self.compression == 'bz2': import bz2 - if isinstance(source, basestring): + if isinstance(source, basestring) or PY3: source = bz2.BZ2File(source, 'rb') else: - raise ValueError('Python cannot read bz2 from open file ' + raise ValueError('Python 2 cannot read bz2 from open file ' 'handle') else: raise ValueError('Unrecognized compression type: %s' %
This is the one modification related to issue #11070 which affects non-S3 interactions with `read_csv`. The Python 3 standard library has an improved capability for handling bz2 compression, so a simple change will let `read_csv` stream bz2-compressed files.
https://api.github.com/repos/pandas-dev/pandas/pulls/11072
2015-09-12T13:32:12Z
2015-09-13T14:52:53Z
2015-09-13T14:52:53Z
2015-09-14T20:12:22Z
ENH Recognize 's3n' and 's3a' as an S3 address
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 3b3bf8cffe41b..b45c843d28eb8 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -467,6 +467,7 @@ Other enhancements - ``pd.read_csv`` can now read bz2-compressed files incrementally, and the C parser can read bz2-compressed files from AWS S3 (:issue:`11070`, :issue:`11072`). +- In ``pd.read_csv``, recognize "s3n://" and "s3a://" URLs as designating S3 file storage (:issue:`11070`, :issue:`11071`). .. _whatsnew_0170.api: diff --git a/pandas/io/common.py b/pandas/io/common.py index c6ece61f05a01..5ab5640ca12c0 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -66,9 +66,9 @@ def _is_url(url): def _is_s3_url(url): - """Check for an s3 url""" + """Check for an s3, s3n, or s3a url""" try: - return parse_url(url).scheme == 's3' + return parse_url(url).scheme in ['s3', 's3n', 's3a'] except: return False diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index fabe4ce40b22f..205140e02a8ea 100755 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -4253,6 +4253,22 @@ def test_parse_public_s3_bucket(self): nt.assert_false(df.empty) tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df) + @tm.network + def test_parse_public_s3n_bucket(self): + # Read from AWS s3 as "s3n" URL + df = pd.read_csv('s3n://pandas-test/tips.csv', nrows=10) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df) + + @tm.network + def test_parse_public_s3a_bucket(self): + # Read from AWS s3 as "s3a" URL + df = pd.read_csv('s3a://pandas-test/tips.csv', nrows=10) + self.assertTrue(isinstance(df, pd.DataFrame)) + self.assertFalse(df.empty) + tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df) + @tm.network def test_s3_fails(self): import boto
This PR allows `read_csv` to recognize that "s3n://" designates a valid AWS S3 address. Partially addresses issue #11070 .
https://api.github.com/repos/pandas-dev/pandas/pulls/11071
2015-09-12T13:29:25Z
2015-09-14T19:49:34Z
2015-09-14T19:49:34Z
2015-09-14T20:09:26Z
DOC: Re-organize whatsnew
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index c3b12f4e73b01..914c18a66af61 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -38,10 +38,12 @@ Highlights include: - The sorting API has been revamped to remove some long-time inconsistencies, see :ref:`here <whatsnew_0170.api_breaking.sorting>` - Support for a ``datetime64[ns]`` with timezones as a first-class dtype, see :ref:`here <whatsnew_0170.tz>` - The default for ``to_datetime`` will now be to ``raise`` when presented with unparseable formats, - previously this would return the original input, see :ref:`here <whatsnew_0170.api_breaking.to_datetime>` + previously this would return the original input. Also, date parse + functions now return consistent results. See :ref:`here <whatsnew_0170.api_breaking.to_datetime>` - The default for ``dropna`` in ``HDFStore`` has changed to ``False``, to store by default all rows even if they are all ``NaN``, see :ref:`here <whatsnew_0170.api_breaking.hdf_dropna>` -- Support for ``Series.dt.strftime`` to generate formatted strings for datetime-likes, see :ref:`here <whatsnew_0170.strftime>` +- Datetime accessor (``dt``) now supports ``Series.dt.strftime`` to generate formatted strings for datetime-likes, and ``Series.dt.total_seconds`` to generate each duration of the timedelta in seconds. See :ref:`here <whatsnew_0170.strftime>` +- ``Period`` and ``PeriodIndex`` can handle multiplied freq like ``3D``, which corresponding to 3 days span. See :ref:`here <whatsnew_0170.periodfreq>` - Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`) - Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`) - Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` @@ -169,8 +171,11 @@ Each method signature only includes relevant arguments. Currently, these are lim .. _whatsnew_0170.strftime: -Support strftime for Datetimelikes -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Additional methods for ``dt`` accessor +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +strftime +"""""""" We are now supporting a ``Series.dt.strftime`` method for datetime-likes to generate a formatted string (:issue:`10110`). Examples: @@ -190,6 +195,18 @@ We are now supporting a ``Series.dt.strftime`` method for datetime-likes to gene The string format is as the python standard library and details can be found `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_ +total_seconds +""""""""""""" + +``pd.Series`` of type ``timedelta64`` has new method ``.dt.total_seconds()`` returning the duration of the timedelta in seconds (:issue:`10817`) + +.. ipython:: python + + # TimedeltaIndex + s = pd.Series(pd.timedelta_range('1 minutes', periods=4)) + s + s.dt.total_seconds() + .. _whatsnew_0170.periodfreq: Period Frequency Enhancement @@ -240,7 +257,7 @@ See the :ref:`docs <io.sas>` for more details. .. _whatsnew_0170.matheval: Support for Math Functions in .eval() -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :meth:`~pandas.eval` now supports calling math functions (:issue:`4893`) @@ -307,7 +324,6 @@ has been changed to make this keyword unnecessary - the change is shown below. Other enhancements ^^^^^^^^^^^^^^^^^^ - - ``merge`` now accepts the argument ``indicator`` which adds a Categorical-type column (by default called ``_merge``) to the output object that takes on the values (:issue:`8790`) =================================== ================ @@ -326,93 +342,52 @@ Other enhancements For more, see the :ref:`updated docs <merging.indicator>` -- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`) -- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`) -- Enable writing complex values to HDF stores when using table format (:issue:`10447`) -- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`) -- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`) - - .. ipython:: python - - ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13]) - ser.interpolate(limit=1, limit_direction='both') - -- Round DataFrame to variable number of decimal places (:issue:`10568`). +- ``pd.merge`` will now allow duplicate column names if they are not merged upon (:issue:`10639`). - .. ipython :: python +- ``pd.pivot`` will now allow passing index as ``None`` (:issue:`3962`). - df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'], - index=['first', 'second', 'third']) - df - df.round(2) - df.round({'A': 0, 'C': 2}) +- ``concat`` will now use existing Series names if provided (:issue:`10698`). -- ``pd.read_sql`` and ``to_sql`` can accept database URI as ``con`` parameter (:issue:`10214`) -- Enable ``pd.read_hdf`` to be used without specifying a key when the HDF file contains a single dataset (:issue:`10443`) -- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`) -- Enable serialization of lists and dicts to strings in ``ExcelWriter`` (:issue:`8188`) -- Added functionality to use the ``base`` argument when resampling a ``TimeDeltaIndex`` (:issue:`10530`) -- ``DatetimeIndex`` can be instantiated using strings contains ``NaT`` (:issue:`7599`) -- The string parsing of ``to_datetime``, ``Timestamp`` and ``DatetimeIndex`` has been made consistent. (:issue:`7599`) + .. ipython:: python - Prior to v0.17.0, ``Timestamp`` and ``to_datetime`` may parse year-only datetime-string incorrectly using today's date, otherwise ``DatetimeIndex`` - uses the beginning of the year. ``Timestamp`` and ``to_datetime`` may raise ``ValueError`` in some types of datetime-string which ``DatetimeIndex`` - can parse, such as a quarterly string. + foo = pd.Series([1,2], name='foo') + bar = pd.Series([1,2]) + baz = pd.Series([4,5]) - Previous Behavior + Previous Behavior: .. code-block:: python - In [1]: Timestamp('2012Q2') - Traceback - ... - ValueError: Unable to parse 2012Q2 - - # Results in today's date. - In [2]: Timestamp('2014') - Out [2]: 2014-08-12 00:00:00 - - v0.17.0 can parse them as below. It works on ``DatetimeIndex`` also. + In [1] pd.concat([foo, bar, baz], 1) + Out[1]: + 0 1 2 + 0 1 1 4 + 1 2 2 5 - New Behaviour + New Behavior: .. ipython:: python - Timestamp('2012Q2') - Timestamp('2014') - DatetimeIndex(['2012Q2', '2014']) - - .. note:: - - If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``. - - .. ipython:: python - - import pandas.tseries.offsets as offsets - Timestamp.now() - Timestamp.now() + offsets.DateOffset(years=1) - -- ``to_datetime`` can now accept ``yearfirst`` keyword (:issue:`7599`) - -- ``pandas.tseries.offsets`` larger than the ``Day`` offset can now be used with with ``Series`` for addition/subtraction (:issue:`10699`). See the :ref:`Documentation <timeseries.offsetseries>` for more details. - -- ``pd.Series`` of type ``timedelta64`` has new method ``.dt.total_seconds()`` returning the duration of the timedelta in seconds (:issue:`10817`) + pd.concat([foo, bar, baz], 1) -- ``pd.Timedelta.total_seconds()`` now returns Timedelta duration to ns precision (previously microsecond precision) (:issue:`10939`) +- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`) -- ``.as_blocks`` will now take a ``copy`` optional argument to return a copy of the data, default is to copy (no change in behavior from prior versions), (:issue:`9607`) -- ``regex`` argument to ``DataFrame.filter`` now handles numeric column names instead of raising ``ValueError`` (:issue:`10384`). -- ``pd.read_stata`` will now read Stata 118 type files. (:issue:`9882`) +- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`) -- ``pd.merge`` will now allow duplicate column names if they are not merged upon (:issue:`10639`). + .. ipython:: python -- ``pd.pivot`` will now allow passing index as ``None`` (:issue:`3962`). + ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13]) + ser.interpolate(limit=1, limit_direction='both') -- ``read_sql_table`` will now allow reading from views (:issue:`10750`). +- Round DataFrame to variable number of decimal places (:issue:`10568`). -- ``msgpack`` submodule has been updated to 0.4.6 with backward compatibility (:issue:`10581`) + .. ipython :: python -- ``DataFrame.to_dict`` now accepts the *index* option in ``orient`` keyword argument (:issue:`10844`). + df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'], + index=['first', 'second', 'third']) + df + df.round(2) + df.round({'A': 0, 'C': 2}) - ``drop_duplicates`` and ``duplicated`` now accept ``keep`` keyword to target first, last, and all duplicates. ``take_last`` keyword is deprecated, see :ref:`deprecations <whatsnew_0170.deprecations>` (:issue:`6511`, :issue:`8505`) @@ -444,37 +419,50 @@ Other enhancements ``tolerance`` is also exposed by the lower level ``Index.get_indexer`` and ``Index.get_loc`` methods. -- Support pickling of ``Period`` objects (:issue:`10439`) +- Added functionality to use the ``base`` argument when resampling a ``TimeDeltaIndex`` (:issue:`10530`) -- ``DataFrame.apply`` will return a Series of dicts if the passed function returns a dict and ``reduce=True`` (:issue:`8735`). +- ``DatetimeIndex`` can be instantiated using strings contains ``NaT`` (:issue:`7599`) + +- ``to_datetime`` can now accept ``yearfirst`` keyword (:issue:`7599`) + +- ``pandas.tseries.offsets`` larger than the ``Day`` offset can now be used with with ``Series`` for addition/subtraction (:issue:`10699`). See the :ref:`Documentation <timeseries.offsetseries>` for more details. + +- ``pd.Timedelta.total_seconds()`` now returns Timedelta duration to ns precision (previously microsecond precision) (:issue:`10939`) - ``PeriodIndex`` now supports arithmetic with ``np.ndarray`` (:issue:`10638`) -- ``concat`` will now use existing Series names if provided (:issue:`10698`). +- Support pickling of ``Period`` objects (:issue:`10439`) - .. ipython:: python +- ``.as_blocks`` will now take a ``copy`` optional argument to return a copy of the data, default is to copy (no change in behavior from prior versions), (:issue:`9607`) - foo = pd.Series([1,2], name='foo') - bar = pd.Series([1,2]) - baz = pd.Series([4,5]) +- ``regex`` argument to ``DataFrame.filter`` now handles numeric column names instead of raising ``ValueError`` (:issue:`10384`). - Previous Behavior: +- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`) - .. code-block:: python +- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`) - In [1] pd.concat([foo, bar, baz], 1) - Out[1]: - 0 1 2 - 0 1 1 4 - 1 2 2 5 +- Enable serialization of lists and dicts to strings in ``ExcelWriter`` (:issue:`8188`) - New Behavior: +- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`) - .. ipython:: python +- ``pd.read_sql`` and ``to_sql`` can accept database URI as ``con`` parameter (:issue:`10214`) - pd.concat([foo, bar, baz], 1) +- ``read_sql_table`` will now allow reading from views (:issue:`10750`). + +- Enable writing complex values to HDF stores when using table format (:issue:`10447`) + +- Enable ``pd.read_hdf`` to be used without specifying a key when the HDF file contains a single dataset (:issue:`10443`) + +- ``pd.read_stata`` will now read Stata 118 type files. (:issue:`9882`) + +- ``msgpack`` submodule has been updated to 0.4.6 with backward compatibility (:issue:`10581`) + +- ``DataFrame.to_dict`` now accepts the *index* option in ``orient`` keyword argument (:issue:`10844`). + +- ``DataFrame.apply`` will return a Series of dicts if the passed function returns a dict and ``reduce=True`` (:issue:`8735`). - Allow passing `kwargs` to the interpolation methods (:issue:`10378`). + - Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`) @@ -547,9 +535,13 @@ Previous Replacement Changes to to_datetime and to_timedelta ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The default for ``pd.to_datetime`` error handling has changed to ``errors='raise'``. In prior versions it was ``errors='ignore'``. -Furthermore, the ``coerce`` argument has been deprecated in favor of ``errors='coerce'``. This means that invalid parsing will raise rather that return the original -input as in previous versions. (:issue:`10636`) +Error handling +"""""""""""""" + +The default for ``pd.to_datetime`` error handling has changed to ``errors='raise'``. +In prior versions it was ``errors='ignore'``. Furthermore, the ``coerce`` argument +has been deprecated in favor of ``errors='coerce'``. This means that invalid parsing +will raise rather that return the original input as in previous versions. (:issue:`10636`) Previous Behavior: @@ -573,7 +565,7 @@ Of course you can coerce this as well. to_datetime(['2009-07-31', 'asd'], errors='coerce') -To keep the previous behaviour, you can use ``errors='ignore'``: +To keep the previous behavior, you can use ``errors='ignore'``: .. ipython:: python @@ -582,6 +574,48 @@ To keep the previous behaviour, you can use ``errors='ignore'``: Furthermore, ``pd.to_timedelta`` has gained a similar API, of ``errors='raise'|'ignore'|'coerce'``, and the ``coerce`` keyword has been deprecated in favor of ``errors='coerce'``. +Consistent Parsing +"""""""""""""""""" + +The string parsing of ``to_datetime``, ``Timestamp`` and ``DatetimeIndex`` has +been made consistent. (:issue:`7599`) + +Prior to v0.17.0, ``Timestamp`` and ``to_datetime`` may parse year-only datetime-string incorrectly using today's date, otherwise ``DatetimeIndex`` +uses the beginning of the year. ``Timestamp`` and ``to_datetime`` may raise ``ValueError`` in some types of datetime-string which ``DatetimeIndex`` +can parse, such as a quarterly string. + +Previous Behavior: + +.. code-block:: python + + In [1]: Timestamp('2012Q2') + Traceback + ... + ValueError: Unable to parse 2012Q2 + + # Results in today's date. + In [2]: Timestamp('2014') + Out [2]: 2014-08-12 00:00:00 + +v0.17.0 can parse them as below. It works on ``DatetimeIndex`` also. + +New Behavior: + +.. ipython:: python + + Timestamp('2012Q2') + Timestamp('2014') + DatetimeIndex(['2012Q2', '2014']) + +.. note:: + + If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``. + + .. ipython:: python + + import pandas.tseries.offsets as offsets + Timestamp.now() + Timestamp.now() + offsets.DateOffset(years=1) .. _whatsnew_0170.api_breaking.convert_objects: @@ -656,7 +690,7 @@ Operator equal on ``Index`` should behavior similarly to ``Series`` (:issue:`994 Starting in v0.17.0, comparing ``Index`` objects of different lengths will raise a ``ValueError``. This is to be consistent with the behavior of ``Series``. -Previous behavior: +Previous Behavior: .. code-block:: python @@ -669,7 +703,7 @@ Previous behavior: In [4]: pd.Index([1, 2, 3]) == pd.Index([1, 2]) Out[4]: False -New behavior: +New Behavior: .. code-block:: python @@ -706,14 +740,14 @@ Boolean comparisons of a ``Series`` vs ``None`` will now be equivalent to compar s.iloc[1] = None s -Previous behavior: +Previous Behavior: .. code-block:: python In [5]: s==None TypeError: Could not compare <type 'NoneType'> type with Series -New behavior: +New Behavior: .. ipython:: python @@ -742,7 +776,7 @@ HDFStore dropna behavior The default behavior for HDFStore write functions with ``format='table'`` is now to keep rows that are all missing. Previously, the behavior was to drop rows that were all missing save the index. The previous behavior can be replicated using the ``dropna=True`` option. (:issue:`9382`) -Previously: +Previous Behavior: .. ipython:: python @@ -768,7 +802,7 @@ Previously: 2 2 NaN -New behavior: +New Behavior: .. ipython:: python :suppress:
Reorganized release note for 0.17. There are some descriptions which looks the same level, but one in a highlights and the other is not.
https://api.github.com/repos/pandas-dev/pandas/pulls/11068
2015-09-12T09:05:48Z
2015-09-12T09:22:34Z
2015-09-12T09:22:34Z
2015-09-12T10:45:07Z
DOC: Missing Excel index images
diff --git a/doc/source/_static/new-excel-index.png b/doc/source/_static/new-excel-index.png new file mode 100644 index 0000000000000..479237c3712d2 Binary files /dev/null and b/doc/source/_static/new-excel-index.png differ diff --git a/doc/source/_static/old-excel-index.png b/doc/source/_static/old-excel-index.png new file mode 100644 index 0000000000000..5281367a5ad9d Binary files /dev/null and b/doc/source/_static/old-excel-index.png differ
Adds missing static files that didn't get pushed in https://github.com/pydata/pandas/pull/10967 @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/11067
2015-09-11T22:33:26Z
2015-09-11T23:00:48Z
2015-09-11T23:00:48Z
2015-09-11T23:05:56Z
DOC: clean up 0.17 whatsnew
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 5d9e415b85acf..2c192ee33061b 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -21,9 +21,14 @@ users upgrade to this version. After installing pandas-datareader, you can easily change your imports: - .. code-block:: Python + .. code-block:: python + + from pandas.io import data, wb + + becomes + + .. code-block:: python - from pandas.io import data, wb # becomes from pandas_datareader import data, wb Highlights include: @@ -53,44 +58,60 @@ Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsne New features ~~~~~~~~~~~~ -- ``merge`` now accepts the argument ``indicator`` which adds a Categorical-type column (by default called ``_merge``) to the output object that takes on the values (:issue:`8790`) +.. _whatsnew_0170.tz: - =================================== ================ - Observation Origin ``_merge`` value - =================================== ================ - Merge key only in ``'left'`` frame ``left_only`` - Merge key only in ``'right'`` frame ``right_only`` - Merge key in both frames ``both`` - =================================== ================ +Datetime with TZ +^^^^^^^^^^^^^^^^ - .. ipython:: python +We are adding an implementation that natively supports datetime with timezones. A ``Series`` or a ``DataFrame`` column previously +*could* be assigned a datetime with timezones, and would work as an ``object`` dtype. This had performance issues with a large +number rows. See the :ref:`docs <timeseries.timezone_series>` for more details. (:issue:`8260`, :issue:`10763`, :issue:`11034`). - df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b']}) - df2 = pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]}) - pd.merge(df1, df2, on='col1', how='outer', indicator=True) +The new implementation allows for having a single-timezone across all rows, with operations in a performant manner. - For more, see the :ref:`updated docs <merging.indicator>` +.. ipython:: python -- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`) -- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`) -- Enable writing complex values to HDF stores when using table format (:issue:`10447`) -- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`) -- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`) + df = DataFrame({'A' : date_range('20130101',periods=3), + 'B' : date_range('20130101',periods=3,tz='US/Eastern'), + 'C' : date_range('20130101',periods=3,tz='CET')}) + df + df.dtypes - .. ipython:: python +.. ipython:: python - ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13]) - ser.interpolate(limit=1, limit_direction='both') + df.B + df.B.dt.tz_localize(None) -- Round DataFrame to variable number of decimal places (:issue:`10568`). +This uses a new-dtype representation as well, that is very similar in look-and-feel to its numpy cousin ``datetime64[ns]`` - .. ipython :: python +.. ipython:: python - df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'], - index=['first', 'second', 'third']) - df - df.round(2) - df.round({'A': 0, 'C': 2}) + df['B'].dtype + type(df['B'].dtype) + +.. note:: + + There is a slightly different string repr for the underlying ``DatetimeIndex`` as a result of the dtype changes, but + functionally these are the same. + + Previous Behavior: + + .. code-block:: python + + In [1]: pd.date_range('20130101',periods=3,tz='US/Eastern') + Out[1]: DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00', + '2013-01-03 00:00:00-05:00'], + dtype='datetime64[ns]', freq='D', tz='US/Eastern') + + In [2]: pd.date_range('20130101',periods=3,tz='US/Eastern').dtype + Out[2]: dtype('<M8[ns]') + + New Behavior: + + .. ipython:: python + + pd.date_range('20130101',periods=3,tz='US/Eastern') + pd.date_range('20130101',periods=3,tz='US/Eastern').dtype .. _whatsnew_0170.gil: @@ -286,6 +307,46 @@ has been changed to make this keyword unnecessary - the change is shown below. Other enhancements ^^^^^^^^^^^^^^^^^^ + +- ``merge`` now accepts the argument ``indicator`` which adds a Categorical-type column (by default called ``_merge``) to the output object that takes on the values (:issue:`8790`) + + =================================== ================ + Observation Origin ``_merge`` value + =================================== ================ + Merge key only in ``'left'`` frame ``left_only`` + Merge key only in ``'right'`` frame ``right_only`` + Merge key in both frames ``both`` + =================================== ================ + + .. ipython:: python + + df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b']}) + df2 = pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]}) + pd.merge(df1, df2, on='col1', how='outer', indicator=True) + + For more, see the :ref:`updated docs <merging.indicator>` + +- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`) +- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`) +- Enable writing complex values to HDF stores when using table format (:issue:`10447`) +- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`) +- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`) + + .. ipython:: python + + ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13]) + ser.interpolate(limit=1, limit_direction='both') + +- Round DataFrame to variable number of decimal places (:issue:`10568`). + + .. ipython :: python + + df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'], + index=['first', 'second', 'third']) + df + df.round(2) + df.round({'A': 0, 'C': 2}) + - ``pd.read_sql`` and ``to_sql`` can accept database URI as ``con`` parameter (:issue:`10214`) - Enable ``pd.read_hdf`` to be used without specifying a key when the HDF file contains a single dataset (:issue:`10443`) - Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`) @@ -321,13 +382,15 @@ Other enhancements Timestamp('2014') DatetimeIndex(['2012Q2', '2014']) - .. note:: If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``. + .. note:: - .. ipython:: python + If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``. - import pandas.tseries.offsets as offsets - Timestamp.now() - Timestamp.now() + offsets.DateOffset(years=1) + .. ipython:: python + + import pandas.tseries.offsets as offsets + Timestamp.now() + Timestamp.now() + offsets.DateOffset(years=1) - ``to_datetime`` can now accept ``yearfirst`` keyword (:issue:`7599`) @@ -411,6 +474,9 @@ Other enhancements pd.concat([foo, bar, baz], 1) +- Allow passing `kwargs` to the interpolation methods (:issue:`10378`). +- Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`) + .. _whatsnew_0170.api: @@ -516,60 +582,6 @@ To keep the previous behaviour, you can use ``errors='ignore'``: Furthermore, ``pd.to_timedelta`` has gained a similar API, of ``errors='raise'|'ignore'|'coerce'``, and the ``coerce`` keyword has been deprecated in favor of ``errors='coerce'``. -.. _whatsnew_0170.tz: - -Datetime with TZ -~~~~~~~~~~~~~~~~ - -We are adding an implementation that natively supports datetime with timezones. A ``Series`` or a ``DataFrame`` column previously -*could* be assigned a datetime with timezones, and would work as an ``object`` dtype. This had performance issues with a large -number rows. See the :ref:`docs <timeseries.timezone_series>` for more details. (:issue:`8260`, :issue:`10763`, :issue:`11034`). - -The new implementation allows for having a single-timezone across all rows, with operations in a performant manner. - -.. ipython:: python - - df = DataFrame({'A' : date_range('20130101',periods=3), - 'B' : date_range('20130101',periods=3,tz='US/Eastern'), - 'C' : date_range('20130101',periods=3,tz='CET')}) - df - df.dtypes - -.. ipython:: python - - df.B - df.B.dt.tz_localize(None) - -This uses a new-dtype representation as well, that is very similar in look-and-feel to its numpy cousin ``datetime64[ns]`` - -.. ipython:: python - - df['B'].dtype - type(df['B'].dtype) - -.. note:: - - There is a slightly different string repr for the underlying ``DatetimeIndex`` as a result of the dtype changes, but - functionally these are the same. - - Previous Behavior: - - .. code-block:: python - - In [1]: pd.date_range('20130101',periods=3,tz='US/Eastern') - Out[1]: DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00', - '2013-01-03 00:00:00-05:00'], - dtype='datetime64[ns]', freq='D', tz='US/Eastern') - - In [2]: pd.date_range('20130101',periods=3,tz='US/Eastern').dtype - Out[2]: dtype('<M8[ns]') - - New Behavior: - - .. ipython:: python - - pd.date_range('20130101',periods=3,tz='US/Eastern') - pd.date_range('20130101',periods=3,tz='US/Eastern').dtype .. _whatsnew_0170.api_breaking.convert_objects: @@ -847,11 +859,10 @@ Other API Changes - Line and kde plot with ``subplots=True`` now uses default colors, not all black. Specify ``color='k'`` to draw all lines in black (:issue:`9894`) - Calling the ``.value_counts()`` method on a Series with ``categorical`` dtype now returns a Series with a ``CategoricalIndex`` (:issue:`10704`) -- Allow passing `kwargs` to the interpolation methods (:issue:`10378`). - The metadata properties of subclasses of pandas objects will now be serialized (:issue:`10553`). - ``groupby`` using ``Categorical`` follows the same rule as ``Categorical.unique`` described above (:issue:`10508`) -- Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`) -- When constructing ``DataFrame`` with an array of ``complex64`` dtype that meant the corresponding column was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`) +- When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column + was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`) - ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`) @@ -869,8 +880,6 @@ Other API Changes Deprecations ^^^^^^^^^^^^ -.. note:: These indexing function have been deprecated in the documentation since 0.11.0. - - For ``Series`` the following indexing functions are deprecated (:issue:`10177`). ===================== ================================= @@ -891,6 +900,8 @@ Deprecations ``.icol(j)`` ``.iloc[:, j]`` ===================== ================================= +.. note:: These indexing function have been deprecated in the documentation since 0.11.0. + - ``Categorical.name`` was deprecated to make ``Categorical`` more ``numpy.ndarray`` like. Use ``Series(cat, name="whatever")`` instead (:issue:`10482`). - Setting missing values (NaN) in a ``Categorical``'s ``categories`` will issue a warning (:issue:`10748`). You can still have missing values in the ``values``. - ``drop_duplicates`` and ``duplicated``'s ``take_last`` keyword was deprecated in favor of ``keep``. (:issue:`6511`, :issue:`8505`) @@ -908,7 +919,6 @@ Deprecations Removal of prior version deprecations/changes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`) - Removal of ``na_last`` parameters from ``Series.order()`` and ``Series.sort()``, in favor of ``na_position``, xref (:issue:`5231`) - Remove of ``percentile_width`` from ``.describe()``, in favor of ``percentiles``. (:issue:`7088`) - Removal of ``colSpace`` parameter from ``DataFrame.to_string()``, in favor of ``col_space``, circa 0.8.0 version. @@ -1089,3 +1099,4 @@ Bug Fixes - Bug in ``Index`` arithmetic may result in incorrect class (:issue:`10638`) - Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`) - Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`) +- Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`)
Mainly some rearranging (eg the datetime tz was somewhere in the middle of the API changes, moved it to in front of the new features)
https://api.github.com/repos/pandas-dev/pandas/pulls/11059
2015-09-11T09:20:20Z
2015-09-11T11:14:04Z
2015-09-11T11:14:04Z
2015-09-11T11:14:09Z
DOC: Updated doc-string using new doc-string design for DataFrameFormatter
diff --git a/pandas/core/format.py b/pandas/core/format.py index 985b349273130..0c1a3dbadbd86 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -58,18 +58,13 @@ the print configuration (controlled by set_option), 'right' out of the box.""" -force_unicode_docstring = """ - force_unicode : bool, default False - Always return a unicode result. Deprecated in v0.10.0 as string - formatting is now rendered to unicode by default.""" - return_docstring = """ Returns ------- formatted : string (or unicode, depending on data and options)""" -docstring_to_string = common_docstring + justify_docstring + force_unicode_docstring + return_docstring +docstring_to_string = common_docstring + justify_docstring + return_docstring class CategoricalFormatter(object): @@ -300,7 +295,7 @@ class DataFrameFormatter(TableFormatter): """ __doc__ = __doc__ if __doc__ else '' - __doc__ += docstring_to_string + __doc__ += common_docstring + justify_docstring + return_docstring def __init__(self, frame, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 77b8c4cf35aad..0eeface27238f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1414,7 +1414,7 @@ def to_stata( write_index=write_index) writer.write_file() - @Appender(fmt.common_docstring + fmt.justify_docstring + fmt.return_docstring, indents=1) + @Appender(fmt.docstring_to_string, indents=1) def to_string(self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, @@ -1442,7 +1442,7 @@ def to_string(self, buf=None, columns=None, col_space=None, result = formatter.buf.getvalue() return result - @Appender(fmt.common_docstring + fmt.justify_docstring + fmt.return_docstring, indents=1) + @Appender(fmt.docstring_to_string, indents=1) def to_html(self, buf=None, columns=None, col_space=None, colSpace=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True,
`DataFrameFormatter` does not have this parameter: `force_unicode_docstring`. This change uses the doc-string re-design in #11011
https://api.github.com/repos/pandas-dev/pandas/pulls/11057
2015-09-11T05:26:28Z
2015-09-13T20:16:22Z
2015-09-13T20:16:22Z
2015-09-13T20:27:43Z
BUG: GH10645 and GH10692 where operation on large Index would error
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 0b6f6522dfde0..1626ecbf98e80 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1033,7 +1033,7 @@ Bug Fixes - Bug in ``Index.take`` may add unnecessary ``freq`` attribute (:issue:`10791`) - Bug in ``merge`` with empty ``DataFrame`` may raise ``IndexError`` (:issue:`10824`) - Bug in ``to_latex`` where unexpected keyword argument for some documented arguments (:issue:`10888`) - +- Bug in indexing of large ``DataFrame`` where ``IndexError`` is uncaught (:issue:`10645` and :issue:`10692`) - Bug in ``read_csv`` when using the ``nrows`` or ``chunksize`` parameters if file contains only a header line (:issue:`9535`) - Bug in serialization of ``category`` types in HDF5 in presence of alternate encodings. (:issue:`10366`) - Bug in ``pd.DataFrame`` when constructing an empty DataFrame with a string dtype (:issue:`9428`) diff --git a/pandas/core/index.py b/pandas/core/index.py index 025b8c9d0e250..c60509f00ebac 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -4727,7 +4727,7 @@ def __contains__(self, key): try: self.get_loc(key) return True - except KeyError: + except LookupError: return False def __reduce__(self): diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 71bba3a9edea2..8b4528ef451ef 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1040,7 +1040,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): # if we are a label return me try: return labels.get_loc(obj) - except KeyError: + except LookupError: if isinstance(obj, tuple) and isinstance(labels, MultiIndex): if is_setter and len(obj) == labels.nlevels: return {'key': obj} @@ -1125,7 +1125,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): else: try: return labels.get_loc(obj) - except KeyError: + except LookupError: # allow a not found key only if we are a setter if not is_list_like_indexer(obj) and is_setter: return {'key': obj} diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index c48807365913c..acffbd12d1c9a 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -4602,7 +4602,17 @@ def test_indexing_dtypes_on_empty(self): assert_series_equal(df2.loc[:,'a'], df2.iloc[:,0]) assert_series_equal(df2.loc[:,'a'], df2.ix[:,0]) + def test_large_dataframe_indexing(self): + #GH10692 + result = DataFrame({'x': range(10**6)}) + result.loc[len(result)] = len(result) + 1 + expected = DataFrame({'x': range(10**6 + 1)}) + assert_frame_equal(result, expected) + def test_large_mi_dataframe_indexing(self): + #GH10645 + result = MultiIndex.from_arrays([range(10**6), range(10**6)]) + assert(not (10**6, 0) in result) class TestCategoricalIndex(tm.TestCase):
closes #10645 closes #10692 replaces #10675 Do I need `@slow` for these tests?
https://api.github.com/repos/pandas-dev/pandas/pulls/11049
2015-09-10T11:42:38Z
2015-09-10T22:11:55Z
2015-09-10T22:11:55Z
2015-09-10T22:12:02Z
DOC/CLN: typo and redundant code
diff --git a/doc/README.rst b/doc/README.rst index 7f001192f5d73..06d95e6b9c44d 100644 --- a/doc/README.rst +++ b/doc/README.rst @@ -114,7 +114,7 @@ Often it will be necessary to rebuild the C extension after updating:: Building the documentation ^^^^^^^^^^^^^^^^^^^^^^^^^^ -So how do you build the docs? Navigate to your local the folder +So how do you build the docs? Navigate to your local folder ``pandas/doc/`` directory in the console and run:: python make.py html diff --git a/doc/source/gotchas.rst b/doc/source/gotchas.rst index cf4a86d530180..fe7ab67b7f759 100644 --- a/doc/source/gotchas.rst +++ b/doc/source/gotchas.rst @@ -297,7 +297,7 @@ concise means of selecting data from a pandas object: df df.ix[['b', 'c', 'e']] -This is, of course, completely equivalent *in this case* to using th +This is, of course, completely equivalent *in this case* to using the ``reindex`` method: .. ipython:: python @@ -455,7 +455,7 @@ parse HTML tables in the top-level pandas io function ``read_html``. * Drawbacks - * |lxml|_ does *not* make any guarantees about the results of it's parse + * |lxml|_ does *not* make any guarantees about the results of its parse *unless* it is given |svm|_. * In light of the above, we have chosen to allow you, the user, to use the diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 7133a6b6d6baf..a87476ee0f847 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -218,7 +218,6 @@ def __init__(self, key=None, level=None, freq=None, axis=0, sort=False): self.obj=None self.indexer=None self.binner=None - self.grouper=None @property def ax(self): @@ -424,7 +423,7 @@ def _get_indices(self, names): """ safe get multiple indices, translate keys for datelike to underlying repr """ def get_converter(s): - # possibly convert to they actual key types + # possibly convert to the actual key types # in the indices, could be a Timestamp or a np.datetime64 if isinstance(s, (Timestamp,datetime.datetime)): return lambda key: Timestamp(key)
https://api.github.com/repos/pandas-dev/pandas/pulls/11048
2015-09-10T10:52:17Z
2015-09-10T20:48:47Z
2015-09-10T20:48:47Z
2015-09-10T20:48:47Z
DOC: correct quoting constants order
diff --git a/doc/source/io.rst b/doc/source/io.rst index f3d14b78bbf54..f95fdd502d306 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -149,7 +149,8 @@ They can take a number of arguments: Quoted items can include the delimiter and it will be ignored. - ``quoting`` : int, Controls whether quotes should be recognized. Values are taken from `csv.QUOTE_*` values. - Acceptable values are 0, 1, 2, and 3 for QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONE, and QUOTE_NONNUMERIC, respectively. + Acceptable values are 0, 1, 2, and 3 for QUOTE_MINIMAL, QUOTE_ALL, + QUOTE_NONNUMERIC and QUOTE_NONE, respectively. - ``skipinitialspace`` : boolean, default ``False``, Skip spaces after delimiter - ``escapechar`` : string, to specify how to escape quoted data - ``comment``: Indicates remainder of line should not be parsed. If found at the
Small correction, QUOTE_NONE and QUOTE_NONNUMERIC have to be switched: ``` In [1]: import csv In [2]: csv.QUOTE_NONNUMERIC Out[2]: 2 In [3]: csv.QUOTE_NONE Out[3]: 3 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11046
2015-09-10T08:50:49Z
2015-09-10T10:57:47Z
2015-09-10T10:57:47Z
2015-09-10T10:57:48Z
DOC: Fix misspelling of max_colwidth in documentation.
diff --git a/doc/source/options.rst b/doc/source/options.rst index 753c4cc52cab8..fb57175f96eaa 100644 --- a/doc/source/options.rst +++ b/doc/source/options.rst @@ -187,7 +187,7 @@ dataframes to stretch across pages, wrapped over the full column vs row-wise. pd.reset_option('large_repr') pd.reset_option('max_rows') -``display.max_columnwidth`` sets the maximum width of columns. Cells +``display.max_colwidth`` sets the maximum width of columns. Cells of this length or longer will be truncated with an ellipsis. .. ipython:: python
One location referencing `display.max_colwidth` was incorrectly spelled as `display.max_columnwidth`.
https://api.github.com/repos/pandas-dev/pandas/pulls/11037
2015-09-09T20:14:32Z
2015-09-09T21:10:44Z
2015-09-09T21:10:44Z
2015-09-09T21:37:01Z
BUG: Fixed bug in len(DataFrame.groupby) causing IndexError when there's a NaN-only column (issue11016)
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 7100f78cb3c7a..6570306e79596 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -951,7 +951,7 @@ Bug Fixes - Bug in ``to_datetime`` and ``to_timedelta`` causing ``Index`` name to be lost (:issue:`10875`) - +- Bug in ``len(DataFrame.groupby)`` causing IndexError when there's a column containing only NaNs (:issue: `11016`) - Bug that caused segfault when resampling an empty Series (:issue:`10228`) - Bug in ``DatetimeIndex`` and ``PeriodIndex.value_counts`` resets name from its result, but retains in result's ``Index``. (:issue:`10150`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 7133a6b6d6baf..1d5a92d43d680 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -400,7 +400,7 @@ def __init__(self, obj, keys=None, axis=0, level=None, self.exclusions = set(exclusions) if exclusions else set() def __len__(self): - return len(self.indices) + return len(self.groups) def __unicode__(self): # TODO: Better unicode/repr for GroupBy object diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index a85e68602493b..a97a0a9ede6f9 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -837,6 +837,12 @@ def test_len(self): expected = len(set([(x.year, x.month) for x in df.index])) self.assertEqual(len(grouped), expected) + # issue 11016 + df = pd.DataFrame(dict(a=[np.nan]*3, b=[1,2,3])) + self.assertEqual(len(df.groupby(('a'))), 0) + self.assertEqual(len(df.groupby(('b'))), 3) + self.assertEqual(len(df.groupby(('a', 'b'))), 3) + def test_groups(self): grouped = self.df.groupby(['A']) groups = grouped.groups
This is the new PR for Fixed issue #11016
https://api.github.com/repos/pandas-dev/pandas/pulls/11031
2015-09-09T01:51:42Z
2015-09-09T11:16:52Z
2015-09-09T11:16:52Z
2015-09-09T12:40:45Z
Fix common typo in documentation
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst index 2eaf143a3e0b8..8785a8d092d48 100644 --- a/doc/source/visualization.rst +++ b/doc/source/visualization.rst @@ -375,7 +375,7 @@ For example, horizontal and custom-positioned boxplot can be drawn by See the :meth:`boxplot <matplotlib.axes.Axes.boxplot>` method and the -`matplotlib boxplot documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot>`__ for more. +`matplotlib boxplot documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot>`__ for more. The existing interface ``DataFrame.boxplot`` to plot boxplot still can be used. @@ -601,7 +601,7 @@ Below example shows a bubble chart using a dataframe column values as bubble siz plt.close('all') See the :meth:`scatter <matplotlib.axes.Axes.scatter>` method and the -`matplotlib scatter documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`__ for more. +`matplotlib scatter documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`__ for more. .. _visualization.hexbin: @@ -665,7 +665,7 @@ given by column ``z``. The bins are aggregated with numpy's ``max`` function. plt.close('all') See the :meth:`hexbin <matplotlib.axes.Axes.hexbin>` method and the -`matplotlib hexbin documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hexbin>`__ for more. +`matplotlib hexbin documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hexbin>`__ for more. .. _visualization.pie: @@ -761,7 +761,7 @@ If you pass values whose sum total is less than 1.0, matplotlib draws a semicirc @savefig series_pie_plot_semi.png series.plot(kind='pie', figsize=(6, 6)) -See the `matplotlib pie documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie>`__ for more. +See the `matplotlib pie documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie>`__ for more. .. ipython:: python :suppress: @@ -1445,7 +1445,7 @@ Finally, there is a helper function ``pandas.tools.plotting.table`` to create a plt.close('all') -**Note**: You can get table instances on the axes using ``axes.tables`` property for further decorations. See the `matplotlib table documenation <http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.table>`__ for more. +**Note**: You can get table instances on the axes using ``axes.tables`` property for further decorations. See the `matplotlib table documentation <http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.table>`__ for more. .. _visualization.colormaps:
documenation -> documentation
https://api.github.com/repos/pandas-dev/pandas/pulls/11027
2015-09-08T17:22:31Z
2015-09-08T17:27:36Z
2015-09-08T17:27:36Z
2015-09-08T17:28:01Z
DOC: Add GroupBy.count
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 0293fc655742e..7133a6b6d6baf 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -719,6 +719,12 @@ def irow(self, i): FutureWarning, stacklevel=2) return self.nth(i) + def count(self): + """ Compute count of group, excluding missing values """ + + # defined here for API doc + raise NotImplementedError + def mean(self): """ Compute mean of groups, excluding missing values @@ -2674,6 +2680,7 @@ def value_counts(self, normalize=False, sort=True, ascending=False, return Series(out, index=mi) def count(self): + """ Compute count of group, excluding missing values """ ids, _, ngroups = self.grouper.group_info val = self.obj.get_values() @@ -3458,6 +3465,7 @@ def _apply_to_column_groupbys(self, func): keys=self._selected_obj.columns, axis=1) def count(self): + """ Compute count of group, excluding missing values """ from functools import partial from pandas.lib import count_level_2d from pandas.core.common import _isnull_ndarraylike as isnull
Related to #11013. Define `GroupBy.count` for API doc and added docstring.
https://api.github.com/repos/pandas-dev/pandas/pulls/11025
2015-09-08T13:51:54Z
2015-09-08T15:21:31Z
2015-09-08T15:21:31Z
2015-09-08T20:35:25Z
BUG: DatetimeIndex.freq can defer by ufunc
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 1ec73edbb82e5..80145df181756 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -3151,6 +3151,39 @@ def test_nat(self): self.assertIs(DatetimeIndex([np.nan])[0], pd.NaT) + def test_ufunc_coercions(self): + idx = date_range('2011-01-01', periods=3, freq='2D', name='x') + + delta = np.timedelta64(1, 'D') + for result in [idx + delta, np.add(idx, delta)]: + tm.assertIsInstance(result, DatetimeIndex) + exp = date_range('2011-01-02', periods=3, freq='2D', name='x') + tm.assert_index_equal(result, exp) + self.assertEqual(result.freq, '2D') + + for result in [idx - delta, np.subtract(idx, delta)]: + tm.assertIsInstance(result, DatetimeIndex) + exp = date_range('2010-12-31', periods=3, freq='2D', name='x') + tm.assert_index_equal(result, exp) + self.assertEqual(result.freq, '2D') + + delta = np.array([np.timedelta64(1, 'D'), np.timedelta64(2, 'D'), + np.timedelta64(3, 'D')]) + for result in [idx + delta, np.add(idx, delta)]: + tm.assertIsInstance(result, DatetimeIndex) + exp = DatetimeIndex(['2011-01-02', '2011-01-05', '2011-01-08'], + freq='3D', name='x') + tm.assert_index_equal(result, exp) + self.assertEqual(result.freq, '3D') + + for result in [idx - delta, np.subtract(idx, delta)]: + tm.assertIsInstance(result, DatetimeIndex) + exp = DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'], + freq='D', name='x') + tm.assert_index_equal(result, exp) + self.assertEqual(result.freq, 'D') + + class TestPeriodIndex(DatetimeLike, tm.TestCase): _holder = PeriodIndex _multiprocess_can_split_ = True @@ -3306,7 +3339,7 @@ def test_pickle_compat_construction(self): def test_ufunc_coercions(self): # normal ops are also tested in tseries/test_timedeltas.py idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'], - freq='2H', name='x') + freq='2H', name='x') for result in [idx * 2, np.multiply(idx, 2)]: tm.assertIsInstance(result, TimedeltaIndex) @@ -3323,7 +3356,7 @@ def test_ufunc_coercions(self): self.assertEqual(result.freq, 'H') idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'], - freq='2H', name='x') + freq='2H', name='x') for result in [ - idx, np.negative(idx)]: tm.assertIsInstance(result, TimedeltaIndex) exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'], @@ -3332,7 +3365,7 @@ def test_ufunc_coercions(self): self.assertEqual(result.freq, '-2H') idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'], - freq='H', name='x') + freq='H', name='x') for result in [ abs(idx), np.absolute(idx)]: tm.assertIsInstance(result, TimedeltaIndex) exp = TimedeltaIndex(['2H', '1H', '0H', '1H', '2H'], diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 966bd5c8d0ab5..c2dc625bd6ece 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -694,6 +694,14 @@ def _sub_datelike(self, other): result = self._maybe_mask_results(result,fill_value=tslib.iNaT) return TimedeltaIndex(result,name=self.name,copy=False) + def _maybe_update_attributes(self, attrs): + """ Update Index attributes (e.g. freq) depending on op """ + freq = attrs.get('freq', None) + if freq is not None: + # no need to infer if freq is None + attrs['freq'] = 'infer' + return attrs + def _add_delta(self, delta): from pandas import TimedeltaIndex name = self.name
Follow up of #10638. `DatetimeIndex.freq` also can be changed when other arg is an ndarray. As the same as #10638, freq is re-infered only when it exists. Otherwise, leave it as `None` even if the result can be on specific freq. This is based on other functions behavior as below: ``` idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03']) idx # DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], dtype='datetime64[ns]', freq=None) idx.take([0, 2]) # DatetimeIndex(['2011-01-01', '2011-01-03'], dtype='datetime64[ns]', freq=None) idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], freq='D') idx.take([0, 2]) # DatetimeIndex(['2011-01-01', '2011-01-03'], dtype='datetime64[ns]', freq='2D') ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11024
2015-09-08T13:07:49Z
2015-09-09T08:47:32Z
2015-09-09T08:47:32Z
2015-09-09T08:47:50Z
PERF: use NaT comparisons in int64/datetimelikes #11010
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index cbcee664d8be4..7100f78cb3c7a 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1009,11 +1009,10 @@ Bug Fixes - Bug in ``to_json`` which was causing segmentation fault when serializing 0-rank ndarray (:issue:`9576`) - Bug in plotting functions may raise ``IndexError`` when plotted on ``GridSpec`` (:issue:`10819`) - Bug in plot result may show unnecessary minor ticklabels (:issue:`10657`) -- Bug in ``groupby`` incorrect computation for aggregation on ``DataFrame`` with ``NaT`` (E.g ``first``, ``last``, ``min``). (:issue:`10590`) +- Bug in ``groupby`` incorrect computation for aggregation on ``DataFrame`` with ``NaT`` (E.g ``first``, ``last``, ``min``). (:issue:`10590`, :issue:`11010`) - Bug when constructing ``DataFrame`` where passing a dictionary with only scalar values and specifying columns did not raise an error (:issue:`10856`) - Bug in ``.var()`` causing roundoff errors for highly similar values (:issue:`10242`) - Bug in ``DataFrame.plot(subplots=True)`` with duplicated columns outputs incorrect result (:issue:`10962`) - Bug in ``Index`` arithmetic may result in incorrect class (:issue:`10638`) - Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`) - Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`) - diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 1f5855e63dee8..0293fc655742e 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1523,8 +1523,6 @@ def aggregate(self, values, how, axis=0): if is_datetime_or_timedelta_dtype(values.dtype): values = values.view('int64') - values[values == tslib.iNaT] = np.nan - # GH 7754 is_numeric = True elif is_bool_dtype(values.dtype): values = _algos.ensure_float64(values) diff --git a/pandas/src/generate_code.py b/pandas/src/generate_code.py index b055d75df4cf4..8c5c7d709e5f1 100644 --- a/pandas/src/generate_code.py +++ b/pandas/src/generate_code.py @@ -739,7 +739,7 @@ def group_last_%(name)s(ndarray[%(dest_type2)s, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != %(nan_val)s: nobs[lab, j] += 1 resx[lab, j] = val @@ -785,7 +785,7 @@ def group_nth_%(name)s(ndarray[%(dest_type2)s, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != %(nan_val)s: nobs[lab, j] += 1 if nobs[lab, j] == rank: resx[lab, j] = val @@ -1013,7 +1013,7 @@ def group_max_%(name)s(ndarray[%(dest_type2)s, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != %(nan_val)s: nobs[lab, j] += 1 if val > maxx[lab, j]: maxx[lab, j] = val @@ -1027,7 +1027,7 @@ def group_max_%(name)s(ndarray[%(dest_type2)s, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != %(nan_val)s: nobs[lab, 0] += 1 if val > maxx[lab, 0]: maxx[lab, 0] = val @@ -1076,7 +1076,8 @@ def group_min_%(name)s(ndarray[%(dest_type2)s, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != %(nan_val)s: + nobs[lab, j] += 1 if val < minx[lab, j]: minx[lab, j] = val @@ -1090,7 +1091,7 @@ def group_min_%(name)s(ndarray[%(dest_type2)s, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != %(nan_val)s: nobs[lab, 0] += 1 if val < minx[lab, 0]: minx[lab, 0] = val diff --git a/pandas/src/generated.pyx b/pandas/src/generated.pyx index 2f2fd528999d6..767e7d6292b6d 100644 --- a/pandas/src/generated.pyx +++ b/pandas/src/generated.pyx @@ -7315,7 +7315,7 @@ def group_last_float64(ndarray[float64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, j] += 1 resx[lab, j] = val @@ -7360,7 +7360,7 @@ def group_last_float32(ndarray[float32_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, j] += 1 resx[lab, j] = val @@ -7405,7 +7405,7 @@ def group_last_int64(ndarray[int64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != iNaT: nobs[lab, j] += 1 resx[lab, j] = val @@ -7451,7 +7451,7 @@ def group_nth_float64(ndarray[float64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, j] += 1 if nobs[lab, j] == rank: resx[lab, j] = val @@ -7497,7 +7497,7 @@ def group_nth_float32(ndarray[float32_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, j] += 1 if nobs[lab, j] == rank: resx[lab, j] = val @@ -7543,7 +7543,7 @@ def group_nth_int64(ndarray[int64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != iNaT: nobs[lab, j] += 1 if nobs[lab, j] == rank: resx[lab, j] = val @@ -7592,7 +7592,8 @@ def group_min_float64(ndarray[float64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: + nobs[lab, j] += 1 if val < minx[lab, j]: minx[lab, j] = val @@ -7606,7 +7607,7 @@ def group_min_float64(ndarray[float64_t, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, 0] += 1 if val < minx[lab, 0]: minx[lab, 0] = val @@ -7654,7 +7655,8 @@ def group_min_float32(ndarray[float32_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: + nobs[lab, j] += 1 if val < minx[lab, j]: minx[lab, j] = val @@ -7668,7 +7670,7 @@ def group_min_float32(ndarray[float32_t, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, 0] += 1 if val < minx[lab, 0]: minx[lab, 0] = val @@ -7716,7 +7718,8 @@ def group_min_int64(ndarray[int64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != iNaT: + nobs[lab, j] += 1 if val < minx[lab, j]: minx[lab, j] = val @@ -7730,7 +7733,7 @@ def group_min_int64(ndarray[int64_t, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != iNaT: nobs[lab, 0] += 1 if val < minx[lab, 0]: minx[lab, 0] = val @@ -7779,7 +7782,7 @@ def group_max_float64(ndarray[float64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, j] += 1 if val > maxx[lab, j]: maxx[lab, j] = val @@ -7793,7 +7796,7 @@ def group_max_float64(ndarray[float64_t, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, 0] += 1 if val > maxx[lab, 0]: maxx[lab, 0] = val @@ -7841,7 +7844,7 @@ def group_max_float32(ndarray[float32_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, j] += 1 if val > maxx[lab, j]: maxx[lab, j] = val @@ -7855,7 +7858,7 @@ def group_max_float32(ndarray[float32_t, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != NAN: nobs[lab, 0] += 1 if val > maxx[lab, 0]: maxx[lab, 0] = val @@ -7903,7 +7906,7 @@ def group_max_int64(ndarray[int64_t, ndim=2] out, val = values[i, j] # not nan - if val == val: + if val == val and val != iNaT: nobs[lab, j] += 1 if val > maxx[lab, j]: maxx[lab, j] = val @@ -7917,7 +7920,7 @@ def group_max_int64(ndarray[int64_t, ndim=2] out, val = values[i, 0] # not nan - if val == val: + if val == val and val != iNaT: nobs[lab, 0] += 1 if val > maxx[lab, 0]: maxx[lab, 0] = val
closes #11010 ``` In [10]: %timeit gr['3rd'].count() 100 loops, best of 3: 15.1 ms per loop In [11]: %timeit gr['3rd'].min() 100 loops, best of 3: 8.4 ms per loop In [12]: %timeit gr['3rd'].max() 100 loops, best of 3: 8.47 ms per loop In [13]: %timeit gr['3rd'].first() 100 loops, best of 3: 10.5 ms per loop In [14]: %timeit gr['3rd'].last() 100 loops, best of 3: 10.3 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11023
2015-09-07T22:43:56Z
2015-09-08T00:30:05Z
2015-09-08T00:30:05Z
2015-09-08T00:30:05Z
BUG: Exception when setting a major- or minor-axis slice of a Panel with RHS a DataFrame
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index f88e5c0a11f9f..4e8cfdfa16a12 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -964,6 +964,8 @@ Bug Fixes - Bug causes memory leak in time-series line and area plot (:issue:`9003`) +- Bug when setting a ``Panel`` sliced along the major or minor axes when the right-hand side is a ``DataFrame`` (:issue:`11014`) + - Bug in line and kde plot cannot accept multiple colors when ``subplots=True`` (:issue:`9894`) - Bug in ``DataFrame.plot`` raises ``ValueError`` when color name is specified by multiple characters (:issue:`10387`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 7cf1942046e75..71bba3a9edea2 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -442,11 +442,15 @@ def can_do_equal_len(): # we have an equal len Frame if isinstance(value, ABCDataFrame) and value.ndim > 1: + sub_indexer = list(indexer) for item in labels: - # align to - v = np.nan if item not in value else \ - self._align_series(indexer[0], value[item]) + if item in value: + sub_indexer[info_axis] = item + v = self._align_series(tuple(sub_indexer), value[item]) + else: + v = np.nan + setter(item, v) # we have an equal len ndarray/convertible to our labels diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index d45e6e50cafb3..7c67ded16139c 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -506,6 +506,20 @@ def test_setitem_ndarray(self): assert_almost_equal(P[key].values, data) + def test_set_minor_major(self): + # GH 11014 + df1 = DataFrame(['a', 'a', 'a', np.nan, 'a', np.nan]) + df2 = DataFrame([1.0, np.nan, 1.0, np.nan, 1.0, 1.0]) + panel = Panel({'Item1' : df1, 'Item2': df2}) + + newminor = notnull(panel.iloc[:, :, 0]) + panel.loc[:, :, 'NewMinor'] = newminor + assert_frame_equal(panel.loc[:, :, 'NewMinor'], newminor.astype(object)) + + newmajor = notnull(panel.iloc[:, 0, :]) + panel.loc[:, 'NewMajor', :] = newmajor + assert_frame_equal(panel.loc[:, 'NewMajor', :], newmajor.astype(object)) + def test_major_xs(self): ref = self.panel['ItemA']
Fixes GH #11014 This isn't actually a recent regression. The bug was introduced in 0.15.0 with this commit: https://github.com/pydata/pandas/commit/30246a7d2b113b7115fd0708655ae8e1c3f2e6c5; it was just made more common (i.e., it happens on panels without mixed dtype) in 0.16.2 by this commit: https://github.com/pydata/pandas/commit/5c394677e10dac38fe3375e2564bb76cf8bbffca.
https://api.github.com/repos/pandas-dev/pandas/pulls/11021
2015-09-07T18:33:05Z
2015-09-07T20:16:06Z
2015-09-07T20:16:06Z
2015-09-19T00:38:09Z
BUG: Unable to infer negative freq
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index f88e5c0a11f9f..b861bf51b80eb 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1009,4 +1009,6 @@ Bug Fixes - Bug in ``.var()`` causing roundoff errors for highly similar values (:issue:`10242`) - Bug in ``DataFrame.plot(subplots=True)`` with duplicated columns outputs incorrect result (:issue:`10962`) - Bug in ``Index`` arithmetic may result in incorrect class (:issue:`10638`) +- Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`) +- Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`) diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 36bc0755f9a6a..1ec73edbb82e5 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -3329,7 +3329,7 @@ def test_ufunc_coercions(self): exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'], freq='-2H', name='x') tm.assert_index_equal(result, exp) - self.assertEqual(result.freq, None) + self.assertEqual(result.freq, '-2H') idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'], freq='H', name='x') diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index d7eaab5a5a186..6a4257d101473 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -887,7 +887,8 @@ def __init__(self, index, warn=True): if len(index) < 3: raise ValueError('Need at least 3 dates to infer frequency') - self.is_monotonic = self.index.is_monotonic + self.is_monotonic = (self.index.is_monotonic_increasing or + self.index.is_monotonic_decreasing) @cache_readonly def deltas(self): @@ -971,7 +972,6 @@ def month_position_check(self): from calendar import monthrange for y, m, d, wd in zip(years, months, days, weekdays): - wd = datetime(y, m, d).weekday() if calendar_start: calendar_start &= d == 1 @@ -1025,7 +1025,7 @@ def _infer_daily_rule(self): monthly_rule = self._get_monthly_rule() if monthly_rule: - return monthly_rule + return _maybe_add_count(monthly_rule, self.mdiffs[0]) if self.is_unique: days = self.deltas[0] / _ONE_DAY @@ -1111,7 +1111,7 @@ def _infer_daily_rule(self): def _maybe_add_count(base, count): - if count > 1: + if count != 1: return '%d%s' % (count, base) else: return base diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index fb6929c77f6b0..e15be45ef305a 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -2615,15 +2615,24 @@ def generate_range(start=None, end=None, periods=None, start = end - (periods - 1) * offset cur = start - - while cur <= end: - yield cur - - # faster than cur + offset - next_date = offset.apply(cur) - if next_date <= cur: - raise ValueError('Offset %s did not increment date' % offset) - cur = next_date + if offset.n >= 0: + while cur <= end: + yield cur + + # faster than cur + offset + next_date = offset.apply(cur) + if next_date <= cur: + raise ValueError('Offset %s did not increment date' % offset) + cur = next_date + else: + while cur >= end: + yield cur + + # faster than cur + offset + next_date = offset.apply(cur) + if next_date >= cur: + raise ValueError('Offset %s did not decrement date' % offset) + cur = next_date prefix_mapping = dict((offset._prefix, offset) for offset in [ YearBegin, # 'AS' diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py index 4a72b094917b5..24edc54582ec1 100644 --- a/pandas/tseries/tests/test_base.py +++ b/pandas/tseries/tests/test_base.py @@ -494,6 +494,15 @@ def test_take(self): self.assert_index_equal(result, expected) self.assertIsNone(result.freq) + def test_infer_freq(self): + # GH 11018 + for freq in ['A', '2A', '-2A', 'Q', '-1Q', 'M', '-1M', 'D', '3D', '-3D', + 'W', '-1W', 'H', '2H', '-2H', 'T', '2T', 'S', '-3S']: + idx = pd.date_range('2011-01-01 09:00:00', freq=freq, periods=10) + result = pd.DatetimeIndex(idx.asi8, freq='infer') + tm.assert_index_equal(idx, result) + self.assertEqual(result.freq, freq) + class TestTimedeltaIndexOps(Ops): @@ -1108,6 +1117,14 @@ def test_take(self): self.assert_index_equal(result, expected) self.assertIsNone(result.freq) + def test_infer_freq(self): + # GH 11018 + for freq in ['D', '3D', '-3D', 'H', '2H', '-2H', 'T', '2T', 'S', '-3S']: + idx = pd.timedelta_range('1', freq=freq, periods=10) + result = pd.TimedeltaIndex(idx.asi8, freq='infer') + tm.assert_index_equal(idx, result) + self.assertEqual(result.freq, freq) + class TestPeriodIndexOps(Ops): diff --git a/pandas/tseries/tests/test_frequencies.py b/pandas/tseries/tests/test_frequencies.py index a642c12786940..d9bc64136e390 100644 --- a/pandas/tseries/tests/test_frequencies.py +++ b/pandas/tseries/tests/test_frequencies.py @@ -539,7 +539,7 @@ def test_infer_freq_businesshour(self): def test_not_monotonic(self): rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002']) rng = rng[::-1] - self.assertIsNone(rng.inferred_freq) + self.assertEqual(rng.inferred_freq, '-1A-JAN') def test_non_datetimeindex(self): rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002']) diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index d3d09356648b0..69dc70698ca28 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -1539,8 +1539,7 @@ def test_tdi_ops_attributes(self): result = - rng exp = timedelta_range('-2 days', periods=5, freq='-2D', name='x') tm.assert_index_equal(result, exp) - # tdi doesn't infer negative freq - self.assertEqual(result.freq, None) + self.assertEqual(result.freq, '-2D') rng = pd.timedelta_range('-2 days', periods=5, freq='D', name='x') @@ -1548,7 +1547,6 @@ def test_tdi_ops_attributes(self): exp = TimedeltaIndex(['2 days', '1 days', '0 days', '1 days', '2 days'], name='x') tm.assert_index_equal(result, exp) - # tdi doesn't infer negative freq self.assertEqual(result.freq, None) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index a021195ea6c04..565ce43dc46a1 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -1260,6 +1260,18 @@ def test_date_range_gen_error(self): rng = date_range('1/1/2000 00:00', '1/1/2000 00:18', freq='5min') self.assertEqual(len(rng), 4) + def test_date_range_negative_freq(self): + # GH 11018 + rng = date_range('2011-12-31', freq='-2A', periods=3) + exp = pd.DatetimeIndex(['2011-12-31', '2009-12-31', '2007-12-31'], freq='-2A') + self.assert_index_equal(rng, exp) + self.assertEqual(rng.freq, '-2A') + + rng = date_range('2011-01-31', freq='-2M', periods=3) + exp = pd.DatetimeIndex(['2011-01-31', '2010-11-30', '2010-09-30'], freq='-2M') + self.assert_index_equal(rng, exp) + self.assertEqual(rng.freq, '-2M') + def test_first_subset(self): ts = _simple_ts('1/1/2000', '1/1/2010', freq='12h') result = ts.first('10d')
Fixed 2 issues: - `date_range` can't handle negative calendar-based freq (like `A`, `Q` and `M`). ``` import pandas as pd # OK pd.date_range('2011-01-01', freq='-1D', periods=3) # DatetimeIndex(['2011-01-01', '2010-12-31', '2010-12-30'], dtype='datetime64[ns]', freq='-1D') # NG pd.date_range('2011-01-01', freq='-1M', periods=3) # DatetimeIndex([], dtype='datetime64[ns]', freq='-1M') ``` - Unable to infer negative freq. ``` pd.DatetimeIndex(['2011-01-05', '2011-01-03', '2011-01-01'], freq='infer') # DatetimeIndex(['2011-01-05', '2011-01-03', '2011-01-01'], dtype='datetime64[ns]', freq=None) pd.TimedeltaIndex(['-1 days', '-3 days', '-5 days'], freq='infer') # TimedeltaIndex(['-1 days', '-3 days', '-5 days'], dtype='timedelta64[ns]', freq=None) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/11018
2015-09-07T15:44:46Z
2015-09-07T20:19:58Z
2015-09-07T20:19:58Z
2015-09-07T20:23:10Z
STY: enable PLR5501
diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py index 422436d376f69..72cb410c9068d 100644 --- a/pandas/tests/copy_view/test_indexing.py +++ b/pandas/tests/copy_view/test_indexing.py @@ -941,15 +941,14 @@ def test_column_as_series(backend, using_copy_on_write, warn_copy_on_write): if using_copy_on_write: s[0] = 0 + elif warn_copy_on_write: + with tm.assert_cow_warning(): + s[0] = 0 else: - if warn_copy_on_write: - with tm.assert_cow_warning(): + warn = SettingWithCopyWarning if dtype_backend == "numpy" else None + with pd.option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(warn): s[0] = 0 - else: - warn = SettingWithCopyWarning if dtype_backend == "numpy" else None - with pd.option_context("chained_assignment", "warn"): - with tm.assert_produces_warning(warn): - s[0] = 0 expected = Series([0, 2, 3], name="a") tm.assert_series_equal(s, expected) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 2a3a0a54d0767..0ca6bf0de94dd 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -1693,12 +1693,11 @@ def test_rolling_quantile_interpolation_options(quantile, interpolation, data): if np.isnan(q1): assert np.isnan(q2) + elif not IS64: + # Less precision on 32-bit + assert np.allclose([q1], [q2], rtol=1e-07, atol=0) else: - if not IS64: - # Less precision on 32-bit - assert np.allclose([q1], [q2], rtol=1e-07, atol=0) - else: - assert q1 == q2 + assert q1 == q2 def test_invalid_quantile_value(): diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index cb0b4d549f49e..4e542d1b7f04a 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -335,9 +335,8 @@ def validate_percentile(q: float | Iterable[float]) -> np.ndarray: if q_arr.ndim == 0: if not 0 <= q_arr <= 1: raise ValueError(msg) - else: - if not all(0 <= qs <= 1 for qs in q_arr): - raise ValueError(msg) + elif not all(0 <= qs <= 1 for qs in q_arr): + raise ValueError(msg) return q_arr diff --git a/pyproject.toml b/pyproject.toml index ebdf9deb034b5..4f11cfb17edd1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -337,8 +337,6 @@ ignore = [ "PLR2004", # comparison-with-itself "PLR0124", - # Consider `elif` instead of `else` then `if` to remove indentation level - "PLR5501", # collection-literal-concatenation "RUF005", # pairwise-over-zipped (>=PY310 only)
- [ ] 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/56895
2024-01-15T20:42:04Z
2024-01-16T16:06:50Z
2024-01-16T16:06:50Z
2024-01-16T16:18:44Z
STY: Remove black-specific rule
diff --git a/pyproject.toml b/pyproject.toml index ebdf9deb034b5..89965b4f6765d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -246,8 +246,6 @@ select = [ ignore = [ ### Intentionally disabled - # space before : (needed for how black formats slicing) - "E203", # module level import not at top of file "E402", # do not assign a lambda expression, use a def
As `pandas` uses `ruff` as the formatter now, I think that we can safely enable this rule. - [ ] 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/56894
2024-01-15T20:30:57Z
2024-01-16T16:07:24Z
2024-01-16T16:07:24Z
2024-01-16T16:18:27Z
Backport PR #56891 on branch 2.2.x (DOC: Add deprecated markers for downcast keyword)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index de25a02c6b37c..f8728c61e46fc 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7187,6 +7187,8 @@ def fillna( or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). + .. deprecated:: 2.2.0 + Returns ------- {klass} or None @@ -7522,6 +7524,8 @@ def ffill( or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). + .. deprecated:: 2.2.0 + Returns ------- {klass} or None @@ -7713,6 +7717,8 @@ def bfill( or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). + .. deprecated:: 2.2.0 + Returns ------- {klass} or None
Backport PR #56891: DOC: Add deprecated markers for downcast keyword
https://api.github.com/repos/pandas-dev/pandas/pulls/56893
2024-01-15T19:38:00Z
2024-01-15T19:57:42Z
2024-01-15T19:57:41Z
2024-01-15T19:57:42Z
TYP: Update pyright
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 73ac14f1ed5ce..fc71d785da8bc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -132,7 +132,7 @@ repos: types: [python] stages: [manual] additional_dependencies: &pyright_dependencies - - pyright@1.1.339 + - pyright@1.1.347 - id: pyright # note: assumes python env is setup and activated name: pyright reportGeneralTypeIssues diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 73d69105541d8..5b114ff1f2111 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -88,7 +88,7 @@ class DeprecatedOption(NamedTuple): class RegisteredOption(NamedTuple): key: str - defval: object + defval: Any doc: str validator: Callable[[object], Any] | None cb: Callable[[str], Any] | None diff --git a/pandas/_config/localization.py b/pandas/_config/localization.py index 5c1a0ff139533..69a56d3911316 100644 --- a/pandas/_config/localization.py +++ b/pandas/_config/localization.py @@ -10,7 +10,10 @@ import platform import re import subprocess -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, + cast, +) from pandas._config.config import options @@ -152,7 +155,7 @@ def get_locales( out_locales = [] for x in split_raw_locales: try: - out_locales.append(str(x, encoding=options.display.encoding)) + out_locales.append(str(x, encoding=cast(str, options.display.encoding))) except UnicodeError: # 'locale -a' is used to populated 'raw_locales' and on # Redhat 7 Linux (and maybe others) prints locale names diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index 32ecd264262d6..c8befabbf86de 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -69,16 +69,26 @@ def fast_multiget( mapping: dict, keys: np.ndarray, # object[:] default=..., -) -> np.ndarray: ... +) -> ArrayLike: ... def fast_unique_multiple_list_gen(gen: Generator, sort: bool = ...) -> list: ... def fast_unique_multiple_list(lists: list, sort: bool | None = ...) -> list: ... +@overload def map_infer( arr: np.ndarray, f: Callable[[Any], Any], - convert: bool = ..., + *, + convert: Literal[False], ignore_na: bool = ..., ) -> np.ndarray: ... @overload +def map_infer( + arr: np.ndarray, + f: Callable[[Any], Any], + *, + convert: bool = ..., + ignore_na: bool = ..., +) -> ArrayLike: ... +@overload def maybe_convert_objects( objects: npt.NDArray[np.object_], *, @@ -164,14 +174,26 @@ def is_all_arraylike(obj: list) -> bool: ... # Functions which in reality take memoryviews def memory_usage_of_objects(arr: np.ndarray) -> int: ... # object[:] # np.int64 +@overload def map_infer_mask( arr: np.ndarray, f: Callable[[Any], Any], mask: np.ndarray, # const uint8_t[:] - convert: bool = ..., + *, + convert: Literal[False], na_value: Any = ..., dtype: np.dtype = ..., ) -> np.ndarray: ... +@overload +def map_infer_mask( + arr: np.ndarray, + f: Callable[[Any], Any], + mask: np.ndarray, # const uint8_t[:] + *, + convert: bool = ..., + na_value: Any = ..., + dtype: np.dtype = ..., +) -> ArrayLike: ... def indices_fast( index: npt.NDArray[np.intp], labels: np.ndarray, # const int64_t[:] diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index c483f35513a40..5eb20960f0e3d 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -2864,10 +2864,11 @@ def map_infer_mask( ndarray[object] arr, object f, const uint8_t[:] mask, + *, bint convert=True, object na_value=no_default, cnp.dtype dtype=np.dtype(object) -) -> np.ndarray: +) -> "ArrayLike": """ Substitute for np.vectorize with pandas-friendly dtype inference. @@ -2887,7 +2888,7 @@ def map_infer_mask( Returns ------- - np.ndarray + np.ndarray or an ExtensionArray """ cdef Py_ssize_t n = len(arr) result = np.empty(n, dtype=dtype) @@ -2941,8 +2942,8 @@ def _map_infer_mask( @cython.boundscheck(False) @cython.wraparound(False) def map_infer( - ndarray arr, object f, bint convert=True, bint ignore_na=False -) -> np.ndarray: + ndarray arr, object f, *, bint convert=True, bint ignore_na=False +) -> "ArrayLike": """ Substitute for np.vectorize with pandas-friendly dtype inference. @@ -2956,7 +2957,7 @@ def map_infer( Returns ------- - np.ndarray + np.ndarray or an ExtensionArray """ cdef: Py_ssize_t i, n @@ -3091,7 +3092,7 @@ def to_object_array_tuples(rows: object) -> np.ndarray: @cython.wraparound(False) @cython.boundscheck(False) -def fast_multiget(dict mapping, object[:] keys, default=np.nan) -> np.ndarray: +def fast_multiget(dict mapping, object[:] keys, default=np.nan) -> "ArrayLike": cdef: Py_ssize_t i, n = len(keys) object val diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index d4da5840689de..b73b49eca3e18 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -4,6 +4,7 @@ TYPE_CHECKING, ClassVar, Literal, + cast, ) import numpy as np @@ -637,7 +638,7 @@ def _str_map( # error: Argument 1 to "dtype" has incompatible type # "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; expected # "Type[object]" - dtype=np.dtype(dtype), # type: ignore[arg-type] + dtype=np.dtype(cast(type, dtype)), ) if not na_value_is_na: diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 8c8787d15c8fe..a76eef8095695 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -7,6 +7,7 @@ TYPE_CHECKING, Callable, Union, + cast, ) import warnings @@ -327,7 +328,7 @@ def _str_map( # error: Argument 1 to "dtype" has incompatible type # "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; expected # "Type[object]" - dtype=np.dtype(dtype), # type: ignore[arg-type] + dtype=np.dtype(cast(type, dtype)), ) if not na_value_is_na: @@ -640,7 +641,7 @@ def _str_map( mask.view("uint8"), convert=False, na_value=na_value, - dtype=np.dtype(dtype), # type: ignore[arg-type] + dtype=np.dtype(cast(type, dtype)), ) return result diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 6313c2e2c98de..55421090d4202 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -4,7 +4,10 @@ from __future__ import annotations import tokenize -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, + Any, +) import warnings from pandas.util._exceptions import find_stack_level @@ -177,7 +180,7 @@ def eval( level: int = 0, target=None, inplace: bool = False, -): +) -> Any: """ Evaluate a Python expression as a string using various backends. diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 3e4227a8a2598..52ec4a0b012e3 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -258,7 +258,9 @@ def _use_inf_as_na(key) -> None: globals()["INF_AS_NA"] = False -def _isna_array(values: ArrayLike, inf_as_na: bool = False): +def _isna_array( + values: ArrayLike, inf_as_na: bool = False +) -> npt.NDArray[np.bool_] | NDFrame: """ Return an array indicating which values of the input array are NaN / NA. @@ -275,6 +277,7 @@ def _isna_array(values: ArrayLike, inf_as_na: bool = False): Array of boolean values denoting the NA status of each element. """ dtype = values.dtype + result: npt.NDArray[np.bool_] | NDFrame if not isinstance(values, np.ndarray): # i.e. ExtensionArray diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c01e551b38c32..c2b809e5b6d3e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9802,7 +9802,9 @@ def explode( return result.__finalize__(self, method="explode") - def unstack(self, level: IndexLabel = -1, fill_value=None, sort: bool = True): + def unstack( + self, level: IndexLabel = -1, fill_value=None, sort: bool = True + ) -> DataFrame | Series: """ Pivot a level of the (necessarily hierarchical) index labels. diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 62afcf8badb50..02bbc73c05d70 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -491,7 +491,7 @@ def copy(self, name: Hashable | None = None, deep: bool = False) -> Self: new_index = self._rename(name=name) return new_index - def _minmax(self, meth: str): + def _minmax(self, meth: str) -> int | float: no_steps = len(self) - 1 if no_steps == -1: return np.nan @@ -500,13 +500,13 @@ def _minmax(self, meth: str): return self.start + self.step * no_steps - def min(self, axis=None, skipna: bool = True, *args, **kwargs) -> int: + def min(self, axis=None, skipna: bool = True, *args, **kwargs) -> int | float: """The minimum value of the RangeIndex""" nv.validate_minmax_axis(axis) nv.validate_min(args, kwargs) return self._minmax("min") - def max(self, axis=None, skipna: bool = True, *args, **kwargs) -> int: + def max(self, axis=None, skipna: bool = True, *args, **kwargs) -> int | float: """The maximum value of the RangeIndex""" nv.validate_minmax_axis(axis) nv.validate_max(args, kwargs) diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py index 559977bacf881..fa085a1f0262b 100644 --- a/pandas/core/ops/common.py +++ b/pandas/core/ops/common.py @@ -40,7 +40,7 @@ def wrapper(method: F) -> F: return wrapper -def _unpack_zerodim_and_defer(method, name: str): +def _unpack_zerodim_and_defer(method: F, name: str) -> F: """ Boilerplate for pandas conventions in arithmetic and comparison methods. @@ -75,7 +75,9 @@ def new_method(self, other): return method(self, other) - return new_method + # error: Incompatible return value type (got "Callable[[Any, Any], Any]", + # expected "F") + return new_method # type: ignore[return-value] def get_op_result_name(left, right): diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index ea74c17917279..ff973f6defc09 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -568,7 +568,8 @@ def pivot( # error: Argument 1 to "unstack" of "DataFrame" has incompatible type "Union # [List[Any], ExtensionArray, ndarray[Any, Any], Index, Series]"; expected # "Hashable" - result = indexed.unstack(columns_listlike) # type: ignore[arg-type] + # unstack with a MultiIndex returns a DataFrame + result = cast("DataFrame", indexed.unstack(columns_listlike)) # type: ignore[arg-type] result.index.names = [ name if name is not lib.no_default else None for name in result.index.names ] diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 3493f1c78da91..39cd619715a91 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -4,6 +4,7 @@ from typing import ( TYPE_CHECKING, cast, + overload, ) import warnings @@ -451,7 +452,11 @@ def _unstack_multiple( result = data while clocs: val = clocs.pop(0) - result = result.unstack(val, fill_value=fill_value, sort=sort) + # error: Incompatible types in assignment (expression has type + # "DataFrame | Series", variable has type "DataFrame") + result = result.unstack( # type: ignore[assignment] + val, fill_value=fill_value, sort=sort + ) clocs = [v if v < val else v - 1 for v in clocs] return result @@ -460,7 +465,9 @@ def _unstack_multiple( dummy_df = data.copy(deep=False) dummy_df.index = dummy_index - unstacked = dummy_df.unstack( + # error: Incompatible types in assignment (expression has type "DataFrame | + # Series", variable has type "DataFrame") + unstacked = dummy_df.unstack( # type: ignore[assignment] "__placeholder__", fill_value=fill_value, sort=sort ) if isinstance(unstacked, Series): @@ -486,7 +493,21 @@ def _unstack_multiple( return unstacked -def unstack(obj: Series | DataFrame, level, fill_value=None, sort: bool = True): +@overload +def unstack(obj: Series, level, fill_value=..., sort: bool = ...) -> DataFrame: + ... + + +@overload +def unstack( + obj: Series | DataFrame, level, fill_value=..., sort: bool = ... +) -> Series | DataFrame: + ... + + +def unstack( + obj: Series | DataFrame, level, fill_value=None, sort: bool = True +) -> Series | DataFrame: if isinstance(level, (tuple, list)): if len(level) != 1: # _unstack_multiple only handles MultiIndexes, @@ -573,10 +594,14 @@ def _unstack_extension_series( # equiv: result.droplevel(level=0, axis=1) # but this avoids an extra copy result.columns = result.columns._drop_level_numbers([0]) - return result + # error: Incompatible return value type (got "DataFrame | Series", expected + # "DataFrame") + return result # type: ignore[return-value] -def stack(frame: DataFrame, level=-1, dropna: bool = True, sort: bool = True): +def stack( + frame: DataFrame, level=-1, dropna: bool = True, sort: bool = True +) -> Series | DataFrame: """ Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index @@ -659,7 +684,9 @@ def stack_multiple(frame: DataFrame, level, dropna: bool = True, sort: bool = Tr if all(lev in frame.columns.names for lev in level): result = frame for lev in level: - result = stack(result, lev, dropna=dropna, sort=sort) + # error: Incompatible types in assignment (expression has type + # "Series | DataFrame", variable has type "DataFrame") + result = stack(result, lev, dropna=dropna, sort=sort) # type: ignore[assignment] # Otherwise, level numbers may change as each successive level is stacked elif all(isinstance(lev, int) for lev in level): @@ -672,7 +699,9 @@ def stack_multiple(frame: DataFrame, level, dropna: bool = True, sort: bool = Tr while level: lev = level.pop(0) - result = stack(result, lev, dropna=dropna, sort=sort) + # error: Incompatible types in assignment (expression has type + # "Series | DataFrame", variable has type "DataFrame") + result = stack(result, lev, dropna=dropna, sort=sort) # type: ignore[assignment] # Decrement all level numbers greater than current, as these # have now shifted down by one level = [v if v <= lev else v - 1 for v in level] @@ -894,6 +923,7 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame: if len(level) > 1: # Arrange columns in the order we want to take them, e.g. level=[2, 0, 1] sorter = np.argsort(level) + assert isinstance(stack_cols, MultiIndex) ordered_stack_cols = stack_cols._reorder_ilevels(sorter) else: ordered_stack_cols = stack_cols @@ -956,13 +986,15 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame: codes, uniques = factorize(frame.index, use_na_sentinel=False) index_levels = [uniques] index_codes = list(np.tile(codes, (1, ratio))) - if isinstance(stack_cols, MultiIndex): + if isinstance(ordered_stack_cols, MultiIndex): column_levels = ordered_stack_cols.levels column_codes = ordered_stack_cols.drop_duplicates().codes else: column_levels = [ordered_stack_cols.unique()] column_codes = [factorize(ordered_stack_cols_unique, use_na_sentinel=False)[0]] - column_codes = [np.repeat(codes, len(frame)) for codes in column_codes] + # error: Incompatible types in assignment (expression has type "list[ndarray[Any, + # dtype[Any]]]", variable has type "FrozenList") + column_codes = [np.repeat(codes, len(frame)) for codes in column_codes] # type: ignore[assignment] result.index = MultiIndex( levels=index_levels + column_levels, codes=index_codes + column_codes, diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 29d17e7174ee9..bdcf55e61d2d1 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -29,8 +29,6 @@ Scalar, ) - from pandas import Series - class ObjectStringArrayMixin(BaseStringArrayMethods): """ @@ -75,7 +73,9 @@ def _str_map( mask = isna(arr) map_convert = convert and not np.all(mask) try: - result = lib.map_infer_mask(arr, f, mask.view(np.uint8), map_convert) + result = lib.map_infer_mask( + arr, f, mask.view(np.uint8), convert=map_convert + ) except (TypeError, AttributeError) as err: # Reraise the exception if callable `f` got wrong number of args. # The user may want to be warned by this, instead of getting NaN @@ -456,7 +456,7 @@ def _str_lstrip(self, to_strip=None): def _str_rstrip(self, to_strip=None): return self._str_map(lambda x: x.rstrip(to_strip)) - def _str_removeprefix(self, prefix: str) -> Series: + def _str_removeprefix(self, prefix: str): # outstanding question on whether to use native methods for users on Python 3.9+ # https://github.com/pandas-dev/pandas/pull/39226#issuecomment-836719770, # in which case we could do return self._str_map(str.removeprefix) @@ -468,7 +468,7 @@ def removeprefix(text: str) -> str: return self._str_map(removeprefix) - def _str_removesuffix(self, suffix: str) -> Series: + def _str_removesuffix(self, suffix: str): return self._str_map(lambda x: x.removesuffix(suffix)) def _str_extract(self, pat: str, flags: int = 0, expand: bool = True): diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index b80ed9ac50dce..fcf4f7606a594 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -5,6 +5,7 @@ from typing import ( TYPE_CHECKING, + Any, overload, ) import warnings @@ -89,7 +90,8 @@ def to_timedelta( | Series, unit: UnitChoices | None = None, errors: DateTimeErrorChoices = "raise", -) -> Timedelta | TimedeltaIndex | Series | NaTType: + # returning Any for errors="ignore" +) -> Timedelta | TimedeltaIndex | Series | NaTType | Any: """ Convert argument to timedelta. diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index ab2dc20ccbd02..d521d91ab3b7b 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -41,7 +41,9 @@ if TYPE_CHECKING: from matplotlib.axes import Axes + from matplotlib.container import BarContainer from matplotlib.figure import Figure + from matplotlib.patches import Polygon from pandas._typing import PlottingOrientation @@ -112,7 +114,8 @@ def _plot( # type: ignore[override] *, bins, **kwds, - ): + # might return a subset from the possible return types of Axes.hist(...)[2]? + ) -> BarContainer | Polygon | list[BarContainer | Polygon]: if column_num == 0: cls._initialize_stacker(ax, stacking_id, len(bins) - 1) @@ -171,7 +174,8 @@ def _make_plot(self, fig: Figure) -> None: if self.by is not None: ax.set_title(pprint_thing(label)) - self._append_legend_handles_labels(artists[0], label) + # error: Value of type "Polygon" is not indexable + self._append_legend_handles_labels(artists[0], label) # type: ignore[index,arg-type] def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None: """merge BoxPlot/KdePlot properties to passed kwds""" diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index 4e542d1b7f04a..178284c7d75b6 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -265,7 +265,7 @@ def validate_bool_kwarg( f'For argument "{arg_name}" expected type bool, received ' f"type {type(value).__name__}." ) - return value # pyright: ignore[reportGeneralTypeIssues] + return value def validate_fillna_kwargs(value, method, validate_scalar_dict_value: bool = True): diff --git a/pyright_reportGeneralTypeIssues.json b/pyright_reportGeneralTypeIssues.json index da27906e041cf..1589988603506 100644 --- a/pyright_reportGeneralTypeIssues.json +++ b/pyright_reportGeneralTypeIssues.json @@ -41,7 +41,6 @@ "pandas/core/arrays/string_arrow.py", "pandas/core/arrays/timedeltas.py", "pandas/core/computation/align.py", - "pandas/core/computation/ops.py", "pandas/core/construction.py", "pandas/core/dtypes/cast.py", "pandas/core/dtypes/common.py",
Newer releases of pyright infer return types of partially annotated functions, which uncovers quite a few difficult-to-fix type errors (some functions had no return types because it would create too many typing errors elsewhere). (pyright can also try to infer return types for completely unannotated functions, but that is disabled for now in pyright_reportGeneralTypeIssues.json as it would trigger more difficult-to-fix cases.)
https://api.github.com/repos/pandas-dev/pandas/pulls/56892
2024-01-15T17:31:47Z
2024-01-16T22:32:04Z
2024-01-16T22:32:04Z
2024-01-17T02:50:02Z
DOC: Add deprecated markers for downcast keyword
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index caac11b6ab4f6..81ffb243cd302 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7208,6 +7208,8 @@ def fillna( or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). + .. deprecated:: 2.2.0 + Returns ------- {klass} or None @@ -7543,6 +7545,8 @@ def ffill( or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). + .. deprecated:: 2.2.0 + Returns ------- {klass} or None @@ -7734,6 +7738,8 @@ def bfill( or the string 'infer' which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). + .. deprecated:: 2.2.0 + Returns ------- {klass} or None
- [ ] 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/56891
2024-01-15T16:28:09Z
2024-01-15T19:36:59Z
2024-01-15T19:36:59Z
2024-01-15T20:36:37Z
TST: extension tests use its own fixtures
diff --git a/pandas/tests/extension/base/accumulate.py b/pandas/tests/extension/base/accumulate.py index 9189ef7ec9aa5..9a41a3a582c4a 100644 --- a/pandas/tests/extension/base/accumulate.py +++ b/pandas/tests/extension/base/accumulate.py @@ -26,6 +26,7 @@ def check_accumulate(self, ser: pd.Series, op_name: str, skipna: bool): expected = getattr(alt, op_name)(skipna=skipna) tm.assert_series_equal(result, expected, check_dtype=False) + @pytest.mark.parametrize("skipna", [True, False]) def test_accumulate_series(self, data, all_numeric_accumulations, skipna): op_name = all_numeric_accumulations ser = pd.Series(data) diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py index 3fb116430861a..c7b768f6e3c88 100644 --- a/pandas/tests/extension/base/dtype.py +++ b/pandas/tests/extension/base/dtype.py @@ -114,6 +114,7 @@ def test_get_common_dtype(self, dtype): # only case we can test in general) assert dtype._get_common_dtype([dtype]) == dtype + @pytest.mark.parametrize("skipna", [True, False]) def test_infer_dtype(self, data, data_missing, skipna): # only testing that this works without raising an error res = infer_dtype(data, skipna=skipna) diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py index 9f38246d1a317..75628ea177fc2 100644 --- a/pandas/tests/extension/base/groupby.py +++ b/pandas/tests/extension/base/groupby.py @@ -34,6 +34,7 @@ def test_grouping_grouper(self, data_for_grouping): tm.assert_numpy_array_equal(gr1.grouping_vector, df.A.values) tm.assert_extension_array_equal(gr2.grouping_vector, data_for_grouping) + @pytest.mark.parametrize("as_index", [True, False]) def test_groupby_extension_agg(self, as_index, data_for_grouping): df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], "B": data_for_grouping}) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index ba247f51e5f1b..c803a8113b4a4 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -37,6 +37,7 @@ def test_value_counts_default_dropna(self, data): kwarg = sig.parameters["dropna"] assert kwarg.default is True + @pytest.mark.parametrize("dropna", [True, False]) def test_value_counts(self, all_data, dropna): all_data = all_data[:10] if dropna: @@ -96,6 +97,7 @@ def test_apply_simple_series(self, data): result = pd.Series(data).apply(id) assert isinstance(result, pd.Series) + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map(self, data_missing, na_action): result = data_missing.map(lambda x: x, na_action=na_action) expected = data_missing.to_numpy() @@ -211,6 +213,7 @@ def test_nargsort(self, data_missing_for_sorting, na_position, expected): result = nargsort(data_missing_for_sorting, na_position=na_position) tm.assert_numpy_array_equal(result, expected) + @pytest.mark.parametrize("ascending", [True, False]) def test_sort_values(self, data_for_sorting, ascending, sort_by_key): ser = pd.Series(data_for_sorting) result = ser.sort_values(ascending=ascending, key=sort_by_key) @@ -224,6 +227,7 @@ def test_sort_values(self, data_for_sorting, ascending, sort_by_key): tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("ascending", [True, False]) def test_sort_values_missing( self, data_missing_for_sorting, ascending, sort_by_key ): @@ -235,6 +239,7 @@ def test_sort_values_missing( expected = ser.iloc[[0, 2, 1]] tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("ascending", [True, False]) def test_sort_values_frame(self, data_for_sorting, ascending): df = pd.DataFrame({"A": [1, 2, 1], "B": data_for_sorting}) result = df.sort_values(["A", "B"]) @@ -243,6 +248,7 @@ def test_sort_values_frame(self, data_for_sorting, ascending): ) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize("keep", ["first", "last", False]) def test_duplicated(self, data, keep): arr = data.take([0, 1, 0, 1]) result = arr.duplicated(keep=keep) diff --git a/pandas/tests/extension/base/reduce.py b/pandas/tests/extension/base/reduce.py index 2a443901fa41a..6ea1b3a6fbe9d 100644 --- a/pandas/tests/extension/base/reduce.py +++ b/pandas/tests/extension/base/reduce.py @@ -77,6 +77,7 @@ def check_reduce_frame(self, ser: pd.Series, op_name: str, skipna: bool): tm.assert_extension_array_equal(result1, expected) + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna): op_name = all_boolean_reductions ser = pd.Series(data) @@ -95,6 +96,7 @@ def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna): self.check_reduce(ser, op_name, skipna) @pytest.mark.filterwarnings("ignore::RuntimeWarning") + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna): op_name = all_numeric_reductions ser = pd.Series(data) @@ -113,6 +115,7 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna): # min/max with empty produce numpy warnings self.check_reduce(ser, op_name, skipna) + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_frame(self, data, all_numeric_reductions, skipna): op_name = all_numeric_reductions ser = pd.Series(data) diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index ba756b471eb8b..7ee2c23c5b23a 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -105,9 +105,10 @@ def test_setitem_sequence_broadcasts(self, data, box_in_series): assert data[0] == data[2] assert data[1] == data[2] - def test_setitem_scalar(self, data, indexer_li): + @pytest.mark.parametrize("setter", ["loc", "iloc"]) + def test_setitem_scalar(self, data, setter): arr = pd.Series(data) - setter = indexer_li(arr) + setter = getattr(arr, setter) setter[0] = data[1] assert arr[0] == data[1] diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 64b897d27a835..69958b51c9e47 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -257,6 +257,7 @@ def test_fillna_copy_series(self, data_missing, using_copy_on_write): with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False): super().test_fillna_copy_series(data_missing) + @pytest.mark.parametrize("dropna", [True, False]) def test_value_counts(self, all_data, dropna): all_data = all_data[:10] if dropna: diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 8d0bb85b2a01f..05a112e464677 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -271,6 +271,7 @@ def test_compare_scalar(self, data, comparison_op): ser = pd.Series(data) self._compare_other(ser, data, comparison_op, data[0]) + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map(self, data_missing, na_action): if data_missing.dtype.kind in "mM": result = data_missing.map(lambda x: x, na_action=na_action) @@ -423,6 +424,7 @@ def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool: return False return True + @pytest.mark.parametrize("skipna", [True, False]) def test_accumulate_series(self, data, all_numeric_accumulations, skipna, request): pa_type = data.dtype.pyarrow_dtype op_name = all_numeric_accumulations @@ -524,6 +526,7 @@ def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool): expected = getattr(alt, op_name)(skipna=skipna) tm.assert_almost_equal(result, expected) + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request): dtype = data.dtype pa_dtype = dtype.pyarrow_dtype @@ -549,6 +552,7 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, reque request.applymarker(xfail_mark) super().test_reduce_series_numeric(data, all_numeric_reductions, skipna) + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_boolean( self, data, all_boolean_reductions, skipna, na_value, request ): @@ -585,6 +589,7 @@ def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool): }[arr.dtype.kind] return cmp_dtype + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_frame(self, data, all_numeric_reductions, skipna, request): op_name = all_numeric_reductions if op_name == "skew": @@ -2325,6 +2330,7 @@ def test_str_extract_expand(): tm.assert_series_equal(result, expected) +@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) def test_duration_from_strings_with_nat(unit): # GH51175 strings = ["1000", "NaT"] @@ -2827,6 +2833,7 @@ def test_dt_components(): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize("skipna", [True, False]) def test_boolean_reduce_series_all_null(all_boolean_reductions, skipna): # GH51624 ser = pd.Series([None], dtype="float64[pyarrow]") diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index edf560dda36e7..bd4ab5077c6e8 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -134,6 +134,7 @@ def test_combine_add(self, data_repeated): expected = pd.Series([a + val for a in list(orig_data1)]) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map(self, data, na_action): result = data.map(lambda x: x, na_action=na_action) tm.assert_extension_array_equal(result, data) @@ -174,6 +175,7 @@ def test_array_repr(self, data, size): super().test_array_repr(data, size) @pytest.mark.xfail(reason="TBD") + @pytest.mark.parametrize("as_index", [True, False]) def test_groupby_extension_agg(self, as_index, data_for_grouping): super().test_groupby_extension_agg(as_index, data_for_grouping) diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index 4b25b2768849e..6352bf76f96bb 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -100,6 +100,7 @@ def _supports_accumulation(self, ser, op_name: str) -> bool: def _supports_reduction(self, obj, op_name: str) -> bool: return op_name in ["min", "max", "median", "mean", "std", "any", "all"] + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna): meth = all_boolean_reductions msg = f"'{meth}' with datetime64 dtypes is deprecated and will raise in" @@ -113,6 +114,7 @@ def test_series_constructor(self, data): data = data._with_freq(None) super().test_series_constructor(data) + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map(self, data, na_action): result = data.map(lambda x: x, na_action=na_action) tm.assert_extension_array_equal(result, data) diff --git a/pandas/tests/extension/test_masked.py b/pandas/tests/extension/test_masked.py index 0e19c4078b471..3efc561d6a125 100644 --- a/pandas/tests/extension/test_masked.py +++ b/pandas/tests/extension/test_masked.py @@ -169,6 +169,7 @@ def data_for_grouping(dtype): class TestMaskedArrays(base.ExtensionTests): + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map(self, data_missing, na_action): result = data_missing.map(lambda x: x, na_action=na_action) if data_missing.dtype == Float32Dtype(): diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 0893c6231197e..3f54f6cbbba69 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -313,6 +313,7 @@ def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool): tm.assert_almost_equal(result, expected) @pytest.mark.skip("TODO: tests not written yet") + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_frame(self, data, all_numeric_reductions, skipna): pass diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index 4fe9c160d66af..2d1d213322bac 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -109,6 +109,7 @@ def test_diff(self, data, periods): else: super().test_diff(data, periods) + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map(self, data, na_action): result = data.map(lambda x: x, na_action=na_action) tm.assert_extension_array_equal(result, data) diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 2efcc192aa15b..d8f14383ef114 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -102,6 +102,7 @@ class TestSparseArray(base.ExtensionTests): def _supports_reduction(self, obj, op_name: str) -> bool: return True + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request): if all_numeric_reductions in [ "prod", @@ -126,6 +127,7 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, reque super().test_reduce_series_numeric(data, all_numeric_reductions, skipna) + @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_frame(self, data, all_numeric_reductions, skipna, request): if all_numeric_reductions in [ "prod", @@ -366,6 +368,7 @@ def test_map(self, func, na_action, expected): result = data.map(func, na_action=na_action) tm.assert_extension_array_equal(result, expected) + @pytest.mark.parametrize("na_action", [None, "ignore"]) def test_map_raises(self, data, na_action): # GH52096 msg = "fill value in the sparse values not supported" @@ -486,6 +489,7 @@ def test_array_repr(self, data, size): super().test_array_repr(data, size) @pytest.mark.xfail(reason="result does not match expected") + @pytest.mark.parametrize("as_index", [True, False]) def test_groupby_extension_agg(self, as_index, data_for_grouping): super().test_groupby_extension_agg(as_index, data_for_grouping)
This reverts a small part of https://github.com/pandas-dev/pandas/pull/56583, for the changes made in the `pandas/tests/extension` directory This is still a bit brittle, as there is currently no check inplace we don't change this back in the future -> https://github.com/pandas-dev/pandas/issues/56735. I was thinking we could run the tests for one of our own extension arrays outside of the pandas tests, will comment more on the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/56889
2024-01-15T15:45:03Z
2024-01-15T17:52:25Z
2024-01-15T17:52:25Z
2024-01-15T19:10:56Z
DOC: Additions/updates to documentation : grammar changes to documentation
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 82af8122a6bbd..78d22c768b865 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -19,7 +19,7 @@ Bug reports and enhancement requests ==================================== Bug reports and enhancement requests are an important part of making pandas more stable and -are curated though Github issues. When reporting and issue or request, please select the `appropriate +are curated though Github issues. When reporting an issue or request, please select the `appropriate category and fill out the issue form fully <https://github.com/pandas-dev/pandas/issues/new/choose>`_ to ensure others and the core development team can fully understand the scope of the issue.
- [x] closes #56885 - [ ] [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/56886
2024-01-15T10:59:13Z
2024-01-15T16:29:18Z
2024-01-15T16:29:18Z
2024-01-15T16:29:27Z
DOC: fix EX03 in pandas.ExcelWriter
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 8658715b8bf3e..4bf6a3e97f0c6 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -86,7 +86,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.Timestamp.ceil \ pandas.Timestamp.floor \ pandas.Timestamp.round \ - pandas.ExcelWriter \ pandas.read_json \ pandas.io.json.build_table_schema \ pandas.io.formats.style.Styler.to_latex \ diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 786f719337b84..2189f54263dec 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -935,7 +935,7 @@ class ExcelWriter(Generic[_WorkbookT]): is installed otherwise `openpyxl <https://pypi.org/project/openpyxl/>`__ * `odswriter <https://pypi.org/project/odswriter/>`__ for ods files - See ``DataFrame.to_excel`` for typical usage. + See :meth:`DataFrame.to_excel` for typical usage. The writer should be used as a context manager. Otherwise, call `close()` to save and close any opened file handles. @@ -1031,7 +1031,7 @@ class ExcelWriter(Generic[_WorkbookT]): Here, the `if_sheet_exists` parameter can be set to replace a sheet if it already exists: - >>> with ExcelWriter( + >>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... mode="a", ... engine="openpyxl", @@ -1042,7 +1042,8 @@ class ExcelWriter(Generic[_WorkbookT]): You can also write multiple DataFrames to a single sheet. Note that the ``if_sheet_exists`` parameter needs to be set to ``overlay``: - >>> with ExcelWriter("path_to_file.xlsx", + >>> with pd.ExcelWriter( + ... "path_to_file.xlsx", ... mode="a", ... engine="openpyxl", ... if_sheet_exists="overlay",
- [ ] ref #56804 (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. Also add a cross-reference in the docstring.
https://api.github.com/repos/pandas-dev/pandas/pulls/56884
2024-01-15T05:27:43Z
2024-01-15T06:51:57Z
2024-01-15T06:51:57Z
2024-01-15T07:24:05Z