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
ENH Change ExcelFile to accept a workbook for the path_or_buf argument.
diff --git a/doc/source/release.rst b/doc/source/release.rst index 34720c49b163b..659947cae1ea7 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -133,7 +133,10 @@ Improvements to existing features (0.4.3 and 0.5.0) (:issue:`4981`). - Better string representations of ``MultiIndex`` (including ability to roundtrip via ``repr``). (:issue:`3347`, :issue:`4935`) - + - Both ExcelFile and read_excel to accept an xlrd.Book for the io + (formerly path_or_buf) argument; this requires engine to be set. + (:issue:`4961`). + API Changes ~~~~~~~~~~~ diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 02dbc381a10be..6b83fada19001 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -45,11 +45,13 @@ def get_writer(engine_name): except KeyError: raise ValueError("No Excel writer '%s'" % engine_name) -def read_excel(path_or_buf, sheetname, **kwds): +def read_excel(io, sheetname, **kwds): """Read an Excel table into a pandas DataFrame Parameters ---------- + io : string, file-like object or xlrd workbook + If a string, expected to be a path to xls or xlsx file sheetname : string Name of Excel sheet header : int, default 0 @@ -74,7 +76,10 @@ def read_excel(path_or_buf, sheetname, **kwds): values are overridden, otherwise they're appended to verbose : boolean, default False Indicate number of NA values placed in non-numeric columns - + engine: string, default None + If io is not a buffer or path, this must be set to identify io. + Acceptable values are None or xlrd + Returns ------- parsed : DataFrame @@ -84,7 +89,10 @@ def read_excel(path_or_buf, sheetname, **kwds): kwds.pop('kind') warn("kind keyword is no longer supported in read_excel and may be " "removed in a future version", FutureWarning) - return ExcelFile(path_or_buf).parse(sheetname=sheetname, **kwds) + + engine = kwds.pop('engine', None) + + return ExcelFile(io, engine=engine).parse(sheetname=sheetname, **kwds) class ExcelFile(object): @@ -94,10 +102,13 @@ class ExcelFile(object): Parameters ---------- - path : string or file-like object - Path to xls or xlsx file + io : string, file-like object or xlrd workbook + If a string, expected to be a path to xls or xlsx file + engine: string, default None + If io is not a buffer or path, this must be set to identify io. + Acceptable values are None or xlrd """ - def __init__(self, path_or_buf, **kwds): + def __init__(self, io, **kwds): import xlrd # throw an ImportError if we need to @@ -106,14 +117,22 @@ def __init__(self, path_or_buf, **kwds): raise ImportError("pandas requires xlrd >= 0.9.0 for excel " "support, current version " + xlrd.__VERSION__) - self.path_or_buf = path_or_buf - self.tmpfile = None - - if isinstance(path_or_buf, compat.string_types): - self.book = xlrd.open_workbook(path_or_buf) - else: - data = path_or_buf.read() + self.io = io + + engine = kwds.pop('engine', None) + + if engine is not None and engine != 'xlrd': + raise ValueError("Unknown engine: %s" % engine) + + if isinstance(io, compat.string_types): + self.book = xlrd.open_workbook(io) + elif engine == "xlrd" and isinstance(io, xlrd.Book): + self.book = io + elif hasattr(io, "read"): + data = io.read() self.book = xlrd.open_workbook(file_contents=data) + else: + raise ValueError('Must explicitly set engine if not passing in buffer or path for io.') def parse(self, sheetname, header=0, skiprows=None, skip_footer=0, index_col=None, parse_cols=None, parse_dates=False, @@ -261,9 +280,9 @@ def sheet_names(self): return self.book.sheet_names() def close(self): - """close path_or_buf if necessary""" - if hasattr(self.path_or_buf, 'close'): - self.path_or_buf.close() + """close io if necessary""" + if hasattr(self.io, 'close'): + self.io.close() def __enter__(self): return self diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 2bcf4789412f6..cd101d325f21d 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -254,6 +254,26 @@ def test_excel_read_buffer(self): f = open(pth, 'rb') xl = ExcelFile(f) xl.parse('Sheet1', index_col=0, parse_dates=True) + + def test_read_xlrd_Book(self): + _skip_if_no_xlrd() + _skip_if_no_xlwt() + + import xlrd + + pth = '__tmp_excel_read_worksheet__.xls' + df = self.frame + + with ensure_clean(pth) as pth: + df.to_excel(pth, "SheetA") + book = xlrd.open_workbook(pth) + + with ExcelFile(book, engine="xlrd") as xl: + result = xl.parse("SheetA") + tm.assert_frame_equal(df, result) + + result = read_excel(book, sheetname="SheetA", engine="xlrd") + tm.assert_frame_equal(df, result) def test_xlsx_table(self): _skip_if_no_xlrd()
That will also mean that read_excel accepts workbooks too. (closes #4961 and #4959)
https://api.github.com/repos/pandas-dev/pandas/pulls/4962
2013-09-24T05:04:38Z
2013-09-27T04:39:58Z
2013-09-27T04:39:58Z
2014-06-26T19:32:20Z
WIP: Refactoring SQL code into per-flavor classes.
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index ceea902649690..0da7a99809741 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -3,12 +3,11 @@ retrieval and to reduce dependency on DB-specific API. """ from __future__ import print_function -from datetime import datetime, date +import datetime -from pandas.compat import range, lzip, map, zip, raise_with_traceback +from pandas.compat import range, lzip, map, zip, raise_with_traceback, u import pandas.compat as compat import numpy as np -import traceback import sqlite3 import warnings @@ -17,7 +16,7 @@ from pandas.core.api import DataFrame, isnull from pandas.io import sql_legacy -from pandas.core.base import PandasObject +from pandas.core.base import StringMixin class SQLAlchemyRequired(ImportError): @@ -136,9 +135,12 @@ def read_sql(sql, con=None, index_col=None, flavor=None, driver=None, if params is None: params = [] - # TODO make sure con is a con and not a cursor etc. + # TODO: Actually convert everything to a cursor first... + klass = flavor_mapping.get(flavor, None) + if klass is None: + raise ValueError("Unknown SQL flavor: %s" % flavor) - pandas_sql = PandasSQL(con=con, engine=engine) + pandas_sql = klass(con=con, engine=engine) return pandas_sql.read_sql(sql, index_col=index_col, params=params, flavor=flavor, coerce_float=coerce_float) @@ -158,8 +160,11 @@ def write_frame(frame, name, con=None, flavor='sqlite', if_exists='fail', engine replace: If table exists, drop it, recreate it, and insert data. append: If table exists, insert data. Create if does not exist. """ - pandas_sql = PandasSQL(con=con, engine=engine) - pandas_sql.write_frame(frame, name, flavor=flavor, if_exists=if_exists, **kwargs) + klass = flavor_mapping.get(flavor, None) + if klass is None: + raise ValueError('Unknown flavor %s' % name) + pandas_sql = klass(con=con, engine=engine) + pandas_sql.write_frame(frame, name, if_exists=if_exists, **kwargs) # This is an awesome function def _engine_read_table_name(table_name, engine, meta=None, index_col=None): @@ -173,11 +178,12 @@ def _engine_read_table_name(table_name, engine, meta=None, index_col=None): index_col: columns to set as index, optional ''' - table = PandasSQLWithEngine(engine=engine)._get_table(table_name) + backend = SQLAlchemyBackend(engine=engine) + table = backend._get_table(table_name) if table is not None: sql_select = table.select() - return PandasSQLWithEngine(engine=engine).read_sql(sql_select, index_col=index_col) + return backend.read_sql(sql_select, index_col=index_col) else: raise ValueError("Table %s not found with %s." % table_name, engine) @@ -254,112 +260,147 @@ def sequence2dict(seq): d[str(k)] = v return d +# # legacy names +# get_schema = PandasSQL._create_schema +frame_query = read_sql +read_frame = read_sql -class PandasSQLFactory(type): - def __call__(cls, engine=None, con=None, cur=None): - if cls is PandasSQL: - if engine: - return PandasSQLWithEngine(engine=engine) - elif con: - if cur is None: - cur = con.cursor() - return PandasSQLWithCur(cur=cur) - elif cur: - return PandasSQLWithCur(cur=cur) - else: - raise ValueError("PandasSQL must be created with an engine," - " connection or cursor.") - - if cls is PandasSQLWithEngine: - return type.__call__(cls, engine) - elif cls is PandasSQLWithCon: - return type.__call__(cls, con) - elif cls is PandasSQLWithCur: - return type.__call__(cls, cur) - else: - raise NotImplementedError - +def _get_backend(self, engine=None, con=None, cursor=None, flavor=None): + if engine: + return SQLAlchemyEngineBackend(engine) + if not flavor: + raise ValueError("Must specify a flavor with a non-SQLAlchemy" + " database.") + if con: + cursor = con.cursor() + if not cursor: + raise ValueError("Must pass either a connection or a cursor") + if flavor not in flavor_mapping: + raise ValueError("Unknown flavor %s" % flavor) + return flavor_mapping[flavor](cursor) + + +class BackendBase(StringMixin): + def __init__(self, cursor, *args, **kwargs): + self.cur = cursor + # PROPERTIES AND METHODS THAT NEED TO BE DEFINED: + # schema_format (format string) + # table_query_format (format string) + # sqltypes (dict) + # _cur_write(frame, table, names, cur) + # flavor + + #### Methods to be overwritten in subclasses... + flavor = 'generic' + + def __unicode__(self): + return u("<%s(flavor=%s, object=%s)>") % (self.__class__.__name__, self.flavor, + self.cur) + + def _write_helper(frame, table, names): + "cursor write method" + raise NotImplementedError("No write helper defined for flavor %s." % + self.flavor) + @property + def sqltype(self): + "dict of types to convert" + raise AttributeError("No sqltype mapping for flavor %s." % self.flavor) + + @property + def schema_format(self): + "template for create table schema" + # better than attribute error. + raise AttributeError("Don't have a template for flavor %s." % self.flavor) + + @property + def table_query_format(self): + "format string for table info query" + raise AttributeError("No table query for flavor %s." % self.flavor) + + ### End quasi-required properties and methods -class PandasSQL(PandasObject): - __metaclass__ = PandasSQLFactory + def execute(self, sql, retry=False, params=None): + try: + # don't need to check for params here, execute should do it + # instead. + self.cur.execute(sql, params) + except Exception as e: + msg = "Execution failed with sql: %s\nError: %s" % (sql, e) + if retry: + warnings.warn(msg, DatabaseError) + self.cur.execute(sql, params) + else: + raise_with_traceback(DatabaseError(msg)) + return self.cur - def read_sql(self, sql, index_col=None, coerce_float=True, params=None, flavor='sqlite'): - # Note coerce_float ignored in engine + def tquery(self, sql, retry=True, params=None, con=None): if params is None: params = [] - data, columns = self._get_data_and_columns( - sql=sql, params=params, flavor=flavor) - return self._frame_from_data_and_columns(data, columns, - index_col=index_col, - coerce_float=coerce_float) - def write_frame(self, frame, name, con=None, flavor='sqlite', if_exists='fail', engine=None, **kwargs): + cur = self.execute(sql, retry=retry, params=params) + result = self._safe_fetch(cur) + + #### I believe this part is unnecessary + # try: + # # TODO: Why would this raise???? + # cur.close() + # except Exception as e: + # excName = e.__class__.__name__ + # if excName == 'OperationalError': # pragma: no cover + # raise_with_traceback(ex) + # else: + # warnings.warn("Error: %s. Retrying..." % e, UserWarning) + # if retry: + # return self.tquery(sql, retry=False, params=params, + # cur=cur) + # else: + # raise + + # This makes absolutely no sense to me + if result and len(result[0]) == 1: + # python 3 compat + result = list(next(zip(*result))) + # whaa? + elif result is None: # pragma: no cover + result = [] + return result + + def _has_table(self, name): + query = self.table_query_format % name + return len(self.tquery(query)) > 0 + + def uquery(self, sql, retry=True, params=None, con=None): """ - Write records stored in a DataFrame to a SQL database. + Does the same thing as tquery, but instead of returning results, it + returns the number of rows affected. Good for update queries. - Parameters - ---------- - frame: DataFrame - name: name of SQL table - con: an open SQL database connection object - flavor: {'sqlite', 'mysql', 'oracle'}, default 'sqlite' - if_exists: {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. + Needs to be wrapped in some kind of catch errors call. """ - kwargs = self._pop_dep_append_kwarg(kwargs) + if params is None: + params = [] - exists = self._has_table(name, flavor=flavor) - if exists: - if if_exists == 'fail': - raise ValueError("Table '%s' already exists." % name) - elif if_exists == 'replace': - self._drop_table(name) - # do I have to create too? - else: - self._create_table( - frame, name, flavor) # flavor is ignored with engine + result = self.execute(sql, retry=retry, params=params) + return result.row_count - self._write(frame, name, flavor) + def _create_table(self, frame, name, flavor, keys=None): + # Elements that are always going to be the same between tables - def _get_data_and_columns(self, *args, **kwargs): - raise ValueError("PandasSQL must be created with an engine," - " connection or cursor.") - - def _has_table(self, name, flavor='sqlite'): - # Note: engine overrides this, to use engine.has_table - flavor_map = { - 'sqlite': ("SELECT name FROM sqlite_master " - "WHERE type='table' AND name='%s';") % name, - 'mysql': "SHOW TABLES LIKE '%s'" % name} - query = flavor_map.get(flavor, None) - if query is None: - raise NotImplementedError - return len(self.tquery(query)) > 0 + # Replace spaces in DataFrame column names with _. + safe_columns = [s.replace( ' ', '_').strip() + for s in frame.dtypes.index] + sqltypes = frame.dtypes.apply(self._get_sqltype) - def _drop_table(self, name): - # Previously this worried about connection tp cursor then closing... - drop_sql = "DROP TABLE %s" % name - self.execute(drop_sql) + if len(sqltypes) != safe_columns: + raise AssertionError("Columns and dtypes should be equal lengths") - @staticmethod - def _create_schema(frame, name, flavor, keys=None): - "Return a CREATE TABLE statement to suit the contents of a DataFrame." - lookup_type = lambda dtype: PandasSQL._get_sqltype(dtype.type, flavor) - # Replace spaces in DataFrame column names with _. - safe_columns = [s.replace( - ' ', '_').strip() for s in frame.dtypes.index] - column_types = lzip(safe_columns, map(lookup_type, frame.dtypes)) - if flavor == 'sqlite': - columns = ',\n '.join('[%s] %s' % x for x in column_types) - elif flavor == 'mysql': - columns = ',\n '.join('`%s` %s' % x for x in column_types) - elif flavor == 'postgres': - columns = ',\n '.join('%s %s' % x for x in column_types) - else: - raise ValueError("Don't have a template for that database flavor.") + column_types = lzip(safe_columns, sqltypes) + schema_format = self.schema_format + columns = ',\n '.join(schema_format % x for x in column_types) + self._generate_table_sql(keys, columns, name) + def _generate_table_sql(self, keys, columns, name): + # might make more sense to just incorporate this + # into _create_table keystr = '' if keys is not None: if isinstance(keys, compat.string_types): @@ -369,30 +410,41 @@ def _create_schema(frame, name, flavor, keys=None): %(columns)s %(keystr)s );""" - create_statement = template % {'name': name, 'columns': columns, + create_sql = template % {'name': name, 'columns': columns, 'keystr': keystr} - return create_statement + self.execute(create_sql) - @staticmethod - def _frame_from_data_and_columns(data, columns, index_col=None, coerce_float=True): - df = DataFrame.from_records(data, columns=columns) - if index_col is not None: - df.set_index(index_col, inplace=True) - return df + def _write(self, frame, name): + # cur = con.cursor() + # Replace spaces in DataFrame column names with _. + safe_names = [s.replace(' ', '_').strip() for s in frame.columns] + self._write_helper(frame, name, safe_names) + # # TODO: put this close separately... + # self.cur.close() - @staticmethod - def _pop_dep_append_kwarg(kwargs): - if 'append' in kwargs: - from warnings import warn - warn("append is deprecated, use if_exists='append'", FutureWarning) - if kwargs.pop('append'): - kwargs['if_exists'] = 'append' - else: - kwargs['if_exists'] = 'fail' - return kwargs + @classmethod + def _create_schema(cls, frame, name, keys=None): + "Return a CREATE TABLE statement to suit the contents of a DataFrame." - @staticmethod - def _safe_fetch(cur): + @classmethod + def _get_sqltype(cls, pytype, flavor): + # have to do it in reverse order...that way maintains same thing + if issubclass(pytype, np.bool_): + return cls.sqltype['bool'] + elif pytype is datetime.date: + return cls.sqltype['date'] + elif issubclass(pytype, np.datetime64) or pytype is datetime.datetime: + # Caution: np.datetime64 is also a subclass of np.number. + return cls.sqltype['datetime'] + elif issubclass(pytype, np.integer): + return cls.sqltype['integer'] + elif issubclass(pytype, np.floating): + return cls.sqltype['float'] + else: + return cls.sqltype['default'] + + @classmethod + def _safe_fetch(cls, cur): '''ensures result of fetchall is a list''' try: result = cur.fetchall() @@ -403,202 +455,127 @@ def _safe_fetch(cur): excName = e.__class__.__name__ if excName == 'OperationalError': return [] + raise - @staticmethod - def _get_sqltype(pytype, flavor): - sqltype = {'mysql': 'VARCHAR (63)', - 'sqlite': 'TEXT', - 'postgres': 'text'} - - if issubclass(pytype, np.floating): - sqltype['mysql'] = 'FLOAT' - sqltype['sqlite'] = 'REAL' - sqltype['postgres'] = 'real' - - if issubclass(pytype, np.integer): - # TODO: Refine integer size. - sqltype['mysql'] = 'BIGINT' - sqltype['sqlite'] = 'INTEGER' - sqltype['postgres'] = 'integer' - - if issubclass(pytype, np.datetime64) or pytype is datetime: - # Caution: np.datetime64 is also a subclass of np.number. - sqltype['mysql'] = 'DATETIME' - sqltype['sqlite'] = 'TIMESTAMP' - sqltype['postgres'] = 'timestamp' - - if pytype is datetime.date: - sqltype['mysql'] = 'DATE' - sqltype['sqlite'] = 'TIMESTAMP' - sqltype['postgres'] = 'date' - - if issubclass(pytype, np.bool_): - sqltype['sqlite'] = 'INTEGER' - sqltype['postgres'] = 'boolean' - - return sqltype[flavor] - - -class PandasSQLWithCur(PandasSQL): - def __init__(self, cur): - self.cur = cur - - def execute(self, sql, retry=False, params=None): - if params is None: - params = [] - try: - if params: - self.cur.execute(sql, params) - else: - self.cur.execute(sql) - return self.cur - except Exception as e: - try: - con.rollback() - except Exception: # pragma: no cover - ex = DatabaseError( - "Execution failed on sql: %s\n%s\nunable to rollback" % (sql, e)) - raise_with_traceback(ex) - - ex = DatabaseError("Execution failed on sql: %s" % sql) - raise_with_traceback(ex) + def _get_data_and_columns(self, sql, params): + cursor = self.execute(sql, params=params) + data = self._safe_fetch(cursor) + columns = [col_desc[0] for col_desc in cursor.description] + # TODO: Remove this + cursor.close() + return data, columns - def tquery(self, sql, retry=True, params=None, con=None): + def read_sql(self, sql, index_col=None, coerce_float=True, params=None): + # Note coerce_float ignored here...not sure why if params is None: params = [] + data, columns = self._get_data_and_columns(sql=sql, params=params) + df = DataFrame.from_records(data, columns=columns) + if index_col is not None: + df.set_index(index_col, inplace=True) + return df - # result = _cur_tquery(sql, retry=retry, params=params) - - ### previously _cur_tquery - cur = self.execute(sql, retry=retry, params=params) - result = self._safe_fetch(self.cur) - - if con is not None: - try: - cur.close() - con.commit() - except Exception as e: - excName = e.__class__.__name__ - if excName == 'OperationalError': # pragma: no cover - print ('Failed to commit, may need to restart interpreter') - else: - raise - - traceback.print_exc() - if retry: - return self.tquery(sql, retry=False, params=params, con=con) - ### - - # This makes into tuples? - if result and len(result[0]) == 1: - # python 3 compat - result = list(lzip(*result)[0]) - elif result is None: # pragma: no cover - result = [] - return result - - def uquery(self, sql, retry=True, params=None, con=None): + def write_frame(self, frame, name, con=None, flavor='sqlite', + if_exists='fail', engine=None, **kwargs): """ - Does the same thing as tquery, but instead of returning results, it - returns the number of rows affected. Good for update queries. + Write records stored in a DataFrame to a SQL database. + + Parameters + ---------- + frame: DataFrame + name: name of SQL table + con: an open SQL database connection object + flavor: {'sqlite', 'mysql', 'oracle'}, default 'sqlite' + if_exists: {'fail', 'replace', 'append'}, default 'fail' + fail: If table exists, do nothing. + replace: If table exists, drop it, recreate it, and insert data. + append: If table exists, insert data. Create if does not exist. """ - if params is None: - params = [] + self._pop_dep_append_kwarg(kwargs) - cur = self.execute(sql, retry=retry, params=params) - row_count = cur.rowcount + exists = self._has_table(name) + if exists: + if if_exists == 'fail': + raise ValueError("Table '%s' already exists." % name) + elif if_exists == 'replace': + # drop and force recreate + self._drop_table(name) + exists = False + elif if_exists == 'append': + pass + else: + raise ValueError("Unknown option for if_exists: %s" % if_exists) - if con: # Not sure if this is needed.... - try: - con.commit() - except Exception as e: - excName = e.__class__.__name__ - if excName != 'OperationalError': - raise - - traceback.print_exc() - if retry: - print ( - 'Looks like your connection failed, reconnecting...') - return self.uquery(sql, con, retry=False) - return row_count - - def _get_data_and_columns(self, sql, con=None, flavor=None, driver=None, - username=None, password=None, host=None, port=None, - database=None, coerce_float=True, params=None): - - # dialect = flavor - # try: - # connection = get_connection(con, dialect, driver, username, password, - # host, port, database) - # except LegacyMySQLConnection: - # warnings.warn("For more robust support, connect using " - # "SQLAlchemy. See documentation.") - # return sql_legacy.read_frame(sql, con, index_col, coerce_float, - # params) + if not exists: + self._create_table(frame, name) - cursor = self.execute(sql, params=params) - data = PandasSQL._safe_fetch(cursor) - columns = [col_desc[0] for col_desc in cursor.description] - cursor.close() - return data, columns + self._write(frame, name) - def _create_table(self, frame, name, flavor, keys=None): - create_sql = get_schema(frame, name, flavor, keys) - self.execute(create_sql) + # TODO: Remove this + @classmethod + def _pop_dep_append_kwarg(cls, kwargs): + if 'append' in kwargs: + from warnings import warn + warn("append is deprecated, use if_exists='append'", FutureWarning) + if kwargs.pop('append'): + # should this be setdefault? + kwargs['if_exists'] = 'append' + else: + # should this be setdefault? + kwargs['if_exists'] = 'fail' + return kwargs - def _write(self, frame, name, flavor='sqlite'): - # cur = con.cursor() - # Replace spaces in DataFrame column names with _. - safe_names = [s.replace(' ', '_').strip() for s in frame.columns] - flavor_picker = {'sqlite': self._cur_write_sqlite, - 'mysql': self._cur_write_mysql} + def write_frame(self, frame, name, if_exists='fail', **kwargs): + """ + Write records stored in a DataFrame to a SQL database. - func = flavor_picker.get(flavor, None) - if func is None: - raise NotImplementedError - func(frame, name, safe_names, self.cur) - self.cur.close() + Parameters + ---------- + frame: DataFrame + name: name of SQL table + con: an open SQL database connection object + flavor: {'sqlite', 'mysql', 'oracle'}, default 'sqlite' + if_exists: {'fail', 'replace', 'append'}, default 'fail' + fail: If table exists, do nothing. + replace: If table exists, drop it, recreate it, and insert data. + append: If table exists, insert data. Create if does not exist. + """ + kwargs['if_exists'] = if_exists + self._pop_dep_append_kwarg(kwargs) + if_exists = kwargs['if_exists'] + exists = self._has_table(name) - @staticmethod - def _cur_write_sqlite(frame, table, names, cur): - bracketed_names = ['[' + column + ']' for column in names] - col_names = ','.join(bracketed_names) - wildcards = ','.join(['?'] * len(names)) - insert_query = 'INSERT INTO %s (%s) VALUES (%s)' % ( - table, col_names, wildcards) - # pandas types are badly handled if there is only 1 column ( Issue - # #3628 ) - if len(frame.columns) != 1: - data = [tuple(x) for x in frame.values] - else: - data = [tuple(x) for x in frame.values.tolist()] - cur.executemany(insert_query, data) + if exists: + if if_exists == 'fail': + raise ValueError("Table '%s' already exists." % name) + elif if_exists == 'replace': + # drop table and create a new one + self._drop_table(name) + exists = False + elif if_exists == 'append': + # just let it go - going to append at end anyways + pass + else: + raise ValueError("Invalid `if_exists` option: %s" % if_exists) - @staticmethod - def _cur_write_mysql(frame, table, names, cur): - bracketed_names = ['`' + column + '`' for column in names] - col_names = ','.join(bracketed_names) - wildcards = ','.join([r'%s'] * len(names)) - insert_query = "INSERT INTO %s (%s) VALUES (%s)" % ( - table, col_names, wildcards) - # pandas types are badly handled if there is only 1 column ( Issue - # #3628 ) - if len(frame.columns) != 1: - data = [tuple(x) for x in frame.values] - else: - data = [tuple(x) for x in frame.values.tolist()] - cur.executemany(insert_query, data) + if not exists: + self._create_table(frame, name) + self._write(frame, name, flavor) -class PandasSQLWithCon(PandasSQL): - def __init__(self, con): - raise NotImplementedError + def _drop_table(self, name): + # Previously this worried about connection tp cursor then closing... + drop_sql = "DROP TABLE %s" % name + self.execute(drop_sql) -class PandasSQLWithEngine(PandasSQL): - def __init__(self, engine): - self.engine = engine +class SQLAlchemyEngineBackend(BackendBase): + flavor = 'sqla' + _initialized_sqltype = False + def __init__(self, engine, *args, **kwargs): + # helps with compatibility with backend base + self.cur = self.engine = engine + self._initialize_sqltype() def execute(self, sql, retry=True, params=None): try: @@ -607,36 +584,21 @@ def execute(self, sql, retry=True, params=None): ex = DatabaseError("Execution failed with: %s" % e) raise_with_traceback(ex) + # TODO: Remove me - I think it needs superclass method, because it doesn't guarantee tuples?? def tquery(self, sql, retry=False, params=None): if params is None: params = [] result = self.execute(sql, params=params) return result.fetchall() - def uquery(self, sql, retry=False, params=None): - if params is None: - params = [] - result = self.execute(sql, params=params) - return result.rowcount - def _get_data_and_columns(self, sql, params, **kwargs): result = self.execute(sql, params=params) - data = result.fetchall() + data = self._safe_fetch(result) columns = result.keys() return data, columns - def write_frame(self, frame, name, if_exists='fail', **kwargs): - self._pop_dep_append_kwarg(kwargs) - - exists = self.engine.has_table(name) - if exists: - if if_exists == 'fail': - raise ValueError("Table '%s' already exists." % name) - elif if_exists == 'replace': - self._drop_table(name) - - self._create_table(frame, name) - self._write(frame, name) + def _has_table(self, name): + return self.engine.has_table(name) def _write(self, frame, table_name, **kwargs): table = self._get_table(table_name) @@ -661,63 +623,145 @@ def maybe_asscalar(i): def _has_table(self, name): return self.engine.has_table(name) - def _get_table(self, table_name, meta=None): + def _get_table(self, table_name): if self.engine.has_table(table_name): - if not meta: - from sqlalchemy.schema import MetaData - meta = MetaData(self.engine) - meta.reflect(self.engine) - return meta.tables[table_name] + self.meta.tables[table_name] else: return None + @property + def meta(self): + from sqlalchemy.schema import MetaData + meta = MetaData(self.engine) + meta.reflect(self.engine) + return meta.tables[table_name] + def _drop_table(self, table_name): if self.engine.has_table(table_name): table = self._get_table(table_name) table.drop - def _create_table(self, frame, table_name, keys=None, meta=None): + def _create_table(self, frame, table_name, keys=None): from sqlalchemy import Table, Column if keys is None: keys = [] - if not meta: # Do we need meta param? - from sqlalchemy.schema import MetaData - meta = MetaData(self.engine) - meta.reflect(self.engine) - safe_columns = [s.replace( - ' ', '_').strip() for s in frame.dtypes.index] # may not be safe enough... + # may not be safe enough... + safe_columns = [s.replace( ' ', '_').strip() + for s in frame.dtypes.index] column_types = map(self._lookup_type, frame.dtypes) - columns = [(col_name, col_sqltype, col_name in keys) + columns = [Column(col_name, col_sqltype, primary_key=(col_name in keys)) for col_name, col_sqltype in zip(safe_columns, column_types)] - columns = map(lambda (name, typ, pk): Column( - name, typ, primary_key=pk), columns) - table = Table(table_name, meta, *columns) + table = Table(table_name, self.meta, *columns) table.create() - def _lookup_type(self, dtype): + @classmethod + def _initialize_sqltype(cls): + if cls._initialized_sqltype: + return + # avoid import errors here... from sqlalchemy import INT, FLOAT, TEXT, BOOLEAN + sqltype = { + 'default': TEXT, + 'integer': INT, + 'float': FLOAT, + 'datetime': DATETIME, + 'date': DATE, + 'bool': BOOLEAN + } + cls.sqltype = sqltype + cls._initialized_sqltype = True + +class SQLiteBackend(BackendBase): + table_query_format = ("SELECT name FROM sqlite_master " + "WHERE type='table' AND name='%s';") + sqltype = {'default': 'VARCHAR (63)', + 'float': 'REAL', + 'integer': 'INTEGER', + 'datetime': 'TIMESTAMP', + 'date': 'TIMESTAMP', + 'bool': 'INTEGER', + } + flavor = 'sqlite' + schema_format = '[%s] %s' + + def _write_helper(self, frame, table, names): + cur = self.cur + bracketed_names = ['[' + column + ']' for column in names] + col_names = ','.join(bracketed_names) + wildcards = ','.join(['?'] * len(names)) + insert_query = 'INSERT INTO %s (%s) VALUES (%s)' % ( + table, col_names, wildcards) + # pandas types are badly handled if there is only 1 column ( Issue + # #3628 ) + if len(frame.columns) != 1: + data = [tuple(x) for x in frame.values] + else: + data = [tuple(x) for x in frame.values.tolist()] + cur.executemany(insert_query, data) - pytype = dtype.type - - if issubclass(pytype, np.floating): - return FLOAT - if issubclass(pytype, np.integer): - # TODO: Refine integer size. - return INT - if issubclass(pytype, np.datetime64) or pytype is datetime: - # Caution: np.datetime64 is also a subclass of np.number. - return DATETIME - if pytype is datetime.date: - return DATE - if issubclass(pytype, np.bool_): - return BOOLEAN - return TEXT - - -# legacy names -get_schema = PandasSQL._create_schema -frame_query = read_sql -read_frame = read_sql +class MySQLBackend(BackendBase): + table_query_format = "SHOW TABLES LIKE '%s'" + sqltype = {'default': 'VARCHAR(63)', + 'float': 'FLOAT', + 'integer': 'BIGINT', + 'datetime': 'DATETIME', + 'date': 'DATE', + # slight change from previous - aliased to TINYINT in general, + # there's a BIT dtype too, not sure what to do with that. + 'bool': 'BOOL'} + flavor = 'mysql' + schema_format = '`%s` %s' + + def _write_helper(frame, table, names): + # TODO: almost the same between MySQL and SQLite - consider combining + bracketed_names = ['`' + column + '`' for column in names] + col_names = ','.join(bracketed_names) + wildcards = ','.join([r'%s'] * len(names)) + insert_query = "INSERT INTO %s (%s) VALUES (%s)" % ( + table, col_names, wildcards) + # pandas types are badly handled if there is only 1 column ( Issue + # #3628 ) + if len(frame.columns) != 1: + data = [tuple(x) for x in frame.values] + else: + data = [tuple(x) for x in frame.values.tolist()] + self.cur.executemany(insert_query, data) + +class PostgresBackend(BackendBase): + table_query_format = ("select * from information_schema.tables where " + "table_name=%s") + sqltype = {'default': 'text', + 'date': 'date', + 'bool': 'boolean', + 'datetime': 'timestamp', + 'integer': 'integer', + 'float': 'real' + } + flavor = 'postgres' + schema_format = '%s %s' + def _write_helper(frame, table, names): + # TODO: almost the same between MySQL and SQLite - consider combining + col_names = ','.join(names) + # not sure whether this is the correct format here... + wildcards = ','.join(['%s'] * len(names)) + insert_query = "INSERT INTO %s (%s) VALUES (%s)" % ( + table, col_names, wildcards) + # pandas types are badly handled if there is only 1 column ( Issue + # #3628 ) + if len(frame.columns) != 1: + data = [tuple(x) for x in frame.values] + else: + data = [tuple(x) for x in frame.values.tolist()] + self.cur.executemany(insert_query, data) + # * table_query_format + +flavor_mapping = { + 'sqlite': SQLiteBackend, + 'postgres': PostgresBackend, + 'mysql': MySQLBackend, + 'sqla': SQLAlchemyEngineBackend, + 'oracle': SQLAlchemyEngineBackend, +}
Still don't have down the code to dispatch appropriately (though I'm not even clear why the existing code has individual flavors, given that it appears to only accept SQLAlchemy objects anyways). Also would be helpful to cover additional cases where we get connections and want to convert to cursors.
https://api.github.com/repos/pandas-dev/pandas/pulls/4958
2013-09-24T02:23:45Z
2014-01-29T05:54:33Z
null
2014-01-29T05:54:33Z
BUG: fix incorrect TypeError raise
diff --git a/doc/source/release.rst b/doc/source/release.rst index 442dcd0305913..04908ee8c9e03 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -453,6 +453,8 @@ Bug Fixes - Fixed a bug with setting invalid or out-of-range values in indexing enlargement scenarios (:issue:`4940`) - Tests for fillna on empty Series (:issue:`4346`), thanks @immerrr + - Fixed a bug where ``ValueError`` wasn't correctly raised when column names + weren't strings (:issue:`4956`) pandas 0.12.0 ------------- diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 65edaed89c1f7..491e090cab4fe 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3033,7 +3033,9 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, new_blocks.append(b) except: raise ValueError( - "cannot match existing table structure for [%s] on appending data" % ','.join(items)) + "cannot match existing table structure for [%s] on " + "appending data" % ','.join(com.pprint_thing(item) for + item in items)) blocks = new_blocks # add my values diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index ee438cb2cd45a..a79ac9d3f9e40 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -3696,6 +3696,21 @@ def test_store_datetime_mixed(self): # self.assertRaises(Exception, store.put, 'foo', df, format='table') + def test_append_with_diff_col_name_types_raises_value_error(self): + df = DataFrame(np.random.randn(10, 1)) + df2 = DataFrame({'a': np.random.randn(10)}) + df3 = DataFrame({(1, 2): np.random.randn(10)}) + df4 = DataFrame({('1', 2): np.random.randn(10)}) + df5 = DataFrame({('1', 2, object): np.random.randn(10)}) + + with ensure_clean('__%s__.h5' % tm.rands(20)) as store: + name = 'df_%s' % tm.rands(10) + store.append(name, df) + + for d in (df2, df3, df4, df5): + with tm.assertRaises(ValueError): + store.append(name, d) + def _test_sort(obj): if isinstance(obj, DataFrame):
TypeError was being raised when a ValueError was raised because the ValueError's message wasn't being converted to a string. closes #4956
https://api.github.com/repos/pandas-dev/pandas/pulls/4957
2013-09-24T01:52:16Z
2013-09-24T02:20:40Z
2013-09-24T02:20:40Z
2014-06-12T14:21:17Z
ENH: Added colspecs detection to read_fwf
diff --git a/.gitignore b/.gitignore index df7002a79d974..da76a414865e5 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ pandas/io/*.json .project .pydevproject +.settings diff --git a/doc/source/io.rst b/doc/source/io.rst index 01795f6a4a9bf..5e04fcff61539 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -742,10 +742,13 @@ function works with data files that have known and fixed column widths. The function parameters to ``read_fwf`` are largely the same as `read_csv` with two extra parameters: - - ``colspecs``: a list of pairs (tuples), giving the extents of the - fixed-width fields of each line as half-open intervals [from, to[ - - ``widths``: a list of field widths, which can be used instead of - ``colspecs`` if the intervals are contiguous + - ``colspecs``: A list of pairs (tuples) giving the extents of the + fixed-width fields of each line as half-open intervals (i.e., [from, to[ ). + String value 'infer' can be used to instruct the parser to try detecting + the column specifications from the first 100 rows of the data. Default + behaviour, if not specified, is to infer. + - ``widths``: A list of field widths which can be used instead of 'colspecs' + if the intervals are contiguous. .. ipython:: python :suppress: @@ -789,6 +792,18 @@ column widths for contiguous columns: The parser will take care of extra white spaces around the columns so it's ok to have extra separation between the columns in the file. +.. versionadded:: 0.13.0 + +By default, ``read_fwf`` will try to infer the file's ``colspecs`` by using the +first 100 rows of the file. It can do it only in cases when the columns are +aligned and correctly separated by the provided ``delimiter`` (default delimiter +is whitespace). + +.. ipython:: python + + df = pd.read_fwf('bar.csv', header=None, index_col=0) + df + .. ipython:: python :suppress: diff --git a/doc/source/release.rst b/doc/source/release.rst index f3f86dec92502..177381346e2d1 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -59,6 +59,7 @@ New features - Added ``isin`` method to DataFrame (:issue:`4211`) - Clipboard functionality now works with PySide (:issue:`4282`) - New ``extract`` string method returns regex matches more conveniently (:issue:`4685`) + - Auto-detect field widths in read_fwf when unspecified (:issue:`4488`) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 0796f34ead839..0e3c3b50fcd85 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -421,6 +421,9 @@ Enhancements can also be used. - ``read_stata` now accepts Stata 13 format (:issue:`4291`) + - ``read_fwf`` now infers the column specifications from the first 100 rows of + the file if the data has correctly separated and properly aligned columns + using the delimiter provided to the function (:issue:`4488`). .. _whatsnew_0130.experimental: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index e0b12277f4416..3ef3cbf856fef 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -160,11 +160,15 @@ """ % (_parser_params % _table_sep) _fwf_widths = """\ -colspecs : a list of pairs (tuples), giving the extents - of the fixed-width fields of each line as half-open internals - (i.e., [from, to[ ). -widths : a list of field widths, which can be used instead of - 'colspecs' if the intervals are contiguous. +colspecs : list of pairs (int, int) or 'infer'. optional + A list of pairs (tuples) giving the extents of the fixed-width + fields of each line as half-open intervals (i.e., [from, to[ ). + String value 'infer' can be used to instruct the parser to try + detecting the column specifications from the first 100 rows of + the data (default='infer'). +widths : list of ints. optional + A list of field widths which can be used instead of 'colspecs' if + the intervals are contiguous. """ _read_fwf_doc = """ @@ -184,7 +188,8 @@ def _read(filepath_or_buffer, kwds): if skipfooter is not None: kwds['skip_footer'] = skipfooter - filepath_or_buffer, _ = get_filepath_or_buffer(filepath_or_buffer) + filepath_or_buffer, _ = get_filepath_or_buffer(filepath_or_buffer, + encoding) if kwds.get('date_parser', None) is not None: if isinstance(kwds['parse_dates'], bool): @@ -267,8 +272,8 @@ def _read(filepath_or_buffer, kwds): } _fwf_defaults = { - 'colspecs': None, - 'widths': None + 'colspecs': 'infer', + 'widths': None, } _c_unsupported = set(['skip_footer']) @@ -412,15 +417,15 @@ def parser_f(filepath_or_buffer, @Appender(_read_fwf_doc) -def read_fwf(filepath_or_buffer, colspecs=None, widths=None, **kwds): +def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, **kwds): # Check input arguments. if colspecs is None and widths is None: raise ValueError("Must specify either colspecs or widths") - elif colspecs is not None and widths is not None: + elif colspecs not in (None, 'infer') and widths is not None: raise ValueError("You must specify only one of 'widths' and " "'colspecs'") - # Compute 'colspec' from 'widths', if specified. + # Compute 'colspecs' from 'widths', if specified. if widths is not None: colspecs, col = [], 0 for w in widths: @@ -519,7 +524,8 @@ def _clean_options(self, options, engine): engine = 'python' elif sep is not None and len(sep) > 1: # wait until regex engine integrated - engine = 'python' + if engine not in ('python', 'python-fwf'): + engine = 'python' # C engine not supported yet if engine == 'c': @@ -2012,31 +2018,65 @@ class FixedWidthReader(object): """ A reader of fixed-width lines. """ - def __init__(self, f, colspecs, filler, thousands=None, encoding=None): + def __init__(self, f, colspecs, delimiter, comment): self.f = f - self.colspecs = colspecs - self.filler = filler # Empty characters between fields. - self.thousands = thousands - if encoding is None: - encoding = get_option('display.encoding') - self.encoding = encoding - - if not isinstance(colspecs, (tuple, list)): + self.buffer = None + self.delimiter = '\r\n' + delimiter if delimiter else '\n\r\t ' + self.comment = comment + if colspecs == 'infer': + self.colspecs = self.detect_colspecs() + else: + self.colspecs = colspecs + + if not isinstance(self.colspecs, (tuple, list)): raise TypeError("column specifications must be a list or tuple, " "input was a %r" % type(colspecs).__name__) - for colspec in colspecs: + for colspec in self.colspecs: if not (isinstance(colspec, (tuple, list)) and - len(colspec) == 2 and - isinstance(colspec[0], int) and - isinstance(colspec[1], int)): + len(colspec) == 2 and + isinstance(colspec[0], (int, np.integer)) and + isinstance(colspec[1], (int, np.integer))): raise TypeError('Each column specification must be ' '2 element tuple or list of integers') + def get_rows(self, n): + rows = [] + for i, row in enumerate(self.f, 1): + rows.append(row) + if i >= n: + break + self.buffer = iter(rows) + return rows + + def detect_colspecs(self, n=100): + # Regex escape the delimiters + delimiters = ''.join([r'\%s' % x for x in self.delimiter]) + pattern = re.compile('([^%s]+)' % delimiters) + rows = self.get_rows(n) + max_len = max(map(len, rows)) + mask = np.zeros(max_len + 1, dtype=int) + if self.comment is not None: + rows = [row.partition(self.comment)[0] for row in rows] + for row in rows: + for m in pattern.finditer(row): + mask[m.start():m.end()] = 1 + shifted = np.roll(mask, 1) + shifted[0] = 0 + edges = np.where((mask ^ shifted) == 1)[0] + return list(zip(edges[::2], edges[1::2])) + def next(self): - line = next(self.f) + if self.buffer is not None: + try: + line = next(self.buffer) + except StopIteration: + self.buffer = None + line = next(self.f) + else: + line = next(self.f) # Note: 'colspecs' is a sequence of half-open intervals. - return [line[fromm:to].strip(self.filler or ' ') + return [line[fromm:to].strip(self.delimiter) for (fromm, to) in self.colspecs] # Iterator protocol in Python 3 uses __next__() @@ -2050,10 +2090,10 @@ class FixedWidthFieldParser(PythonParser): """ def __init__(self, f, **kwds): # Support iterators, convert to a list. - self.colspecs = list(kwds.pop('colspecs')) + self.colspecs = kwds.pop('colspecs') PythonParser.__init__(self, f, **kwds) def _make_reader(self, f): self.data = FixedWidthReader(f, self.colspecs, self.delimiter, - encoding=self.encoding) + self.comment) diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 4e0c00c8a31eb..44e40dc34ff25 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -1706,7 +1706,7 @@ def test_utf16_example(self): self.assertEquals(len(result), 50) def test_converters_corner_with_nas(self): - # skip aberration observed on Win64 Python 3.2.2 + # skip aberration observed on Win64 Python 3.2.2 if hash(np.int64(-1)) != -2: raise nose.SkipTest("skipping because of windows hash on Python" " 3.2.2") @@ -2078,19 +2078,19 @@ def test_fwf(self): read_fwf(StringIO(data3), colspecs=colspecs, widths=[6, 10, 10, 7]) with tm.assertRaisesRegexp(ValueError, "Must specify either"): - read_fwf(StringIO(data3)) + read_fwf(StringIO(data3), colspecs=None, widths=None) def test_fwf_colspecs_is_list_or_tuple(self): with tm.assertRaisesRegexp(TypeError, 'column specifications must be a list or ' 'tuple.+'): - fwr = pd.io.parsers.FixedWidthReader(StringIO(self.data1), - {'a': 1}, ',') + pd.io.parsers.FixedWidthReader(StringIO(self.data1), + {'a': 1}, ',', '#') def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(self): with tm.assertRaisesRegexp(TypeError, 'Each column specification must be.+'): - read_fwf(StringIO(self.data1), {'a': 1}) + read_fwf(StringIO(self.data1), [('a', 1)]) def test_fwf_regression(self): # GH 3594 @@ -2223,6 +2223,107 @@ def test_iteration_open_handle(self): expected = Series(['DDD', 'EEE', 'FFF', 'GGG']) tm.assert_series_equal(result, expected) + +class TestFwfColspaceSniffing(unittest.TestCase): + def test_full_file(self): + # File with all values + test = '''index A B C +2000-01-03T00:00:00 0.980268513777 3 foo +2000-01-04T00:00:00 1.04791624281 -4 bar +2000-01-05T00:00:00 0.498580885705 73 baz +2000-01-06T00:00:00 1.12020151869 1 foo +2000-01-07T00:00:00 0.487094399463 0 bar +2000-01-10T00:00:00 0.836648671666 2 baz +2000-01-11T00:00:00 0.157160753327 34 foo''' + colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) + expected = read_fwf(StringIO(test), colspecs=colspecs) + tm.assert_frame_equal(expected, read_fwf(StringIO(test))) + + def test_full_file_with_missing(self): + # File with missing values + test = '''index A B C +2000-01-03T00:00:00 0.980268513777 3 foo +2000-01-04T00:00:00 1.04791624281 -4 bar + 0.498580885705 73 baz +2000-01-06T00:00:00 1.12020151869 1 foo +2000-01-07T00:00:00 0 bar +2000-01-10T00:00:00 0.836648671666 2 baz + 34''' + colspecs = ((0, 19), (21, 35), (38, 40), (42, 45)) + expected = read_fwf(StringIO(test), colspecs=colspecs) + tm.assert_frame_equal(expected, read_fwf(StringIO(test))) + + def test_full_file_with_spaces(self): + # File with spaces in columns + test = ''' +Account Name Balance CreditLimit AccountCreated +101 Keanu Reeves 9315.45 10000.00 1/17/1998 +312 Gerard Butler 90.00 1000.00 8/6/2003 +868 Jennifer Love Hewitt 0 17000.00 5/25/1985 +761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 +317 Bill Murray 789.65 5000.00 2/5/2007 +'''.strip('\r\n') + colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) + expected = read_fwf(StringIO(test), colspecs=colspecs) + tm.assert_frame_equal(expected, read_fwf(StringIO(test))) + + def test_full_file_with_spaces_and_missing(self): + # File with spaces and missing values in columsn + test = ''' +Account Name Balance CreditLimit AccountCreated +101 10000.00 1/17/1998 +312 Gerard Butler 90.00 1000.00 8/6/2003 +868 5/25/1985 +761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 +317 Bill Murray 789.65 +'''.strip('\r\n') + colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70)) + expected = read_fwf(StringIO(test), colspecs=colspecs) + tm.assert_frame_equal(expected, read_fwf(StringIO(test))) + + def test_messed_up_data(self): + # Completely messed up file + test = ''' + Account Name Balance Credit Limit Account Created + 101 10000.00 1/17/1998 + 312 Gerard Butler 90.00 1000.00 + + 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006 + 317 Bill Murray 789.65 +'''.strip('\r\n') + colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79)) + expected = read_fwf(StringIO(test), colspecs=colspecs) + tm.assert_frame_equal(expected, read_fwf(StringIO(test))) + + def test_multiple_delimiters(self): + test = r''' +col1~~~~~col2 col3++++++++++++++++++col4 +~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves + 33+++122.33\\\bar.........Gerard Butler +++44~~~~12.01 baz~~Jennifer Love Hewitt +~~55 11+++foo++++Jada Pinkett-Smith +..66++++++.03~~~bar Bill Murray +'''.strip('\r\n') + colspecs = ((0, 4), (7, 13), (15, 19), (21, 41)) + expected = read_fwf(StringIO(test), colspecs=colspecs, + delimiter=' +~.\\') + tm.assert_frame_equal(expected, read_fwf(StringIO(test), + delimiter=' +~.\\')) + + def test_variable_width_unicode(self): + if not compat.PY3: + raise nose.SkipTest('Bytes-related test - only needs to work on Python 3') + test = ''' +שלום שלום +ום שלל +של ום +'''.strip('\r\n') + expected = pd.read_fwf(BytesIO(test.encode('utf8')), + colspecs=[(0, 4), (5, 9)], header=None) + tm.assert_frame_equal(expected, read_fwf(BytesIO(test.encode('utf8')), + header=None)) + + class TestCParserHighMemory(ParserTests, unittest.TestCase): def read_csv(self, *args, **kwds):
closes #4488 Implemented an algorithm that uses a bitmask to detect the gaps between the columns. Also the reader buffers the lines used for detection in case it's input is not seek-able. Added tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/4955
2013-09-23T22:52:12Z
2013-09-30T10:18:12Z
2013-09-30T10:18:12Z
2014-06-13T19:04:55Z
BUG: Fixed _format_labels in tile.py for np.inf.
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index ce42ee3b7bc88..7d2555e8cba81 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -505,6 +505,12 @@ normally distributed data into equal-size quartiles like so: factor value_counts(factor) +We can also pass infinite values to define the bins: +.. ipython:: python + + arr = np.random.randn(20) + factor = cut(arr, [-np.inf, 0, np.inf]) + factor .. _basics.apply: diff --git a/doc/source/release.rst b/doc/source/release.rst index 12787c5d04b45..eec2e91f0a755 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -462,6 +462,8 @@ Bug Fixes - Fixed ``copy()`` to shallow copy axes/indices as well and thereby keep separate metadata. (:issue:`4202`, :issue:`4830`) - Fixed skiprows option in Python parser for read_csv (:issue:`4382`) + - Fixed bug preventing ``cut`` from working with ``np.inf`` levels without + explicitly passing labels (:issue:`3415`) pandas 0.12.0 ------------- diff --git a/pandas/tools/tests/test_tile.py b/pandas/tools/tests/test_tile.py index 53258864b1ab8..86a43f648526b 100644 --- a/pandas/tools/tests/test_tile.py +++ b/pandas/tools/tests/test_tile.py @@ -114,6 +114,22 @@ def test_na_handling(self): ex_result = np.where(com.isnull(arr), np.nan, result) tm.assert_almost_equal(result, ex_result) + def test_inf_handling(self): + data = np.arange(6) + data_ser = Series(data) + + result = cut(data, [-np.inf, 2, 4, np.inf]) + result_ser = cut(data_ser, [-np.inf, 2, 4, np.inf]) + + ex_levels = ['(-inf, 2]', '(2, 4]', '(4, inf]'] + + np.testing.assert_array_equal(result.levels, ex_levels) + np.testing.assert_array_equal(result_ser.levels, ex_levels) + self.assertEquals(result[5], '(4, inf]') + self.assertEquals(result[0], '(-inf, 2]') + self.assertEquals(result_ser[5], '(4, inf]') + self.assertEquals(result_ser[0], '(-inf, 2]') + def test_qcut(self): arr = np.random.randn(1000) diff --git a/pandas/tools/tile.py b/pandas/tools/tile.py index aa64b046c6891..0c1d6d1c1cbab 100644 --- a/pandas/tools/tile.py +++ b/pandas/tools/tile.py @@ -245,7 +245,7 @@ def _format_label(x, precision=3): else: # pragma: no cover return sgn + '.'.join(('%d' % whole, val)) else: - return sgn + '%d' % whole + return sgn + '%0.f' % whole else: return str(x)
Fixes issue https://github.com/pydata/pandas/issues/3415.
https://api.github.com/repos/pandas-dev/pandas/pulls/4954
2013-09-23T20:04:51Z
2013-09-25T15:10:31Z
2013-09-25T15:10:31Z
2014-06-19T23:59:23Z
BUG: Make sure series-series boolean comparions are label based (GH4947)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 65e6ca0e1d95c..026791438a905 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -374,6 +374,8 @@ Bug Fixes - appending a 0-len table will work correctly (:issue:`4273`) - ``to_hdf`` was raising when passing both arguments ``append`` and ``table`` (:issue:`4584`) - reading from a store with duplicate columns across dtypes would raise (:issue:`4767`) + - Fixed a bug where ``ValueError`` wasn't correctly raised when column names + weren't strings (:issue:`4956`) - Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while trying to access trans[pos + 1] (:issue:`4496`) - The ``by`` argument now works correctly with the ``layout`` argument @@ -500,8 +502,6 @@ Bug Fixes - Fixed a bug with setting invalid or out-of-range values in indexing enlargement scenarios (:issue:`4940`) - Tests for fillna on empty Series (:issue:`4346`), thanks @immerrr - - Fixed a bug where ``ValueError`` wasn't correctly raised when column names - weren't strings (:issue:`4956`) - Fixed ``copy()`` to shallow copy axes/indices as well and thereby keep separate metadata. (:issue:`4202`, :issue:`4830`) - Fixed skiprows option in Python parser for read_csv (:issue:`4382`) @@ -521,6 +521,7 @@ Bug Fixes - Fix a bug where reshaping a ``Series`` to its own shape raised ``TypeError`` (:issue:`4554`) and other reshaping issues. - Bug in setting with ``ix/loc`` and a mixed int/string index (:issue:`4544`) + - Make sure series-series boolean comparions are label based (:issue:`4947`) pandas 0.12.0 ------------- diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 4ce2143fdd92c..c1c6e6e2f83d3 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -564,21 +564,31 @@ def na_op(x, y): y = com._ensure_object(y) result = lib.vec_binop(x, y, op) else: - result = lib.scalar_binop(x, y, op) + try: + + # let null fall thru + if not isnull(y): + y = bool(y) + result = lib.scalar_binop(x, y, op) + except: + raise TypeError("cannot compare a dtyped [{0}] array with " + "a scalar of type [{1}]".format(x.dtype,type(y).__name__)) return result def wrapper(self, other): if isinstance(other, pd.Series): name = _maybe_match_name(self, other) + + other = other.reindex_like(self).fillna(False).astype(bool) return self._constructor(na_op(self.values, other.values), - index=self.index, name=name) + index=self.index, name=name).fillna(False).astype(bool) elif isinstance(other, pd.DataFrame): return NotImplemented else: # scalars return self._constructor(na_op(self.values, other), - index=self.index, name=self.name) + index=self.index, name=self.name).fillna(False).astype(bool) return wrapper diff --git a/pandas/core/series.py b/pandas/core/series.py index 1bc35008cc341..79faad93ff1c1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -21,7 +21,8 @@ _values_from_object, _possibly_cast_to_datetime, _possibly_castable, _possibly_convert_platform, - ABCSparseArray, _maybe_match_name) + ABCSparseArray, _maybe_match_name, _ensure_object) + from pandas.core.index import (Index, MultiIndex, InvalidIndexError, _ensure_index, _handle_legacy_indexes) from pandas.core.indexing import ( @@ -1170,7 +1171,7 @@ def duplicated(self, take_last=False): ------- duplicated : Series """ - keys = com._ensure_object(self.values) + keys = _ensure_object(self.values) duplicated = lib.duplicated(keys, take_last=take_last) return self._constructor(duplicated, index=self.index, name=self.name) diff --git a/pandas/lib.pyx b/pandas/lib.pyx index f5205ae0c3133..56ef9a4fcb160 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -672,6 +672,9 @@ def scalar_binop(ndarray[object] values, object val, object op): object x result = np.empty(n, dtype=object) + if util._checknull(val): + result.fill(val) + return result for i in range(n): x = values[i] diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index ce8d84840ed69..e8d9f3a7fc7cc 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -4523,8 +4523,10 @@ def f(): def test_logical_with_nas(self): d = DataFrame({'a': [np.nan, False], 'b': [True, True]}) + # GH4947 + # bool comparisons should return bool result = d['a'] | d['b'] - expected = Series([np.nan, True]) + expected = Series([False, True]) assert_series_equal(result, expected) # GH4604, automatic casting here @@ -4533,10 +4535,6 @@ def test_logical_with_nas(self): assert_series_equal(result, expected) result = d['a'].fillna(False,downcast=False) | d['b'] - expected = Series([True, True],dtype=object) - assert_series_equal(result, expected) - - result = (d['a'].fillna(False,downcast=False) | d['b']).convert_objects() expected = Series([True, True]) assert_series_equal(result, expected) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index a70f2931e36fe..7f3ea130259dc 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2757,6 +2757,93 @@ def test_comparison_different_length(self): b = Series([2, 3, 4]) self.assertRaises(ValueError, a.__eq__, b) + def test_comparison_label_based(self): + + # GH 4947 + # comparisons should be label based + + a = Series([True, False, True], list('bca')) + b = Series([False, True, False], list('abc')) + + expected = Series([True, False, False], list('bca')) + result = a & b + assert_series_equal(result,expected) + + expected = Series([True, False, True], list('bca')) + result = a | b + assert_series_equal(result,expected) + + expected = Series([False, False, True], list('bca')) + result = a ^ b + assert_series_equal(result,expected) + + # rhs is bigger + a = Series([True, False, True], list('bca')) + b = Series([False, True, False, True], list('abcd')) + + expected = Series([True, False, False], list('bca')) + result = a & b + assert_series_equal(result,expected) + + expected = Series([True, False, True], list('bca')) + result = a | b + assert_series_equal(result,expected) + + # filling + + # vs empty + result = a & Series([]) + expected = Series([False, False, False], list('bca')) + assert_series_equal(result,expected) + + result = a | Series([]) + expected = Series([True, False, True], list('bca')) + assert_series_equal(result,expected) + + # vs non-matching + result = a & Series([1],['z']) + expected = Series([False, False, False], list('bca')) + assert_series_equal(result,expected) + + result = a | Series([1],['z']) + expected = Series([True, False, True], list('bca')) + assert_series_equal(result,expected) + + # identity + # we would like s[s|e] == s to hold for any e, whether empty or not + for e in [Series([]),Series([1],['z']),Series(['z']),Series(np.nan,b.index),Series(np.nan,a.index)]: + result = a[a | e] + assert_series_equal(result,a[a]) + + # vs scalars + index = list('bca') + t = Series([True,False,True]) + + for v in [True,1,2]: + result = Series([True,False,True],index=index) | v + expected = Series([True,True,True],index=index) + assert_series_equal(result,expected) + + for v in [np.nan,'foo']: + self.assertRaises(TypeError, lambda : t | v) + + for v in [False,0]: + result = Series([True,False,True],index=index) | v + expected = Series([True,False,True],index=index) + assert_series_equal(result,expected) + + for v in [True,1]: + result = Series([True,False,True],index=index) & v + expected = Series([True,False,True],index=index) + assert_series_equal(result,expected) + + for v in [False,0]: + result = Series([True,False,True],index=index) & v + expected = Series([False,False,False],index=index) + assert_series_equal(result,expected) + for v in [np.nan]: + self.assertRaises(TypeError, lambda : t & v) + def test_between(self): s = Series(bdate_range('1/1/2000', periods=20).asobject) s[::2] = np.nan @@ -2793,12 +2880,14 @@ def test_scalar_na_cmp_corners(self): def tester(a, b): return a & b - self.assertRaises(ValueError, tester, s, datetime(2005, 1, 1)) + self.assertRaises(TypeError, tester, s, datetime(2005, 1, 1)) s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)]) s[::2] = np.nan - assert_series_equal(tester(s, list(s)), s) + expected = Series(True,index=s.index) + expected[::2] = False + assert_series_equal(tester(s, list(s)), expected) d = DataFrame({'A': s}) # TODO: Fix this exception - needs to be fixed! (see GH5035)
closes #4947 You ask for a boolean comparsion, that is what you get ``` In [1]: a = Series([True, False, True], list('bca')) In [2]: b = Series([False, True, False], list('abc')) In [19]: a Out[19]: b True c False a True dtype: bool In [20]: b Out[20]: a False b True c False dtype: bool In [21]: a & b Out[21]: b True c False a False dtype: bool In [22]: a | b Out[22]: b True c False a True dtype: bool In [23]: a ^ b Out[23]: b False c False a True dtype: bool In [24]: a & Series([]) Out[24]: b False c False a False dtype: bool In [25]: a | Series([]) Out[25]: b True c False a True dtype: bool ``` these ok? ``` In [9]: Series([np.nan,np.nan])&Series([np.nan,np.nan]) Out[9]: 0 False 1 False dtype: bool In [10]: Series([np.nan,np.nan])|Series([np.nan,np.nan]) Out[10]: 0 False 1 False dtype: bool ``` scalars ``` In [30]: a | True Out[30]: b True c True a True dtype: bool In [31]: a | False Out[31]: b True c False a True dtype: bool In [32]: a & True Out[32]: b True c False a True dtype: bool In [33]: a & False Out[33]: b False c False a False dtype: bool ``` Invalid scalars ``` In [28]: a | 'foo' TypeError: cannot compare a dtyped [bool] array with a scalar of type [bool] In [29]: a | np.nan TypeError: cannot compare a dtyped [bool] array with a scalar of type [float] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4953
2013-09-23T18:15:50Z
2013-10-01T13:28:40Z
2013-10-01T13:28:40Z
2014-06-26T17:16:32Z
BUG: pd.isnull with tuple argumnet should return same results as list (#4872)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 793d52223b6f5..04e7d84f46357 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -215,6 +215,7 @@ API Changes - moved timedeltas support to pandas.tseries.timedeltas.py; add timedeltas string parsing, add top-level ``to_timedelta`` function - ``NDFrame`` now is compatible with Python's toplevel ``abs()`` function (:issue:`4821`). + - `pd.isnull` now treats tuple argumnent the same way as list (:issue:`4872`). Internal Refactoring ~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/common.py b/pandas/core/common.py index d3fa10abc7681..ba2f2314660e2 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -92,8 +92,11 @@ def isnull(obj): def _isnull_new(obj): - if lib.isscalar(obj): + is_tuple = isinstance(obj, tuple) + if not is_tuple and lib.isscalar(obj): return lib.checknull(obj) + elif is_tuple: + return _isnull_ndarraylike(np.asarray(obj)) if isinstance(obj, (ABCSeries, np.ndarray)): return _isnull_ndarraylike(obj) @@ -117,8 +120,11 @@ def _isnull_old(obj): ------- boolean ndarray or boolean ''' - if lib.isscalar(obj): + is_tuple = isinstance(obj, tuple) + if not is_tuple and lib.isscalar(obj): return lib.checknull_old(obj) + elif is_tuple: + return _isnull_ndarraylike_old(np.asarray(obj)) if isinstance(obj, (ABCSeries, np.ndarray)): return _isnull_ndarraylike_old(obj) diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 8c5764a3f59a6..078763a024ae2 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -89,6 +89,27 @@ def test_isnull(): tm.assert_frame_equal(result, expected) +def test_isnull_tuples(): + result = isnull((1, 2)) + exp = np.array([False, False]) + assert(np.array_equal(result, exp)) + + result = isnull([(False,)]) + exp = np.array([[False]]) + assert(np.array_equal(result, exp)) + + result = isnull([(1,), (2,)]) + exp = np.array([[False], [False]]) + assert(np.array_equal(result, exp)) + + # list of strings / unicode + result = isnull(('foo', 'bar')) + assert(not result.any()) + + result = isnull((u('foo'), u('bar'))) + assert(not result.any()) + + def test_isnull_lists(): result = isnull([[False]]) exp = np.array([[False]])
Fix for issue #4872. Now tuple argument for pd.isnull behaves the same way as list pd.isnull(list(tuple_argument)).
https://api.github.com/repos/pandas-dev/pandas/pulls/4952
2013-09-23T15:21:58Z
2013-09-29T02:32:34Z
null
2014-07-06T10:05:54Z
CLN: removed Panel.fillna, replacing within core/generic.py/fillna
diff --git a/doc/source/release.rst b/doc/source/release.rst index 33e421fa55960..efde15bc23d3c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -254,7 +254,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - ``swapaxes`` on a ``Panel`` with the same axes specified now return a copy - support attribute access for setting - - filter supports same api as original ``DataFrame`` filter + - ``filter`` supports same api as original ``DataFrame`` filter + - ``fillna`` refactored to ``core/generic.py``, while > 3ndim is ``NotImplemented`` - Series now inherits from ``NDFrame`` rather than directly from ``ndarray``. There are several minor changes that affect the API. diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 36c3ff9085d87..4553e4804e98b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1569,6 +1569,18 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, return result + # > 3d + if self.ndim > 3: + raise NotImplementedError('cannot fillna with a method for > 3dims') + + # 3d + elif self.ndim == 3: + + # fill in 2d chunks + result = dict([ (col,s.fillna(method=method, value=value)) for col, s in compat.iteritems(self) ]) + return self._constructor.from_dict(result) + + # 2d or less method = com._clean_fill_method(method) new_data = self._data.interpolate(method=method, axis=axis, diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 45101b1e2afd5..5f90eb9fa31a7 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -750,54 +750,6 @@ def _combine_panel(self, other, func): return self._constructor(result_values, items, major, minor) - def fillna(self, value=None, method=None): - """ - Fill NaN values using the specified method. - - Member Series / TimeSeries are filled separately. - - Parameters - ---------- - value : any kind (should be same type as array) - Value to use to fill holes (e.g. 0) - - method : {'backfill', 'bfill', 'pad', 'ffill', None}, default 'pad' - Method to use for filling holes in reindexed Series - - pad / ffill: propagate last valid observation forward to next valid - backfill / bfill: use NEXT valid observation to fill gap - - Returns - ------- - y : DataFrame - - See also - -------- - DataFrame.reindex, DataFrame.asfreq - """ - if isinstance(value, (list, tuple)): - raise TypeError('"value" parameter must be a scalar or dict, but ' - 'you passed a "{0}"'.format(type(value).__name__)) - if value is None: - if method is None: - raise ValueError('must specify a fill method or value') - result = {} - for col, s in compat.iteritems(self): - result[col] = s.fillna(method=method, value=value) - - return self._constructor.from_dict(result) - else: - if method is not None: - raise ValueError('cannot specify both a fill method and value') - new_data = self._data.fillna(value) - return self._constructor(new_data) - - def ffill(self): - return self.fillna(method='ffill') - - def bfill(self): - return self.fillna(method='bfill') - def major_xs(self, key, copy=True): """ Return slice of panel along major axis diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 9b34631ecc894..4f7e75b401216 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -849,23 +849,11 @@ def test_sort_index(self): # assert_panel_equal(sorted_panel, self.panel) def test_fillna(self): + self.assert_(not np.isfinite(self.panel4d.values).all()) filled = self.panel4d.fillna(0) self.assert_(np.isfinite(filled.values).all()) - filled = self.panel4d.fillna(method='backfill') - assert_panel_equal(filled['l1'], - self.panel4d['l1'].fillna(method='backfill')) - - panel4d = self.panel4d.copy() - panel4d['str'] = 'foo' - - filled = panel4d.fillna(method='backfill') - assert_panel_equal(filled['l1'], - panel4d['l1'].fillna(method='backfill')) - - empty = self.panel4d.reindex(labels=[]) - filled = empty.fillna(0) - assert_panel4d_equal(filled, empty) + self.assertRaises(NotImplementedError, self.panel4d.fillna, method='pad') def test_swapaxes(self): result = self.panel4d.swapaxes('labels', 'items')
https://api.github.com/repos/pandas-dev/pandas/pulls/4951
2013-09-23T14:20:55Z
2013-09-23T14:33:56Z
2013-09-23T14:33:56Z
2014-06-21T04:20:45Z
Pairwise versions for rolling_cov, ewmcov and expanding_cov
diff --git a/doc/source/computation.rst b/doc/source/computation.rst index 66e0d457e33b6..7bd3c1aa03d90 100644 --- a/doc/source/computation.rst +++ b/doc/source/computation.rst @@ -59,6 +59,19 @@ The ``Series`` object has a method ``cov`` to compute covariance between series Analogously, ``DataFrame`` has a method ``cov`` to compute pairwise covariances among the series in the DataFrame, also excluding NA/null values. +.. _computation.covariance.caveats: + +.. note:: + + Assuming the missing data are missing at random this results in an estimate + for the covariance matrix which is unbiased. However, for many applications + this estimate may not be acceptable because the estimated covariance matrix + is not guaranteed to be positive semi-definite. This could lead to + estimated correlations having absolute values which are greater than one, + and/or a non-invertible covariance matrix. See `Estimation of covariance + matrices <http://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_matrices>`_ + for more details. + .. ipython:: python frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e']) @@ -99,6 +112,12 @@ correlation methods are provided: All of these are currently computed using pairwise complete observations. +.. note:: + + Please see the :ref:`caveats <computation.covariance.caveats>` associated + with this method of calculating correlation matrices in the + :ref:`covariance section <computation.covariance>`. + .. ipython:: python frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e']) @@ -325,11 +344,14 @@ Binary rolling moments two ``Series`` or any combination of ``DataFrame/Series`` or ``DataFrame/DataFrame``. Here is the behavior in each case: -- two ``Series``: compute the statistic for the pairing +- two ``Series``: compute the statistic for the pairing. - ``DataFrame/Series``: compute the statistics for each column of the DataFrame - with the passed Series, thus returning a DataFrame -- ``DataFrame/DataFrame``: compute statistic for matching column names, - returning a DataFrame + with the passed Series, thus returning a DataFrame. +- ``DataFrame/DataFrame``: by default compute the statistic for matching column + names, returning a DataFrame. If the keyword argument ``pairwise=True`` is + passed then computes the statistic for each pair of columns, returning a + ``Panel`` whose ``items`` are the dates in question (see :ref:`the next section + <stats.moments.corr_pairwise>`). For example: @@ -340,20 +362,42 @@ For example: .. _stats.moments.corr_pairwise: -Computing rolling pairwise correlations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Computing rolling pairwise covariances and correlations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In financial data analysis and other fields it's common to compute correlation -matrices for a collection of time series. More difficult is to compute a -moving-window correlation matrix. This can be done using the -``rolling_corr_pairwise`` function, which yields a ``Panel`` whose ``items`` -are the dates in question: +In financial data analysis and other fields it's common to compute covariance +and correlation matrices for a collection of time series. Often one is also +interested in moving-window covariance and correlation matrices. This can be +done by passing the ``pairwise`` keyword argument, which in the case of +``DataFrame`` inputs will yield a ``Panel`` whose ``items`` are the dates in +question. In the case of a single DataFrame argument the ``pairwise`` argument +can even be omitted: + +.. note:: + + Missing values are ignored and each entry is computed using the pairwise + complete observations. Please see the :ref:`covariance section + <computation.covariance>` for :ref:`caveats + <computation.covariance.caveats>` associated with this method of + calculating covariance and correlation matrices. .. ipython:: python - correls = rolling_corr_pairwise(df, 50) + covs = rolling_cov(df[['B','C','D']], df[['A','B','C']], 50, pairwise=True) + covs[df.index[-50]] + +.. ipython:: python + + correls = rolling_corr(df, 50) correls[df.index[-50]] +.. note:: + + Prior to version 0.14 this was available through ``rolling_corr_pairwise`` + which is now simply syntactic sugar for calling ``rolling_corr(..., + pairwise=True)`` and deprecated. This is likely to be removed in a future + release. + You can efficiently retrieve the time series of correlations between two columns using ``ix`` indexing: diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt index 95537878871b1..344198d6e5ef1 100644 --- a/doc/source/v0.14.0.txt +++ b/doc/source/v0.14.0.txt @@ -183,6 +183,19 @@ These are out-of-bounds selections Because of the default `align` value changes, coordinates of bar plots are now located on integer values (0.0, 1.0, 2.0 ...). This is intended to make bar plot be located on the same coodinates as line plot. However, bar plot may differs unexpectedly when you manually adjust the bar location or drawing area, such as using `set_xlim`, `set_ylim`, etc. In this cases, please modify your script to meet with new coordinates. +- ``pairwise`` keyword was added to the statistical moment functions + ``rolling_cov``, ``rolling_corr``, ``ewmcov``, ``ewmcorr``, + ``expanding_cov``, ``expanding_corr`` to allow the calculation of moving + window covariance and correlation matrices (:issue:`4950`). See + :ref:`Computing rolling pairwise covariances and correlations + <stats.moments.corr_pairwise>` in the docs. + + .. ipython:: python + + df = DataFrame(np.random.randn(10,4),columns=list('ABCD')) + covs = rolling_cov(df[['A','B','C']], df[['B','C','D']], 5, pairwise=True) + covs[df.index[-1]] + MultiIndexing Using Slicers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/stats/moments.py b/pandas/stats/moments.py index ec01113abc8f2..523f055eaf605 100644 --- a/pandas/stats/moments.py +++ b/pandas/stats/moments.py @@ -5,14 +5,14 @@ from __future__ import division from functools import wraps +from collections import defaultdict from numpy import NaN import numpy as np from pandas.core.api import DataFrame, Series, Panel, notnull import pandas.algos as algos -import pandas.core.common as com -from pandas.core.common import _values_from_object +import pandas.core.common as pdcom from pandas.util.decorators import Substitution, Appender @@ -31,13 +31,22 @@ #------------------------------------------------------------------------------ # Docs +# The order of arguments for the _doc_template is: +# (header, args, kwargs, returns, notes) + _doc_template = """ %s Parameters ---------- +%s%s +Returns +------- +%s %s -window : int +""" + +_roll_kw = """window : int Size of the moving window. This is the number of observations used for calculating the statistic. min_periods : int, default None @@ -49,11 +58,9 @@ for `freq`. center : boolean, default False Set the labels at the center of the window. - -Returns -------- -%s +""" +_roll_notes = r""" Notes ----- By default, the result is set to the right edge of the window. This can be @@ -65,12 +72,7 @@ """ -_ewm_doc = r"""%s - -Parameters ----------- -%s -com : float. optional +_ewm_kw = r"""com : float. optional Center of mass: :math:`\alpha = 1 / (1 + com)`, span : float, optional Specify decay in terms of span, :math:`\alpha = 2 / (span + 1)` @@ -85,8 +87,9 @@ adjust : boolean, default True Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average) +""" -%s +_ewm_notes = """ Notes ----- Either center of mass or span must be specified @@ -99,55 +102,51 @@ :math:`c = (s - 1) / 2` So a "20-day EWMA" would have center 9.5. - -Returns -------- -y : type of input argument """ - -_expanding_doc = """ -%s - -Parameters ----------- -%s -min_periods : int, default None +_expanding_kw = """min_periods : int, default None Minimum number of observations in window required to have a value (otherwise result is NA). freq : string or DateOffset object, optional (default None) Frequency to conform the data to before computing the statistic. Specified as a frequency string or DateOffset object. `time_rule` is a legacy alias for `freq`. - -Returns -------- -%s - -Notes ------ -The `freq` keyword is used to conform time series data to a specified -frequency by resampling the data. This is done with the default parameters -of :meth:`~pandas.Series.resample` (i.e. using the `mean`). """ -_type_of_input = "y : type of input argument" +_type_of_input_retval = "y : type of input argument" _flex_retval = """y : type depends on inputs - DataFrame / DataFrame -> DataFrame (matches on columns) + DataFrame / DataFrame -> DataFrame (matches on columns) or Panel (pairwise) DataFrame / Series -> Computes result for each column Series / Series -> Series""" -_unary_arg = "arg : Series, DataFrame" +_pairwise_retval = "y : Panel whose items are df1.index values" + +_unary_arg = "arg : Series, DataFrame\n" _binary_arg_flex = """arg1 : Series, DataFrame, or ndarray -arg2 : Series, DataFrame, or ndarray""" +arg2 : Series, DataFrame, or ndarray, optional + if not supplied then will default to arg1 and produce pairwise output +""" _binary_arg = """arg1 : Series, DataFrame, or ndarray -arg2 : Series, DataFrame, or ndarray""" +arg2 : Series, DataFrame, or ndarray +""" + +_pairwise_arg = """df1 : DataFrame +df2 : DataFrame +""" + +_pairwise_kw = """pairwise : bool, default False + If False then only matching columns between arg1 and arg2 will be used and + the output will be a DataFrame. + If True then all pairwise combinations will be calculated and the output + will be a Panel in the case of DataFrame inputs. In the case of missing + elements, only complete pairwise observations will be used. +""" -_bias_doc = r"""bias : boolean, default False +_bias_kw = r"""bias : boolean, default False Use a standard estimation bias correction """ @@ -194,27 +193,47 @@ def rolling_count(arg, window, freq=None, center=False, time_rule=None): return return_hook(result) -@Substitution("Unbiased moving covariance.", _binary_arg_flex, _flex_retval) +@Substitution("Unbiased moving covariance.", _binary_arg_flex, + _roll_kw+_pairwise_kw, _flex_retval, _roll_notes) @Appender(_doc_template) -def rolling_cov(arg1, arg2, window, min_periods=None, freq=None, - center=False, time_rule=None): +def rolling_cov(arg1, arg2=None, window=None, min_periods=None, freq=None, + center=False, time_rule=None, pairwise=None): + if window is None and isinstance(arg2, (int, float)): + window = arg2 + arg2 = arg1 + pairwise = True if pairwise is None else pairwise # only default unset + elif arg2 is None: + arg2 = arg1 + pairwise = True if pairwise is None else pairwise # only default unset arg1 = _conv_timerule(arg1, freq, time_rule) arg2 = _conv_timerule(arg2, freq, time_rule) window = min(window, len(arg1), len(arg2)) def _get_cov(X, Y): - mean = lambda x: rolling_mean(x, window, min_periods,center=center) - count = rolling_count(X + Y, window,center=center) + mean = lambda x: rolling_mean(x, window, min_periods, center=center) + count = rolling_count(X + Y, window, center=center) bias_adj = count / (count - 1) return (mean(X * Y) - mean(X) * mean(Y)) * bias_adj - rs = _flex_binary_moment(arg1, arg2, _get_cov) + rs = _flex_binary_moment(arg1, arg2, _get_cov, pairwise=bool(pairwise)) return rs -@Substitution("Moving sample correlation.", _binary_arg_flex, _flex_retval) +@Substitution("Moving sample correlation.", _binary_arg_flex, + _roll_kw+_pairwise_kw, _flex_retval, _roll_notes) @Appender(_doc_template) -def rolling_corr(arg1, arg2, window, min_periods=None, freq=None, - center=False, time_rule=None): +def rolling_corr(arg1, arg2=None, window=None, min_periods=None, freq=None, + center=False, time_rule=None, pairwise=None): + if window is None and isinstance(arg2, (int, float)): + window = arg2 + arg2 = arg1 + pairwise = True if pairwise is None else pairwise # only default unset + elif arg2 is None: + arg2 = arg1 + pairwise = True if pairwise is None else pairwise # only default unset + arg1 = _conv_timerule(arg1, freq, time_rule) + arg2 = _conv_timerule(arg2, freq, time_rule) + window = min(window, len(arg1), len(arg2)) + def _get_corr(a, b): num = rolling_cov(a, b, window, min_periods, freq=freq, center=center, time_rule=time_rule) @@ -223,16 +242,17 @@ def _get_corr(a, b): rolling_std(b, window, min_periods, freq=freq, center=center, time_rule=time_rule)) return num / den - return _flex_binary_moment(arg1, arg2, _get_corr) + return _flex_binary_moment(arg1, arg2, _get_corr, pairwise=bool(pairwise)) -def _flex_binary_moment(arg1, arg2, f): +def _flex_binary_moment(arg1, arg2, f, pairwise=False): if not (isinstance(arg1,(np.ndarray, Series, DataFrame)) and isinstance(arg2,(np.ndarray, Series, DataFrame))): raise TypeError("arguments to moment function must be of type " "np.ndarray/Series/DataFrame") - if isinstance(arg1, (np.ndarray,Series)) and isinstance(arg2, (np.ndarray,Series)): + if isinstance(arg1, (np.ndarray, Series)) and \ + isinstance(arg2, (np.ndarray,Series)): X, Y = _prep_binary(arg1, arg2) return f(X, Y) elif isinstance(arg1, DataFrame): @@ -241,10 +261,23 @@ def _flex_binary_moment(arg1, arg2, f): X, Y = arg1.align(arg2, join='outer') X = X + 0 * Y Y = Y + 0 * X - res_columns = arg1.columns.union(arg2.columns) - for col in res_columns: - if col in X and col in Y: - results[col] = f(X[col], Y[col]) + if pairwise is False: + res_columns = arg1.columns.union(arg2.columns) + for col in res_columns: + if col in X and col in Y: + results[col] = f(X[col], Y[col]) + elif pairwise is True: + results = defaultdict(dict) + for i, k1 in enumerate(arg1.columns): + for j, k2 in enumerate(arg2.columns): + if j<i and arg2 is arg1: + # Symmetric case + results[k1][k2] = results[k2][k1] + else: + results[k1][k2] = f(arg1[k1], arg2[k2]) + return Panel.from_dict(results).swapaxes('items', 'major') + else: + raise ValueError("'pairwise' is not True/False") else: res_columns = arg1.columns X, Y = arg1.align(arg2, axis=0, join='outer') @@ -258,38 +291,17 @@ def _flex_binary_moment(arg1, arg2, f): return _flex_binary_moment(arg2, arg1, f) -def rolling_corr_pairwise(df, window, min_periods=None): - """ - Computes pairwise rolling correlation matrices as Panel whose items are - dates. - - Parameters - ---------- - df : DataFrame - window : int - Size of the moving window. This is the number of observations used for - calculating the statistic. - min_periods : int, default None - Minimum number of observations in window required to have a value - (otherwise result is NA). - - Returns - ------- - correls : Panel - """ - from pandas import Panel - from collections import defaultdict - - all_results = defaultdict(dict) - - for i, k1 in enumerate(df.columns): - for k2 in df.columns[i:]: - corr = rolling_corr(df[k1], df[k2], window, - min_periods=min_periods) - all_results[k1][k2] = corr - all_results[k2][k1] = corr - - return Panel.from_dict(all_results).swapaxes('items', 'major') +@Substitution("Deprecated. Use rolling_corr(..., pairwise=True) instead.\n\n" + "Pairwise moving sample correlation", _pairwise_arg, + _roll_kw, _pairwise_retval, _roll_notes) +@Appender(_doc_template) +def rolling_corr_pairwise(df1, df2=None, window=None, min_periods=None, + freq=None, center=False, time_rule=None): + import warnings + warnings.warn("rolling_corr_pairwise is deprecated, use rolling_corr(..., pairwise=True)", FutureWarning) + return rolling_corr(df1, df2, window=window, min_periods=min_periods, + freq=freq, center=center, time_rule=time_rule, + pairwise=True) def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center=False, @@ -338,7 +350,8 @@ def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center=False, def _center_window(rs, window, axis): if axis > rs.ndim-1: - raise ValueError("Requested axis is larger then no. of argument dimensions") + raise ValueError("Requested axis is larger then no. of argument " + "dimensions") offset = int((window - 1) / 2.) if isinstance(rs, (Series, DataFrame, Panel)): @@ -401,8 +414,9 @@ def _get_center_of_mass(com, span, halflife): return float(com) -@Substitution("Exponentially-weighted moving average", _unary_arg, "") -@Appender(_ewm_doc) +@Substitution("Exponentially-weighted moving average", _unary_arg, _ewm_kw, + _type_of_input_retval, _ewm_notes) +@Appender(_doc_template) def ewma(arg, com=None, span=None, halflife=None, min_periods=0, freq=None, time_rule=None, adjust=True): com = _get_center_of_mass(com, span, halflife) @@ -424,8 +438,9 @@ def _first_valid_index(arr): return notnull(arr).argmax() if len(arr) else 0 -@Substitution("Exponentially-weighted moving variance", _unary_arg, _bias_doc) -@Appender(_ewm_doc) +@Substitution("Exponentially-weighted moving variance", _unary_arg, + _ewm_kw+_bias_kw, _type_of_input_retval, _ewm_notes) +@Appender(_doc_template) def ewmvar(arg, com=None, span=None, halflife=None, min_periods=0, bias=False, freq=None, time_rule=None): com = _get_center_of_mass(com, span, halflife) @@ -440,8 +455,9 @@ def ewmvar(arg, com=None, span=None, halflife=None, min_periods=0, bias=False, return result -@Substitution("Exponentially-weighted moving std", _unary_arg, _bias_doc) -@Appender(_ewm_doc) +@Substitution("Exponentially-weighted moving std", _unary_arg, + _ewm_kw+_bias_kw, _type_of_input_retval, _ewm_notes) +@Appender(_doc_template) def ewmstd(arg, com=None, span=None, halflife=None, min_periods=0, bias=False, time_rule=None): result = ewmvar(arg, com=com, span=span, halflife=halflife, time_rule=time_rule, @@ -451,38 +467,56 @@ def ewmstd(arg, com=None, span=None, halflife=None, min_periods=0, bias=False, ewmvol = ewmstd -@Substitution("Exponentially-weighted moving covariance", _binary_arg, "") -@Appender(_ewm_doc) -def ewmcov(arg1, arg2, com=None, span=None, halflife=None, min_periods=0, bias=False, - freq=None, time_rule=None): - X, Y = _prep_binary(arg1, arg2) - - X = _conv_timerule(X, freq, time_rule) - Y = _conv_timerule(Y, freq, time_rule) - - mean = lambda x: ewma(x, com=com, span=span, halflife=halflife, min_periods=min_periods) +@Substitution("Exponentially-weighted moving covariance", _binary_arg_flex, + _ewm_kw+_pairwise_kw, _type_of_input_retval, _ewm_notes) +@Appender(_doc_template) +def ewmcov(arg1, arg2=None, com=None, span=None, halflife=None, min_periods=0, bias=False, + freq=None, time_rule=None, pairwise=None): + if arg2 is None: + arg2 = arg1 + pairwise = True if pairwise is None else pairwise + elif isinstance(arg2, (int, float)) and com is None: + com = arg2 + arg2 = arg1 + pairwise = True if pairwise is None else pairwise + arg1 = _conv_timerule(arg1, freq, time_rule) + arg2 = _conv_timerule(arg2, freq, time_rule) - result = (mean(X * Y) - mean(X) * mean(Y)) - com = _get_center_of_mass(com, span, halflife) + def _get_ewmcov(X, Y): + mean = lambda x: ewma(x, com=com, span=span, halflife=halflife, min_periods=min_periods) + return (mean(X * Y) - mean(X) * mean(Y)) + result = _flex_binary_moment(arg1, arg2, _get_ewmcov, + pairwise=bool(pairwise)) if not bias: + com = _get_center_of_mass(com, span, halflife) result *= (1.0 + 2.0 * com) / (2.0 * com) return result -@Substitution("Exponentially-weighted moving " "correlation", _binary_arg, "") -@Appender(_ewm_doc) -def ewmcorr(arg1, arg2, com=None, span=None, halflife=None, min_periods=0, - freq=None, time_rule=None): - X, Y = _prep_binary(arg1, arg2) - - X = _conv_timerule(X, freq, time_rule) - Y = _conv_timerule(Y, freq, time_rule) +@Substitution("Exponentially-weighted moving correlation", _binary_arg_flex, + _ewm_kw+_pairwise_kw, _type_of_input_retval, _ewm_notes) +@Appender(_doc_template) +def ewmcorr(arg1, arg2=None, com=None, span=None, halflife=None, min_periods=0, + freq=None, time_rule=None, pairwise=None): + if arg2 is None: + arg2 = arg1 + pairwise = True if pairwise is None else pairwise + elif isinstance(arg2, (int, float)) and com is None: + com = arg2 + arg2 = arg1 + pairwise = True if pairwise is None else pairwise + arg1 = _conv_timerule(arg1, freq, time_rule) + arg2 = _conv_timerule(arg2, freq, time_rule) - mean = lambda x: ewma(x, com=com, span=span, halflife=halflife, min_periods=min_periods) - var = lambda x: ewmvar(x, com=com, span=span, halflife=halflife, min_periods=min_periods, - bias=True) - return (mean(X * Y) - mean(X) * mean(Y)) / _zsqrt(var(X) * var(Y)) + def _get_ewmcorr(X, Y): + mean = lambda x: ewma(x, com=com, span=span, halflife=halflife, min_periods=min_periods) + var = lambda x: ewmvar(x, com=com, span=span, halflife=halflife, min_periods=min_periods, + bias=True) + return (mean(X * Y) - mean(X) * mean(Y)) / _zsqrt(var(X) * var(Y)) + result = _flex_binary_moment(arg1, arg2, _get_ewmcorr, + pairwise=bool(pairwise)) + return result def _zsqrt(x): @@ -546,7 +580,7 @@ def _use_window(minp, window): def _rolling_func(func, desc, check_minp=_use_window): - @Substitution(desc, _unary_arg, _type_of_input) + @Substitution(desc, _unary_arg, _roll_kw, _type_of_input_retval, _roll_notes) @Appender(_doc_template) @wraps(func) def f(arg, window, min_periods=None, freq=None, center=False, @@ -729,8 +763,8 @@ def rolling_window(arg, window=None, win_type=None, min_periods=None, if win_type is not None: raise ValueError(('Do not specify window type if using custom ' 'weights')) - window = com._asarray_tuplesafe(window).astype(float) - elif com.is_integer(window): # window size + window = pdcom._asarray_tuplesafe(window).astype(float) + elif pdcom.is_integer(window): # window size if win_type is None: raise ValueError('Must specify window type') try: @@ -779,8 +813,8 @@ def _pop_args(win_type, arg_names, kwargs): def _expanding_func(func, desc, check_minp=_use_window): - @Substitution(desc, _unary_arg, _type_of_input) - @Appender(_expanding_doc) + @Substitution(desc, _unary_arg, _expanding_kw, _type_of_input_retval, "") + @Appender(_doc_template) @wraps(func) def f(arg, min_periods=1, freq=None, center=False, time_rule=None, **kwargs): @@ -876,46 +910,54 @@ def expanding_quantile(arg, quantile, min_periods=1, freq=None, freq=freq, center=center, time_rule=time_rule) -@Substitution("Unbiased expanding covariance.", _binary_arg_flex, _flex_retval) -@Appender(_expanding_doc) -def expanding_cov(arg1, arg2, min_periods=1, freq=None, center=False, - time_rule=None): +@Substitution("Unbiased expanding covariance.", _binary_arg_flex, + _expanding_kw+_pairwise_kw, _flex_retval, "") +@Appender(_doc_template) +def expanding_cov(arg1, arg2=None, min_periods=1, freq=None, center=False, + time_rule=None, pairwise=None): + if arg2 is None: + arg2 = arg1 + pairwise = True if pairwise is None else pairwise + elif isinstance(arg2, (int, float)) and min_periods is None: + min_periods = arg2 + arg2 = arg1 + pairwise = True if pairwise is None else pairwise window = max(len(arg1), len(arg2)) return rolling_cov(arg1, arg2, window, min_periods=min_periods, freq=freq, - center=center, time_rule=time_rule) + center=center, time_rule=time_rule, pairwise=pairwise) -@Substitution("Expanding sample correlation.", _binary_arg_flex, _flex_retval) -@Appender(_expanding_doc) -def expanding_corr(arg1, arg2, min_periods=1, freq=None, center=False, - time_rule=None): +@Substitution("Expanding sample correlation.", _binary_arg_flex, + _expanding_kw+_pairwise_kw, _flex_retval, "") +@Appender(_doc_template) +def expanding_corr(arg1, arg2=None, min_periods=1, freq=None, center=False, + time_rule=None, pairwise=None): + if arg2 is None: + arg2 = arg1 + pairwise = True if pairwise is None else pairwise + elif isinstance(arg2, (int, float)) and min_periods is None: + min_periods = arg2 + arg2 = arg1 + pairwise = True if pairwise is None else pairwise window = max(len(arg1), len(arg2)) return rolling_corr(arg1, arg2, window, min_periods=min_periods, - freq=freq, center=center, time_rule=time_rule) - + freq=freq, center=center, time_rule=time_rule, + pairwise=pairwise) -def expanding_corr_pairwise(df, min_periods=1): - """ - Computes pairwise expanding correlation matrices as Panel whose items are - dates. - - Parameters - ---------- - df : DataFrame - min_periods : int, default 1 - Minimum number of observations in window required to have a value - (otherwise result is NA). - Returns - ------- - correls : Panel - """ - - window = len(df) - - return rolling_corr_pairwise(df, window, min_periods=min_periods) +@Substitution("Deprecated. Use expanding_corr(..., pairwise=True) instead.\n\n" + "Pairwise expanding sample correlation", _pairwise_arg, + _expanding_kw, _pairwise_retval, "") +@Appender(_doc_template) +def expanding_corr_pairwise(df1, df2=None, min_periods=1, freq=None, + center=False, time_rule=None): + import warnings + warnings.warn("expanding_corr_pairwise is deprecated, use expanding_corr(..., pairwise=True)", FutureWarning) + return expanding_corr(df1, df2, min_periods=min_periods, + freq=freq, center=center, time_rule=time_rule, + pairwise=True) def expanding_apply(arg, func, min_periods=1, freq=None, center=False, diff --git a/pandas/stats/tests/test_moments.py b/pandas/stats/tests/test_moments.py index a8359c102a902..97f08e7052c87 100644 --- a/pandas/stats/tests/test_moments.py +++ b/pandas/stats/tests/test_moments.py @@ -586,6 +586,9 @@ def test_rolling_cov(self): result = mom.rolling_cov(A, B, 50, min_periods=25) assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1]) + def test_rolling_cov_pairwise(self): + self._check_pairwise_moment(mom.rolling_cov, 10, min_periods=5) + def test_rolling_corr(self): A = self.series B = A + randn(len(A)) @@ -603,12 +606,14 @@ def test_rolling_corr(self): assert_almost_equal(result[-1], a.corr(b)) def test_rolling_corr_pairwise(self): - panel = mom.rolling_corr_pairwise(self.frame, 10, min_periods=5) + self._check_pairwise_moment(mom.rolling_corr, 10, min_periods=5) + + def _check_pairwise_moment(self, func, *args, **kwargs): + panel = func(self.frame, *args, **kwargs) - correl = panel.ix[:, 1, 5] - exp = mom.rolling_corr(self.frame[1], self.frame[5], - 10, min_periods=5) - tm.assert_series_equal(correl, exp) + actual = panel.ix[:, 1, 5] + expected = func(self.frame[1], self.frame[5], *args, **kwargs) + tm.assert_series_equal(actual, expected) def test_flex_binary_moment(self): # GH3155 @@ -666,9 +671,15 @@ def _check(method): def test_ewmcov(self): self._check_binary_ew(mom.ewmcov) + def test_ewmcov_pairwise(self): + self._check_pairwise_moment(mom.ewmcov, span=10, min_periods=5) + def test_ewmcorr(self): self._check_binary_ew(mom.ewmcorr) + def test_ewmcorr_pairwise(self): + self._check_pairwise_moment(mom.ewmcorr, span=10, min_periods=5) + def _check_binary_ew(self, func): A = Series(randn(50), index=np.arange(50)) B = A[2:] + randn(48) @@ -746,12 +757,20 @@ def test_expanding_cov(self): def test_expanding_max(self): self._check_expanding(mom.expanding_max, np.max, preserve_nan=False) + def test_expanding_cov_pairwise(self): + result = mom.expanding_cov(self.frame) + + rolling_result = mom.rolling_cov(self.frame, len(self.frame), + min_periods=1) + + for i in result.items: + assert_almost_equal(result[i], rolling_result[i]) + def test_expanding_corr_pairwise(self): - result = mom.expanding_corr_pairwise(self.frame) + result = mom.expanding_corr(self.frame) - rolling_result = mom.rolling_corr_pairwise(self.frame, - len(self.frame), - min_periods=1) + rolling_result = mom.rolling_corr(self.frame, len(self.frame), + min_periods=1) for i in result.items: assert_almost_equal(result[i], rolling_result[i])
I added the functions rolling_cov_pairwise(), expanding_cov_pairwise() and ewmcov_pairwise(). I also modified the behaviour of rolling_corr_pairwise(), expanding_corr_pairwise() and ewmcorr_pairwise() slightly so that now these can be computed between different DataFrames and the resulting matrices at each time slice will be rectangular rather than square. I think this is what was asked for in the original discussion that gave rise to issue #1853. Fixes #1853
https://api.github.com/repos/pandas-dev/pandas/pulls/4950
2013-09-23T12:23:36Z
2014-03-28T14:47:49Z
2014-03-28T14:47:49Z
2014-06-12T17:47:11Z
BUG: Conflict between thousands sep and date parser.
diff --git a/doc/source/release.rst b/doc/source/release.rst index 75097ee50e8c1..cd0a2ba6e3884 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -447,6 +447,7 @@ Bug Fixes - Fixed a bug in ``convert_objects`` for > 2 ndims (:issue:`4937`) - Fixed a bug in DataFrame/Panel cache insertion and subsequent indexing (:issue:`4939`) - Fixed string methods for ``FrozenNDArray`` and ``FrozenList`` (:issue:`4929`) + - Fixed conflict between thousands separator and date parser in csv_parser (:issue:`4678`) pandas 0.12.0 ------------- diff --git a/pandas/io/date_converters.py b/pandas/io/date_converters.py index 2be477f49e28b..5c99ab4d0a664 100644 --- a/pandas/io/date_converters.py +++ b/pandas/io/date_converters.py @@ -26,7 +26,7 @@ def parse_all_fields(year_col, month_col, day_col, hour_col, minute_col, minute_col = _maybe_cast(minute_col) second_col = _maybe_cast(second_col) return lib.try_parse_datetime_components(year_col, month_col, day_col, - hour_col, minute_col, second_col) + hour_col, minute_col, second_col) def generic_parser(parse_func, *cols): diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 7b9347a821fad..c109508ea2c19 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1020,6 +1020,14 @@ def _set(x): else: _set(val) + elif isinstance(self.parse_dates, dict): + for val in self.parse_dates.values(): + if isinstance(val, list): + for k in val: + _set(k) + else: + _set(val) + def set_error_bad_lines(self, status): self._reader.set_error_bad_lines(int(status)) @@ -1269,6 +1277,7 @@ def __init__(self, f, **kwds): self._make_reader(f) else: self.data = f + self.columns = self._infer_columns() # we are processing a multi index column @@ -1292,6 +1301,38 @@ def __init__(self, f, **kwds): self.index_names = index_names self._first_chunk = True + if self.parse_dates: + self._no_thousands_columns = self._set_no_thousands_columns() + else: + self._no_thousands_columns = None + + def _set_no_thousands_columns(self): + # Create a set of column ids that are not to be stripped of thousands operators. + noconvert_columns = set() + + def _set(x): + if com.is_integer(x): + noconvert_columns.add(x) + else: + noconvert_columns.add(self.columns.index(x)) + + if isinstance(self.parse_dates, list): + for val in self.parse_dates: + if isinstance(val, list): + for k in val: + _set(k) + else: + _set(val) + + elif isinstance(self.parse_dates, dict): + for val in self.parse_dates.values(): + if isinstance(val, list): + for k in val: + _set(k) + else: + _set(val) + return noconvert_columns + def _make_reader(self, f): sep = self.delimiter @@ -1500,7 +1541,6 @@ def _next_line(self): line = next(self.data) line = self._check_comments([line])[0] - line = self._check_thousands([line])[0] self.pos += 1 self.buf.append(line) @@ -1532,9 +1572,10 @@ def _check_thousands(self, lines): ret = [] for l in lines: rl = [] - for x in l: + for i, x in enumerate(l): if (not isinstance(x, compat.string_types) or self.thousands not in x or + (self._no_thousands_columns and i in self._no_thousands_columns) or nonnum.search(x.strip())): rl.append(x) else: @@ -1608,7 +1649,6 @@ def _rows_to_cols(self, content): raise AssertionError() if col_len != zip_len and self.index_col is not False: - row_num = -1 i = 0 for (i, l) in enumerate(content): if len(l) != col_len: diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index fb2b3fdd33bf1..6c32224dc7808 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -233,6 +233,18 @@ def test_1000_sep_with_decimal(self): df = self.read_table(StringIO(data_with_odd_sep), sep='|', thousands='.', decimal=',') tm.assert_frame_equal(df, expected) + def test_separator_date_conflict(self): + # Regression test for issue #4678: make sure thousands separator and + # date parsing do not conflict. + data = '06-02-2013;13:00;1-000.215' + expected = DataFrame( + [[datetime(2013, 6, 2, 13, 0, 0), 1000.215]], + columns=['Date', 2] + ) + + df = self.read_csv(StringIO(data), sep=';', thousands='-', parse_dates={'Date': [0, 1]}, header=None) + tm.assert_frame_equal(df, expected) + def test_squeeze(self): data = """\ a,1 diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index e0bbc1a4e64c1..2a3f85b550a7c 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -708,20 +708,22 @@ def try_parse_datetime_components(ndarray[object] years, Py_ssize_t i, n ndarray[object] result int secs + double float_secs double micros from datetime import datetime n = len(years) - if (len(months) != n and len(days) != n and len(hours) != n and - len(minutes) != n and len(seconds) != n): + if (len(months) != n or len(days) != n or len(hours) != n or + len(minutes) != n or len(seconds) != n): raise ValueError('Length of all datetime components must be equal') result = np.empty(n, dtype='O') for i from 0 <= i < n: - secs = int(seconds[i]) + float_secs = float(seconds[i]) + secs = int(float_secs) - micros = seconds[i] - secs + micros = float_secs - secs if micros > 0: micros = micros * 1000000
closes #4678 closes #4322 I've fixed the C parser portion. The issue there was that it did not handle the case where parse_dates is a dict. Python parser fix yet to come. That test still fails. Example: s = '06-02-2013;13:00;1-000,215;0,215;0,185;0,205;0,00' d = pd.read_csv(StringIO(s), header=None, parse_dates={'Date': [0, 1]}, thousands='-', sep=';', decimal=',') Then d should have a column 'Date' with value "2013-06-02 13:00:00"
https://api.github.com/repos/pandas-dev/pandas/pulls/4945
2013-09-23T03:43:26Z
2013-09-26T01:03:38Z
2013-09-26T01:03:38Z
2014-06-24T14:30:24Z
DOC: Added to docstrings in factorize function GH2916
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index f6b1131120aa6..5778a524a584a 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -109,9 +109,13 @@ def factorize(values, sort=False, order=None, na_sentinel=-1): Parameters ---------- - values : sequence - sort : + values : ndarray (1-d) + Sequence + sort : boolean, default False + Sort by values order : + na_sentinel: int, default -1 + Value to mark "not found" Returns -------
https://api.github.com/repos/pandas-dev/pandas/pulls/4944
2013-09-23T03:16:10Z
2013-09-26T00:51:38Z
2013-09-26T00:51:38Z
2014-06-27T14:49:45Z
BUG: Fixed a bug with setting invalid or out-of-range values in indexing enlargement scenarios (GH4940)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 444f25e8662bd..33e421fa55960 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -449,6 +449,8 @@ Bug Fixes - Fixed a bug in ``convert_objects`` for > 2 ndims (:issue:`4937`) - Fixed a bug in DataFrame/Panel cache insertion and subsequent indexing (:issue:`4939`) - Fixed string methods for ``FrozenNDArray`` and ``FrozenList`` (:issue:`4929`) + - Fixed a bug with setting invalid or out-of-range values in indexing + enlargement scenarios (:issue:`4940`) pandas 0.12.0 ------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 3779e78599bde..cb738df6966da 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -750,6 +750,13 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): is_int_index = _is_integer_index(labels) if com.is_integer(obj) and not is_int_index: + + # if we are setting and its not a valid location + # its an insert which fails by definition + if is_setter: + if obj >= len(self.obj) and not isinstance(labels, MultiIndex): + raise ValueError("cannot set by positional indexing with enlargement") + return obj try: @@ -1340,7 +1347,12 @@ def _safe_append_to_index(index, key): try: return index.insert(len(index), key) except: - return Index(np.concatenate([index.asobject.values,np.array([key])])) + + # raise here as this is basically an unsafe operation and we want + # it to be obvious that you are doing something wrong + + raise ValueError("unsafe appending to index of " + "type {0} with a key {1}".format(index.__class__.__name__,key)) def _maybe_convert_indices(indices, n): """ if we have negative indicies, translate to postive here diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index e0a9d2b937225..45543547fd64b 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -1078,6 +1078,12 @@ def test_icol(self): def test_set_value(self): + # this is invalid because it is not a valid type for this index + self.assertRaises(ValueError, self.frame.set_value, 'foobar', 'B', 1.5) + + res = self.frame + res.index = res.index.astype(object) + res = self.frame.set_value('foobar', 'B', 1.5) self.assert_(res is not self.frame) self.assert_(res.index[-1] == 'foobar') diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 267cc8605366c..ced4cbdc4dc36 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1480,6 +1480,30 @@ def test_series_partial_set(self): result = ser.iloc[[1,1,0,0]] assert_series_equal(result, expected) + def test_partial_set_invalid(self): + + # GH 4940 + # allow only setting of 'valid' values + + df = tm.makeTimeDataFrame() + + def f(): + df.loc[100.0, :] = df.ix[0] + self.assertRaises(ValueError, f) + def f(): + df.loc[100,:] = df.ix[0] + self.assertRaises(ValueError, f) + def f(): + df.loc['a',:] = df.ix[0] + self.assertRaises(ValueError, f) + + def f(): + df.ix[100.0, :] = df.ix[0] + self.assertRaises(ValueError, f) + def f(): + df.ix[100,:] = df.ix[0] + self.assertRaises(ValueError, f) + def test_cache_updating(self): # GH 4939, make sure to update the cache on setitem
closes #4940
https://api.github.com/repos/pandas-dev/pandas/pulls/4943
2013-09-23T01:08:07Z
2013-09-23T11:38:40Z
2013-09-23T11:38:40Z
2014-06-23T14:34:13Z
BUG: Fixed a bug in DataFrame/Panel cache insertion and subsequent indexing GH4939
diff --git a/doc/source/release.rst b/doc/source/release.rst index 789fbd0fe4ccc..b7b5c8835a265 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -438,6 +438,7 @@ Bug Fixes - Fixed a bug in ``Series.hist`` where two figures were being created when the ``by`` argument was passed (:issue:`4112`, :issue:`4113`). - Fixed a bug in ``convert_objects`` for > 2 ndims (:issue:`4937`) + - Fixed a bug in DataFrame/Panel cache insertion and subsequent indexing (:issue:`4939`) pandas 0.12.0 ------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 53d3687854cac..36c3ff9085d87 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -825,14 +825,20 @@ def _maybe_cache_changed(self, item, value): maybe it has changed """ self._data.set(item, value) - def _maybe_update_cacher(self): - """ see if we need to update our parent cacher """ + def _maybe_update_cacher(self, clear=False): + """ see if we need to update our parent cacher + if clear, then clear our cache """ cacher = getattr(self,'_cacher',None) if cacher is not None: cacher[1]()._maybe_cache_changed(cacher[0],self) + if clear: + self._clear_item_cache() - def _clear_item_cache(self): - self._item_cache.clear() + def _clear_item_cache(self, i=None): + if i is not None: + self._item_cache.pop(i,None) + else: + self._item_cache.clear() def _set_item(self, key, value): self._data.set(key, value) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 4f5e6623e1512..3779e78599bde 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -190,12 +190,14 @@ def _setitem_with_indexer(self, indexer, value): new_values = np.concatenate([self.obj.values, [value]]) self.obj._data = self.obj._constructor(new_values, index=new_index, name=self.obj.name) + self.obj._maybe_update_cacher(clear=True) return self.obj elif self.ndim == 2: index = self.obj._get_axis(0) labels = _safe_append_to_index(index, indexer) self.obj._data = self.obj.reindex_axis(labels,0)._data + self.obj._maybe_update_cacher(clear=True) return getattr(self.obj,self.name).__setitem__(indexer,value) # set using setitem (Panel and > dims) @@ -255,6 +257,7 @@ def setter(item, v): # set the item, possibly having a dtype change s = s.copy() s._data = s._data.setitem(pi,v) + s._maybe_update_cacher(clear=True) self.obj[item] = s def can_do_equal_len(): @@ -327,6 +330,7 @@ def can_do_equal_len(): value = self._align_panel(indexer, value) self.obj._data = self.obj._data.setitem(indexer,value) + self.obj._maybe_update_cacher(clear=True) def _align_series(self, indexer, ser): # indexer to assign Series can be tuple or scalar diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index aad9fb2f95483..267cc8605366c 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1480,6 +1480,21 @@ def test_series_partial_set(self): result = ser.iloc[[1,1,0,0]] assert_series_equal(result, expected) + def test_cache_updating(self): + # GH 4939, make sure to update the cache on setitem + + df = tm.makeDataFrame() + df['A'] # cache series + df.ix["Hello Friend"] = df.ix[0] + self.assert_("Hello Friend" in df['A'].index) + self.assert_("Hello Friend" in df['B'].index) + + panel = tm.makePanel() + panel.ix[0] # get first item into cache + panel.ix[:, :, 'A+1'] = panel.ix[:, :, 'A'] + 1 + self.assert_("A+1" in panel.ix[0].columns) + self.assert_("A+1" in panel.ix[1].columns) + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
closes #4939
https://api.github.com/repos/pandas-dev/pandas/pulls/4942
2013-09-22T23:59:54Z
2013-09-23T00:24:59Z
2013-09-23T00:24:59Z
2014-06-20T04:53:26Z
DOC: add dynamically generated doc-strings for generic functions
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index a2531ebd43c82..47a5bb8f56a4f 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -180,8 +180,13 @@ class to receive bound method def u(s): return s + def u_safe(s): return s + + def function_object(f): + return f + else: string_types = basestring, integer_types = (int, long) @@ -198,6 +203,9 @@ def u_safe(s): except: return s + def function_object(f): + return f.im_func + string_and_binary_types = string_types + (binary_type,) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 799d96f46a15b..80b8f5825599c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4716,7 +4716,7 @@ def combineMult(self, other): DataFrame._setup_axes( ['index', 'columns'], info_axis=1, stat_axis=0, axes_are_reversed=True) - +DataFrame._setup_generic_methods() _EMPTY_SERIES = Series([]) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 4553e4804e98b..91f2cbcfcdefa 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2,6 +2,8 @@ import warnings import operator import weakref +import copy + import numpy as np import pandas.lib as lib @@ -16,7 +18,8 @@ import pandas.core.common as com import pandas.core.datetools as datetools from pandas import compat, _np_version_under1p7 -from pandas.compat import map, zip, lrange +from pandas.compat import map, zip, lrange, function_object +from pandas.util.decorators import Generic from pandas.core.common import (isnull, notnull, is_list_like, _values_from_object, _infer_dtype_from_scalar, _maybe_promote, @@ -145,13 +148,17 @@ def _setup_axes( # indexing support cls._ix = None - if info_axis is not None: - cls._info_axis_number = info_axis - cls._info_axis_name = axes[info_axis] + if info_axis is None: + info_axis = 0 + + cls._info_axis_number = info_axis + cls._info_axis_name = axes[info_axis] - if stat_axis is not None: - cls._stat_axis_number = stat_axis - cls._stat_axis_name = axes[stat_axis] + if stat_axis is None: + stat_axis = 0 + + cls._stat_axis_number = stat_axis + cls._stat_axis_name = axes[stat_axis] # setup the actual axis if build_axes: @@ -172,6 +179,49 @@ def set_axis(a, i): for k, v in ns.items(): setattr(cls, k, v) + @classmethod + def _setup_generic_methods(cls, allow_matching=False): + """ + setup any defined generic functions + note that this will override any defined local method + unless allow_matching=True + """ + + for name, g in compat.iteritems(Generic.functions): + + # allow an overriden function to propogate + func = g.func + if not allow_matching: + if function_object(getattr(cls,name)) != func: + continue + + doc = copy.copy(func.__doc__) + subs = copy.copy(g.subs) + subs['return_type'] = cls.__name__ + subs['info_axis'] = cls._info_axis_name + subs['stat_axis'] = cls._stat_axis_name + subs['allowed_axes'] = "({0})".format(', '.join(cls._AXIS_ORDERS)) + + if 'axes' in subs: + + def fmt_axes(i, axis): + lines = subs['axes'].split('\n') + s = '\n'.join([ " {0}".format(l) for l in lines[1:] ]) + extra = '\n ' if i > 0 else '' + return "{0}{1} : {2}\n{3}".format(extra,axis,lines[0],s) + subs['axes'] = ''.join([ fmt_axes(i, axis) for i, axis in enumerate(cls._AXIS_ORDERS) ]) + + # create out new function, setting the docstring and name + def new_scope(func,name,doc): + def new_func(self, *args, **kwargs): + return func(self, *args, **kwargs) + new_func.__doc__ = doc + new_func.__name__ = name + return new_func + + new_func = new_scope(func,name,doc.format(**subs)) + setattr(cls,name,new_func) + def _construct_axes_dict(self, axes=None, **kwargs): """ return an axes dictionary for myself """ d = dict([(a, self._get_axis(a)) for a in (axes or self._AXIS_ORDERS)]) @@ -310,6 +360,7 @@ def _set_axis(self, axis, labels): self._data.set_axis(axis, labels) self._clear_item_cache() + @Generic() def transpose(self, *args, **kwargs): """ Permute the dimensions of the Object @@ -328,7 +379,7 @@ def transpose(self, *args, **kwargs): Returns ------- - y : same as input + y : {return_type} """ # construct the args @@ -350,14 +401,17 @@ def transpose(self, *args, **kwargs): new_values = new_values.copy() return self._constructor(new_values, **new_axes) + @Generic() def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately Returns ------- - y : same as input + y : {return_type} """ + if self.ndim == 1: + axis1 = axis2 = 0 i = self._get_axis_number(axis1) j = self._get_axis_number(axis2) @@ -376,10 +430,14 @@ def swapaxes(self, axis1, axis2, copy=True): return self._constructor(new_values, *new_axes) + @Generic() def pop(self, item): """ - Return item and drop from frame. Raise KeyError if not found. + Return the item from the {info_axis} and drop from object. + + Raise KeyError if not found. """ + result = self[item] del self[item] return result @@ -391,6 +449,7 @@ def squeeze(self): except: return self + @Generic() def swaplevel(self, i, j, axis=0): """ Swap levels i and j in a MultiIndex on a particular axis @@ -402,7 +461,7 @@ def swaplevel(self, i, j, axis=0): Returns ------- - swapped : type of caller (new object) + swapped : {return_type} """ axis = self._get_axis_number(axis) result = self.copy() @@ -413,6 +472,7 @@ def swaplevel(self, i, j, axis=0): #---------------------------------------------------------------------- # Rename + @Generic({ 'axes' : "dict-like or function, optional\nTransformation to apply to that axis values" }) def rename(self, *args, **kwargs): """ Alter axes input function or @@ -421,22 +481,15 @@ def rename(self, *args, **kwargs): Parameters ---------- - axis keywords for this object - (e.g. index for Series, - index,columns for DataFrame, - items,major_axis,minor_axis for Panel) - : dict-like or function, optional - Transformation to apply to that axis values - - copy : boolean, default True - Also copy underlying data + {axes} + copy : boolean, default True, copy underlying data inplace : boolean, default False - Whether to return a new PandasObject. If True then value of copy is - ignored. + Whether to return a new {return_type}. + If True then value of copy is ignored. Returns ------- - renamed : PandasObject (new object) + renamed : {return_type} """ axes, kwargs = self._construct_axes_from_arguments(args, kwargs) @@ -480,9 +533,10 @@ def f(x): else: return result._propogate_attributes(self) + @Generic() def rename_axis(self, mapper, axis=0, copy=True, inplace=False): """ - Alter index and / or columns using input function or functions. + Alter a specific axes using input function or functions. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. @@ -496,7 +550,7 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False): Returns ------- - renamed : type of caller + renamed : {return_type} """ axis = self._get_axis_name(axis) d = { 'copy' : copy, 'inplace' : inplace } @@ -877,6 +931,7 @@ def __delitem__(self, key): except KeyError: pass + @Generic() def take(self, indices, axis=0, convert=True): """ Analogous to ndarray.take @@ -889,7 +944,7 @@ def take(self, indices, axis=0, convert=True): Returns ------- - taken : type of caller + taken : {return_type} """ # check/convert indicies here @@ -907,6 +962,7 @@ def take(self, indices, axis=0, convert=True): new_data = self._data.take(indices, axis=baxis) return self._constructor(new_data) + @Generic() def select(self, crit, axis=0): """ Return data corresponding to axis labels matching criteria @@ -919,7 +975,7 @@ def select(self, crit, axis=0): Returns ------- - selection : type of caller + selection : {return_type} """ axis = self._get_axis_number(axis) axis_name = self._get_axis_name(axis) @@ -933,12 +989,13 @@ def select(self, crit, axis=0): return self.reindex(**{axis_name: new_axis}) + @Generic() def reindex_like(self, other, method=None, copy=True, limit=None): """ return an object with matching indicies to myself Parameters ---------- - other : Object + other : PandasObject method : string or None copy : boolean, default True limit : int, default None @@ -951,11 +1008,12 @@ def reindex_like(self, other, method=None, copy=True, limit=None): Returns ------- - reindexed : same as input + reindexed : {return_type} """ d = other._construct_axes_dict(method=method) return self.reindex(**d) + @Generic() def drop(self, labels, axis=0, level=None): """ Return new object with labels in requested axis removed @@ -969,7 +1027,7 @@ def drop(self, labels, axis=0, level=None): Returns ------- - dropped : type of caller + dropped : {return_type} """ axis_name = self._get_axis_name(axis) axis, axis_ = self._get_axis(axis), axis @@ -1002,6 +1060,7 @@ def drop(self, labels, axis=0, level=None): return self.ix[tuple(slicer)] + @Generic() def add_prefix(self, prefix): """ Concatenate prefix string with panel items names. @@ -1012,11 +1071,12 @@ def add_prefix(self, prefix): Returns ------- - with_prefix : type of caller + with_prefix : {return_type} """ new_data = self._data.add_prefix(prefix) return self._constructor(new_data) + @Generic() def add_suffix(self, suffix): """ Concatenate suffix string with panel items names @@ -1027,25 +1087,25 @@ def add_suffix(self, suffix): Returns ------- - with_suffix : type of caller + with_suffix : {return_type} """ new_data = self._data.add_suffix(suffix) return self._constructor(new_data) + @Generic() def sort_index(self, axis=0, ascending=True): """ Sort object by labels (along an axis) Parameters ---------- - axis : {0, 1} - Sort index/rows versus columns + axis : {allowed_axes} ascending : boolean, default True Sort ascending vs. descending Returns ------- - sorted_obj : type of caller + sorted_obj : {return_type} """ axis = self._get_axis_number(axis) axis_name = self._get_axis_name(axis) @@ -1058,18 +1118,20 @@ def sort_index(self, axis=0, ascending=True): new_axis = labels.take(sort_index) return self.reindex(**{axis_name: new_axis}) + @Generic({ 'axes' : + "array-like, optional\nNew labels / index to conform to. " + "Preferably an Index object to\navoid duplicating data" }) def reindex(self, *args, **kwargs): - """Conform DataFrame to new index with optional filling logic, placing + """ + Conform {return_type} to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False Parameters ---------- - axes : array-like, optional (can be specified in order, or as keywords) - New labels / index to conform to. Preferably an Index object to - avoid duplicating data - method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None + {axes} + method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed DataFrame pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap @@ -1092,7 +1154,7 @@ def reindex(self, *args, **kwargs): Returns ------- - reindexed : same type as calling instance + reindexed : {return_type} """ # construct the args @@ -1151,6 +1213,7 @@ def _needs_reindex_multi(self, axes, method, level): def _reindex_multi(self, axes, copy, fill_value): return NotImplemented + @Generic() def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True, limit=None, fill_value=np.nan): """Conform input object to new index with optional filling logic, placing @@ -1164,7 +1227,7 @@ def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True, New labels / index to conform to. Preferably an Index object to avoid duplicating data axis : allowed axis for the input - method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None + method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed DataFrame pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap @@ -1186,7 +1249,7 @@ def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True, Returns ------- - reindexed : same type as calling instance + reindexed : {return_type} """ self._consolidate_inplace() @@ -1245,6 +1308,7 @@ def _reindex_axis(self, new_index, fill_method, axis, copy): else: return self._constructor(new_data) + @Generic() def filter(self, items=None, like=None, regex=None, axis=None): """ Restrict the info axis to set of items or wildcard @@ -1252,16 +1316,21 @@ def filter(self, items=None, like=None, regex=None, axis=None): Parameters ---------- items : list-like - List of info axis to restrict to (must not all be present) + List of values to restrict to (must not all be present) like : string Keep info axis where "arg in col == True" regex : string (regular expression) Keep info axis with re.search(regex, col) == True + axis : the axis to filter Notes ----- Arguments are mutually exclusive, but this is not checked for + Returns + ------- + {return_type} + """ import re @@ -1326,6 +1395,7 @@ def _consolidate_inplace(self): f = lambda: self._data.consolidate() self._data = self._protect_consolidate(f) + @Generic() def consolidate(self, inplace=False): """ Compute NDFrame with "consolidated" internals (data of each dtype @@ -1339,7 +1409,7 @@ def consolidate(self, inplace=False): Returns ------- - consolidated : type of caller + consolidated : {return_type} """ if inplace: self._consolidate_inplace() @@ -1455,6 +1525,7 @@ def as_blocks(self, columns=None): def blocks(self): return self.as_blocks() + @Generic() def astype(self, dtype, copy=True, raise_on_error=True): """ Cast object to input numpy.dtype @@ -1467,13 +1538,14 @@ def astype(self, dtype, copy=True, raise_on_error=True): Returns ------- - casted : type of caller + casted : {return_type} """ mgr = self._data.astype( dtype, copy=copy, raise_on_error=raise_on_error) return self._constructor(mgr)._propogate_attributes(self) + @Generic() def copy(self, deep=True): """ Make a copy of this object @@ -1485,7 +1557,7 @@ def copy(self, deep=True): Returns ------- - copy : type of caller + copy : {return_type} """ data = self._data if deep: @@ -1511,6 +1583,7 @@ def convert_objects(self, convert_dates=True, convert_numeric=False, copy=True): #---------------------------------------------------------------------- # Filling NA's + @Generic() def fillna(self, value=None, method=None, axis=0, inplace=False, limit=None, downcast=None): """ @@ -1518,7 +1591,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, Parameters ---------- - method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None + method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap @@ -1526,13 +1599,13 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, Value to use to fill holes (e.g. 0), alternately a dict of values specifying which value to use for each column (columns not in the dict will not be filled). This value cannot be a list. - axis : {0, 1}, default 0 + axis : {{0, 1}}, default 0 0: fill column-by-column 1: fill row-by-row inplace : boolean, default False - If True, fill the DataFrame in place. Note: this will modify any - other views on this DataFrame, like if you took a no-copy slice of - an existing DataFrame, for example a column in a DataFrame. Returns + If True, fill the {return_type} in place. Note: this will modify any + other views on this {return_type}, like if you took a no-copy slice of + an existing {return_type}, for example a column in a {return_type}. Returns a reference to the filled object, which is self if inplace=True limit : int, default None Maximum size gap to forward or backward fill @@ -1546,7 +1619,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, Returns ------- - filled : DataFrame + filled : {return_type} """ if isinstance(value, (list, tuple)): raise TypeError('"value" parameter must be a scalar or dict, but ' @@ -1625,6 +1698,7 @@ def bfill(self, axis=0, inplace=False, limit=None, downcast=None): return self.fillna(method='bfill', axis=axis, inplace=inplace, limit=limit, downcast=downcast) + @Generic() def replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None): """ @@ -1653,7 +1727,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, * dict: - - Nested dictionaries, e.g., {'a': {'b': nan}}, are read as + - Nested dictionaries, e.g., {{'a': {{'b': nan}} }}, are read as follows: look in column 'a' for the value 'b' and replace it with nan. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested @@ -1688,7 +1762,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, string. Otherwise, `to_replace` must be ``None`` because this parameter will be interpreted as a regular expression or a list, dict, or array of regular expressions. - method : string, optional, {'pad', 'ffill', 'bfill'} + method : string, optional, {{'pad', 'ffill', 'bfill'}} The method to use when for replacement, when ``to_replace`` is a ``list``. @@ -1700,7 +1774,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, Returns ------- - filled : NDFrame + filled : {return_type} Raises ------ @@ -1913,6 +1987,7 @@ def interpolate(self, to_replace, method='pad', axis=0, inplace=False, #---------------------------------------------------------------------- # Action Methods + @Generic() def abs(self): """ Return an object with absolute value taken. Only applicable to objects @@ -1920,7 +1995,7 @@ def abs(self): Returns ------- - abs: type of caller + abs: {return_type} """ obj = np.abs(self) @@ -2053,6 +2128,7 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, return groupby(self, by, axis=axis, level=level, as_index=as_index, sort=sort, group_keys=group_keys, squeeze=squeeze) + @Generic() def asfreq(self, freq, method=None, how=None, normalize=False): """ Convert all TimeSeries inside to specified frequency using DateOffset @@ -2061,23 +2137,24 @@ def asfreq(self, freq, method=None, how=None, normalize=False): Parameters ---------- freq : DateOffset object, or string - method : {'backfill', 'bfill', 'pad', 'ffill', None} + method : {{'backfill', 'bfill', 'pad', 'ffill', None}} Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill methdo - how : {'start', 'end'}, default end + how : {{'start', 'end'}}, default end For PeriodIndex only, see PeriodIndex.asfreq normalize : bool, default False Whether to reset output index to midnight Returns ------- - converted : type of caller + converted : {return_type} """ from pandas.tseries.resample import asfreq return asfreq(self, freq, method=method, how=how, normalize=normalize) + @Generic() def at_time(self, time, asof=False): """ Select values at particular time of day (e.g. 9:30AM) @@ -2088,7 +2165,7 @@ def at_time(self, time, asof=False): Returns ------- - values_at_time : type of caller + values_at_time : {return_type} """ try: indexer = self.index.indexer_at_time(time, asof=asof) @@ -2096,6 +2173,7 @@ def at_time(self, time, asof=False): except AttributeError: raise TypeError('Index must be DatetimeIndex') + @Generic() def between_time(self, start_time, end_time, include_start=True, include_end=True): """ @@ -2110,7 +2188,7 @@ def between_time(self, start_time, end_time, include_start=True, Returns ------- - values_between_time : type of caller + values_between_time : {return_type} """ try: indexer = self.index.indexer_between_time( @@ -2157,6 +2235,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None, limit=limit, base=base) return sampler.resample(self) + @Generic() def first(self, offset): """ Convenience method for subsetting initial periods of time series data @@ -2172,7 +2251,7 @@ def first(self, offset): Returns ------- - subset : type of caller + subset : {return_type} """ from pandas.tseries.frequencies import to_offset if not isinstance(self.index, DatetimeIndex): @@ -2191,6 +2270,7 @@ def first(self, offset): return self.ix[:end] + @Generic() def last(self, offset): """ Convenience method for subsetting final periods of time series data @@ -2206,7 +2286,7 @@ def last(self, offset): Returns ------- - subset : type of caller + subset : {return_type} """ from pandas.tseries.frequencies import to_offset if not isinstance(self.index, DatetimeIndex): @@ -2221,6 +2301,7 @@ def last(self, offset): start = self.index.searchsorted(start_date, side='right') return self.ix[start:] + @Generic() def align(self, other, join='outer', axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0): """ @@ -2229,8 +2310,8 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, Parameters ---------- - other : DataFrame or Series - join : {'outer', 'inner', 'left', 'right'}, default 'outer' + other : PandasObject + join : {{'outer', 'inner', 'left', 'right'}}, default 'outer' axis : allowed axis of the other object, default None Align on index (0), columns (1), or both (None) level : int or name @@ -2244,12 +2325,12 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, "compatible" value method : str, default None limit : int, default None - fill_axis : {0, 1}, default 0 + fill_axis : {{0, 1}}, default 0 Filling axis, method and limit Returns ------- - (left, right) : (type of input, type of other) + (left, right) : ({return_type}, type of other) Aligned objects """ from pandas import DataFrame, Series @@ -2362,6 +2443,7 @@ def _align_series(self, other, join='outer', axis=None, level=None, else: return left_result, right_result + @Generic() def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, try_cast=False, raise_on_error=True): """ @@ -2370,8 +2452,8 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, Parameters ---------- - cond : boolean DataFrame or array - other : scalar or DataFrame + cond : boolean {return_type} or array + other : scalar or PandasObject inplace : boolean, default False Whether to perform the operation in place on the data axis : alignment axis if needed, default None @@ -2384,7 +2466,7 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, Returns ------- - wh : DataFrame + wh : {return_type} """ if isinstance(cond, NDFrame): cond = cond.reindex(**self._construct_axes_dict()) @@ -2499,6 +2581,7 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, return self._constructor(new_data) + @Generic() def mask(self, cond): """ Returns copy of self whose values are replaced with nan if the @@ -2510,7 +2593,7 @@ def mask(self, cond): Returns ------- - wh: same as input + wh: {return_type} """ return self.where(~cond, np.nan) @@ -2544,21 +2627,21 @@ def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None, np.putmask(rs.values, mask, np.nan) return rs + @Generic() def cumsum(self, axis=None, skipna=True): """ Return DataFrame of cumulative sums over requested axis. Parameters ---------- - axis : {0, 1} - 0 for row-wise, 1 for column-wise + axis : the axis to operate, defaults to [{stat_axis}] skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA Returns ------- - y : DataFrame + y : {return_type} """ if axis is None: axis = self._stat_axis_number @@ -2580,21 +2663,21 @@ def cumsum(self, axis=None, skipna=True): result = y.cumsum(axis) return self._wrap_array(result, self.axes, copy=False) + @Generic() def cumprod(self, axis=None, skipna=True): """ Return cumulative product over requested axis as DataFrame Parameters ---------- - axis : {0, 1} - 0 for row-wise, 1 for column-wise + axis : the axis to operate, defaults to [{stat_axis}] skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA Returns ------- - y : DataFrame + y : {return_type} """ if axis is None: axis = self._stat_axis_number @@ -2615,21 +2698,21 @@ def cumprod(self, axis=None, skipna=True): result = y.cumprod(axis) return self._wrap_array(result, self.axes, copy=False) + @Generic() def cummax(self, axis=None, skipna=True): """ Return DataFrame of cumulative max over requested axis. Parameters ---------- - axis : {0, 1} - 0 for row-wise, 1 for column-wise + axis : the axis to operate, defaults to [{stat_axis}] skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA Returns ------- - y : DataFrame + y : {return_type} """ if axis is None: axis = self._stat_axis_number @@ -2651,21 +2734,21 @@ def cummax(self, axis=None, skipna=True): result = np.maximum.accumulate(y, axis) return self._wrap_array(result, self.axes, copy=False) + @Generic() def cummin(self, axis=None, skipna=True): """ Return DataFrame of cumulative min over requested axis. Parameters ---------- - axis : {0, 1} - 0 for row-wise, 1 for column-wise + axis : the axis to operate, defaults to [{stat_axis}] skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA Returns ------- - y : DataFrame + y : {return_type} """ if axis is None: axis = self._stat_axis_number @@ -2781,25 +2864,34 @@ def tshift(self, periods=1, freq=None, axis=0, **kwds): return self._constructor(new_data) - def truncate(self, before=None, after=None, copy=True): - """Function truncate a sorted DataFrame / Series before and/or after + @Generic() + def truncate(self, before=None, after=None, axis=None, copy=True): + """Function truncate a sorted {return_type} before and/or after some particular dates. Parameters ---------- before : date - Truncate before date + Truncate before date after : date - Truncate after date + Truncate after date + axis : the axis to operate, defaults to [{stat_axis}] + copy : optional, return a copy of the truncation Returns ------- - truncated : type of caller + truncated : {return_type} """ + if axis is None: + axis = self._stat_axis_number + axis = self._get_axis_number(axis) + axis_name = self._get_axis_name(axis) + # if we have a date index, convert to dates, otherwise # treat like a slice - if self.index.is_all_dates: + ax = self._get_axis(axis) + if ax.is_all_dates: from pandas.tseries.tools import to_datetime before = to_datetime(before) after = to_datetime(after) @@ -2809,10 +2901,12 @@ def truncate(self, before=None, after=None, copy=True): raise AssertionError('Truncate: %s must be after %s' % (before, after)) - result = self.ix[before:after] + slicer = [ slice(None,None) ] * self._AXIS_LEN + slicer[axis] = slice(before,after) + result = self.ix[tuple(slicer)] - if isinstance(self.index, MultiIndex): - result.index = self.index.truncate(before, after) + if isinstance(ax, MultiIndex): + setattr(result,axis_name,ax.truncate(before, after)) if copy: result = result.copy() diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 5f90eb9fa31a7..d644968811a28 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -1016,7 +1016,7 @@ def shift(self, lags, freq=None, axis='major'): def tshift(self, periods=1, freq=None, axis='major', **kwds): return super(Panel, self).tshift(periods, freq, axis, **kwds) - def truncate(self, before=None, after=None, axis='major'): + def truncate(self, before=None, after=None, axis='major', copy=False): """Function truncates a sorted Panel before and/or after some particular values on the requested axis @@ -1370,6 +1370,7 @@ def min(self, axis='major', skipna=True): slicers={'major_axis': 'index', 'minor_axis': 'columns'}) Panel._add_aggregate_operations() +Panel._setup_generic_methods() WidePanel = Panel LongPanel = DataFrame diff --git a/pandas/core/panelnd.py b/pandas/core/panelnd.py index 8f427568a4102..c168965d38e8f 100644 --- a/pandas/core/panelnd.py +++ b/pandas/core/panelnd.py @@ -108,5 +108,6 @@ def func(self, *args, **kwargs): # add the aggregate operations klass._add_aggregate_operations() + klass._setup_generic_methods(allow_matching=True) return klass diff --git a/pandas/core/series.py b/pandas/core/series.py index 9f7ab0cb0346b..d1cff145b2855 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3124,6 +3124,7 @@ def to_period(self, freq=None, copy=True): return self._constructor(new_values, index=new_index, name=self.name) Series._setup_axes(['index'], info_axis=0) +Series._setup_generic_methods() _INDEX_TYPES = ndarray, Index, list, tuple # reinstall the SeriesIndexer diff --git a/pandas/util/decorators.py b/pandas/util/decorators.py index d83b1eb778763..7271110f69468 100644 --- a/pandas/util/decorators.py +++ b/pandas/util/decorators.py @@ -3,7 +3,6 @@ import sys import warnings - def deprecate(name, alternative, alt_name=None): alt_name = alt_name or alternative.__name__ @@ -106,6 +105,24 @@ def __call__(self, func): return func +class Generic(object): + """ + A function decorator that will hold specific functions for the named classes + of the target function. + """ + functions = {} + + def __init__(self, subs=None): + if subs is None: + subs = dict() + self.subs = subs + self.func = None + + def __call__(self, func): + self.func = func + self.functions[func.__name__] = self + return func + def indent(text, indents=1): if not text or not isinstance(text, str): return ''
closes #4717 ``` In [2]: pd.DataFrame.reindex? Type: instancemethod String Form:<unbound method DataFrame.reindex> File: /mnt/home/jreback/pandas/pandas/core/generic.py Definition: pd.DataFrame.reindex(self, *args, **kwargs) Docstring: Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False Parameters ---------- index : array-like, optional New labels / index to conform to. Preferably an Index object to avoid duplicating data columns : array-like, optional New labels / index to conform to. Preferably an Index object to avoid duplicating data method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None Method to use for filling holes in reindexed DataFrame pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap copy : boolean, default True Return a new object, even if the passed indexes are the same level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level fill_value : scalar, default np.NaN Value to use for missing values. Defaults to NaN, but can be any "compatible" value limit : int, default None Maximum size gap to forward or backward fill takeable : boolean, default False treat the passed as positional values Examples -------- >>> df.reindex(index=[date1, date2, date3], columns=['A', 'B', 'C']) Returns ------- reindexed : DataFrame ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4941
2013-09-22T23:37:57Z
2013-10-01T00:05:03Z
null
2014-08-13T07:00:34Z
BUG: Fixed a bug in convert_objects for > 2 ndims GH4937
diff --git a/doc/source/release.rst b/doc/source/release.rst index 47e0cfd78271e..789fbd0fe4ccc 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -437,7 +437,7 @@ Bug Fixes - Fixed ``_ensure_numeric`` does not check for complex numbers (:issue:`4902`) - Fixed a bug in ``Series.hist`` where two figures were being created when the ``by`` argument was passed (:issue:`4112`, :issue:`4113`). - + - Fixed a bug in ``convert_objects`` for > 2 ndims (:issue:`4937`) pandas 0.12.0 ------------- diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 72b0212f77ac9..bc16f549f0cf1 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -331,7 +331,6 @@ Enhancements can also be used. - ``read_stata` now accepts Stata 13 format (:issue:`4291`) - .. _whatsnew_0130.experimental: Experimental diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 585b1c817ff19..3ab1bfb2c58ed 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1164,8 +1164,8 @@ def convert(self, convert_dates=True, convert_numeric=True, copy=True, by_item=T values = self.iget(i) values = com._possibly_convert_objects( - values, convert_dates=convert_dates, convert_numeric=convert_numeric) - values = _block_shape(values) + values.ravel(), convert_dates=convert_dates, convert_numeric=convert_numeric).reshape(values.shape) + values = _block_shape(values, ndim=self.ndim) items = self.items.take([i]) placement = None if is_unique else [i] newb = make_block( @@ -1175,7 +1175,7 @@ def convert(self, convert_dates=True, convert_numeric=True, copy=True, by_item=T else: values = com._possibly_convert_objects( - self.values, convert_dates=convert_dates, convert_numeric=convert_numeric) + self.values.ravel(), convert_dates=convert_dates, convert_numeric=convert_numeric).reshape(self.values.shape) blocks.append( make_block(values, self.items, self.ref_items, ndim=self.ndim)) @@ -3610,7 +3610,7 @@ def _merge_blocks(blocks, items, dtype=None, _can_consolidate=True): def _block_shape(values, ndim=1, shape=None): """ guarantee the shape of the values to be at least 1 d """ - if values.ndim == ndim: + if values.ndim <= ndim: if shape is None: shape = values.shape values = values.reshape(tuple((1,) + shape)) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index a498cca528043..0195fe30a05c8 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1010,6 +1010,14 @@ def test_conform(self): assert(conformed.index.equals(self.panel.major_axis)) assert(conformed.columns.equals(self.panel.minor_axis)) + 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(convert_numeric='force') + assert_panel_equal(result, expected) + def test_reindex(self): ref = self.panel['ItemB'] @@ -1287,9 +1295,6 @@ def test_to_panel_duplicates(self): def test_filter(self): pass - def test_apply(self): - pass - def test_compound(self): compounded = self.panel.compound() @@ -1350,7 +1355,7 @@ def test_tshift(self): assert_panel_equal(shifted, shifted2) inferred_ts = Panel(panel.values, - items=panel.items, + items=panel.items, major_axis=Index(np.asarray(panel.major_axis)), minor_axis=panel.minor_axis) shifted = inferred_ts.tshift(1)
closes #4937
https://api.github.com/repos/pandas-dev/pandas/pulls/4938
2013-09-22T18:46:31Z
2013-09-22T19:28:16Z
2013-09-22T19:28:16Z
2014-06-22T04:28:57Z
ENH: Add 'records' outtype to to_dict method.
diff --git a/doc/source/release.rst b/doc/source/release.rst index 769b47b18db08..f6afea583762b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -47,6 +47,8 @@ pandas 0.13 - Added a more informative error message when plot arguments contain overlapping color and style arguments (:issue:`4402`) - Significant table writing performance improvements in ``HDFStore`` + - ``to_dict`` now takes ``records`` as a possible outtype. Returns an array + of column-keyed dictionaries. (:pullrequest:`4936`) **API Changes** diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 7da2f03ad4c74..b74de1c7be17b 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -81,6 +81,8 @@ Enhancements - Clipboard functionality now works with PySide (:issue:`4282`) - Added a more informative error message when plot arguments contain overlapping color and style arguments (:issue:`4402`) + - ``to_dict`` now takes ``records`` as a possible outtype. Returns an array + of column-keyed dictionaries. (:pullrequest:`4936`) Bug Fixes ~~~~~~~~~ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0f3bcb32f7287..c0e868f27345c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -962,11 +962,11 @@ def to_dict(self, outtype='dict'): Parameters ---------- - outtype : str {'dict', 'list', 'series'} + outtype : str {'dict', 'list', 'series', 'records'} Determines the type of the values of the dictionary. The default `dict` is a nested dictionary {column -> {index -> value}}. `list` returns {column -> list(values)}. `series` returns - {column -> Series(values)}. + {column -> Series(values)}. `records` returns [{columns -> value}]. Abbreviations are allowed. @@ -983,6 +983,9 @@ def to_dict(self, outtype='dict'): return dict((k, v.tolist()) for k, v in compat.iteritems(self)) elif outtype.lower().startswith('s'): return dict((k, v) for k, v in compat.iteritems(self)) + elif outtype.lower().startswith('r'): + return [dict((k, v) for k, v in zip(self.columns, row)) \ + for row in self.values] else: # pragma: no cover raise ValueError("outtype %s not understood" % outtype) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 1b405eae08797..c5ecba3555784 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3396,6 +3396,14 @@ def test_to_dict(self): for k2, v2 in compat.iteritems(v): self.assertEqual(v2, recons_data[k][k2]) + recons_data = DataFrame(test_data).to_dict("r") + + expected_records = [{'A': 1.0, 'B': '1'}, + {'A': 2.0, 'B': '2'}, + {'A': nan, 'B': '3'}] + + tm.assert_almost_equal(recons_data, expected_records) + def test_to_records_dt64(self): df = DataFrame([["one", "two", "three"], ["four", "five", "six"]],
`to_json` has a records type that turns a DataFrame into a ``` [{'a': 1, 'b': 3}, {'a': 2, 'b': 4}] ``` records json string. It'd be nice if you could do a similar thing but not have to go `json.loads`.
https://api.github.com/repos/pandas-dev/pandas/pulls/4936
2013-09-22T16:11:12Z
2013-09-30T13:44:54Z
2013-09-30T13:44:54Z
2014-06-12T14:29:29Z
ENH: Better string representation for MultiIndex
diff --git a/doc/source/release.rst b/doc/source/release.rst index 8ba0574df97cb..1d29e64860b2d 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -131,6 +131,8 @@ Improvements to existing features (:issue:`3441`, :issue:`4933`) - ``pandas`` is now tested with two different versions of ``statsmodels`` (0.4.3 and 0.5.0) (:issue:`4981`). + - Better string representations of ``MultiIndex`` (including ability to roundtrip + via ``repr``). (:issue:`3347`, :issue:`4935`) API Changes ~~~~~~~~~~~ diff --git a/pandas/core/index.py b/pandas/core/index.py index 7f136450daf6e..d488a29182a18 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1,6 +1,6 @@ # pylint: disable=E1101,E1103,W0232 from functools import partial -from pandas.compat import range, zip, lrange, lzip +from pandas.compat import range, zip, lrange, lzip, u from pandas import compat import numpy as np @@ -17,6 +17,10 @@ from pandas.core.common import _values_from_object, is_float, is_integer from pandas.core.config import get_option +# simplify +default_pprint = lambda x: com.pprint_thing(x, escape_chars=('\t', '\r', '\n'), + quote_strings=True) + __all__ = ['Index'] @@ -2052,18 +2056,40 @@ def _array_values(self): def dtype(self): return np.dtype('O') + def __repr__(self): + encoding = get_option('display.encoding') + attrs = [('levels', default_pprint(self.levels)), + ('labels', default_pprint(self.labels))] + if not all(name is None for name in self.names): + attrs.append(('names', default_pprint(self.names))) + if self.sortorder is not None: + attrs.append(('sortorder', default_pprint(self.sortorder))) + + space = ' ' * (len(self.__class__.__name__) + 1) + prepr = (u("\n%s") % space).join([u("%s=%s") % (k, v) + for k, v in attrs]) + res = u("%s(%s)") % (self.__class__.__name__, prepr) + + if not compat.PY3: + # needs to be str in Python 2 + res = res.encode(encoding) + return res + + def __unicode__(self): """ Return a string representation for a particular Index Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. """ - output = 'MultiIndex\n%s' - - summary = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'), - quote_strings=True) - - return output % summary + rows = self.format(names=True) + max_rows = get_option('display.max_rows') + if len(rows) > max_rows: + spaces = (len(rows[0]) - 3) // 2 + centered = ' ' * spaces + half = max_rows // 2 + rows = rows[:half] + [centered + '...' + centered] + rows[-half:] + return "\n".join(rows) def __len__(self): return len(self.labels[0])
Fixes #3347. All interested parties are invited to submit test cases. cc @y-p @hayd --- Examples: ``` In [1]: import pandas as pd In [2]: pd.MultiIndex.from_arrays([[1, 1, 1, 1], [1, 3, 5, 7], [9, 9, 1, 1]]) Out[2]: MultiIndex(levels=[[1], [1, 3, 5, 7], [1, 9]] labels=[[0, 0, 0, 0], [0, 1, 2, 3], [1, 1, 0, 0]]) In [3]: mi = _ In [4]: mi.names = list('abc') In [5]: print mi a b c 1 1 9 3 9 5 1 7 1 ``` And with too many rows: ``` In [10]: pd.set_option('display.max_rows', 15) In [11]: lst1 = [1] * 3 + [2] * 5 + [3] * 2 In [12]: lst1 Out[12]: [1, 1, 1, 2, 2, 2, 2, 2, 3, 3] In [13]: lst2 = ['a'] * 6 + ['b'] * 3 + ['c'] * 1 In [14]: lst2 Out[14]: ['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c'] In [15]: mi = pd.MultiIndex.from_arrays([lst1 * 10, lst2 * 10, range(100)]); mi Out[15]: MultiIndex(levels=[[1, 2, 3], [u'a', u'b', u'c'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]] labels=[[0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2], [0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]) In [16]: mi = _ In [17]: print mi 1 a 0 1 2 2 a 3 4 5 ... 2 a 93 94 95 b 96 97 3 b 98 c 99 ``` Not sure how to handle too wide -- wrap? format() doesn't try to sparsify after a column with values everywhere. ``` In [19]: mi = pd.MultiIndex.from_arrays([lst1 * 10, lst2 * 10, range(100)] * 10) In [20]: print mi 1 a 0 1 a 0 1 a 0 1 a 0 1 a 0 1 a 0 1 a 0 1 a 0 1 a 0 1 a 0 1 1 a 1 1 a 1 1 a 1 1 a 1 1 a 1 1 a 1 1 a 1 1 a 1 1 a 1 2 1 a 2 1 a 2 1 a 2 1 a 2 1 a 2 1 a 2 1 a 2 1 a 2 1 a 2 2 a 3 2 a 3 2 a 3 2 a 3 2 a 3 2 a 3 2 a 3 2 a 3 2 a 3 2 a 3 4 2 a 4 2 a 4 2 a 4 2 a 4 2 a 4 2 a 4 2 a 4 2 a 4 2 a 4 5 2 a 5 2 a 5 2 a 5 2 a 5 2 a 5 2 a 5 2 a 5 2 a 5 2 a 5 ... 2 a 93 2 a 93 2 a 93 2 a 93 2 a 93 2 a 93 2 a 93 2 a 93 2 a 93 2 a 93 94 2 a 94 2 a 94 2 a 94 2 a 94 2 a 94 2 a 94 2 a 94 2 a 94 2 a 94 95 2 a 95 2 a 95 2 a 95 2 a 95 2 a 95 2 a 95 2 a 95 2 a 95 2 a 95 b 96 2 b 96 2 b 96 2 b 96 2 b 96 2 b 96 2 b 96 2 b 96 2 b 96 2 b 96 97 2 b 97 2 b 97 2 b 97 2 b 97 2 b 97 2 b 97 2 b 97 2 b 97 2 b 97 3 b 98 3 b 98 3 b 98 3 b 98 3 b 98 3 b 98 3 b 98 3 b 98 3 b 98 3 b 98 c 99 3 c 99 3 c 99 3 c 99 3 c 99 3 c 99 3 c 99 3 c 99 3 c 99 3 c 99 ``` ``` In [9]: labels = [('foo', '2012-07-26T00:00:00', 'b5c2700'), ...: ('foo', '2012-08-06T00:00:00', '900b2ca'), ...: ('foo', '2012-08-15T00:00:00', '07f1ce0'), ...: ('foo', '2012-09-25T00:00:00', '5c93e83'), ...: ('foo', '2012-09-25T00:00:00', '9345bba')] In [10]: print pd.MultiIndex.from_tuples(labels) foo 2012-07-26T00:00:00 b5c2700 2012-08-06T00:00:00 900b2ca 2012-08-15T00:00:00 07f1ce0 2012-09-25T00:00:00 5c93e83 9345bba ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4935
2013-09-22T05:28:08Z
2013-09-27T00:30:19Z
2013-09-27T00:30:19Z
2014-06-20T15:58:33Z
ENH: Make ExcelWriter & ExcelFile contextmanagers
diff --git a/doc/source/io.rst b/doc/source/io.rst index 951960493975e..a0e41a96181a2 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -1672,14 +1672,13 @@ The Panel class also has a ``to_excel`` instance method, which writes each DataFrame in the Panel to a separate sheet. In order to write separate DataFrames to separate sheets in a single Excel file, -one can use the ExcelWriter class, as in the following example: +one can pass an :class:`~pandas.io.excel.ExcelWriter`. .. code-block:: python - writer = ExcelWriter('path_to_file.xlsx') - df1.to_excel(writer, sheet_name='Sheet1') - df2.to_excel(writer, sheet_name='Sheet2') - writer.save() + with ExcelWriter('path_to_file.xlsx') as writer: + df1.to_excel(writer, sheet_name='Sheet1') + df2.to_excel(writer, sheet_name='Sheet2') .. _io.excel.writers: @@ -1693,14 +1692,13 @@ Excel writer engines 1. the ``engine`` keyword argument 2. the filename extension (via the default specified in config options) -By default ``pandas`` only supports -`openpyxl <http://packages.python.org/openpyxl/>`__ as a writer for ``.xlsx`` -and ``.xlsm`` files and `xlwt <http://www.python-excel.org/>`__ as a writer for -``.xls`` files. If you have multiple engines installed, you can change the -default engine via the ``io.excel.xlsx.writer`` and ``io.excel.xls.writer`` -options. +By default, ``pandas`` uses `openpyxl <http://packages.python.org/openpyxl/>`__ +for ``.xlsx`` and ``.xlsm`` files and `xlwt <http://www.python-excel.org/>`__ +for ``.xls`` files. If you have multiple engines installed, you can set the +default engine through :ref:`setting the config options <basics.working_with_options>` +``io.excel.xlsx.writer`` and ``io.excel.xls.writer``. -For example if the optional `XlsxWriter <http://xlsxwriter.readthedocs.org>`__ +For example if the `XlsxWriter <http://xlsxwriter.readthedocs.org>`__ module is installed you can use it as a xlsx writer engine as follows: .. code-block:: python @@ -1712,8 +1710,8 @@ module is installed you can use it as a xlsx writer engine as follows: writer = ExcelWriter('path_to_file.xlsx', engine='xlsxwriter') # Or via pandas configuration. - from pandas import set_option - set_option('io.excel.xlsx.writer', 'xlsxwriter') + from pandas import options + options.io.excel.xlsx.writer = 'xlsxwriter' df.to_excel('path_to_file.xlsx', sheet_name='Sheet1') diff --git a/doc/source/release.rst b/doc/source/release.rst index 75097ee50e8c1..444f25e8662bd 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -126,6 +126,8 @@ Improvements to existing features - ``read_json`` now raises a (more informative) ``ValueError`` when the dict contains a bad key and ``orient='split'`` (:issue:`4730`, :issue:`4838`) - ``read_stata`` now accepts Stata 13 format (:issue:`4291`) + - ``ExcelWriter`` and ``ExcelFile`` can be used as contextmanagers. + (:issue:`3441`, :issue:`4933`) API Changes ~~~~~~~~~~~ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0482312a71547..799d96f46a15b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3453,7 +3453,7 @@ def unstack(self, level=-1): See also -------- DataFrame.pivot : Pivot a table based on column values. - DataFrame.stack : Pivot a level of the column labels (inverse operation + DataFrame.stack : Pivot a level of the column labels (inverse operation from `unstack`). Examples diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 6ce8eb697268b..02dbc381a10be 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -14,7 +14,7 @@ from pandas import json from pandas.compat import map, zip, reduce, range, lrange, u, add_metaclass from pandas.core import config -from pandas.core.common import pprint_thing, PandasError +from pandas.core.common import pprint_thing import pandas.compat as compat from warnings import warn @@ -260,6 +260,17 @@ def _parse_excel(self, sheetname, header=0, skiprows=None, skip_footer=0, def sheet_names(self): return self.book.sheet_names() + def close(self): + """close path_or_buf if necessary""" + if hasattr(self.path_or_buf, 'close'): + self.path_or_buf.close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def _trim_excel_header(row): # trim header row so auto-index inference works @@ -408,6 +419,17 @@ def check_extension(cls, ext): else: return True + # Allow use as a contextmanager + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + """synonym for save, to make it more file-like""" + return self.save() + class _OpenpyxlWriter(ExcelWriter): engine = 'openpyxl' diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 94f3e5a8cf746..2bcf4789412f6 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -275,6 +275,18 @@ def test_xlsx_table(self): tm.assert_frame_equal(df4, df.ix[:-1]) tm.assert_frame_equal(df4, df5) + def test_reader_closes_file(self): + _skip_if_no_xlrd() + _skip_if_no_openpyxl() + + pth = os.path.join(self.dirpath, 'test.xlsx') + f = open(pth, 'rb') + with ExcelFile(f) as xlsx: + # parses okay + df = xlsx.parse('Sheet1', index_col=0) + + self.assertTrue(f.closed) + class ExcelWriterBase(SharedItems): # Base class for test cases to run with different Excel writers. @@ -310,6 +322,21 @@ def test_excel_sheet_by_name_raise(self): self.assertRaises(xlrd.XLRDError, xl.parse, '0') + def test_excelwriter_contextmanager(self): + ext = self.ext + pth = os.path.join(self.dirpath, 'testit.{0}'.format(ext)) + + with ensure_clean(pth) as pth: + with ExcelWriter(pth) as writer: + self.frame.to_excel(writer, 'Data1') + self.frame2.to_excel(writer, 'Data2') + + with ExcelFile(pth) as reader: + found_df = reader.parse('Data1') + found_df2 = reader.parse('Data2') + tm.assert_frame_equal(found_df, self.frame) + tm.assert_frame_equal(found_df2, self.frame2) + def test_roundtrip(self): _skip_if_no_xlrd() ext = self.ext
Fixes #3441. both can be used in with statements now. Makes it easier to use with multiple writers, etc. Plus touch up the docs on writers and such.
https://api.github.com/repos/pandas-dev/pandas/pulls/4933
2013-09-22T02:47:02Z
2013-09-23T04:15:21Z
2013-09-23T04:15:21Z
2014-06-16T04:28:54Z
ENH/API: allow customization of requests thru opener
diff --git a/doc/source/release.rst b/doc/source/release.rst index c3a8e7b0b578e..ff81d2994eaee 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -123,6 +123,8 @@ Improvements to existing features - ``read_json`` now raises a (more informative) ``ValueError`` when the dict contains a bad key and ``orient='split'`` (:issue:`4730`, :issue:`4838`) - ``read_stata`` now accepts Stata 13 format (:issue:`4291`) + - ``read_html`` now has an ``opener`` argument to allow customization of + requests (:issue:`4927`). API Changes ~~~~~~~~~~~ diff --git a/pandas/io/common.py b/pandas/io/common.py index 02242c5a91493..3162c8aad5e05 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -1,6 +1,7 @@ """Common IO api utilities""" import sys +import socket import zipfile from contextlib import contextmanager, closing @@ -9,15 +10,22 @@ if compat.PY3: - from urllib.request import urlopen - _urlopen = urlopen + from urllib.request import urlopen as _urlopen, build_opener from urllib.parse import urlparse as parse_url import urllib.parse as compat_parse from urllib.parse import uses_relative, uses_netloc, uses_params, urlencode from urllib.error import URLError from http.client import HTTPException + + @contextmanager + def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, + opener=None): + _opener = opener or build_opener() + with _opener.open(url, data, timeout) as f: + yield f + else: - from urllib2 import urlopen as _urlopen + from urllib2 import urlopen as _urlopen, build_opener from urllib import urlencode from urlparse import urlparse as parse_url from urlparse import uses_relative, uses_netloc, uses_params @@ -26,10 +34,11 @@ from contextlib import contextmanager, closing from functools import wraps - # @wraps(_urlopen) @contextmanager - def urlopen(*args, **kwargs): - with closing(_urlopen(*args, **kwargs)) as f: + def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, + opener=None): + _opener = opener or build_opener() + with closing(_opener.open(url, data, timeout)) as f: yield f diff --git a/pandas/io/html.py b/pandas/io/html.py index df94e0ffa2e79..d92dbf757e079 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -13,7 +13,7 @@ import numpy as np from pandas import DataFrame, MultiIndex, isnull -from pandas.io.common import _is_url, urlopen, parse_url +from pandas.io.common import _is_url, urlopen, parse_url, URLError from pandas.compat import range, lrange, lmap, u, map from pandas import compat @@ -101,7 +101,7 @@ def _get_skiprows_iter(skiprows): ' rows'.format(type(skiprows))) -def _read(io): +def _read(io, opener=None): """Try to read from a url, file or string. Parameters @@ -113,7 +113,7 @@ def _read(io): raw_text : str """ if _is_url(io): - with urlopen(io) as url: + with urlopen(io, opener=opener) as url: raw_text = url.read() elif hasattr(io, 'read'): raw_text = io.read() @@ -169,8 +169,9 @@ class _HtmlFrameParser(object): See each method's respective documentation for details on their functionality. """ - def __init__(self, io, match, attrs): + def __init__(self, io, opener, match, attrs): self.io = io + self.opener = opener self.match = match self.attrs = attrs @@ -421,7 +422,7 @@ def _parse_tables(self, doc, match, attrs): return tables def _setup_build_doc(self): - raw_text = _read(self.io) + raw_text = _read(self.io, opener=self.opener) if not raw_text: raise AssertionError('No text parsed from document: ' '{0}'.format(self.io)) @@ -558,6 +559,12 @@ def _build_doc(self): else: # something else happened: maybe a faulty connection raise + except URLError: + r = parse(_read(self.io, opener=self.opener), parser=parser) + try: + r = r.getroot() + except AttributeError: + pass else: if not hasattr(r, 'text_content'): raise XMLSyntaxError("no text parsed from document", 0, 0, 0) @@ -750,7 +757,8 @@ def _validate_parser_flavor(flavor): return flavor -def _parse(flavor, io, match, header, index_col, skiprows, infer_types, attrs): +def _parse(flavor, io, opener, match, header, index_col, skiprows, infer_types, + attrs): # bonus: re.compile is idempotent under function iteration so you can pass # a compiled regex to it and it will return itself flavor = _validate_parser_flavor(flavor) @@ -760,7 +768,7 @@ def _parse(flavor, io, match, header, index_col, skiprows, infer_types, attrs): retained = None for flav in flavor: parser = _parser_dispatch(flav) - p = parser(io, compiled_match, attrs) + p = parser(io, opener, compiled_match, attrs) try: tables = p.parse_tables() @@ -776,7 +784,7 @@ def _parse(flavor, io, match, header, index_col, skiprows, infer_types, attrs): def read_html(io, match='.+', flavor=None, header=None, index_col=None, - skiprows=None, infer_types=True, attrs=None): + skiprows=None, infer_types=True, attrs=None, opener=None): r"""Read an HTML table into a DataFrame. Parameters @@ -858,6 +866,9 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, <http://www.w3.org/TR/html-markup/table.html>`__. It contains the latest information on table attributes for the modern web. + opener : %s.OpenerDirector + An OpenerDirector object that allows you customize your request header. + Returns ------- dfs : list of DataFrames @@ -899,5 +910,8 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, if isinstance(skiprows, numbers.Integral) and skiprows < 0: raise AssertionError('cannot skip rows starting from the end of the ' 'data (you passed a negative value)') - return _parse(flavor, io, match, header, index_col, skiprows, infer_types, - attrs) + return _parse(flavor, io, opener, match, header, index_col, skiprows, + infer_types, attrs) + + +read_html.__doc__ %= 'urllib.request' if compat.PY3 else 'urllib2' diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py index 44e4b5cfda7b6..f9555847bd002 100644 --- a/pandas/io/tests/test_html.py +++ b/pandas/io/tests/test_html.py @@ -426,6 +426,16 @@ def test_gold_canyon(self): attrs={'id': 'table'}, infer_types=False)[0] self.assert_(gc in df.to_string()) + @slow + def test_custom_opener(self): + from pandas.io.common import build_opener + opener = build_opener() + opener.addheaders = [('User-agent', 'Mozilla/5.0')] + url = 'http://www.transfermarkt.co.uk/en/premier-league/gegentorminuten/wettbewerb_GB1.html' + res = read_html(url, opener=opener) + self.assert_(isinstance(res, list)) + self.assert_(isinstance(res[0], DataFrame)) + class TestReadHtmlLxml(TestCase): def run_read_html(self, *args, **kwargs):
closes #4927
https://api.github.com/repos/pandas-dev/pandas/pulls/4931
2013-09-22T02:28:22Z
2013-09-23T03:29:44Z
null
2014-06-24T19:51:24Z
Scatterplot Update for #3473
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 49dc31514da7a..2d2218c60119f 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -419,37 +419,6 @@ def test_explicit_label(self): ax = df.plot(x='a', y='b', label='LABEL') self.assertEqual(ax.xaxis.get_label().get_text(), 'LABEL') - @slow - def test_plot_xy(self): - import matplotlib.pyplot as plt - # columns.inferred_type == 'string' - df = tm.makeTimeDataFrame() - self._check_data(df.plot(x=0, y=1), - df.set_index('A')['B'].plot()) - self._check_data(df.plot(x=0), df.set_index('A').plot()) - self._check_data(df.plot(y=0), df.B.plot()) - self._check_data(df.plot(x='A', y='B'), - df.set_index('A').B.plot()) - self._check_data(df.plot(x='A'), df.set_index('A').plot()) - self._check_data(df.plot(y='B'), df.B.plot()) - - # columns.inferred_type == 'integer' - df.columns = lrange(1, len(df.columns) + 1) - self._check_data(df.plot(x=1, y=2), - df.set_index(1)[2].plot()) - self._check_data(df.plot(x=1), df.set_index(1).plot()) - self._check_data(df.plot(y=1), df[1].plot()) - - # figsize and title - ax = df.plot(x=1, y=2, title='Test', figsize=(16, 8)) - - self.assertEqual(ax.title.get_text(), 'Test') - assert_array_equal(np.round(ax.figure.get_size_inches()), - np.array((16., 8.))) - - # columns.inferred_type == 'mixed' - # TODO add MultiIndex test - @slow def test_xcompat(self): import pandas as pd @@ -534,6 +503,27 @@ def test_subplots(self): [self.assert_(label.get_visible()) for label in ax.get_yticklabels()] + @slow + def test_plot_scatter(self): + from matplotlib.pylab import close + df = DataFrame(randn(6, 4), + index=list(string.ascii_letters[:6]), + columns=['x', 'y', 'z', 'four']) + + _check_plot_works(df.plot, x='x', y='y', kind='scatter') + _check_plot_works(df.plot, x='x', y='y', kind='scatter', legend=False) + _check_plot_works(df.plot, x='x', y='y', kind='scatter', subplots=True) + _check_plot_works(df.plot, x='x', y='y', kind='scatter', stacked=True) + + df = DataFrame(randn(10, 15), + index=list(string.ascii_letters[:10]), + columns=lrange(15)) + _check_plot_works(df.plot, x=1, y=2, kind='scatter') + + df = DataFrame({'a': [0, 1], 'b': [1, 0]}) + _check_plot_works(df.plot, x='a',y='b',kind='scatter') + + @slow def test_plot_bar(self): from matplotlib.pylab import close diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 6631a3cf8c6f1..d76534d285917 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1193,7 +1193,29 @@ def _post_plot_logic(self): for ax in self.axes: ax.legend(loc='best') - +class ScatterPlot(MPLPlot): + def __init__(self, data, **kwargs): + MPLPlot.__init__(self, data, **kwargs) + if 'x' not in kwargs and 'y' not in kwargs: + raise ValueError( 'Scatterplot requires and X and Y column') + + def _make_plot(self): + plotf = self._get_plot_function() + colors = self._get_colors() + + for i, (label, y) in enumerate(self._iter_data()): + ax = self._get_ax(i) + #kwds = self.kwds.copy() + x, y = self.kwds['x'], self.kwds['y'] + #print x, y + ax = ax.scatter(x, y) + style = self._get_style(i, label) + + def _post_plot_logic(self): + if self.subplots and self.legend: + for ax in self.axes: + ax.legend(loc='best') + class LinePlot(MPLPlot): def __init__(self, data, **kwargs): @@ -1554,7 +1576,7 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True, secondary_y=False, **kwds): """ - Make line or bar plot of DataFrame's series with the index on the x-axis + Make line, bar, or scater plots of DataFrame series with the index on the x-axis using matplotlib / pylab. Parameters @@ -1585,10 +1607,11 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True, ax : matplotlib axis object, default None style : list or dict matplotlib line style per column - kind : {'line', 'bar', 'barh', 'kde', 'density'} + kind : {'line', 'bar', 'barh', 'kde', 'density', 'scatter'} bar : vertical bar plot barh : horizontal bar plot kde/density : Kernel Density Estimation plot + scatter: scatter plot logx : boolean, default False For line plots, use log scaling on x axis logy : boolean, default False @@ -1624,6 +1647,8 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True, klass = BarPlot elif kind == 'kde': klass = KdePlot + elif kind == 'scatter': + klass = ScatterPlot else: raise ValueError('Invalid chart type given %s' % kind) @@ -1639,21 +1664,35 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True, label = kwds.pop('label', label) ser = frame[y] ser.index.name = label - return plot_series(ser, label=label, kind=kind, - use_index=use_index, - rot=rot, xticks=xticks, yticks=yticks, - xlim=xlim, ylim=ylim, ax=ax, style=style, - grid=grid, logx=logx, logy=logy, - secondary_y=secondary_y, title=title, - figsize=figsize, fontsize=fontsize, **kwds) - - plot_obj = klass(frame, kind=kind, subplots=subplots, rot=rot, - legend=legend, ax=ax, style=style, fontsize=fontsize, - use_index=use_index, sharex=sharex, sharey=sharey, - xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, - title=title, grid=grid, figsize=figsize, logx=logx, - logy=logy, sort_columns=sort_columns, - secondary_y=secondary_y, **kwds) + if kind != 'scatter': + return plot_series(ser, label=label, kind=kind, + use_index=use_index, + rot=rot, xticks=xticks, yticks=yticks, + xlim=xlim, ylim=ylim, ax=ax, style=style, + grid=grid, logx=logx, logy=logy, + secondary_y=secondary_y, title=title, + figsize=figsize, fontsize=fontsize, **kwds) + if kind == 'scatter': + plot_obj = klass(frame, x=frame.index, y=ser, + kind=kind, subplots=subplots, rot=rot, + legend=legend, ax=ax, style=style, fontsize=fontsize, + use_index=use_index, sharex=sharex, sharey=sharey, + xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, + title=title, grid=grid, figsize=figsize, logx=logx, + logy=logy, sort_columns=sort_columns, + secondary_y=secondary_y, **kwds) + + else: + plot_obj = klass(frame, kind=kind, subplots=subplots, rot=rot, + legend=legend, ax=ax, style=style, fontsize=fontsize, + use_index=use_index, sharex=sharex, sharey=sharey, + xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, + title=title, grid=grid, figsize=figsize, logx=logx, + logy=logy, sort_columns=sort_columns, + secondary_y=secondary_y, **kwds) + + + plot_obj.generate() plot_obj.draw() if subplots:
Rebased Code for Scatterplot targetting bug #3473
https://api.github.com/repos/pandas-dev/pandas/pulls/4930
2013-09-22T02:13:10Z
2013-09-30T18:48:27Z
null
2014-06-12T21:34:02Z
BUG: Fix FrozenNDArray & FrozenList string methods
diff --git a/doc/source/release.rst b/doc/source/release.rst index 555c79baf8584..75097ee50e8c1 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -446,6 +446,7 @@ Bug Fixes the ``by`` argument was passed (:issue:`4112`, :issue:`4113`). - Fixed a bug in ``convert_objects`` for > 2 ndims (:issue:`4937`) - Fixed a bug in DataFrame/Panel cache insertion and subsequent indexing (:issue:`4939`) + - Fixed string methods for ``FrozenNDArray`` and ``FrozenList`` (:issue:`4929`) pandas 0.12.0 ------------- diff --git a/pandas/core/base.py b/pandas/core/base.py index fb0d56113ede9..14070d8825393 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -122,9 +122,12 @@ def _disabled(self, *args, **kwargs): def __unicode__(self): from pandas.core.common import pprint_thing + return pprint_thing(self, quote_strings=True, + escape_chars=('\t', '\r', '\n')) + + def __repr__(self): return "%s(%s)" % (self.__class__.__name__, - pprint_thing(self, quote_strings=True, - escape_chars=('\t', '\r', '\n'))) + str(self)) __setitem__ = __setslice__ = __delitem__ = __delslice__ = _disabled pop = append = extend = remove = sort = insert = _disabled @@ -154,3 +157,12 @@ def values(self): """returns *copy* of underlying array""" arr = self.view(np.ndarray).copy() return arr + + def __unicode__(self): + """ + Return a string representation for this object. + + Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. + """ + prepr = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),quote_strings=True) + return '%s(%s, dtype=%s)' % (type(self).__name__, prepr, self.dtype) diff --git a/pandas/core/index.py b/pandas/core/index.py index 1d3f181b731e8..f2a22580f16b4 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -228,15 +228,6 @@ def copy(self, names=None, name=None, dtype=None, deep=False): new_index = new_index.astype(dtype) return new_index - def __unicode__(self): - """ - Return a string representation for a particular Index - - Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. - """ - prepr = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),quote_strings=True) - return '%s(%s, dtype=%s)' % (type(self).__name__, prepr, self.dtype) - def to_series(self): """ return a series with both index and values equal to the index keys diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index c6285bc95b855..5d5a269b90428 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -1,10 +1,30 @@ import re import unittest import numpy as np +import pandas.compat as compat +from pandas.compat import u from pandas.core.base import FrozenList, FrozenNDArray from pandas.util.testing import assertRaisesRegexp, assert_isinstance +class CheckStringMixin(object): + def test_string_methods_dont_fail(self): + repr(self.container) + str(self.container) + bytes(self.container) + if not compat.PY3: + unicode(self.container) + + def test_tricky_container(self): + if not hasattr(self, 'unicode_container'): + raise nose.SkipTest('Need unicode_container to test with this') + repr(self.unicode_container) + str(self.unicode_container) + bytes(self.unicode_container) + if not compat.PY3: + unicode(self.unicode_container) + + class CheckImmutable(object): mutable_regex = re.compile('does not support mutable operations') @@ -43,8 +63,9 @@ def check_result(self, result, expected, klass=None): self.assertEqual(result, expected) -class TestFrozenList(CheckImmutable, unittest.TestCase): +class TestFrozenList(CheckImmutable, CheckStringMixin, unittest.TestCase): mutable_methods = ('extend', 'pop', 'remove', 'insert') + unicode_container = FrozenList([u("\u05d0"), u("\u05d1"), "c"]) def setUp(self): self.lst = [1, 2, 3, 4, 5] @@ -68,8 +89,9 @@ def test_inplace(self): self.check_result(r, self.lst) -class TestFrozenNDArray(CheckImmutable, unittest.TestCase): +class TestFrozenNDArray(CheckImmutable, CheckStringMixin, unittest.TestCase): mutable_methods = ('put', 'itemset', 'fill') + unicode_container = FrozenNDArray([u("\u05d0"), u("\u05d1"), "c"]) def setUp(self): self.lst = [3, 5, 7, -2]
Plus basic tests (i.e., "Hey! If you pass me unicode I don't fail - yay!") Previously were showing bad object reprs, now do this: ``` In [4]: mi = MultiIndex.from_arrays([range(10), range(10)]) In [5]: mi Out[5]: MultiIndex [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)] In [6]: mi.levels Out[6]: FrozenList([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) In [7]: mi.levels[0] Out[7]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64) In [8]: mi.labels[0] Out[8]: FrozenNDArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64) In [9]: mi.labels[1] Out[9]: FrozenNDArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64) In [10]: mi = MultiIndex.from MultiIndex.from_arrays MultiIndex.from_tuples In [10]: mi = MultiIndex.from_arrays([range(5), list('abcde')]) In [11]: mi.levels Out[11]: FrozenList([[0, 1, 2, 3, 4], [u'a', u'b', u'c', u'd', u'e']]) In [12]: mi.labels[0] Out[12]: FrozenNDArray([0, 1, 2, 3, 4], dtype=int64) In [13]: mi.labels[1] Out[13]: FrozenNDArray([0, 1, 2, 3, 4], dtype=int64) In [14]: mi.levels[0] Out[14]: Int64Index([0, 1, 2, 3, 4], dtype=int64) In [15]: mi.levels[1] Out[15]: Index([u'a', u'b', u'c', u'd', u'e'], dtype=object) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4929
2013-09-22T01:35:30Z
2013-09-23T01:24:51Z
2013-09-23T01:24:51Z
2014-06-13T23:41:37Z
BUG: Fix bound checking for Timestamp() with dt64 #4065
diff --git a/doc/source/release.rst b/doc/source/release.rst index ebba7444e82d8..3b7bd6544e569 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -555,7 +555,7 @@ Bug Fixes type of headers (:issue:`5048`). - Fixed a bug where ``DatetimeIndex`` joins with ``PeriodIndex`` caused a stack overflow (:issue:`3899`). - + - Fix bound checking for Timestamp() with datetime64 input (:issue:`4065`) pandas 0.12.0 ------------- diff --git a/pandas/core/common.py b/pandas/core/common.py index 2c5ca42c7be86..108b82eaf9056 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -348,6 +348,13 @@ def _pickle_array(arr): def _unpickle_array(bytes): arr = read_array(BytesIO(bytes)) + + # All datetimes should be stored as M8[ns]. When unpickling with + # numpy1.6, it will read these as M8[us]. So this ensures all + # datetime64 types are read as MS[ns] + if is_datetime64_dtype(arr): + arr = arr.view(_NS_DTYPE) + return arr @@ -1780,6 +1787,14 @@ def is_datetime64_dtype(arr_or_dtype): tipo = arr_or_dtype.dtype.type return issubclass(tipo, np.datetime64) +def is_datetime64_ns_dtype(arr_or_dtype): + if isinstance(arr_or_dtype, np.dtype): + tipo = arr_or_dtype + elif isinstance(arr_or_dtype, type): + tipo = np.dtype(arr_or_dtype) + else: + tipo = arr_or_dtype.dtype + return tipo == _NS_DTYPE def is_timedelta64_dtype(arr_or_dtype): if isinstance(arr_or_dtype, np.dtype): diff --git a/pandas/src/datetime.pxd b/pandas/src/datetime.pxd index 1a977aab48514..3e11c9d20fb0d 100644 --- a/pandas/src/datetime.pxd +++ b/pandas/src/datetime.pxd @@ -85,6 +85,9 @@ cdef extern from "datetime/np_datetime.h": npy_int64 year npy_int32 month, day, hour, min, sec, us, ps, as + int cmp_pandas_datetimestruct(pandas_datetimestruct *a, + pandas_datetimestruct *b) + int convert_pydatetime_to_datetimestruct(PyObject *obj, pandas_datetimestruct *out, PANDAS_DATETIMEUNIT *out_bestunit, diff --git a/pandas/src/datetime/np_datetime.c b/pandas/src/datetime/np_datetime.c index 527ce615917cf..c30b404d2b8b2 100644 --- a/pandas/src/datetime/np_datetime.c +++ b/pandas/src/datetime/np_datetime.c @@ -273,6 +273,69 @@ set_datetimestruct_days(npy_int64 days, pandas_datetimestruct *dts) } } +/* + * Compares two pandas_datetimestruct objects chronologically + */ +int +cmp_pandas_datetimestruct(pandas_datetimestruct *a, pandas_datetimestruct *b) +{ + if (a->year > b->year) { + return 1; + } else if (a->year < b->year) { + return -1; + } + + if (a->month > b->month) { + return 1; + } else if (a->month < b->month) { + return -1; + } + + if (a->day > b->day) { + return 1; + } else if (a->day < b->day) { + return -1; + } + + if (a->hour > b->hour) { + return 1; + } else if (a->hour < b->hour) { + return -1; + } + + if (a->min > b->min) { + return 1; + } else if (a->min < b->min) { + return -1; + } + + if (a->sec > b->sec) { + return 1; + } else if (a->sec < b->sec) { + return -1; + } + + if (a->us > b->us) { + return 1; + } else if (a->us < b->us) { + return -1; + } + + if (a->ps > b->ps) { + return 1; + } else if (a->ps < b->ps) { + return -1; + } + + if (a->as > b->as) { + return 1; + } else if (a->as < b->as) { + return -1; + } + + return 0; +} + /* * * Tests for and converts a Python datetime.datetime or datetime.date diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 281ac0cc8a35a..7d67f3b013b37 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -204,7 +204,7 @@ def __new__(cls, data=None, data = _str_to_dt_array(data, offset, dayfirst=dayfirst, yearfirst=yearfirst) else: - data = tools.to_datetime(data) + data = tools.to_datetime(data, errors='raise') data.offset = offset if isinstance(data, DatetimeIndex): if name is not None: @@ -243,14 +243,14 @@ def __new__(cls, data=None, subarr = data.view(_NS_DTYPE) else: try: - subarr = tools.to_datetime(data) + subarr = tools.to_datetime(data, box=False) except ValueError: # tz aware - subarr = tools.to_datetime(data, utc=True) + subarr = tools.to_datetime(data, box=False, utc=True) if not np.issubdtype(subarr.dtype, np.datetime64): - raise TypeError('Unable to convert %s to datetime dtype' - % str(data)) + raise ValueError('Unable to convert %s to datetime dtype' + % str(data)) if isinstance(subarr, DatetimeIndex): if tz is None: @@ -934,7 +934,7 @@ def join(self, other, how='left', level=None, return_indexers=False): 'mixed-integer-float', 'mixed')): try: other = DatetimeIndex(other) - except TypeError: + except (TypeError, ValueError): pass this, other = self._maybe_utc_convert(other) @@ -1051,7 +1051,7 @@ def intersection(self, other): if not isinstance(other, DatetimeIndex): try: other = DatetimeIndex(other) - except TypeError: + except (TypeError, ValueError): pass result = Index.intersection(self, other) if isinstance(result, DatetimeIndex): diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 5329f37095961..cda84a99a95db 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -1,5 +1,5 @@ # pylint: disable-msg=E1101,W0612 -from datetime import datetime, time, timedelta +from datetime import datetime, time, timedelta, date import sys import os import unittest @@ -952,6 +952,81 @@ def test_to_datetime_list_of_integers(self): self.assert_(rng.equals(result)) + def test_to_datetime_dt64s(self): + in_bound_dts = [ + np.datetime64('2000-01-01'), + np.datetime64('2000-01-02'), + ] + + for dt in in_bound_dts: + self.assertEqual( + pd.to_datetime(dt), + Timestamp(dt) + ) + + oob_dts = [ + np.datetime64('1000-01-01'), + np.datetime64('5000-01-02'), + ] + + for dt in oob_dts: + self.assertRaises(ValueError, pd.to_datetime, dt, errors='raise') + self.assertRaises(ValueError, tslib.Timestamp, dt) + self.assert_(pd.to_datetime(dt, coerce=True) is NaT) + + def test_to_datetime_array_of_dt64s(self): + dts = [ + np.datetime64('2000-01-01'), + np.datetime64('2000-01-02'), + ] + + # Assuming all datetimes are in bounds, to_datetime() returns + # an array that is equal to Timestamp() parsing + self.assert_( + np.array_equal( + pd.to_datetime(dts, box=False), + np.array([Timestamp(x).asm8 for x in dts]) + ) + ) + + # A list of datetimes where the last one is out of bounds + dts_with_oob = dts + [np.datetime64('9999-01-01')] + + self.assertRaises( + ValueError, + pd.to_datetime, + dts_with_oob, + coerce=False, + errors='raise' + ) + + self.assert_( + np.array_equal( + pd.to_datetime(dts_with_oob, box=False, coerce=True), + np.array( + [ + Timestamp(dts_with_oob[0]).asm8, + Timestamp(dts_with_oob[1]).asm8, + iNaT, + ], + dtype='M8' + ) + ) + ) + + # With coerce=False and errors='ignore', out of bounds datetime64s + # are converted to their .item(), which depending on the version of + # numpy is either a python datetime.datetime or datetime.date + self.assert_( + np.array_equal( + pd.to_datetime(dts_with_oob, box=False, coerce=False), + np.array( + [dt.item() for dt in dts_with_oob], + dtype='O' + ) + ) + ) + def test_index_to_datetime(self): idx = Index(['1/1/2000', '1/2/2000', '1/3/2000']) diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 4e7daede03085..20138cb8b1eb8 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -4,7 +4,7 @@ import numpy as np from pandas import tslib -from datetime import datetime +import datetime from pandas.core.api import Timestamp @@ -15,19 +15,53 @@ from pandas import _np_version_under1p7 -class TestDatetimeParsingWrappers(unittest.TestCase): - def test_verify_datetime_bounds(self): - for year in (1, 1000, 1677, 2262, 5000): - dt = datetime(year, 1, 1) - self.assertRaises( - ValueError, - tslib.verify_datetime_bounds, - dt - ) +class TestTimestamp(unittest.TestCase): + def test_bounds_with_different_units(self): + out_of_bounds_dates = ( + '1677-09-21', + '2262-04-12', + ) + + time_units = ('D', 'h', 'm', 's', 'ms', 'us') - for year in (1678, 2000, 2261): - tslib.verify_datetime_bounds(datetime(year, 1, 1)) + for date_string in out_of_bounds_dates: + for unit in time_units: + self.assertRaises( + ValueError, + tslib.Timestamp, + np.datetime64(date_string, dtype='M8[%s]' % unit) + ) + + in_bounds_dates = ( + '1677-09-23', + '2262-04-11', + ) + for date_string in in_bounds_dates: + for unit in time_units: + tslib.Timestamp( + np.datetime64(date_string, dtype='M8[%s]' % unit) + ) + + def test_barely_oob_dts(self): + one_us = np.timedelta64(1) + + # By definition we can't go out of bounds in [ns], so we + # convert the datetime64s to [us] so we can go out of bounds + min_ts_us = np.datetime64(tslib.Timestamp.min).astype('M8[us]') + max_ts_us = np.datetime64(tslib.Timestamp.max).astype('M8[us]') + + # No error for the min/max datetimes + tslib.Timestamp(min_ts_us) + tslib.Timestamp(max_ts_us) + + # One us less than the minimum is an error + self.assertRaises(ValueError, tslib.Timestamp, min_ts_us - one_us) + + # One us more than the maximum is an error + self.assertRaises(ValueError, tslib.Timestamp, max_ts_us + one_us) + +class TestDatetimeParsingWrappers(unittest.TestCase): def test_does_not_convert_mixed_integer(self): bad_date_strings = ( '-50000', @@ -97,15 +131,45 @@ def test_number_looking_strings_not_into_datetime(self): arr = np.array(['1', '2', '3', '4', '5'], dtype=object) self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) - def test_dates_outside_of_datetime64_ns_bounds(self): - # These datetimes are outside of the bounds of the - # datetime64[ns] bounds, so they cannot be converted to - # datetimes - arr = np.array(['1/1/1676', '1/2/1676'], dtype=object) - self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + def test_coercing_dates_outside_of_datetime64_ns_bounds(self): + invalid_dates = [ + datetime.date(1000, 1, 1), + datetime.datetime(1000, 1, 1), + '1000-01-01', + 'Jan 1, 1000', + np.datetime64('1000-01-01'), + ] - arr = np.array(['1/1/2263', '1/2/2263'], dtype=object) - self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + for invalid_date in invalid_dates: + self.assertRaises( + ValueError, + tslib.array_to_datetime, + np.array([invalid_date], dtype='object'), + coerce=False, + raise_=True, + ) + self.assert_( + np.array_equal( + tslib.array_to_datetime( + np.array([invalid_date], dtype='object'), coerce=True + ), + np.array([tslib.iNaT], dtype='M8[ns]') + ) + ) + + arr = np.array(['1/1/1000', '1/1/2000'], dtype=object) + self.assert_( + np.array_equal( + tslib.array_to_datetime(arr, coerce=True), + np.array( + [ + tslib.iNaT, + '2000-01-01T00:00:00.000000000-0000' + ], + dtype='M8[ns]' + ) + ) + ) def test_coerce_of_invalid_datetimes(self): arr = np.array(['01-01-2013', 'not_a_date', '1'], dtype=object) @@ -130,11 +194,11 @@ def test_coerce_of_invalid_datetimes(self): ) -class TestTimestamp(unittest.TestCase): +class TestTimestampNsOperations(unittest.TestCase): def setUp(self): if _np_version_under1p7: raise nose.SkipTest('numpy >= 1.7 required') - self.timestamp = Timestamp(datetime.utcnow()) + self.timestamp = Timestamp(datetime.datetime.utcnow()) def assert_ns_timedelta(self, modified_timestamp, expected_value): value = self.timestamp.value diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index 39364d21d4aa1..793d9409e662e 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -89,13 +89,12 @@ def _convert_listlike(arg, box): if isinstance(arg, (list,tuple)): arg = np.array(arg, dtype='O') - if com.is_datetime64_dtype(arg): + if com.is_datetime64_ns_dtype(arg): if box and not isinstance(arg, DatetimeIndex): try: return DatetimeIndex(arg, tz='utc' if utc else None) - except ValueError as e: - values, tz = tslib.datetime_to_datetime64(arg) - return DatetimeIndex._simple_new(values, None, tz=tz) + except ValueError: + pass return arg diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 5f81389f318f8..ff3284b72aecb 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -404,6 +404,11 @@ cpdef object get_value_box(ndarray arr, object loc): # wraparound behavior when using the true int64 lower boundary cdef int64_t _NS_LOWER_BOUND = -9223285636854775000LL cdef int64_t _NS_UPPER_BOUND = 9223372036854775807LL + +cdef pandas_datetimestruct _NS_MIN_DTS, _NS_MAX_DTS +pandas_datetime_to_datetimestruct(_NS_LOWER_BOUND, PANDAS_FR_ns, &_NS_MIN_DTS) +pandas_datetime_to_datetimestruct(_NS_UPPER_BOUND, PANDAS_FR_ns, &_NS_MAX_DTS) + Timestamp.min = Timestamp(_NS_LOWER_BOUND) Timestamp.max = Timestamp(_NS_UPPER_BOUND) @@ -759,7 +764,7 @@ cdef convert_to_tsobject(object ts, object tz, object unit): if is_timestamp(ts): obj.value += ts.nanosecond - _check_dts_bounds(obj.value, &obj.dts) + _check_dts_bounds(&obj.dts) return obj elif PyDate_Check(ts): # Keep the converter same as PyDateTime's @@ -770,7 +775,7 @@ cdef convert_to_tsobject(object ts, object tz, object unit): type(ts)) if obj.value != NPY_NAT: - _check_dts_bounds(obj.value, &obj.dts) + _check_dts_bounds(&obj.dts) if tz is not None: _localize_tso(obj, tz) @@ -825,16 +830,26 @@ cdef inline object _get_zone(object tz): return tz -cdef inline _check_dts_bounds(int64_t value, pandas_datetimestruct *dts): - cdef pandas_datetimestruct dts2 - if dts.year <= 1677 or dts.year >= 2262: - pandas_datetime_to_datetimestruct(value, PANDAS_FR_ns, &dts2) - if dts2.year != dts.year: - fmt = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, dts.month, - dts.day, dts.hour, - dts.min, dts.sec) +class OutOfBoundsDatetime(ValueError): + pass + +cdef inline _check_dts_bounds(pandas_datetimestruct *dts): + cdef: + bint error = False + + if dts.year <= 1677 and cmp_pandas_datetimestruct(dts, &_NS_MIN_DTS) == -1: + error = True + elif ( + dts.year >= 2262 and + cmp_pandas_datetimestruct(dts, &_NS_MAX_DTS) == 1): + error = True - raise ValueError('Out of bounds nanosecond timestamp: %s' % fmt) + if error: + fmt = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, dts.month, + dts.day, dts.hour, + dts.min, dts.sec) + + raise OutOfBoundsDatetime('Out of bounds nanosecond timestamp: %s' % fmt) # elif isinstance(ts, _Timestamp): # tmp = ts @@ -869,12 +884,12 @@ def datetime_to_datetime64(ndarray[object] values): _ts = convert_to_tsobject(val, None, None) iresult[i] = _ts.value - _check_dts_bounds(iresult[i], &_ts.dts) + _check_dts_bounds(&_ts.dts) else: if inferred_tz is not None: raise ValueError('Cannot mix tz-aware with tz-naive values') iresult[i] = _pydatetime_to_dts(val, &dts) - _check_dts_bounds(iresult[i], &dts) + _check_dts_bounds(&dts) else: raise TypeError('Unrecognized value type: %s' % type(val)) @@ -882,14 +897,6 @@ def datetime_to_datetime64(ndarray[object] values): _not_datelike_strings = set(['a','A','m','M','p','P','t','T']) -def verify_datetime_bounds(dt): - """Verify datetime.datetime is within the datetime64[ns] bounds.""" - if dt.year <= 1677 or dt.year >= 2262: - raise ValueError( - 'Given datetime not within valid datetime64[ns] bounds' - ) - return dt - def _does_string_look_like_datetime(date_string): if date_string.startswith('0'): # Strings starting with 0 are more consistent with a @@ -907,15 +914,11 @@ def _does_string_look_like_datetime(date_string): return True -def parse_datetime_string(date_string, verify_bounds=True, **kwargs): +def parse_datetime_string(date_string, **kwargs): if not _does_string_look_like_datetime(date_string): raise ValueError('Given date string not likely a datetime.') dt = parse_date(date_string, **kwargs) - - if verify_bounds: - verify_datetime_bounds(dt) - return dt def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, @@ -942,7 +945,13 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, if utc_convert: _ts = convert_to_tsobject(val, None, unit) iresult[i] = _ts.value - _check_dts_bounds(iresult[i], &_ts.dts) + try: + _check_dts_bounds(&_ts.dts) + except ValueError: + if coerce: + iresult[i] = iNaT + continue + raise else: raise ValueError('Tz-aware datetime.datetime cannot ' 'be converted to datetime64 unless ' @@ -951,12 +960,30 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, iresult[i] = _pydatetime_to_dts(val, &dts) if is_timestamp(val): iresult[i] += (<_Timestamp>val).nanosecond - _check_dts_bounds(iresult[i], &dts) + try: + _check_dts_bounds(&dts) + except ValueError: + if coerce: + iresult[i] = iNaT + continue + raise elif PyDate_Check(val): iresult[i] = _date_to_datetime64(val, &dts) - _check_dts_bounds(iresult[i], &dts) + try: + _check_dts_bounds(&dts) + except ValueError: + if coerce: + iresult[i] = iNaT + continue + raise elif util.is_datetime64_object(val): - iresult[i] = _get_datetime64_nanos(val) + try: + iresult[i] = _get_datetime64_nanos(val) + except ValueError: + if coerce: + iresult[i] = iNaT + continue + raise # if we are coercing, dont' allow integers elif util.is_integer_object(val) and not coerce: @@ -982,17 +1009,26 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, _string_to_dts(val, &dts) iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) - _check_dts_bounds(iresult[i], &dts) + _check_dts_bounds(&dts) except ValueError: try: - result[i] = parse_datetime_string( - val, dayfirst=dayfirst + iresult[i] = _pydatetime_to_dts( + parse_datetime_string(val, dayfirst=dayfirst), + &dts ) except Exception: if coerce: iresult[i] = iNaT continue raise TypeError + + try: + _check_dts_bounds(&dts) + except ValueError: + if coerce: + iresult[i] = iNaT + continue + raise except: if coerce: iresult[i] = iNaT @@ -1000,6 +1036,18 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, raise return result + except OutOfBoundsDatetime: + if raise_: + raise + + oresult = np.empty(n, dtype=object) + for i in range(n): + val = values[i] + if util.is_datetime64_object(val): + oresult[i] = val.item() + else: + oresult[i] = val + return oresult except TypeError: oresult = np.empty(n, dtype=object) @@ -1014,6 +1062,8 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, continue try: oresult[i] = parse_datetime_string(val, dayfirst=dayfirst) + _pydatetime_to_dts(oresult[i], &dts) + _check_dts_bounds(&dts) except Exception: if raise_: raise @@ -1320,7 +1370,7 @@ def array_strptime(ndarray[object] values, object fmt): dts.us = fraction iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) - _check_dts_bounds(iresult[i], &dts) + _check_dts_bounds(&dts) return result @@ -1339,6 +1389,7 @@ cdef inline _get_datetime64_nanos(object val): if unit != PANDAS_FR_ns: pandas_datetime_to_datetimestruct(ival, unit, &dts) + _check_dts_bounds(&dts) return pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) else: return ival @@ -1398,6 +1449,7 @@ def cast_to_nanoseconds(ndarray arr): for i in range(n): pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) + _check_dts_bounds(&dts) return result
closes #4065 To fix the bug, this change adds bounds checking to _get_datetime64_nanos() for numpy datetimes that aren't already in [ns] units. Additionally, it updates _check_dts_bounds() to do the bound check just based off the pandas_datetimestruct, by comparing to the minimum and maximum valid pandas_datetimestructs for datetime64[ns]. It is simpler and more accurate than the previous system.
https://api.github.com/repos/pandas-dev/pandas/pulls/4926
2013-09-21T21:57:03Z
2013-10-07T23:00:26Z
2013-10-07T23:00:26Z
2014-06-21T19:09:49Z
ENH: evaluate datetime ops in python with eval
diff --git a/doc/source/release.rst b/doc/source/release.rst index e49812b207921..a932eda55ff32 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -335,6 +335,9 @@ Experimental Features - A :meth:`~pandas.DataFrame.query` method has been added that allows you to select elements of a ``DataFrame`` using a natural query syntax nearly identical to Python syntax. +- ``pd.eval`` and friends now evaluate operations involving ``datetime64`` + objects in Python space because ``numexpr`` cannot handle ``NaT`` values + (:issue:`4897`). .. _release.bug_fixes-0.13.0: diff --git a/pandas/computation/align.py b/pandas/computation/align.py index 60975bdc8a5b4..f420d0dacf34c 100644 --- a/pandas/computation/align.py +++ b/pandas/computation/align.py @@ -111,14 +111,20 @@ def _align_core(terms): typ = biggest._constructor axes = biggest.axes naxes = len(axes) + gt_than_one_axis = naxes > 1 - for term in (terms[i] for i in term_index): - for axis, items in enumerate(term.value.axes): - if isinstance(term.value, pd.Series) and naxes > 1: - ax, itm = naxes - 1, term.value.index + for value in (terms[i].value for i in term_index): + is_series = isinstance(value, pd.Series) + is_series_and_gt_one_axis = is_series and gt_than_one_axis + + for axis, items in enumerate(value.axes): + if is_series_and_gt_one_axis: + ax, itm = naxes - 1, value.index else: ax, itm = axis, items - axes[ax] = axes[ax].join(itm, how='outer') + + if not axes[ax].is_(itm): + axes[ax] = axes[ax].join(itm, how='outer') for i, ndim in compat.iteritems(ndims): for axis, items in zip(range(ndim), axes): @@ -136,7 +142,7 @@ def _align_core(terms): warnings.warn("Alignment difference on axis {0} is larger" " than an order of magnitude on term {1!r}, " "by more than {2:.4g}; performance may suffer" - "".format(axis, term.name, ordm), + "".format(axis, terms[i].name, ordm), category=pd.io.common.PerformanceWarning) if transpose: diff --git a/pandas/computation/expr.py b/pandas/computation/expr.py index ff9adc26b8201..ba2dffa9e71b8 100644 --- a/pandas/computation/expr.py +++ b/pandas/computation/expr.py @@ -493,8 +493,15 @@ def _possibly_evaluate_binop(self, op, op_class, lhs, rhs, maybe_eval_in_python=('==', '!=')): res = op(lhs, rhs) - # "in"/"not in" ops are always evaluated in python + if (res.op in _cmp_ops_syms and + lhs.is_datetime or rhs.is_datetime and + self.engine != 'pytables'): + # all date ops must be done in python bc numexpr doesn't work well + # with NaT + return self._possibly_eval(res, self.binary_ops) + if res.op in eval_in_python: + # "in"/"not in" ops are always evaluated in python return self._possibly_eval(res, eval_in_python) elif (lhs.return_type == object or rhs.return_type == object and self.engine != 'pytables'): diff --git a/pandas/computation/ops.py b/pandas/computation/ops.py index debc79e33968c..fd5ee159fe2b4 100644 --- a/pandas/computation/ops.py +++ b/pandas/computation/ops.py @@ -5,6 +5,7 @@ import operator as op from functools import partial from itertools import product, islice, chain +from datetime import datetime import numpy as np @@ -161,24 +162,16 @@ def raw(self): self.type)) @property - def kind(self): + def is_datetime(self): try: - return self.type.__name__ + t = self.type.type except AttributeError: - return self.type.type.__name__ + t = self.type + + return issubclass(t, (datetime, np.datetime64)) @property def value(self): - kind = self.kind.lower() - if kind == 'datetime64': - try: - return self._value.asi8 - except AttributeError: - return self._value.view('i8') - elif kind == 'datetime': - return pd.Timestamp(self._value) - elif kind == 'timestamp': - return self._value.asm8.view('i8') return self._value @value.setter @@ -248,6 +241,15 @@ def return_type(self): def isscalar(self): return all(operand.isscalar for operand in self.operands) + @property + def is_datetime(self): + try: + t = self.return_type.type + except AttributeError: + t = self.return_type + + return issubclass(t, (datetime, np.datetime64)) + def _in(x, y): """Compute the vectorized membership of ``x in y`` if possible, otherwise @@ -424,24 +426,20 @@ def stringify(value): lhs, rhs = self.lhs, self.rhs - if (is_term(lhs) and lhs.kind.startswith('datetime') and is_term(rhs) - and rhs.isscalar): + if is_term(lhs) and lhs.is_datetime and is_term(rhs) and rhs.isscalar: v = rhs.value if isinstance(v, (int, float)): v = stringify(v) - v = _ensure_decoded(v) - v = pd.Timestamp(v) + v = pd.Timestamp(_ensure_decoded(v)) if v.tz is not None: v = v.tz_convert('UTC') self.rhs.update(v) - if (is_term(rhs) and rhs.kind.startswith('datetime') and - is_term(lhs) and lhs.isscalar): + if is_term(rhs) and rhs.is_datetime and is_term(lhs) and lhs.isscalar: v = lhs.value if isinstance(v, (int, float)): v = stringify(v) - v = _ensure_decoded(v) - v = pd.Timestamp(v) + v = pd.Timestamp(_ensure_decoded(v)) if v.tz is not None: v = v.tz_convert('UTC') self.lhs.update(v) diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py index 3554b8a3f81e1..e9201c233753f 100755 --- a/pandas/computation/tests/test_eval.py +++ b/pandas/computation/tests/test_eval.py @@ -1003,7 +1003,7 @@ def check_performance_warning_for_poor_alignment(self, engine, parser): expected = ("Alignment difference on axis {0} is larger" " than an order of magnitude on term {1!r}, " "by more than {2:.4g}; performance may suffer" - "".format(1, 's', np.log10(s.size - df.shape[1]))) + "".format(1, 'df', np.log10(s.size - df.shape[1]))) assert_equal(msg, expected) def test_performance_warning_for_poor_alignment(self): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7b9a75753136e..01e0d74ef8ce6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1894,29 +1894,6 @@ def _getitem_frame(self, key): raise ValueError('Must pass DataFrame with boolean values only') return self.where(key) - def _get_index_resolvers(self, axis): - # index or columns - axis_index = getattr(self, axis) - d = dict() - - for i, name in enumerate(axis_index.names): - if name is not None: - key = level = name - else: - # prefix with 'i' or 'c' depending on the input axis - # e.g., you must do ilevel_0 for the 0th level of an unnamed - # multiiindex - level_string = '{prefix}level_{i}'.format(prefix=axis[0], i=i) - key = level_string - level = i - - d[key] = Series(axis_index.get_level_values(level).values, - index=axis_index, name=level) - - # put the index/columns itself in the dict - d[axis] = axis_index - return d - def query(self, expr, **kwargs): """Query the columns of a frame with a boolean expression. @@ -2037,8 +2014,7 @@ def eval(self, expr, **kwargs): """ resolvers = kwargs.pop('resolvers', None) if resolvers is None: - index_resolvers = self._get_index_resolvers('index') - index_resolvers.update(self._get_index_resolvers('columns')) + index_resolvers = self._get_resolvers() resolvers = [self, index_resolvers] kwargs['local_dict'] = _ensure_scope(resolvers=resolvers, **kwargs) return _eval(expr, **kwargs) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 4553e4804e98b..705679136c3d2 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -272,6 +272,42 @@ def _get_block_manager_axis(self, axis): return m - axis return axis + def _get_axis_resolvers(self, axis): + # index or columns + axis_index = getattr(self, axis) + d = dict() + prefix = axis[0] + + for i, name in enumerate(axis_index.names): + if name is not None: + key = level = name + else: + # prefix with 'i' or 'c' depending on the input axis + # e.g., you must do ilevel_0 for the 0th level of an unnamed + # multiiindex + key = '{prefix}level_{i}'.format(prefix=prefix, i=i) + level = i + + level_values = axis_index.get_level_values(level) + s = level_values.to_series() + s.index = axis_index + d[key] = s + + # put the index/columns itself in the dict + if isinstance(axis_index, MultiIndex): + dindex = axis_index + else: + dindex = axis_index.to_series() + + d[axis] = dindex + return d + + def _get_resolvers(self): + d = {} + for axis_name in self._AXIS_ORDERS: + d.update(self._get_axis_resolvers(axis_name)) + return d + @property def _info_axis(self): return getattr(self, self._info_axis_name) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index a6f806d5ce097..e5d2bb17ec7a8 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -11423,6 +11423,57 @@ def test_query_with_partially_named_multiindex(self): for parser, engine in product(['pandas'], ENGINES): yield self.check_query_with_partially_named_multiindex, parser, engine + def test_query_multiindex_get_index_resolvers(self): + for parser, engine in product(['pandas'], ENGINES): + yield self.check_query_multiindex_get_index_resolvers, parser, engine + + def check_query_multiindex_get_index_resolvers(self, parser, engine): + df = mkdf(10, 3, r_idx_nlevels=2, r_idx_names=['spam', 'eggs']) + resolvers = df._get_resolvers() + + def to_series(mi, level): + level_values = mi.get_level_values(level) + s = level_values.to_series() + s.index = mi + return s + + col_series = df.columns.to_series() + expected = {'index': df.index, + 'columns': col_series, + 'spam': to_series(df.index, 'spam'), + 'eggs': to_series(df.index, 'eggs'), + 'C0': col_series} + for k, v in resolvers.items(): + if isinstance(v, Index): + assert v.is_(expected[k]) + elif isinstance(v, Series): + print(k) + tm.assert_series_equal(v, expected[k]) + else: + raise AssertionError("object must be a Series or Index") + + def test_raise_on_panel_with_multiindex(self): + for parser, engine in product(PARSERS, ENGINES): + yield self.check_raise_on_panel_with_multiindex, parser, engine + + def check_raise_on_panel_with_multiindex(self, parser, engine): + skip_if_no_ne() + p = tm.makePanel(7) + p.items = tm.makeCustomIndex(len(p.items), nlevels=2) + with tm.assertRaises(NotImplementedError): + pd.eval('p + 1', parser=parser, engine=engine) + + def test_raise_on_panel4d_with_multiindex(self): + for parser, engine in product(PARSERS, ENGINES): + yield self.check_raise_on_panel4d_with_multiindex, parser, engine + + def check_raise_on_panel4d_with_multiindex(self, parser, engine): + skip_if_no_ne() + p4d = tm.makePanel4D(7) + p4d.items = tm.makeCustomIndex(len(p4d.items), nlevels=2) + with tm.assertRaises(NotImplementedError): + pd.eval('p4d + 1', parser=parser, engine=engine) + class TestDataFrameQueryNumExprPandas(unittest.TestCase): @classmethod @@ -11446,6 +11497,71 @@ def test_date_query_method(self): expec = df[(df.dates1 < '20130101') & ('20130101' < df.dates3)] assert_frame_equal(res, expec) + def test_date_query_with_NaT(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates2'] = date_range('1/1/2013', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.loc[np.random.rand(n) > 0.5, 'dates1'] = pd.NaT + df.loc[np.random.rand(n) > 0.5, 'dates3'] = pd.NaT + res = df.query('dates1 < 20130101 < dates3', engine=engine, + parser=parser) + expec = df[(df.dates1 < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_index_query(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.set_index('dates1', inplace=True, drop=True) + res = df.query('index < 20130101 < dates3', engine=engine, + parser=parser) + expec = df[(df.index < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_index_query_with_NaT(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.iloc[0, 0] = pd.NaT + df.set_index('dates1', inplace=True, drop=True) + res = df.query('index < 20130101 < dates3', engine=engine, + parser=parser) + expec = df[(df.index < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_index_query_with_NaT_duplicates(self): + engine, parser = self.engine, self.parser + n = 10 + d = {} + d['dates1'] = date_range('1/1/2012', periods=n) + d['dates3'] = date_range('1/1/2014', periods=n) + df = DataFrame(d) + df.loc[np.random.rand(n) > 0.5, 'dates1'] = pd.NaT + df.set_index('dates1', inplace=True, drop=True) + res = df.query('index < 20130101 < dates3', engine=engine, parser=parser) + expec = df[(df.index.to_series() < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_query_with_non_date(self): + engine, parser = self.engine, self.parser + + n = 10 + df = DataFrame({'dates': date_range('1/1/2012', periods=n), + 'nondate': np.arange(n)}) + + ops = '==', '!=', '<', '>', '<=', '>=' + + for op in ops: + with tm.assertRaises(TypeError): + df.query('dates %s nondate' % op, parser=parser, engine=engine) + def test_query_scope(self): engine, parser = self.engine, self.parser from pandas.computation.common import NameResolutionError @@ -11608,6 +11724,57 @@ def test_date_query_method(self): expec = df[(df.dates1 < '20130101') & ('20130101' < df.dates3)] assert_frame_equal(res, expec) + def test_date_query_with_NaT(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates2'] = date_range('1/1/2013', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.loc[np.random.rand(n) > 0.5, 'dates1'] = pd.NaT + df.loc[np.random.rand(n) > 0.5, 'dates3'] = pd.NaT + res = df.query('(dates1 < 20130101) & (20130101 < dates3)', + engine=engine, parser=parser) + expec = df[(df.dates1 < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_index_query(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.set_index('dates1', inplace=True, drop=True) + res = df.query('(index < 20130101) & (20130101 < dates3)', + engine=engine, parser=parser) + expec = df[(df.index < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_index_query_with_NaT(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.iloc[0, 0] = pd.NaT + df.set_index('dates1', inplace=True, drop=True) + res = df.query('(index < 20130101) & (20130101 < dates3)', + engine=engine, parser=parser) + expec = df[(df.index < '20130101') & ('20130101' < df.dates3)] + assert_frame_equal(res, expec) + + def test_date_index_query_with_NaT_duplicates(self): + engine, parser = self.engine, self.parser + n = 10 + df = DataFrame(randn(n, 3)) + df['dates1'] = date_range('1/1/2012', periods=n) + df['dates3'] = date_range('1/1/2014', periods=n) + df.loc[np.random.rand(n) > 0.5, 'dates1'] = pd.NaT + df.set_index('dates1', inplace=True, drop=True) + with tm.assertRaises(NotImplementedError): + res = df.query('index < 20130101 < dates3', engine=engine, + parser=parser) + def test_nested_scope(self): engine = self.engine parser = self.parser diff --git a/vb_suite/binary_ops.py b/vb_suite/binary_ops.py index 8293f650425e3..fc84dd8bcdb81 100644 --- a/vb_suite/binary_ops.py +++ b/vb_suite/binary_ops.py @@ -106,7 +106,7 @@ setup = common_setup + """ N = 1000000 halfway = N // 2 - 1 -s = Series(date_range('20010101', periods=N, freq='D')) +s = Series(date_range('20010101', periods=N, freq='T')) ts = s[halfway] """ diff --git a/vb_suite/eval.py b/vb_suite/eval.py index c666cd431cbb4..506d00b8bf9f9 100644 --- a/vb_suite/eval.py +++ b/vb_suite/eval.py @@ -47,12 +47,12 @@ eval_frame_mult_all_threads = \ Benchmark("pd.eval('df * df2 * df3 * df4')", common_setup, name='eval_frame_mult_all_threads', - start_date=datetime(2012, 7, 21)) + start_date=datetime(2013, 7, 21)) eval_frame_mult_one_thread = \ Benchmark("pd.eval('df * df2 * df3 * df4')", setup, name='eval_frame_mult_one_thread', - start_date=datetime(2012, 7, 26)) + start_date=datetime(2013, 7, 26)) eval_frame_mult_python = \ Benchmark("pdl.eval('df * df2 * df3 * df4', engine='python')", @@ -62,7 +62,7 @@ eval_frame_mult_python_one_thread = \ Benchmark("pd.eval('df * df2 * df3 * df4', engine='python')", setup, name='eval_frame_mult_python_one_thread', - start_date=datetime(2012, 7, 26)) + start_date=datetime(2013, 7, 26)) #---------------------------------------------------------------------- # multi and @@ -71,12 +71,12 @@ Benchmark("pd.eval('(df > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0)')", common_setup, name='eval_frame_and_all_threads', - start_date=datetime(2012, 7, 21)) + start_date=datetime(2013, 7, 21)) eval_frame_and_one_thread = \ Benchmark("pd.eval('(df > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0)')", setup, name='eval_frame_and_one_thread', - start_date=datetime(2012, 7, 26)) + start_date=datetime(2013, 7, 26)) setup = common_setup eval_frame_and_python = \ @@ -88,19 +88,19 @@ Benchmark("pd.eval('(df > 0) & (df2 > 0) & (df3 > 0) & (df4 > 0)', engine='python')", setup, name='eval_frame_and_python_one_thread', - start_date=datetime(2012, 7, 26)) + start_date=datetime(2013, 7, 26)) #-------------------------------------------------------------------- # chained comp eval_frame_chained_cmp_all_threads = \ Benchmark("pd.eval('df < df2 < df3 < df4')", common_setup, name='eval_frame_chained_cmp_all_threads', - start_date=datetime(2012, 7, 21)) + start_date=datetime(2013, 7, 21)) eval_frame_chained_cmp_one_thread = \ Benchmark("pd.eval('df < df2 < df3 < df4')", setup, name='eval_frame_chained_cmp_one_thread', - start_date=datetime(2012, 7, 26)) + start_date=datetime(2013, 7, 26)) setup = common_setup eval_frame_chained_cmp_python = \ @@ -111,4 +111,31 @@ eval_frame_chained_cmp_one_thread = \ Benchmark("pd.eval('df < df2 < df3 < df4', engine='python')", setup, name='eval_frame_chained_cmp_python_one_thread', - start_date=datetime(2012, 7, 26)) + start_date=datetime(2013, 7, 26)) + + +common_setup = """from pandas_vb_common import * +""" + +setup = common_setup + """ +N = 1000000 +halfway = N // 2 - 1 +index = date_range('20010101', periods=N, freq='T') +s = Series(index) +ts = s.iloc[halfway] +""" + +series_setup = setup + """ +df = DataFrame({'dates': s.values}) +""" + +query_datetime_series = Benchmark("df.query('dates < ts')", + series_setup, + start_date=datetime(2013, 9, 27)) + +index_setup = setup + """ +df = DataFrame({'a': np.random.randn(N)}, index=index) +""" + +query_datetime_index = Benchmark("df.query('index < ts')", + index_setup, start_date=datetime(2013, 9, 27))
closes #4897 Also adds `DatetimeIndex` comparisons in query expressions and a corresponding vbench for a simple `Timestamp` vs either `Series` or `DatetimeIndex`.
https://api.github.com/repos/pandas-dev/pandas/pulls/4924
2013-09-21T21:47:41Z
2013-09-27T19:34:46Z
2013-09-27T19:34:46Z
2014-06-20T02:58:26Z
CLN: Remove py3 next method from FixedWidthReader
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index c4ea76585df83..7b9347a821fad 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1964,20 +1964,11 @@ def __init__(self, f, colspecs, filler, thousands=None, encoding=None): isinstance(colspec[1], int) ): raise AssertionError() - if compat.PY3: - def next(self): - line = next(self.f) - if isinstance(line, bytes): - line = line.decode(self.encoding) - # Note: 'colspecs' is a sequence of half-open intervals. - return [line[fromm:to].strip(self.filler or ' ') - for (fromm, to) in self.colspecs] - else: - def next(self): - line = next(self.f) - # Note: 'colspecs' is a sequence of half-open intervals. - return [line[fromm:to].strip(self.filler or ' ') - for (fromm, to) in self.colspecs] + def next(self): + line = next(self.f) + # Note: 'colspecs' is a sequence of half-open intervals. + return [line[fromm:to].strip(self.filler or ' ') + for (fromm, to) in self.colspecs] # Iterator protocol in Python 3 uses __next__() __next__ = next
It's unnecessary - get file handle wraps this instead.
https://api.github.com/repos/pandas-dev/pandas/pulls/4923
2013-09-21T20:53:20Z
2013-09-21T21:29:28Z
2013-09-21T21:29:28Z
2014-06-24T23:41:01Z
DOC: show disallowed eval syntax
diff --git a/doc/source/enhancingperf.rst b/doc/source/enhancingperf.rst index bade382f03c59..e59cb6ac30964 100644 --- a/doc/source/enhancingperf.rst +++ b/doc/source/enhancingperf.rst @@ -330,6 +330,42 @@ engine in addition to some extensions available only in pandas. The larger the frame and the larger the expression the more speedup you will see from using :func:`~pandas.eval`. +Supported Syntax +~~~~~~~~~~~~~~~~ + +These operations are supported by :func:`~pandas.eval`: + +- Arithmetic operations except for the left shift (``<<``) and right shift + (``>>``) operators, e.g., ``df + 2 * pi / s ** 4 % 42 - the_golden_ratio`` +- Comparison operations, e.g., ``2 < df < df2`` +- Boolean operations, e.g., ``df < df2 and df3 < df4 or not df_bool`` +- ``list`` and ``tuple`` literals, e.g., ``[1, 2]`` or ``(1, 2)`` +- 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) + +This Python syntax is **not** allowed: + +* Expressions + + - Function calls + - ``is``/``is not`` operations + - ``if`` expressions + - ``lambda`` expressions + - ``list``/``set``/``dict`` comprehensions + - Literal ``dict`` and ``set`` expressions + - ``yield`` expressions + - Generator expressions + - Boolean expressions consisting of only scalar values + +* Statements + + - Neither `simple <http://docs.python.org/2/reference/simple_stmts.html>`__ + nor `compound <http://docs.python.org/2/reference/compound_stmts.html>`__ + statements are allowed. This includes things like ``for``, ``while``, and + ``if``. + + :func:`~pandas.eval` Examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
closes #4898
https://api.github.com/repos/pandas-dev/pandas/pulls/4922
2013-09-21T20:44:17Z
2013-09-22T13:55:27Z
2013-09-22T13:55:27Z
2014-06-19T07:17:07Z
DOC: expand the documentation on the xs method
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index e7af0e325a1b2..a8b9a4be01ae8 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -1590,6 +1590,41 @@ selecting data at a particular level of a MultiIndex easier. df.xs('one', level='second') +You can also select on the columns with :meth:`~pandas.MultiIndex.xs`, by +providing the axis argument + +.. ipython:: python + + df = df.T + df.xs('one', level='second', axis=1) + +:meth:`~pandas.MultiIndex.xs` also allows selection with multiple keys + +.. ipython:: python + + df.xs(('one', 'bar'), level=('second', 'first'), axis=1) + + +.. versionadded:: 0.13.0 + +You can pass ``drop_level=False`` to :meth:`~pandas.MultiIndex.xs` to retain +the level that was selected + +.. ipython:: + + df.xs('one', level='second', axis=1, drop_level=False) + +versus the result with ``drop_level=True`` (the default value) + +.. ipython:: + + df.xs('one', level='second', axis=1, drop_level=True) + +.. ipython:: + :suppress: + + df = df.T + .. _indexing.advanced_reindex: Advanced reindexing and alignment with hierarchical index
closes #4900
https://api.github.com/repos/pandas-dev/pandas/pulls/4921
2013-09-21T20:27:41Z
2013-09-22T02:52:23Z
2013-09-22T02:52:23Z
2014-07-16T08:29:31Z
ENH/REF: More options for interpolation and fillna
diff --git a/doc/source/missing_data.rst b/doc/source/missing_data.rst index 34442852cae84..e7966aa71486c 100644 --- a/doc/source/missing_data.rst +++ b/doc/source/missing_data.rst @@ -271,8 +271,13 @@ examined :ref:`in the API <api.dataframe.missing>`. Interpolation ~~~~~~~~~~~~~ -A linear **interpolate** method has been implemented on Series. The default -interpolation assumes equally spaced points. +.. versionadded:: 0.13.0 + + DataFrame now has the interpolation method. + :meth:`~pandas.Series.interpolate` also gained some additional methods. + +Both Series and Dataframe objects have an ``interpolate`` method that, by default, +performs linear interpolation at missing datapoints. .. ipython:: python :suppress: @@ -328,6 +333,86 @@ For a floating-point index, use ``method='values'``: ser.interpolate(method='values') +You can also interpolate with a DataFrame: + +.. ipython:: python + + df = DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8], + 'B': [.25, np.nan, np.nan, 4, 12.2, 14.4]}) + df.interpolate() + +The ``method`` argument gives access to fancier interpolation methods. +If you have scipy_ installed, you can set pass the name of a 1-d interpolation routine to ``method``. +You'll want to consult the full scipy interpolation documentation_ and reference guide_ for details. +The appropriate interpolation method will depend on the type of data you are working with. +For example, if you are dealing with a time series that is growing at an increasing rate, +``method='quadratic'`` may be appropriate. If you have values approximating a cumulative +distribution function, then ``method='pchip'`` should work well. + +.. warning:: + + These methods require ``scipy``. + +.. ipython:: python + + df.interpolate(method='barycentric') + + df.interpolate(method='pchip') + +When interpolating via a polynomial or spline approximation, you must also specify +the degree or order of the approximation: + +.. ipython:: python + + df.interpolate(method='spline', order=2) + + df.interpolate(method='polynomial', order=2) + +Compare several methods: + +.. ipython:: python + + np.random.seed(2) + + ser = Series(np.arange(1, 10.1, .25)**2 + np.random.randn(37)) + bad = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29, 34, 35, 36]) + ser[bad] = np.nan + methods = ['linear', 'quadratic', 'cubic'] + + df = DataFrame({m: s.interpolate(method=m) for m in methods}) + @savefig compare_interpolations.png + df.plot() + +Another use case is interpolation at *new* values. +Suppose you have 100 observations from some distribution. And let's suppose +that you're particularly interested in what's happening around the middle. +You can mix pandas' ``reindex`` and ``interpolate`` methods to interpolate +at the new values. + +.. ipython:: python + + ser = Series(np.sort(np.random.uniform(size=100))) + + # interpolate at new_index + new_index = ser.index + Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75]) + + interp_s = ser.reindex(new_index).interpolate(method='pchip') + + interp_s[49:51] + +.. _scipy: http://www.scipy.org +.. _documentation: http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation +.. _guide: http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html + + +Like other pandas fill methods, ``interpolate`` accepts a ``limit`` keyword argument. +Use this to limit the number of consecutive interpolations, keeping ``NaN``s for interpolations that are too far from the last valid observation: + +.. ipython:: python + + ser = Series([1, 3, np.nan, np.nan, np.nan, 11]) + ser.interpolate(limit=2) + .. _missing_data.replace: Replacing Generic Values diff --git a/doc/source/release.rst b/doc/source/release.rst index 4a25a98f2cfbe..d098418a6f8de 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -174,6 +174,8 @@ Improvements to existing features - :meth:`~pandas.io.json.json_normalize` is a new method to allow you to create a flat table from semi-structured JSON data. :ref:`See the docs<io.json_normalize>` (:issue:`1067`) - ``DataFrame.from_records()`` will now accept generators (:issue:`4910`) + - ``DataFrame.interpolate()`` and ``Series.interpolate()`` have been expanded to include + interpolation methods from scipy. (:issue:`4915`) API Changes ~~~~~~~~~~~ diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index c6a4c280ca4bb..da3eba677dcf0 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -614,6 +614,34 @@ Experimental - Added PySide support for the qtpandas DataFrameModel and DataFrameWidget. +- DataFrame has a new ``interpolate`` method, similar to Series: + + .. ipython:: python + + df = DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8], + 'B': [.25, np.nan, np.nan, 4, 12.2, 14.4]}) + df.interpolate() + + Additionally, the ``method`` argument to ``interpolate`` has been expanded + to include 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'barycentric', 'krogh', 'piecewise_polynomial', 'pchip' or "polynomial" or 'spline' + and an integer representing the degree or order of the approximation. The new methods + require scipy_. Consult the Scipy reference guide_ and documentation_ for more information + about when the various methods are appropriate. See also the :ref:`pandas interpolation docs<missing_data.interpolate:>`. + + Interpolate now also accepts a ``limit`` keyword argument. + This works similar to ``fillna``'s limit: + + .. ipython:: python + + ser = Series([1, 3, np.nan, np.nan, np.nan, 11]) + ser.interpolate(limit=2) + +.. _scipy: http://www.scipy.org +.. _documentation: http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation +.. _guide: http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html + + .. _whatsnew_0130.refactoring: Internal Refactoring diff --git a/pandas/core/common.py b/pandas/core/common.py index a417e00af5d3e..64599327f72ec 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -1244,6 +1244,153 @@ def backfill_2d(values, limit=None, mask=None): return values +def _clean_interp_method(method, order=None, **kwargs): + valid = ['linear', 'time', 'values', 'nearest', 'zero', 'slinear', + 'quadratic', 'cubic', 'barycentric', 'polynomial', + 'krogh', 'piecewise_polynomial', + 'pchip', 'spline'] + if method in ('spline', 'polynomial') and order is None: + raise ValueError("You must specify the order of the spline or " + "polynomial.") + if method not in valid: + raise ValueError("method must be one of {0}." + "Got '{1}' instead.".format(valid, method)) + return method + + +def interpolate_1d(xvalues, yvalues, method='linear', limit=None, + fill_value=None, bounds_error=False, **kwargs): + """ + Logic for the 1-d interpolation. The result should be 1-d, inputs + xvalues and yvalues will each be 1-d arrays of the same length. + + Bounds_error is currently hardcoded to False since non-scipy ones don't + take it as an argumnet. + """ + # Treat the original, non-scipy methods first. + + invalid = isnull(yvalues) + valid = ~invalid + + valid_y = yvalues[valid] + valid_x = xvalues[valid] + new_x = xvalues[invalid] + + if method == 'time': + if not getattr(xvalues, 'is_all_dates', None): + # if not issubclass(xvalues.dtype.type, np.datetime64): + raise ValueError('time-weighted interpolation only works ' + 'on Series or DataFrames with a ' + 'DatetimeIndex') + method = 'values' + + def _interp_limit(invalid, limit): + """mask off values that won't be filled since they exceed the limit""" + all_nans = np.where(invalid)[0] + violate = [invalid[x:x + limit + 1] for x in all_nans] + violate = np.array([x.all() & (x.size > limit) for x in violate]) + return all_nans[violate] + limit + + xvalues = getattr(xvalues, 'values', xvalues) + yvalues = getattr(yvalues, 'values', yvalues) + + if limit: + violate_limit = _interp_limit(invalid, limit) + if valid.any(): + firstIndex = valid.argmax() + valid = valid[firstIndex:] + invalid = invalid[firstIndex:] + result = yvalues.copy() + if valid.all(): + return yvalues + else: + # have to call np.array(xvalues) since xvalues could be an Index + # which cant be mutated + result = np.empty_like(np.array(xvalues), dtype=np.float64) + result.fill(np.nan) + return result + + if method in ['linear', 'time', 'values']: + if method in ('values', 'index'): + inds = np.asarray(xvalues) + # hack for DatetimeIndex, #1646 + if issubclass(inds.dtype.type, np.datetime64): + inds = inds.view(pa.int64) + + if inds.dtype == np.object_: + inds = lib.maybe_convert_objects(inds) + else: + inds = xvalues + + inds = inds[firstIndex:] + + result[firstIndex:][invalid] = np.interp(inds[invalid], inds[valid], + yvalues[firstIndex:][valid]) + + if limit: + result[violate_limit] = np.nan + return result + + sp_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'barycentric', 'krogh', 'spline', 'polynomial', + 'piecewise_polynomial', 'pchip'] + if method in sp_methods: + new_x = new_x[firstIndex:] + xvalues = xvalues[firstIndex:] + + result[firstIndex:][invalid] = _interpolate_scipy_wrapper(valid_x, + valid_y, new_x, method=method, fill_value=fill_value, + bounds_error=bounds_error, **kwargs) + if limit: + result[violate_limit] = np.nan + return result + + +def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None, + bounds_error=False, order=None, **kwargs): + """ + passed off to scipy.interpolate.interp1d. method is scipy's kind. + Returns an array interpolated at new_x. Add any new methods to + the list in _clean_interp_method + """ + try: + from scipy import interpolate + except ImportError: + raise ImportError('{0} interpolation requires Scipy'.format(method)) + + new_x = np.asarray(new_x) + + # ignores some kwargs that could be passed along. + alt_methods = { + 'barycentric': interpolate.barycentric_interpolate, + 'krogh': interpolate.krogh_interpolate, + 'piecewise_polynomial': interpolate.piecewise_polynomial_interpolate, + } + + try: + alt_methods['pchip'] = interpolate.pchip_interpolate + except AttributeError: + if method == 'pchip': + raise ImportError("Your version of scipy does not support " + "PCHIP interpolation.") + + interp1d_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'polynomial'] + if method in interp1d_methods: + if method == 'polynomial': + method = order + terp = interpolate.interp1d(x, y, kind=method, fill_value=fill_value, + bounds_error=bounds_error) + new_y = terp(new_x) + elif method == 'spline': + terp = interpolate.UnivariateSpline(x, y, k=order) + new_y = terp(new_x) + else: + method = alt_methods[method] + new_y = method(x, y, new_x) + return new_y + + def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None): """ perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result """ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9dadeb4ef6e97..cdac4939ed841 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -13,6 +13,7 @@ from pandas.tseries.index import DatetimeIndex from pandas.tseries.period import PeriodIndex from pandas.core.internals import BlockManager +import pandas.core.array as pa import pandas.core.common as com import pandas.core.datetools as datetools from pandas import compat, _np_version_under1p7 @@ -1963,58 +1964,109 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, else: return self._constructor(new_data) - def interpolate(self, to_replace, method='pad', axis=0, inplace=False, - limit=None): + def interpolate(self, method='linear', axis=0, limit=None, inplace=False, + downcast='infer', **kwargs): """Interpolate values according to different methods. Parameters ---------- - to_replace : dict, Series - method : str - axis : int - inplace : bool - limit : int, default None + method : {'linear', 'time', 'values', 'index' 'nearest', + 'zero', 'slinear', 'quadratic', 'cubic', + 'barycentric', 'krogh', 'polynomial', 'spline' + 'piecewise_polynomial', 'pchip'} + 'linear': ignore the index and treat the values as equally spaced. default + 'time': interpolation works on daily and higher resolution + data to interpolate given length of interval + 'index': use the actual numerical values of the index + 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'barycentric', + 'polynomial' is passed to `scipy.interpolate.interp1d` with the order given + both 'polynomial' and 'spline' requre that you also specify and order (int) + e.g. df.interpolate(method='polynomial', order=4) + 'krogh', 'piecewise_polynomial', 'spline', and 'pchip' are all wrappers + around the scipy interpolation methods of similar names. See the + scipy documentation for more on their behavior: + http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation + http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html + axis : {0, 1}, default 0 + 0: fill column-by-column + 1: fill row-by-row + limit : int, default None. Maximum number of consecutive NaNs to fill. + inplace : bool, default False + downcast : optional, 'infer' or None, defaults to 'infer' Returns ------- - frame : interpolated + Series or DataFrame of same shape interpolated at the NaNs See Also -------- reindex, replace, fillna + + Examples + -------- + + # Filling in NaNs: + >>> s = pd.Series([0, 1, np.nan, 3]) + >>> s.interpolate() + 0 0 + 1 1 + 2 2 + 3 3 + dtype: float64 """ - from warnings import warn - warn('{klass}.interpolate will be removed in v0.14, please use ' - 'either {klass}.fillna or {klass}.replace ' - 'instead'.format(klass=self.__class__), FutureWarning) - if self._is_mixed_type and axis == 1: - return self.T.replace(to_replace, method=method, limit=limit).T + if self.ndim > 2: + raise NotImplementedError("Interpolate has not been implemented " + "on Panel and Panel 4D objects.") - method = com._clean_fill_method(method) + if axis == 0: + ax = self._info_axis_name + elif axis == 1: + self = self.T + ax = 1 + ax = self._get_axis_number(ax) - if isinstance(to_replace, (dict, com.ABCSeries)): - if axis == 0: - return self.replace(to_replace, method=method, inplace=inplace, - limit=limit, axis=axis) - elif axis == 1: - obj = self.T - if inplace: - obj.replace(to_replace, method=method, limit=limit, - inplace=inplace, axis=0) - return obj.T - return obj.replace(to_replace, method=method, limit=limit, - inplace=inplace, axis=0).T - else: - raise ValueError('Invalid value for axis') + if self.ndim == 2: + alt_ax = 1 - ax + else: + alt_ax = ax + + if isinstance(self.index, MultiIndex) and method != 'linear': + raise ValueError("Only `method=linear` interpolation is supported " + "on MultiIndexes.") + + if self._data.get_dtype_counts().get('object') == len(self.T): + raise TypeError("Cannot interpolate with all NaNs.") + + # create/use the index + if method == 'linear': + index = np.arange(len(self._get_axis(alt_ax))) # prior default else: - new_data = self._data.interpolate(method=method, axis=axis, - limit=limit, inplace=inplace, - missing=to_replace, coerce=False) + index = self._get_axis(alt_ax) + + if pd.isnull(index).any(): + raise NotImplementedError("Interpolation with NaNs in the index " + "has not been implemented. Try filling " + "those NaNs before interpolating.") + new_data = self._data.interpolate(method=method, + axis=ax, + index=index, + values=self, + limit=limit, + inplace=inplace, + downcast=downcast, + **kwargs) - if inplace: + if inplace: + if axis == 1: self._data = new_data + self = self.T else: - return self._constructor(new_data) + self._data = new_data + else: + res = self._constructor(new_data, index=self.index) + if axis == 1: + res = res.T + return res #---------------------------------------------------------------------- # Action Methods diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 070745d73b307..0d3a1cfe9dfe1 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -9,7 +9,7 @@ from pandas.core.common import (_possibly_downcast_to_dtype, isnull, notnull, _NS_DTYPE, _TD_DTYPE, ABCSeries, ABCSparseSeries, - is_list_like, _infer_dtype_from_scalar) + is_list_like, _infer_dtype_from_scalar, _values_from_object) from pandas.core.index import (Index, MultiIndex, _ensure_index, _handle_legacy_indexes) from pandas.core.indexing import (_check_slice_bounds, _maybe_convert_indices, @@ -723,9 +723,46 @@ def create_block(v, m, n, item, reshape=True): return [make_block(new_values, self.items, self.ref_items, placement=self._ref_locs, fastpath=True)] - def interpolate(self, method='pad', axis=0, inplace=False, - limit=None, fill_value=None, coerce=False, - downcast=None): + def interpolate(self, method='pad', axis=0, index=None, + values=None, inplace=False, limit=None, + fill_value=None, coerce=False, downcast=None, **kwargs): + + # a fill na type method + try: + m = com._clean_fill_method(method) + except: + m = None + + if m is not None: + return self._interpolate_with_fill(method=m, + axis=axis, + inplace=inplace, + limit=limit, + fill_value=fill_value, + coerce=coerce, + downcast=downcast) + # try an interp method + try: + m = com._clean_interp_method(method, **kwargs) + except: + m = None + + if m is not None: + return self._interpolate(method=m, + index=index, + values=values, + axis=axis, + limit=limit, + fill_value=fill_value, + inplace=inplace, + downcast=downcast, + **kwargs) + + raise ValueError("invalid method '{0}' to interpolate.".format(method)) + + def _interpolate_with_fill(self, method='pad', axis=0, inplace=False, + limit=None, fill_value=None, coerce=False, downcast=None): + """ fillna but using the interpolate machinery """ # if we are coercing, then don't force the conversion # if the block can't hold the type @@ -745,6 +782,44 @@ def interpolate(self, method='pad', axis=0, inplace=False, blocks = [ make_block(values, self.items, self.ref_items, ndim=self.ndim, klass=self.__class__, fastpath=True) ] return self._maybe_downcast(blocks, downcast) + def _interpolate(self, method=None, index=None, values=None, + fill_value=None, axis=0, limit=None, + inplace=False, downcast=None, **kwargs): + """ interpolate using scipy wrappers """ + + data = self.values if inplace else self.values.copy() + + # only deal with floats + if not self.is_float: + if not self.is_integer: + return self + data = data.astype(np.float64) + + if fill_value is None: + fill_value = np.nan + + if method in ('krogh', 'piecewise_polynomial', 'pchip'): + if not index.is_monotonic: + raise ValueError("{0} interpolation requires that the " + "index be monotonic.".format(method)) + # process 1-d slices in the axis direction + + def func(x): + + # process a 1-d slice, returning it + # should the axis argument be handled below in apply_along_axis? + # i.e. not an arg to com.interpolate_1d + return com.interpolate_1d(index, x, method=method, limit=limit, + fill_value=fill_value, bounds_error=False, + **kwargs) + + # interp each column independently + interp_values = np.apply_along_axis(func, axis, data) + + blocks = [make_block(interp_values, self.items, self.ref_items, + ndim=self.ndim, klass=self.__class__, fastpath=True)] + return self._maybe_downcast(blocks, downcast) + def take(self, indexer, ref_items, axis=1): if axis < 1: raise AssertionError('axis must be at least 1, got %d' % axis) diff --git a/pandas/core/series.py b/pandas/core/series.py index d185939d6abc9..3b4dcfba086ee 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2251,57 +2251,6 @@ def asof(self, where): new_values = com.take_1d(values, locs) return self._constructor(new_values, index=where, name=self.name) - def interpolate(self, method='linear'): - """ - Interpolate missing values (after the first valid value) - - Parameters - ---------- - method : {'linear', 'time', 'values'} - Interpolation method. - 'time' interpolation works on daily and higher resolution - data to interpolate given length of interval - 'values' using the actual index numeric values - - Returns - ------- - interpolated : Series - """ - if method == 'time': - if not self.is_time_series: - raise Exception('time-weighted interpolation only works' - 'on TimeSeries') - method = 'values' - # inds = pa.array([d.toordinal() for d in self.index]) - - if method == 'values': - inds = self.index.values - # hack for DatetimeIndex, #1646 - if issubclass(inds.dtype.type, np.datetime64): - inds = inds.view(pa.int64) - - if inds.dtype == np.object_: - inds = lib.maybe_convert_objects(inds) - else: - inds = pa.arange(len(self)) - - values = self.values - - invalid = isnull(values) - valid = -invalid - - result = values.copy() - if valid.any(): - firstIndex = valid.argmax() - valid = valid[firstIndex:] - invalid = invalid[firstIndex:] - inds = inds[firstIndex:] - - result[firstIndex:][invalid] = np.interp( - inds[invalid], inds[valid], values[firstIndex:][valid]) - - return self._constructor(result, index=self.index, name=self.name) - @property def weekday(self): return self._constructor([d.weekday() for d in self.index], index=self.index) diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index b8c143e10111d..e9902bf4d1195 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -6,6 +6,7 @@ import nose import numpy as np +from numpy import nan import pandas as pd from pandas import (Index, Series, DataFrame, Panel, @@ -24,6 +25,20 @@ ensure_clean) import pandas.util.testing as tm + +def _skip_if_no_scipy(): + try: + import scipy.interpolate + except ImportError: + raise nose.SkipTest('scipy.interpolate missing') + + +def _skip_if_no_pchip(): + try: + from scipy.interpolate import pchip_interpolate + except ImportError: + raise nose.SkipTest('scipy.interpolate.pchip missing') + #------------------------------------------------------------------------------ # Generic types test cases @@ -173,6 +188,13 @@ class TestSeries(unittest.TestCase, Generic): _typ = Series _comparator = lambda self, x, y: assert_series_equal(x,y) + def setUp(self): + self.ts = tm.makeTimeSeries() # Was at top level in test_series + self.ts.name = 'ts' + + self.series = tm.makeStringSeries() + self.series.name = 'series' + def test_rename_mi(self): s = Series([11,21,31], index=MultiIndex.from_tuples([("A",x) for x in ["a","B","c"]])) @@ -230,6 +252,152 @@ def test_nonzero_single_element(self): self.assertRaises(ValueError, lambda : bool(s)) self.assertRaises(ValueError, lambda : s.bool()) + def test_interpolate(self): + ts = Series(np.arange(len(self.ts), dtype=float), self.ts.index) + + ts_copy = ts.copy() + ts_copy[5:10] = np.NaN + + linear_interp = ts_copy.interpolate(method='linear') + self.assert_(np.array_equal(linear_interp, ts)) + + ord_ts = Series([d.toordinal() for d in self.ts.index], + index=self.ts.index).astype(float) + + ord_ts_copy = ord_ts.copy() + ord_ts_copy[5:10] = np.NaN + + time_interp = ord_ts_copy.interpolate(method='time') + self.assert_(np.array_equal(time_interp, ord_ts)) + + # try time interpolation on a non-TimeSeries + self.assertRaises(ValueError, self.series.interpolate, method='time') + + def test_interpolate_corners(self): + s = Series([np.nan, np.nan]) + assert_series_equal(s.interpolate(), s) + + s = Series([]).interpolate() + assert_series_equal(s.interpolate(), s) + + _skip_if_no_scipy() + s = Series([np.nan, np.nan]) + assert_series_equal(s.interpolate(method='polynomial', order=1), s) + + s = Series([]).interpolate() + assert_series_equal(s.interpolate(method='polynomial', order=1), s) + + def test_interpolate_index_values(self): + s = Series(np.nan, index=np.sort(np.random.rand(30))) + s[::3] = np.random.randn(10) + + vals = s.index.values.astype(float) + + result = s.interpolate(method='values') + + expected = s.copy() + bad = isnull(expected.values) + good = -bad + expected = Series( + np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad]) + + assert_series_equal(result[bad], expected) + + def test_interpolate_non_ts(self): + s = Series([1, 3, np.nan, np.nan, np.nan, 11]) + with tm.assertRaises(ValueError): + s.interpolate(method='time') + + # New interpolation tests + def test_nan_interpolate(self): + s = Series([0, 1, np.nan, 3]) + result = s.interpolate() + expected = Series([0, 1, 2, 3]) + assert_series_equal(result, expected) + + _skip_if_no_scipy() + result = s.interpolate(method='polynomial', order=1) + assert_series_equal(result, expected) + + def test_nan_irregular_index(self): + s = Series([1, 2, np.nan, 4], index=[1, 3, 5, 9]) + result = s.interpolate() + expected = Series([1, 2, 3, 4], index=[1, 3, 5, 9]) + assert_series_equal(result, expected) + + def test_nan_str_index(self): + s = Series([0, 1, 2, np.nan], index=list('abcd')) + result = s.interpolate() + expected = Series([0, 1, 2, 2], index=list('abcd')) + assert_series_equal(result, expected) + + def test_interp_quad(self): + _skip_if_no_scipy() + sq = Series([1, 4, np.nan, 16], index=[1, 2, 3, 4]) + result = sq.interpolate(method='quadratic') + expected = Series([1., 4., 9., 16.], index=[1, 2, 3, 4]) + assert_series_equal(result, expected) + + def test_interp_scipy_basic(self): + _skip_if_no_scipy() + s = Series([1, 3, np.nan, 12, np.nan, 25]) + # slinear + expected = Series([1., 3., 7.5, 12., 18.5, 25.]) + result = s.interpolate(method='slinear') + assert_series_equal(result, expected) + # nearest + expected = Series([1, 3, 3, 12, 12, 25]) + result = s.interpolate(method='nearest') + assert_series_equal(result, expected) + # zero + expected = Series([1, 3, 3, 12, 12, 25]) + result = s.interpolate(method='zero') + assert_series_equal(result, expected) + # quadratic + expected = Series([1, 3., 6.769231, 12., 18.230769, 25.]) + result = s.interpolate(method='quadratic') + assert_series_equal(result, expected) + # cubic + expected = Series([1., 3., 6.8, 12., 18.2, 25.]) + result = s.interpolate(method='cubic') + assert_series_equal(result, expected) + + def test_interp_limit(self): + s = Series([1, 3, np.nan, np.nan, np.nan, 11]) + expected = Series([1., 3., 5., 7., np.nan, 11.]) + result = s.interpolate(method='linear', limit=2) + assert_series_equal(result, expected) + + def test_interp_all_good(self): + # scipy + _skip_if_no_scipy() + s = Series([1, 2, 3]) + result = s.interpolate(method='polynomial', order=1) + assert_series_equal(result, s) + + # non-scipy + result = s.interpolate() + assert_series_equal(result, s) + + def test_interp_multiIndex(self): + idx = MultiIndex.from_tuples([(0, 'a'), (1, 'b'), (2, 'c')]) + s = Series([1, 2, np.nan], index=idx) + + expected = s.copy() + expected.loc[2] = 2 + expected = expected.astype(np.int64) + result = s.interpolate() + assert_series_equal(result, expected) + + _skip_if_no_scipy() + with tm.assertRaises(ValueError): + s.interpolate(method='polynomial', order=1) + + def test_interp_nonmono_raise(self): + _skip_if_no_scipy() + s = pd.Series([1, 2, 3], index=[0, 2, 1]) + with tm.assertRaises(ValueError): + s.interpolate(method='krogh') class TestDataFrame(unittest.TestCase, Generic): _typ = DataFrame @@ -256,14 +424,178 @@ def test_nonzero_single_element(self): def test_get_numeric_data_preserve_dtype(self): # get the numeric data - o = DataFrame({'A' : [1,'2',3.] }) + o = DataFrame({'A': [1, '2', 3.]}) result = o._get_numeric_data() - expected = DataFrame(index=[0,1,2],dtype=object) + expected = DataFrame(index=[0, 1, 2], dtype=object) self._compare(result, expected) + def test_interp_basic(self): + df = DataFrame({'A': [1, 2, np.nan, 4], 'B': [1, 4, 9, np.nan], + 'C': [1, 2, 3, 5], 'D': list('abcd')}) + expected = DataFrame({'A': [1, 2, 3, 4], 'B': [1, 4, 9, 9], + 'C': [1, 2, 3, 5], 'D': list('abcd')}) + result = df.interpolate() + assert_frame_equal(result, expected) + + result = df.set_index('C').interpolate() + expected = df.set_index('C') + expected.A.loc[3] = 3 + expected.B.loc[5] = 9 + expected[['A', 'B']] = expected[['A', 'B']].astype(np.int64) + + assert_frame_equal(result, expected) + + def test_interp_bad_method(self): + df = DataFrame({'A': [1, 2, np.nan, 4], 'B': [1, 4, 9, np.nan], + 'C': [1, 2, 3, 5], 'D': list('abcd')}) + with tm.assertRaises(ValueError): + df.interpolate(method='not_a_method') + + def test_interp_combo(self): + df = DataFrame({'A': [1., 2., np.nan, 4.], 'B': [1, 4, 9, np.nan], + 'C': [1, 2, 3, 5], 'D': list('abcd')}) + + result = df['A'].interpolate() + expected = Series([1, 2, 3, 4]) + assert_series_equal(result, expected) + + def test_interp_nan_idx(self): + df = DataFrame({'A': [1, 2, np.nan, 4], 'B': [np.nan, 2, 3, 4]}) + df = df.set_index('A') + with tm.assertRaises(NotImplementedError): + df.interpolate(method='values') + + def test_interp_various(self): + _skip_if_no_scipy() + df = DataFrame({'A': [1, 2, np.nan, 4, 5, np.nan, 7], + 'C': [1, 2, 3, 5, 8, 13, 21]}) + df = df.set_index('C') + expected = df.copy() + result = df.interpolate(method='polynomial', order=1) + + expected.A.loc[3] = 2.66666667 + expected.A.loc[13] = 5.76923076 + assert_frame_equal(result, expected) + + result = df.interpolate(method='cubic') + expected.A.loc[3] = 2.81621174 + expected.A.loc[13] = 5.64146581 + assert_frame_equal(result, expected) + + result = df.interpolate(method='nearest') + expected.A.loc[3] = 2 + expected.A.loc[13] = 5 + assert_frame_equal(result, expected, check_dtype=False) + + result = df.interpolate(method='quadratic') + expected.A.loc[3] = 2.82533638 + expected.A.loc[13] = 6.02817974 + assert_frame_equal(result, expected) + + result = df.interpolate(method='slinear') + expected.A.loc[3] = 2.66666667 + expected.A.loc[13] = 5.76923077 + assert_frame_equal(result, expected) + + result = df.interpolate(method='zero') + expected.A.loc[3] = 2. + expected.A.loc[13] = 5 + assert_frame_equal(result, expected, check_dtype=False) + + result = df.interpolate(method='quadratic') + expected.A.loc[3] = 2.82533638 + expected.A.loc[13] = 6.02817974 + assert_frame_equal(result, expected) + + def test_interp_alt_scipy(self): + _skip_if_no_scipy() + df = DataFrame({'A': [1, 2, np.nan, 4, 5, np.nan, 7], + 'C': [1, 2, 3, 5, 8, 13, 21]}) + result = df.interpolate(method='barycentric') + expected = df.copy() + expected['A'].iloc[2] = 3 + expected['A'].iloc[5] = 6 + assert_frame_equal(result, expected) + + result = df.interpolate(method='krogh') + expectedk = df.copy() + expectedk['A'].iloc[2] = 3 + expectedk['A'].iloc[5] = 6 + expectedk['A'] = expected['A'].astype(np.int64) + assert_frame_equal(result, expectedk) + + _skip_if_no_pchip() + result = df.interpolate(method='pchip') + expected['A'].iloc[2] = 3 + expected['A'].iloc[5] = 6.125 + assert_frame_equal(result, expected) + + def test_interp_rowwise(self): + df = DataFrame({0: [1, 2, np.nan, 4], + 1: [2, 3, 4, np.nan], + 2: [np.nan, 4, 5, 6], + 3: [4, np.nan, 6, 7], + 4: [1, 2, 3, 4]}) + result = df.interpolate(axis=1) + expected = df.copy() + expected[1].loc[3] = 5 + expected[2].loc[0] = 3 + expected[3].loc[1] = 3 + expected[4] = expected[4].astype(np.float64) + assert_frame_equal(result, expected) + + # scipy route + _skip_if_no_scipy() + result = df.interpolate(axis=1, method='values') + assert_frame_equal(result, expected) + + result = df.interpolate(axis=0) + expected = df.interpolate() + assert_frame_equal(result, expected) + + def test_rowwise_alt(self): + df = DataFrame({0: [0, .5, 1., np.nan, 4, 8, np.nan, np.nan, 64], + 1: [1, 2, 3, 4, 3, 2, 1, 0, -1]}) + df.interpolate(axis=0) + + def test_interp_leading_nans(self): + df = DataFrame({"A": [np.nan, np.nan, .5, .25, 0], + "B": [np.nan, -3, -3.5, np.nan, -4]}) + result = df.interpolate() + expected = df.copy() + expected['B'].loc[3] = -3.75 + assert_frame_equal(result, expected) + + _skip_if_no_scipy() + result = df.interpolate(method='polynomial', order=1) + assert_frame_equal(result, expected) + + def test_interp_raise_on_only_mixed(self): + df = DataFrame({'A': [1, 2, np.nan, 4], 'B': ['a', 'b', 'c', 'd'], + 'C': [np.nan, 2, 5, 7], 'D': [np.nan, np.nan, 9, 9], + 'E': [1, 2, 3, 4]}) + with tm.assertRaises(TypeError): + df.interpolate(axis=1) + + def test_no_order(self): + _skip_if_no_scipy() + s = Series([0, 1, np.nan, 3]) + with tm.assertRaises(ValueError): + s.interpolate(method='polynomial') + with tm.assertRaises(ValueError): + s.interpolate(method='spline') + + def test_spline(self): + _skip_if_no_scipy() + s = Series([1, 2, np.nan, 4, 5, np.nan, 7]) + result = s.interpolate(method='spline', order=1) + expected = Series([1., 2, 3, 4, 5, 6, 7]) # dtype? + assert_series_equal(result, expected) + + class TestPanel(unittest.TestCase, Generic): _typ = Panel - _comparator = lambda self, x, y: assert_panel_equal(x,y) + _comparator = lambda self, x, y: assert_panel_equal(x, y) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 8abc068fd6d24..6f4725f7db725 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2484,72 +2484,145 @@ def test_timedelta_fillna(self): raise nose.SkipTest("timedelta broken in np 1.6.1") #GH 3371 - from datetime import timedelta - - s = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130102'),Timestamp('20130103 9:01:01')]) + s = Series([Timestamp('20130101'), Timestamp('20130101'), + Timestamp('20130102'), Timestamp('20130103 9:01:01')]) td = s.diff() # reg fillna result = td.fillna(0) - expected = Series([timedelta(0),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)]) - assert_series_equal(result,expected) + expected = Series([timedelta(0), timedelta(0), timedelta(1), + timedelta(days=1, seconds=9*3600+60+1)]) + assert_series_equal(result, expected) # interprested as seconds result = td.fillna(1) - expected = Series([timedelta(seconds=1),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)]) - assert_series_equal(result,expected) + expected = Series([timedelta(seconds=1), timedelta(0), + timedelta(1), timedelta(days=1, seconds=9*3600+60+1)]) + assert_series_equal(result, expected) - result = td.fillna(timedelta(days=1,seconds=1)) - expected = Series([timedelta(days=1,seconds=1),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)]) - assert_series_equal(result,expected) + result = td.fillna(timedelta(days=1, seconds=1)) + expected = Series([timedelta(days=1, seconds=1), timedelta(0), + timedelta(1), timedelta(days=1, seconds=9*3600+60+1)]) + assert_series_equal(result, expected) result = td.fillna(np.timedelta64(int(1e9))) - expected = Series([timedelta(seconds=1),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)]) - assert_series_equal(result,expected) + expected = Series([timedelta(seconds=1), timedelta(0), timedelta(1), + timedelta(days=1, seconds=9*3600+60+1)]) + assert_series_equal(result, expected) from pandas import tslib result = td.fillna(tslib.NaT) - expected = Series([tslib.NaT,timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)],dtype='m8[ns]') - assert_series_equal(result,expected) + expected = Series([tslib.NaT, timedelta(0), timedelta(1), + timedelta(days=1, seconds=9*3600+60+1)], dtype='m8[ns]') + assert_series_equal(result, expected) # ffill td[2] = np.nan result = td.ffill() expected = td.fillna(0) expected[0] = np.nan - assert_series_equal(result,expected) + assert_series_equal(result, expected) # bfill td[2] = np.nan result = td.bfill() expected = td.fillna(0) - expected[2] = timedelta(days=1,seconds=9*3600+60+1) - assert_series_equal(result,expected) + expected[2] = timedelta(days=1, seconds=9*3600+60+1) + assert_series_equal(result, expected) def test_datetime64_fillna(self): - s = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130102'),Timestamp('20130103 9:01:01')]) + s = Series([Timestamp('20130101'), Timestamp('20130101'), + Timestamp('20130102'), Timestamp('20130103 9:01:01')]) s[2] = np.nan # reg fillna result = s.fillna(Timestamp('20130104')) - expected = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130104'),Timestamp('20130103 9:01:01')]) - assert_series_equal(result,expected) + expected = Series([Timestamp('20130101'), Timestamp('20130101'), + Timestamp('20130104'), Timestamp('20130103 9:01:01')]) + assert_series_equal(result, expected) from pandas import tslib result = s.fillna(tslib.NaT) expected = s - assert_series_equal(result,expected) + assert_series_equal(result, expected) # ffill result = s.ffill() - expected = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130103 9:01:01')]) - assert_series_equal(result,expected) + expected = Series([Timestamp('20130101'), Timestamp('20130101'), + Timestamp('20130101'), Timestamp('20130103 9:01:01')]) + assert_series_equal(result, expected) # bfill result = s.bfill() - expected = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130103 9:01:01'),Timestamp('20130103 9:01:01')]) - assert_series_equal(result,expected) + expected = Series([Timestamp('20130101'), Timestamp('20130101'), + Timestamp('20130103 9:01:01'), + Timestamp('20130103 9:01:01')]) + assert_series_equal(result, expected) + + def test_fillna_int(self): + s = Series(np.random.randint(-100, 100, 50)) + s.fillna(method='ffill', inplace=True) + assert_series_equal(s.fillna(method='ffill', inplace=False), s) + + def test_fillna_raise(self): + s = Series(np.random.randint(-100, 100, 50)) + self.assertRaises(TypeError, s.fillna, [1, 2]) + self.assertRaises(TypeError, s.fillna, (1, 2)) + +# TimeSeries-specific + + def test_fillna(self): + ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) + + self.assert_(np.array_equal(ts, ts.fillna(method='ffill'))) + + ts[2] = np.NaN + + self.assert_( + np.array_equal(ts.fillna(method='ffill'), [0., 1., 1., 3., 4.])) + self.assert_(np.array_equal(ts.fillna(method='backfill'), + [0., 1., 3., 3., 4.])) + + self.assert_(np.array_equal(ts.fillna(value=5), [0., 1., 5., 3., 4.])) + + self.assertRaises(ValueError, ts.fillna) + self.assertRaises(ValueError, self.ts.fillna, value=0, method='ffill') + + def test_fillna_bug(self): + x = Series([nan, 1., nan, 3., nan], ['z', 'a', 'b', 'c', 'd']) + filled = x.fillna(method='ffill') + expected = Series([nan, 1., 1., 3., 3.], x.index) + assert_series_equal(filled, expected) + + filled = x.fillna(method='bfill') + expected = Series([1., 1., 3., 3., nan], x.index) + assert_series_equal(filled, expected) + + def test_fillna_inplace(self): + x = Series([nan, 1., nan, 3., nan], ['z', 'a', 'b', 'c', 'd']) + y = x.copy() + + y.fillna(value=0, inplace=True) + + expected = x.fillna(value=0) + assert_series_equal(y, expected) + + def test_fillna_invalid_method(self): + try: + self.ts.fillna(method='ffil') + except ValueError as inst: + self.assert_('ffil' in str(inst)) + + def test_ffill(self): + ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) + ts[2] = np.NaN + assert_series_equal(ts.ffill(), ts.fillna(method='ffill')) + + def test_bfill(self): + ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) + ts[2] = np.NaN + assert_series_equal(ts.bfill(), ts.fillna(method='bfill')) def test_sub_of_datetime_from_TimeSeries(self): from pandas.tseries.timedeltas import _possibly_cast_to_timedelta @@ -4718,84 +4791,8 @@ def test_isin_with_string_scalar(self): s = Series(['aaa', 'b', 'c']) s.isin('aaa') - def test_fillna_int(self): - s = Series(np.random.randint(-100, 100, 50)) - s.fillna(method='ffill', inplace=True) - assert_series_equal(s.fillna(method='ffill', inplace=False), s) - - def test_fillna_raise(self): - s = Series(np.random.randint(-100, 100, 50)) - self.assertRaises(TypeError, s.fillna, [1, 2]) - self.assertRaises(TypeError, s.fillna, (1, 2)) - #------------------------------------------------------------------------------ # TimeSeries-specific - - def test_fillna(self): - ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) - - self.assert_(np.array_equal(ts, ts.fillna(method='ffill'))) - - ts[2] = np.NaN - - self.assert_( - np.array_equal(ts.fillna(method='ffill'), [0., 1., 1., 3., 4.])) - self.assert_(np.array_equal(ts.fillna(method='backfill'), - [0., 1., 3., 3., 4.])) - - self.assert_(np.array_equal(ts.fillna(value=5), [0., 1., 5., 3., 4.])) - - self.assertRaises(ValueError, ts.fillna) - self.assertRaises(ValueError, self.ts.fillna, value=0, method='ffill') - - def test_fillna_bug(self): - x = Series([nan, 1., nan, 3., nan], ['z', 'a', 'b', 'c', 'd']) - filled = x.fillna(method='ffill') - expected = Series([nan, 1., 1., 3., 3.], x.index) - assert_series_equal(filled, expected) - - filled = x.fillna(method='bfill') - expected = Series([1., 1., 3., 3., nan], x.index) - assert_series_equal(filled, expected) - - def test_fillna_inplace(self): - x = Series([nan, 1., nan, 3., nan], ['z', 'a', 'b', 'c', 'd']) - y = x.copy() - - y.fillna(value=0, inplace=True) - - expected = x.fillna(value=0) - assert_series_equal(y, expected) - - def test_fillna_empty(self): - # GH 4346 - - empty = Series() - - result = empty.reindex([1, 2, 3]) - expected = Series([np.nan, np.nan, np.nan], index=[1, 2, 3]) - assert_series_equal(result, expected) - - result = empty.reindex([1, 2, 3], fill_value=0.0) - expected = Series([0.0, 0.0, 0.0], index=[1, 2, 3]) - assert_series_equal(result, expected) - - def test_fillna_invalid_method(self): - try: - self.ts.fillna(method='ffil') - except ValueError as inst: - self.assert_('ffil' in str(inst)) - - def test_ffill(self): - ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) - ts[2] = np.NaN - assert_series_equal(ts.ffill(), ts.fillna(method='ffill')) - - def test_bfill(self): - ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) - ts[2] = np.NaN - assert_series_equal(ts.bfill(), ts.fillna(method='bfill')) - def test_cummethods_bool(self): def cummin(x): return np.minimum.accumulate(x) @@ -4974,50 +4971,6 @@ def test_asfreq(self): self.assert_(len(result) == 0) self.assert_(result is not ts) - def test_interpolate(self): - ts = Series(np.arange(len(self.ts), dtype=float), self.ts.index) - - ts_copy = ts.copy() - ts_copy[5:10] = np.NaN - - linear_interp = ts_copy.interpolate(method='linear') - self.assert_(np.array_equal(linear_interp, ts)) - - ord_ts = Series([d.toordinal() for d in self.ts.index], - index=self.ts.index).astype(float) - - ord_ts_copy = ord_ts.copy() - ord_ts_copy[5:10] = np.NaN - - time_interp = ord_ts_copy.interpolate(method='time') - self.assert_(np.array_equal(time_interp, ord_ts)) - - # try time interpolation on a non-TimeSeries - self.assertRaises(Exception, self.series.interpolate, method='time') - - def test_interpolate_corners(self): - s = Series([np.nan, np.nan]) - assert_series_equal(s.interpolate(), s) - - s = Series([]).interpolate() - assert_series_equal(s.interpolate(), s) - - def test_interpolate_index_values(self): - s = Series(np.nan, index=np.sort(np.random.rand(30))) - s[::3] = np.random.randn(10) - - vals = s.index.values.astype(float) - - result = s.interpolate(method='values') - - expected = s.copy() - bad = isnull(expected.values) - good = -bad - expected = Series( - np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad]) - - assert_series_equal(result[bad], expected) - def test_weekday(self): # Just run the function weekdays = self.ts.weekday
closes #4434 closes #1892 I've basically just hacked out the Series interpolate and stuffed it under generic under a big `if` statement. Gonna make that much cleaner. Moved the interpolation and fillna specific tests in `test_series.py` to `test_generic.py`. API question for you all. The interpolation procedures in Scipy take an array of x-values and an array of y-values that form the basis for the interpolation object. The interpolation object can then be evaluated wherever, but it maps X -> Y; f(x-values) == y-values. So we have 3 arrays to deal with: 1. x-values 2. y-values 3. new values Preferences for names? The other issue is for defaults. Right now I'm thinking 1. x-values: index if numeric. 2. y-values: the Series.values if Series. Each numeric column of DataFrame if DataFrame? 3. new values: Fill NaNs by default. Interpolate at `new values` if an array is given.
https://api.github.com/repos/pandas-dev/pandas/pulls/4915
2013-09-21T13:52:05Z
2013-10-09T20:30:04Z
null
2014-06-12T22:49:52Z
CLN: more plotting test cleanups
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index cb6ec3d648afa..558bf17b0cd5c 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -29,17 +29,11 @@ def _skip_if_no_scipy(): raise nose.SkipTest +@tm.mplskip class TestSeriesPlots(unittest.TestCase): - @classmethod - def setUpClass(cls): - try: - import matplotlib as mpl - mpl.use('Agg', warn=False) - cls.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') - except ImportError: - raise nose.SkipTest("matplotlib not installed") - def setUp(self): + import matplotlib as mpl + self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') self.ts = tm.makeTimeSeries() self.ts.name = 'ts' @@ -50,8 +44,7 @@ def setUp(self): self.iseries.name = 'iseries' def tearDown(self): - import matplotlib.pyplot as plt - plt.close('all') + tm.close() @slow def test_plot(self): @@ -352,24 +345,14 @@ def test_dup_datetime_index_plot(self): _check_plot_works(s.plot) +@tm.mplskip class TestDataFramePlots(unittest.TestCase): - - @classmethod - def setUpClass(cls): - # import sys - # if 'IPython' in sys.modules: - # raise nose.SkipTest - - try: - import matplotlib as mpl - mpl.use('Agg', warn=False) - cls.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') - except ImportError: - raise nose.SkipTest("matplotlib not installed") + def setUp(self): + import matplotlib as mpl + self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') def tearDown(self): - import matplotlib.pyplot as plt - plt.close('all') + tm.close() @slow def test_plot(self): @@ -949,19 +932,10 @@ def test_invalid_kind(self): df.plot(kind='aasdf') +@tm.mplskip class TestDataFrameGroupByPlots(unittest.TestCase): - @classmethod - def setUpClass(cls): - try: - import matplotlib as mpl - mpl.use('Agg', warn=False) - except ImportError: - raise nose.SkipTest - def tearDown(self): - import matplotlib.pyplot as plt - for fignum in plt.get_fignums(): - plt.close(fignum) + tm.close() @slow def test_boxplot(self): @@ -999,13 +973,16 @@ def test_time_series_plot_color_with_empty_kwargs(self): import matplotlib as mpl def_colors = mpl.rcParams['axes.color_cycle'] + index = date_range('1/1/2000', periods=12) + s = Series(np.arange(1, 13), index=index) + + ncolors = 3 - for i in range(3): - ax = Series(np.arange(12) + 1, index=date_range('1/1/2000', - periods=12)).plot() + for i in range(ncolors): + ax = s.plot() line_colors = [l.get_color() for l in ax.get_lines()] - self.assertEqual(line_colors, def_colors[:3]) + self.assertEqual(line_colors, def_colors[:ncolors]) @slow def test_grouped_hist(self): @@ -1155,27 +1132,30 @@ def _check_plot_works(f, *args, **kwargs): import matplotlib.pyplot as plt try: - fig = kwargs['figure'] - except KeyError: - fig = plt.gcf() - plt.clf() - ax = kwargs.get('ax', fig.add_subplot(211)) - ret = f(*args, **kwargs) + try: + fig = kwargs['figure'] + except KeyError: + fig = plt.gcf() - assert ret is not None - assert_is_valid_plot_return_object(ret) + plt.clf() - try: - kwargs['ax'] = fig.add_subplot(212) + ax = kwargs.get('ax', fig.add_subplot(211)) ret = f(*args, **kwargs) - except Exception: - pass - else: + assert_is_valid_plot_return_object(ret) - with ensure_clean() as path: - plt.savefig(path) - plt.close(fig) + 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() as path: + plt.savefig(path) + finally: + tm.close(fig) def curpath(): diff --git a/pandas/tests/test_rplot.py b/pandas/tests/test_rplot.py index e7faa8f25deb3..d59b182b77d4c 100644 --- a/pandas/tests/test_rplot.py +++ b/pandas/tests/test_rplot.py @@ -8,16 +8,11 @@ import nose -try: - import matplotlib.pyplot as plt -except: - raise nose.SkipTest - - def curpath(): pth, _ = os.path.split(os.path.abspath(__file__)) return pth + def between(a, b, x): """Check if x is in the somewhere between a and b. @@ -36,6 +31,8 @@ def between(a, b, x): else: return x <= a and x >= b + +@tm.mplskip class TestUtilityFunctions(unittest.TestCase): """ Tests for RPlot utility functions. @@ -74,9 +71,9 @@ def test_dictionary_union(self): self.assertTrue(2 in keys) self.assertTrue(3 in keys) self.assertTrue(4 in keys) - self.assertTrue(rplot.dictionary_union(dict1, {}) == dict1) - self.assertTrue(rplot.dictionary_union({}, dict1) == dict1) - self.assertTrue(rplot.dictionary_union({}, {}) == {}) + self.assertEqual(rplot.dictionary_union(dict1, {}), dict1) + self.assertEqual(rplot.dictionary_union({}, dict1), dict1) + self.assertEqual(rplot.dictionary_union({}, {}), {}) def test_merge_aes(self): layer1 = rplot.Layer(size=rplot.ScaleSize('test')) @@ -84,14 +81,15 @@ def test_merge_aes(self): rplot.merge_aes(layer1, layer2) self.assertTrue(isinstance(layer2.aes['size'], rplot.ScaleSize)) self.assertTrue(isinstance(layer2.aes['shape'], rplot.ScaleShape)) - self.assertTrue(layer2.aes['size'] == layer1.aes['size']) + self.assertEqual(layer2.aes['size'], layer1.aes['size']) for key in layer2.aes.keys(): if key != 'size' and key != 'shape': self.assertTrue(layer2.aes[key] is None) def test_sequence_layers(self): layer1 = rplot.Layer(self.data) - layer2 = rplot.GeomPoint(x='SepalLength', y='SepalWidth', size=rplot.ScaleSize('PetalLength')) + layer2 = rplot.GeomPoint(x='SepalLength', y='SepalWidth', + size=rplot.ScaleSize('PetalLength')) layer3 = rplot.GeomPolyFit(2) result = rplot.sequence_layers([layer1, layer2, layer3]) self.assertEqual(len(result), 3) @@ -102,6 +100,8 @@ def test_sequence_layers(self): self.assertTrue(self.data is last.data) self.assertTrue(rplot.sequence_layers([layer1])[0] is layer1) + +@tm.mplskip class TestTrellis(unittest.TestCase): def setUp(self): path = os.path.join(curpath(), 'data/tips.csv') @@ -148,11 +148,15 @@ def test_trellis_cols_rows(self): self.assertEqual(self.trellis3.cols, 2) self.assertEqual(self.trellis3.rows, 1) + +@tm.mplskip class TestScaleGradient(unittest.TestCase): def setUp(self): path = os.path.join(curpath(), 'data/iris.csv') self.data = read_csv(path, sep=',') - self.gradient = rplot.ScaleGradient("SepalLength", colour1=(0.2, 0.3, 0.4), colour2=(0.8, 0.7, 0.6)) + self.gradient = rplot.ScaleGradient("SepalLength", colour1=(0.2, 0.3, + 0.4), + colour2=(0.8, 0.7, 0.6)) def test_gradient(self): for index in range(len(self.data)): @@ -164,6 +168,8 @@ def test_gradient(self): self.assertTrue(between(g1, g2, g)) self.assertTrue(between(b1, b2, b)) + +@tm.mplskip class TestScaleGradient2(unittest.TestCase): def setUp(self): path = os.path.join(curpath(), 'data/iris.csv') @@ -190,6 +196,8 @@ def test_gradient2(self): self.assertTrue(between(g2, g3, g)) self.assertTrue(between(b2, b3, b)) + +@tm.mplskip class TestScaleRandomColour(unittest.TestCase): def setUp(self): path = os.path.join(curpath(), 'data/iris.csv') @@ -208,6 +216,8 @@ def test_random_colour(self): self.assertTrue(g <= 1.0) self.assertTrue(b <= 1.0) + +@tm.mplskip class TestScaleConstant(unittest.TestCase): def test_scale_constant(self): scale = rplot.ScaleConstant(1.0) @@ -215,6 +225,7 @@ def test_scale_constant(self): scale = rplot.ScaleConstant("test") self.assertEqual(scale(None, None), "test") + class TestScaleSize(unittest.TestCase): def setUp(self): path = os.path.join(curpath(), 'data/iris.csv') @@ -235,8 +246,10 @@ def f(): self.assertRaises(ValueError, f) +@tm.mplskip class TestRPlot(unittest.TestCase): def test_rplot1(self): + import matplotlib.pyplot as plt path = os.path.join(curpath(), 'data/tips.csv') plt.figure() self.data = read_csv(path, sep=',') @@ -247,6 +260,7 @@ def test_rplot1(self): self.plot.render(self.fig) def test_rplot2(self): + import matplotlib.pyplot as plt path = os.path.join(curpath(), 'data/tips.csv') plt.figure() self.data = read_csv(path, sep=',') @@ -257,6 +271,7 @@ def test_rplot2(self): self.plot.render(self.fig) def test_rplot3(self): + import matplotlib.pyplot as plt path = os.path.join(curpath(), 'data/tips.csv') plt.figure() self.data = read_csv(path, sep=',') @@ -267,6 +282,7 @@ def test_rplot3(self): self.plot.render(self.fig) def test_rplot_iris(self): + import matplotlib.pyplot as plt path = os.path.join(curpath(), 'data/iris.csv') plt.figure() self.data = read_csv(path, sep=',') @@ -277,5 +293,6 @@ def test_rplot_iris(self): self.fig = plt.gcf() plot.render(self.fig) + if __name__ == '__main__': unittest.main() diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index a22d2a65248a9..96888df114950 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -26,16 +26,8 @@ def _skip_if_no_scipy(): raise nose.SkipTest +@tm.mplskip class TestTSPlot(unittest.TestCase): - - @classmethod - def setUpClass(cls): - try: - import matplotlib as mpl - mpl.use('Agg', warn=False) - except ImportError: - raise nose.SkipTest - def setUp(self): freq = ['S', 'T', 'H', 'D', 'W', 'M', 'Q', 'Y'] idx = [period_range('12/31/1999', freq=x, periods=100) for x in freq] @@ -52,9 +44,7 @@ def setUp(self): for x in idx] def tearDown(self): - import matplotlib.pyplot as plt - for fignum in plt.get_fignums(): - plt.close(fignum) + tm.close() @slow def test_ts_plot_with_tz(self): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index e7e930320116b..a5a96d3e03cac 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -18,6 +18,8 @@ from numpy.random import randn, rand import numpy as np +import nose + from pandas.core.common import isnull, _is_sequence import pandas.core.index as index import pandas.core.series as series @@ -70,6 +72,31 @@ def choice(x, size=10): except AttributeError: return np.random.randint(len(x), size=size).choose(x) + +def close(fignum=None): + from matplotlib.pyplot import get_fignums, close as _close + + if fignum is None: + for fignum in get_fignums(): + _close(fignum) + else: + _close(fignum) + + +def mplskip(cls): + """Skip a TestCase instance if matplotlib isn't installed""" + @classmethod + def setUpClass(cls): + try: + import matplotlib as mpl + mpl.use("Agg", warn=False) + except ImportError: + raise nose.SkipTest("matplotlib not installed") + + cls.setUpClass = setUpClass + return cls + + #------------------------------------------------------------------------------ # Console debugging tools
Just a couple of cleanups here and there Adds a new decorator to skip matplotlib in a class method
https://api.github.com/repos/pandas-dev/pandas/pulls/4912
2013-09-21T02:28:14Z
2013-09-21T18:26:06Z
2013-09-21T18:26:06Z
2014-07-16T08:29:28Z
BUG/TST: Allow generators in DataFrame.from_records
diff --git a/doc/source/release.rst b/doc/source/release.rst index 78236bbf821dd..0026e8c27d176 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -169,6 +169,7 @@ Improvements to existing features high-dimensional arrays). - :func:`~pandas.read_html` now supports the ``parse_dates``, ``tupleize_cols`` and ``thousands`` parameters (:issue:`4770`). + - ``DataFrame.from_records()`` accept generators (:issue:`4910`) API Changes ~~~~~~~~~~~ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d778fa096f589..1bbaeffff77bc 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -724,12 +724,17 @@ def from_records(cls, data, index=None, exclude=None, columns=None, values = [first_row] - i = 1 - for row in data: - values.append(row) - i += 1 - if i >= nrows: - break + #if unknown length iterable (generator) + if nrows == None: + #consume whole generator + values += list(data) + else: + i = 1 + for row in data: + values.append(row) + i += 1 + if i >= nrows: + break if dtype is not None: data = np.array(values, dtype=dtype) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 1e4e988431f43..4c31961cbf8fb 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3739,6 +3739,36 @@ def test_from_records_iterator(self): nrows=2) assert_frame_equal(df, xp.reindex(columns=['x','y']), check_dtype=False) + def test_from_records_tuples_generator(self): + def tuple_generator(length): + for i in range(length): + letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + yield (i, letters[i % len(letters)], i/length) + + columns_names = ['Integer', 'String', 'Float'] + columns = [[i[j] for i in tuple_generator(10)] for j in range(len(columns_names))] + data = {'Integer': columns[0], 'String': columns[1], 'Float': columns[2]} + expected = DataFrame(data, columns=columns_names) + + generator = tuple_generator(10) + result = DataFrame.from_records(generator, columns=columns_names) + assert_frame_equal(result, expected) + + def test_from_records_lists_generator(self): + def list_generator(length): + for i in range(length): + letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + yield [i, letters[i % len(letters)], i/length] + + columns_names = ['Integer', 'String', 'Float'] + columns = [[i[j] for i in list_generator(10)] for j in range(len(columns_names))] + data = {'Integer': columns[0], 'String': columns[1], 'Float': columns[2]} + expected = DataFrame(data, columns=columns_names) + + generator = list_generator(10) + result = DataFrame.from_records(generator, columns=columns_names) + assert_frame_equal(result, expected) + def test_from_records_columns_not_modified(self): tuples = [(1, 2, 3), (1, 2, 3),
closes #4910 - nrows implementation doesn't allow unknown size iterator like generators, if nrows = none ends with a TypeError. - To allow generators if nrows=None consume it into a list. - Add two tests of generators input.
https://api.github.com/repos/pandas-dev/pandas/pulls/4911
2013-09-21T00:56:24Z
2013-10-04T20:19:07Z
2013-10-04T20:19:07Z
2014-06-20T19:30:09Z
ENH: Add 'is_' method to Index for identity checks
diff --git a/doc/source/release.rst b/doc/source/release.rst index 789fbd0fe4ccc..70981df6b3187 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -198,6 +198,10 @@ API Changes data - allowing metadata changes. - ``MultiIndex.astype()`` now only allows ``np.object_``-like dtypes and now returns a ``MultiIndex`` rather than an ``Index``. (:issue:`4039`) + - Added ``is_`` method to ``Index`` that allows fast equality comparison of + views (similar to ``np.may_share_memory`` but no false positives, and + changes on ``levels`` and ``labels`` setting on ``MultiIndex``). + (:issue:`4859`, :issue:`4909`) - Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`) - ``__nonzero__`` for all NDFrame objects, will now raise a ``ValueError``, this reverts back to (:issue:`1073`, :issue:`4633`) diff --git a/pandas/core/index.py b/pandas/core/index.py index eea09138a0638..1d3f181b731e8 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -50,6 +50,9 @@ def _shouldbe_timestamp(obj): or tslib.is_timestamp_array(obj)) +_Identity = object + + class Index(FrozenNDArray): """ Immutable ndarray implementing an ordered, sliceable set. The basic object @@ -87,6 +90,35 @@ class Index(FrozenNDArray): _engine_type = _index.ObjectEngine + def is_(self, other): + """ + More flexible, faster check like ``is`` but that works through views + + Note: this is *not* the same as ``Index.identical()``, which checks + that metadata is also the same. + + Parameters + ---------- + other : object + other object to compare against. + + Returns + ------- + True if both have same underlying data, False otherwise : bool + """ + # use something other than None to be clearer + return self._id is getattr(other, '_id', Ellipsis) + + def _reset_identity(self): + "Initializes or resets ``_id`` attribute with new object" + self._id = _Identity() + + def view(self, *args, **kwargs): + result = super(Index, self).view(*args, **kwargs) + if isinstance(result, Index): + result._id = self._id + return result + def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, **kwargs): @@ -151,6 +183,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, return subarr def __array_finalize__(self, obj): + self._reset_identity() if not isinstance(obj, type(self)): # Only relevant if array being created from an Index instance return @@ -279,6 +312,7 @@ def set_names(self, names, inplace=False): raise TypeError("Must pass list-like as `names`.") if inplace: idx = self + idx._reset_identity() else: idx = self._shallow_copy() idx._set_names(names) @@ -554,7 +588,7 @@ def equals(self, other): """ Determines if two Index objects contain the same elements. """ - if self is other: + if self.is_(other): return True if not isinstance(other, Index): @@ -1536,7 +1570,7 @@ def equals(self, other): """ Determines if two Index objects contain the same elements. """ - if self is other: + if self.is_(other): return True # if not isinstance(other, Int64Index): @@ -1645,6 +1679,7 @@ def set_levels(self, levels, inplace=False): idx = self else: idx = self._shallow_copy() + idx._reset_identity() idx._set_levels(levels) return idx @@ -1683,6 +1718,7 @@ def set_labels(self, labels, inplace=False): idx = self else: idx = self._shallow_copy() + idx._reset_identity() idx._set_labels(labels) return idx @@ -1736,6 +1772,8 @@ def __array_finalize__(self, obj): Update custom MultiIndex attributes when a new array is created by numpy, e.g. when calling ndarray.view() """ + # overriden if a view + self._reset_identity() if not isinstance(obj, type(self)): # Only relevant if this array is being created from an Index # instance. @@ -2754,7 +2792,7 @@ def equals(self, other): -------- equal_levels """ - if self is other: + if self.is_(other): return True if not isinstance(other, MultiIndex): diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 5b91f011c98f8..3e7ec5c3a3c12 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -192,6 +192,28 @@ def test_identical(self): i2 = i2.rename('foo') self.assert_(i1.identical(i2)) + def test_is_(self): + ind = Index(range(10)) + self.assertTrue(ind.is_(ind)) + self.assertTrue(ind.is_(ind.view().view().view().view())) + self.assertFalse(ind.is_(Index(range(10)))) + self.assertFalse(ind.is_(ind.copy())) + self.assertFalse(ind.is_(ind.copy(deep=False))) + self.assertFalse(ind.is_(ind[:])) + self.assertFalse(ind.is_(ind.view(np.ndarray).view(Index))) + self.assertFalse(ind.is_(np.array(range(10)))) + self.assertTrue(ind.is_(ind.view().base)) # quasi-implementation dependent + ind2 = ind.view() + ind2.name = 'bob' + self.assertTrue(ind.is_(ind2)) + self.assertTrue(ind2.is_(ind)) + # doesn't matter if Indices are *actually* views of underlying data, + self.assertFalse(ind.is_(Index(ind.values))) + arr = np.array(range(1, 11)) + ind1 = Index(arr, copy=False) + ind2 = Index(arr, copy=False) + self.assertFalse(ind1.is_(ind2)) + def test_asof(self): d = self.dateIndex[0] self.assert_(self.dateIndex.asof(d) is d) @@ -1719,6 +1741,29 @@ def test_identical(self): mi2 = mi2.set_names(['new1','new2']) self.assert_(mi.identical(mi2)) + def test_is_(self): + mi = MultiIndex.from_tuples(lzip(range(10), range(10))) + self.assertTrue(mi.is_(mi)) + self.assertTrue(mi.is_(mi.view())) + self.assertTrue(mi.is_(mi.view().view().view().view())) + mi2 = mi.view() + # names are metadata, they don't change id + mi2.names = ["A", "B"] + self.assertTrue(mi2.is_(mi)) + self.assertTrue(mi.is_(mi2)) + self.assertTrue(mi.is_(mi.set_names(["C", "D"]))) + # levels are inherent properties, they change identity + mi3 = mi2.set_levels([lrange(10), lrange(10)]) + self.assertFalse(mi3.is_(mi2)) + # shouldn't change + self.assertTrue(mi2.is_(mi)) + mi4 = mi3.view() + mi4.set_levels([[1 for _ in range(10)], lrange(10)], inplace=True) + self.assertFalse(mi4.is_(mi3)) + mi5 = mi.view() + mi5.set_levels(mi5.levels, inplace=True) + self.assertFalse(mi5.is_(mi)) + def test_union(self): piece1 = self.index[:5][::-1] piece2 = self.index[3:] diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 8646d261306ca..b9e8684dfa856 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -8,7 +8,7 @@ from pandas.core.common import (isnull, _NS_DTYPE, _INT64_DTYPE, is_list_like,_values_from_object, _maybe_box) -from pandas.core.index import Index, Int64Index +from pandas.core.index import Index, Int64Index, _Identity import pandas.compat as compat from pandas.compat import u from pandas.tseries.frequencies import ( @@ -1029,6 +1029,7 @@ def __array_finalize__(self, obj): self.offset = getattr(obj, 'offset', None) self.tz = getattr(obj, 'tz', None) self.name = getattr(obj, 'name', None) + self._reset_identity() def intersection(self, other): """ @@ -1446,7 +1447,7 @@ def equals(self, other): """ Determines if two Index objects contain the same elements. """ - if self is other: + if self.is_(other): return True if (not hasattr(other, 'inferred_type') or diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py index 45894eb419489..afa267ed5b4e4 100644 --- a/pandas/tseries/period.py +++ b/pandas/tseries/period.py @@ -812,7 +812,7 @@ def equals(self, other): """ Determines if two Index objects contain the same elements. """ - if self is other: + if self.is_(other): return True return np.array_equal(self.asi8, other.asi8) @@ -1076,6 +1076,7 @@ def __array_finalize__(self, obj): self.freq = getattr(obj, 'freq', None) self.name = getattr(obj, 'name', None) + self._reset_identity() def __repr__(self): output = com.pprint_thing(self.__class__) + '\n' diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index b95ea2cacda55..96e96607ad9de 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -1054,9 +1054,6 @@ def test_conv_secondly(self): class TestPeriodIndex(TestCase): - def __init__(self, *args, **kwds): - TestCase.__init__(self, *args, **kwds) - def setUp(self): pass @@ -1168,6 +1165,25 @@ def test_constructor_datetime64arr(self): self.assertRaises(ValueError, PeriodIndex, vals, freq='D') + def test_is_(self): + create_index = lambda: PeriodIndex(freq='A', start='1/1/2001', + end='12/1/2009') + index = create_index() + self.assertTrue(index.is_(index)) + self.assertFalse(index.is_(create_index())) + self.assertTrue(index.is_(index.view())) + self.assertTrue(index.is_(index.view().view().view().view().view())) + self.assertTrue(index.view().is_(index)) + ind2 = index.view() + index.name = "Apple" + self.assertTrue(ind2.is_(index)) + self.assertFalse(index.is_(index[:])) + self.assertFalse(index.is_(index.asfreq('M'))) + self.assertFalse(index.is_(index.asfreq('A'))) + self.assertFalse(index.is_(index - 2)) + self.assertFalse(index.is_(index - 0)) + + def test_comp_period(self): idx = period_range('2007-01', periods=20, freq='M') diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index a6a9bc0211bd9..2b2513b37bab6 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -274,6 +274,12 @@ def assert_range_equal(left, right): class TestTimeSeries(unittest.TestCase): _multiprocess_can_split_ = True + def test_is_(self): + dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') + self.assertTrue(dti.is_(dti)) + self.assertTrue(dti.is_(dti.view())) + self.assertFalse(dti.is_(dti.copy())) + def test_dti_slicing(self): dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') dti2 = dti[[1, 3, 5]] @@ -655,7 +661,7 @@ def test_index_astype_datetime64(self): idx = Index([datetime(2012, 1, 1)], dtype=object) if np.__version__ >= '1.7': - raise nose.SkipTest + raise nose.SkipTest("Test requires numpy < 1.7") casted = idx.astype(np.dtype('M8[D]')) expected = DatetimeIndex(idx.values)
Closes #4859. Adds a method that can quickly tell whether something is a view or not (in the way that actually matters). Also changes checks in `equals()` to use `is_` rather than `is`.
https://api.github.com/repos/pandas-dev/pandas/pulls/4909
2013-09-21T00:23:39Z
2013-09-22T22:17:09Z
2013-09-22T22:17:09Z
2014-06-13T23:57:44Z
Fixing issue #4902.
diff --git a/.gitignore b/.gitignore index 3da165e07c77c..df7002a79d974 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,6 @@ pandas/io/*.json .vagrant *.whl **/wheelhouse/* + +.project +.pydevproject diff --git a/doc/source/release.rst b/doc/source/release.rst index ffb792ca98da5..1e1b665a478a1 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -433,6 +433,7 @@ Bug Fixes - Fix an issue in TextFileReader w/ Python engine (i.e. PythonParser) with thousands != "," (:issue:`4596`) - Bug in getitem with a duplicate index when using where (:issue:`4879`) + - Fixed ``_ensure_numeric`` does not check for complex numbers (:issue:`4902`) pandas 0.12.0 diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 3a185ca83604d..247f429d4b331 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -546,12 +546,14 @@ def _ensure_numeric(x): if isinstance(x, np.ndarray): if x.dtype == np.object_: x = x.astype(np.float64) - elif not (com.is_float(x) or com.is_integer(x)): + elif not (com.is_float(x) or com.is_integer(x) or com.is_complex(x)): try: x = float(x) except Exception: - raise TypeError('Could not convert %s to numeric' % str(x)) - + try: + x = complex(x) + except Exception: + raise TypeError('Could not convert %s to numeric' % str(x)) return x # NA-friendly array comparisons diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 8c5764a3f59a6..740e3d0821cd7 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -14,6 +14,7 @@ import pandas.core.common as com import pandas.util.testing as tm import pandas.core.config as cf +from pandas.core import nanops _multiprocess_can_split_ = True @@ -311,6 +312,54 @@ def test_ensure_int32(): assert(result.dtype == np.int32) +class TestEnsureNumeric(unittest.TestCase): + def test_numeric_values(self): + # Test integer + self.assertEqual(nanops._ensure_numeric(1), 1, 'Failed for int') + # Test float + self.assertEqual(nanops._ensure_numeric(1.1), 1.1, 'Failed for float') + # Test complex + self.assertEqual(nanops._ensure_numeric(1 + 2j), 1 + 2j, + 'Failed for complex') + + def test_ndarray(self): + # Test numeric ndarray + values = np.array([1, 2, 3]) + self.assertTrue(np.allclose(nanops._ensure_numeric(values), values), + 'Failed for numeric ndarray') + + # Test object ndarray + o_values = values.astype(object) + self.assertTrue(np.allclose(nanops._ensure_numeric(o_values), values), + 'Failed for object ndarray') + + # Test convertible string ndarray + s_values = np.array(['1', '2', '3'], dtype=object) + self.assertTrue(np.allclose(nanops._ensure_numeric(s_values), values), + 'Failed for convertible string ndarray') + + # Test non-convertible string ndarray + s_values = np.array(['foo', 'bar', 'baz'], dtype=object) + self.assertRaises(ValueError, + lambda: nanops._ensure_numeric(s_values)) + + def test_convertable_values(self): + self.assertTrue(np.allclose(nanops._ensure_numeric('1'), 1.0), + 'Failed for convertible integer string') + self.assertTrue(np.allclose(nanops._ensure_numeric('1.1'), 1.1), + 'Failed for convertible float string') + self.assertTrue(np.allclose(nanops._ensure_numeric('1+1j'), 1 + 1j), + 'Failed for convertible complex string') + + def test_non_convertable_values(self): + self.assertRaises(TypeError, + lambda: nanops._ensure_numeric('foo')) + self.assertRaises(TypeError, + lambda: nanops._ensure_numeric({})) + self.assertRaises(TypeError, + lambda: nanops._ensure_numeric([])) + + def test_ensure_platform_int(): # verify that when we create certain types of indices
closes #4902, Added a check for complex numbers.
https://api.github.com/repos/pandas-dev/pandas/pulls/4904
2013-09-20T18:58:30Z
2013-09-21T12:03:26Z
2013-09-21T12:03:26Z
2014-08-15T20:01:48Z
CI: allow print_versions to work without pandas install
diff --git a/ci/print_versions.py b/ci/print_versions.py index f2549fe73be24..16418de3c73be 100755 --- a/ci/print_versions.py +++ b/ci/print_versions.py @@ -1,5 +1,22 @@ #!/usr/bin/env python -from pandas.util.print_versions import show_versions -show_versions() +try: + from pandas.util.print_versions import show_versions +except Exception as e: + + print("Failed to import pandas: %s" % e) + + def show_versions(): + import subprocess + import os + fn = __file__ + this_dir = os.path.dirname(fn) + pandas_dir = os.path.dirname(this_dir) + sv_path = os.path.join(pandas_dir, 'pandas', 'util', + 'print_versions.py') + return subprocess.check_call(['python', sv_path]) + + +if __name__ == '__main__': + show_versions() diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py index b7b4a936a1e90..f67cbb4b80f56 100644 --- a/pandas/util/print_versions.py +++ b/pandas/util/print_versions.py @@ -1,20 +1,29 @@ import os import sys + def show_versions(): print("\nINSTALLED VERSIONS") print("------------------") print("Python: %d.%d.%d.%s.%s" % sys.version_info[:]) + try: - (sysname, nodename, release, version, machine) = os.uname() - print("OS: %s %s %s %s" % (sysname, release, version,machine)) + sysname, nodename, release, version, machine = os.uname() + print("OS: %s %s %s %s" % (sysname, release, version, machine)) print("byteorder: %s" % sys.byteorder) - print("LC_ALL: %s" % os.environ.get('LC_ALL',"None")) - print("LANG: %s" % os.environ.get('LANG',"None")) + print("LC_ALL: %s" % os.environ.get('LC_ALL', "None")) + print("LANG: %s" % os.environ.get('LANG', "None")) except: pass print("") + + try: + import pandas + print("pandas: %s" % pandas.__version__) + except: + print("pandas: Not installed") + try: import Cython print("Cython: %s" % Cython.__version__) @@ -129,7 +138,7 @@ def show_versions(): except: print("html5lib: Not installed") - print("\n") + if __name__ == "__main__": show_versions()
https://api.github.com/repos/pandas-dev/pandas/pulls/4901
2013-09-20T18:10:43Z
2013-09-20T22:20:28Z
2013-09-20T22:20:28Z
2014-07-16T08:29:21Z
BUG/TST: Fix failing FRED comparison tests and remove skips.
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 4b2d99dfd176f..091e149ebb1c0 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -369,7 +369,6 @@ def test_fred(self): FRED. """ - raise nose.SkipTest('Skip as this is unstable #4427 ') start = datetime(2010, 1, 1) end = datetime(2013, 1, 27) @@ -381,19 +380,17 @@ def test_fred(self): @network def test_fred_nan(self): - raise nose.SkipTest("Unstable test case - needs to be fixed.") start = datetime(2010, 1, 1) end = datetime(2013, 1, 27) df = web.DataReader("DFII5", "fred", start, end) - assert pd.isnull(df.ix['2010-01-01']) + assert pd.isnull(df.ix['2010-01-01'][0]) @network def test_fred_parts(self): - raise nose.SkipTest("Unstable test case - needs to be fixed.") start = datetime(2010, 1, 1) end = datetime(2013, 1, 27) df = web.get_data_fred("CPIAUCSL", start, end) - self.assertEqual(df.ix['2010-05-01'], 217.23) + self.assertEqual(df.ix['2010-05-01'][0], 217.23) t = df.CPIAUCSL.values assert np.issubdtype(t.dtype, np.floating)
Replacing my mess of a PR in #4890. Fixes #4827 Assertions were being made about arrays (of one item) equaling a scaler.
https://api.github.com/repos/pandas-dev/pandas/pulls/4891
2013-09-20T04:28:00Z
2013-09-20T08:01:33Z
2013-09-20T08:01:33Z
2017-04-05T02:05:40Z
BUG/TST: Fix failing FRED comparison tests.
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 4b2d99dfd176f..dd0b47bcfb90a 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -385,7 +385,7 @@ def test_fred_nan(self): start = datetime(2010, 1, 1) end = datetime(2013, 1, 27) df = web.DataReader("DFII5", "fred", start, end) - assert pd.isnull(df.ix['2010-01-01']) + assert pd.isnull(df.ix['2010-01-01'][0]) @network def test_fred_parts(self): @@ -393,7 +393,7 @@ def test_fred_parts(self): start = datetime(2010, 1, 1) end = datetime(2013, 1, 27) df = web.get_data_fred("CPIAUCSL", start, end) - self.assertEqual(df.ix['2010-05-01'], 217.23) + self.assertEqual(df.ix['2010-05-01'][0], 217.23) t = df.CPIAUCSL.values assert np.issubdtype(t.dtype, np.floating)
Fixes #4827 Assertions were being made about arrays (of one item) equaling a scaler.
https://api.github.com/repos/pandas-dev/pandas/pulls/4890
2013-09-20T04:02:15Z
2013-09-20T04:29:12Z
null
2016-11-03T12:37:25Z
CLN: move README.rst to markdown
diff --git a/README.md b/README.md new file mode 100644 index 0000000000000..e7a139ac26f0c --- /dev/null +++ b/README.md @@ -0,0 +1,213 @@ +# pandas: powerful Python data analysis toolkit + +![Travis-CI Build Status](https://travis-ci.org/pydata/pandas.png) + +## What is it +**pandas** is a Python package providing fast, flexible, and expressive data +structures designed to make working with "relational" or "labeled" data both +easy and intuitive. It aims to be the fundamental high-level building block for +doing practical, **real world** data analysis in Python. Additionally, it has +the broader goal of becoming **the most powerful and flexible open source data +analysis / manipulation tool available in any language**. It is already well on +its way toward this goal. + +## Main Features +Here are just a few of the things that pandas does well: + + - Easy handling of [**missing data**][missing-data] (represented as + `NaN`) in floating point as well as non-floating point data + - Size mutability: columns can be [**inserted and + deleted**][insertion-deletion] from DataFrame and higher dimensional + objects + - Automatic and explicit [**data alignment**][alignment]: objects can + be explicitly aligned to a set of labels, or the user can simply + ignore the labels and let `Series`, `DataFrame`, etc. automatically + align the data for you in computations + - Powerful, flexible [**group by**][groupby] functionality to perform + split-apply-combine operations on data sets, for both aggregating + and transforming data + - Make it [**easy to convert**][conversion] ragged, + differently-indexed data in other Python and NumPy data structures + into DataFrame objects + - Intelligent label-based [**slicing**][slicing], [**fancy + indexing**][fancy-indexing], and [**subsetting**][subsetting] of + large data sets + - Intuitive [**merging**][merging] and [**joining**][joining] data + sets + - Flexible [**reshaping**][reshape] and [**pivoting**][pivot-table] of + data sets + - [**Hierarchical**][mi] labeling of axes (possible to have multiple + labels per tick) + - Robust IO tools for loading data from [**flat files**][flat-files] + (CSV and delimited), [**Excel files**][excel], [**databases**][db], + and saving/loading data from the ultrafast [**HDF5 format**][hdfstore] + - [**Time series**][timeseries]-specific functionality: date range + generation and frequency conversion, moving window statistics, + moving window linear regressions, date shifting and lagging, etc. + + + [missing-data]: http://pandas.pydata.org/pandas-docs/stable/missing_data.html#working-with-missing-data + [insertion-deletion]: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion + [alignment]: http://pandas.pydata.org/pandas-docs/stable/dsintro.html?highlight=alignment#intro-to-data-structures + [groupby]: http://pandas.pydata.org/pandas-docs/stable/groupby.html#group-by-split-apply-combine + [conversion]: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe + [slicing]: http://pandas.pydata.org/pandas-docs/stable/indexing.html#slicing-ranges + [fancy-indexing]: http://pandas.pydata.org/pandas-docs/stable/indexing.html#advanced-indexing-with-ix + [subsetting]: http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing + [merging]: http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging + [joining]: http://pandas.pydata.org/pandas-docs/stable/merging.html#joining-on-index + [reshape]: http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-and-pivot-tables + [pivot-table]: http://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations + [mi]: http://pandas.pydata.org/pandas-docs/stable/indexing.html#hierarchical-indexing-multiindex + [flat-files]: http://pandas.pydata.org/pandas-docs/stable/io.html#csv-text-files + [excel]: http://pandas.pydata.org/pandas-docs/stable/io.html#excel-files + [db]: http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries + [hdfstore]: http://pandas.pydata.org/pandas-docs/stable/io.html#hdf5-pytables + [timeseries]: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-series-date-functionality + +## Where to get it +The source code is currently hosted on GitHub at: +http://github.com/pydata/pandas + +Binary installers for the latest released version are available at the Python +package index + + http://pypi.python.org/pypi/pandas/ + +And via `easy_install`: + +```sh +easy_install pandas +``` + +or `pip`: + +```sh +pip install pandas +``` + +## Dependencies +- [NumPy](http://www.numpy.org): 1.6.1 or higher +- [python-dateutil](http://labix.org/python-dateutil): 1.5 or higher +- [pytz](http://pytz.sourceforge.net) + - Needed for time zone support with ``pandas.date_range`` + +### Highly Recommended Dependencies +- [numexpr](http://code.google.com/p/numexpr/) + - Needed to accelerate some expression evaluation operations + - Required by PyTables +- [bottleneck](http://berkeleyanalytics.com/bottleneck) + - Needed to accelerate certain numerical operations + +### Optional dependencies +- [Cython](http://www.cython.org): Only necessary to build development version. Version 0.17.1 or higher. +- [SciPy](http://www.scipy.org): miscellaneous statistical functions +- [PyTables](http://www.pytables.org): necessary for HDF5-based storage +- [matplotlib](http://matplotlib.sourceforge.net/): for plotting +- [statsmodels](http://statsmodels.sourceforge.net/) + - Needed for parts of `pandas.stats` +- [openpyxl](http://packages.python.org/openpyxl/), [xlrd/xlwt](http://www.python-excel.org/) + - openpyxl version 1.6.1 or higher, for writing .xlsx files + - xlrd >= 0.9.0 + - Needed for Excel I/O +- [boto](https://pypi.python.org/pypi/boto): necessary for Amazon S3 access. +- One of the following combinations of libraries is needed to use the + top-level [`pandas.read_html`][read-html-docs] function: + - [BeautifulSoup4][BeautifulSoup4] and [html5lib][html5lib] (Any + recent version of [html5lib][html5lib] is okay.) + - [BeautifulSoup4][BeautifulSoup4] and [lxml][lxml] + - [BeautifulSoup4][BeautifulSoup4] and [html5lib][html5lib] and [lxml][lxml] + - Only [lxml][lxml], although see [HTML reading gotchas][html-gotchas] + for reasons as to why you should probably **not** take this approach. + +#### Notes about HTML parsing libraries +- If you install [BeautifulSoup4][BeautifulSoup4] you must install + either [lxml][lxml] or [html5lib][html5lib] or both. + `pandas.read_html` will **not** work with *only* `BeautifulSoup4` + installed. +- You are strongly encouraged to read [HTML reading + gotchas][html-gotchas]. It explains issues surrounding the + installation and usage of the above three libraries. +- You may need to install an older version of + [BeautifulSoup4][BeautifulSoup4]: + - Versions 4.2.1, 4.1.3 and 4.0.2 have been confirmed for 64 and + 32-bit Ubuntu/Debian +- Additionally, if you're using [Anaconda][Anaconda] you should + definitely read [the gotchas about HTML parsing][html-gotchas] + libraries +- If you're on a system with `apt-get` you can do + + ```sh + sudo apt-get build-dep python-lxml + ``` + + to get the necessary dependencies for installation of [lxml][lxml]. + This will prevent further headaches down the line. + + [html5lib]: https://github.com/html5lib/html5lib-python "html5lib" + [BeautifulSoup4]: http://www.crummy.com/software/BeautifulSoup "BeautifulSoup4" + [lxml]: http://lxml.de + [Anaconda]: https://store.continuum.io/cshop/anaconda + [NumPy]: http://numpy.scipy.org/ + [html-gotchas]: http://pandas.pydata.org/pandas-docs/stable/gotchas.html#html-table-parsing + [read-html-docs]: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.html.read_html.html#pandas.io.html.read_html + +## Installation from sources +To install pandas from source you need Cython in addition to the normal +dependencies above. Cython can be installed from pypi: + +```sh +pip install cython +``` + +In the `pandas` directory (same one where you found this file after +cloning the git repo), execute: + +```sh +python setup.py install +``` + +or for installing in [development mode](http://www.pip-installer.org/en/latest/usage.html): + +```sh +python setup.py develop +``` + +Alternatively, you can use `pip` if you want all the dependencies pulled +in automatically (the `-e` option is for installing it in [development +mode](http://www.pip-installer.org/en/latest/usage.html)): + +```sh +pip install -e . +``` + +On Windows, you will need to install MinGW and execute: + +```sh +python setup.py build --compiler=mingw32 +python setup.py install +``` + +See http://pandas.pydata.org/ for more information. + +## License +BSD + +## Documentation +The official documentation is hosted on PyData.org: http://pandas.pydata.org/ + +The Sphinx documentation should provide a good starting point for learning how +to use the library. Expect the docs to continue to expand as time goes on. + +## Background +Work on ``pandas`` started at AQR (a quantitative hedge fund) in 2008 and +has been under active development since then. + +## Discussion and Development +Since pandas development is related to a number of other scientific +Python projects, questions are welcome on the scipy-user mailing +list. Specialized discussions or design issues should take place on +the pystatsmodels mailing list / Google group, where +``scikits.statsmodels`` and other libraries will also be discussed: + +http://groups.google.com/group/pystatsmodels diff --git a/README.rst b/README.rst deleted file mode 100644 index da789e704ebad..0000000000000 --- a/README.rst +++ /dev/null @@ -1,199 +0,0 @@ -============================================= -pandas: powerful Python data analysis toolkit -============================================= - -.. image:: https://travis-ci.org/pydata/pandas.png - :target: https://travis-ci.org/pydata/pandas - -What is it -========== - -**pandas** is a Python package providing fast, flexible, and expressive data -structures designed to make working with "relational" or "labeled" data both -easy and intuitive. It aims to be the fundamental high-level building block for -doing practical, **real world** data analysis in Python. Additionally, it has -the broader goal of becoming **the most powerful and flexible open source data -analysis / manipulation tool available in any language**. It is already well on -its way toward this goal. - -Main Features -============= - -Here are just a few of the things that pandas does well: - - - Easy handling of **missing data** (represented as NaN) in floating point as - well as non-floating point data - - Size mutability: columns can be **inserted and deleted** from DataFrame and - higher dimensional objects - - Automatic and explicit **data alignment**: objects can be explicitly - aligned to a set of labels, or the user can simply ignore the labels and - let `Series`, `DataFrame`, etc. automatically align the data for you in - computations - - Powerful, flexible **group by** functionality to perform - split-apply-combine operations on data sets, for both aggregating and - transforming data - - Make it **easy to convert** ragged, differently-indexed data in other - Python and NumPy data structures into DataFrame objects - - Intelligent label-based **slicing**, **fancy indexing**, and **subsetting** - of large data sets - - Intuitive **merging** and **joining** data sets - - Flexible **reshaping** and pivoting of data sets - - **Hierarchical** labeling of axes (possible to have multiple labels per - tick) - - Robust IO tools for loading data from **flat files** (CSV and delimited), - Excel files, databases, and saving / loading data from the ultrafast **HDF5 - format** - - **Time series**-specific functionality: date range generation and frequency - conversion, moving window statistics, moving window linear regressions, - date shifting and lagging, etc. - -Where to get it -=============== - -The source code is currently hosted on GitHub at: http://github.com/pydata/pandas - -Binary installers for the latest released version are available at the Python -package index:: - - http://pypi.python.org/pypi/pandas/ - -And via ``easy_install`` or ``pip``:: - - easy_install pandas - pip install pandas - -Dependencies -============ - - - `NumPy <http://www.numpy.org>`__: 1.6.1 or higher - - `python-dateutil <http://labix.org/python-dateutil>`__ 1.5 or higher - - `pytz <http://pytz.sourceforge.net/>`__ - - Needed for time zone support with ``date_range`` - -Highly Recommended Dependencies -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - `numexpr <http://code.google.com/p/numexpr/>`__ - - Needed to accelerate some expression evaluation operations - - Required by `PyTables` - - `bottleneck <http://berkeleyanalytics.com/bottleneck>`__ - - Needed to accelerate certain numerical operations - -Optional dependencies -~~~~~~~~~~~~~~~~~~~~~ - - - `Cython <http://www.cython.org>`__: Only necessary to build development version. Version 0.17.1 or higher. - - `SciPy <http://www.scipy.org>`__: miscellaneous statistical functions - - `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage - - `matplotlib <http://matplotlib.sourceforge.net/>`__: for plotting - - `statsmodels <http://statsmodels.sourceforge.net/>`__ - - Needed for parts of :mod:`pandas.stats` - - `openpyxl <http://packages.python.org/openpyxl/>`__, `xlrd/xlwt <http://www.python-excel.org/>`__ - - openpyxl version 1.6.1 or higher, for writing .xlsx files - - xlrd >= 0.9.0 - - Needed for Excel I/O - - `boto <https://pypi.python.org/pypi/boto>`__: necessary for Amazon S3 - access. - - One of the following combinations of libraries is needed to use the - top-level :func:`~pandas.io.html.read_html` function: - - - `BeautifulSoup4`_ and `html5lib`_ (Any recent version of `html5lib`_ is - okay.) - - `BeautifulSoup4`_ and `lxml`_ - - `BeautifulSoup4`_ and `html5lib`_ and `lxml`_ - - Only `lxml`_, although see :ref:`HTML reading gotchas <html-gotchas>` - for reasons as to why you should probably **not** take this approach. - - .. warning:: - - - if you install `BeautifulSoup4`_ you must install either - `lxml`_ or `html5lib`_ or both. - :func:`~pandas.io.html.read_html` will **not** work with *only* - `BeautifulSoup4`_ installed. - - You are highly encouraged to read :ref:`HTML reading gotchas - <html-gotchas>`. It explains issues surrounding the installation and - usage of the above three libraries - - You may need to install an older version of `BeautifulSoup4`_: - - Versions 4.2.1, 4.1.3 and 4.0.2 have been confirmed for 64 and - 32-bit Ubuntu/Debian - - Additionally, if you're using `Anaconda`_ you should definitely - read :ref:`the gotchas about HTML parsing libraries <html-gotchas>` - - .. note:: - - - if you're on a system with ``apt-get`` you can do - - .. code-block:: sh - - sudo apt-get build-dep python-lxml - - to get the necessary dependencies for installation of `lxml`_. This - will prevent further headaches down the line. - - -.. _html5lib: https://github.com/html5lib/html5lib-python -.. _BeautifulSoup4: http://www.crummy.com/software/BeautifulSoup -.. _lxml: http://lxml.de -.. _Anaconda: https://store.continuum.io/cshop/anaconda - - -Installation from sources -========================= - -To install pandas from source you need ``cython`` in addition to the normal dependencies above, -which can be installed from pypi:: - - pip install cython - -In the ``pandas`` directory (same one where you found this file after cloning the git repo), execute:: - - python setup.py install - -or for installing in `development mode <http://www.pip-installer.org/en/latest/usage.html>`__:: - - python setup.py develop - -Alternatively, you can use `pip` if you want all the dependencies pulled in automatically -(the optional ``-e`` option is for installing it in -`development mode <http://www.pip-installer.org/en/latest/usage.html>`__):: - - pip install -e . - -On Windows, you will need to install MinGW and execute:: - - python setup.py build --compiler=mingw32 - python setup.py install - -See http://pandas.pydata.org/ for more information. - -License -======= - -BSD - -Documentation -============= - -The official documentation is hosted on PyData.org: http://pandas.pydata.org/ - -The Sphinx documentation should provide a good starting point for learning how -to use the library. Expect the docs to continue to expand as time goes on. - -Background -========== - -Work on ``pandas`` started at AQR (a quantitative hedge fund) in 2008 and -has been under active development since then. - -Discussion and Development -========================== - -Since ``pandas`` development is related to a number of other scientific -Python projects, questions are welcome on the scipy-user mailing -list. Specialized discussions or design issues should take place on -the pystatsmodels mailing list / Google group, where -``scikits.statsmodels`` and other libraries will also be discussed: - -http://groups.google.com/group/pystatsmodels - - .. _NumPy: http://numpy.scipy.org/
Because GitHub's rst is ugly
https://api.github.com/repos/pandas-dev/pandas/pulls/4888
2013-09-19T19:00:25Z
2013-09-19T19:37:58Z
2013-09-19T19:37:58Z
2014-07-16T08:29:15Z
API: disable to_csv and friends on GroupBy objects
diff --git a/doc/source/release.rst b/doc/source/release.rst index 74e54526cfe9a..e49812b207921 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -243,6 +243,8 @@ API Changes - Remove deprecated ``Factor`` (:issue:`3650`) - Remove deprecated ``set_printoptions/reset_printoptions`` (:issue:``3046``) - Remove deprecated ``_verbose_info`` (:issue:`3215`) + - Begin removing methods that don't make sense on ``GroupBy`` objects + (:issue:`4887`). Internal Refactoring ~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 186277777abe8..2e07662bffbfe 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -45,6 +45,16 @@ """ +_apply_whitelist = frozenset(['last', 'first', + 'mean', 'sum', 'min', 'max', + 'head', 'tail', + 'cumsum', 'cumprod', 'cummin', 'cummax', + 'resample', + 'describe', + 'rank', 'quantile', 'count', + 'fillna', 'dtype']) + + class GroupByError(Exception): pass @@ -241,13 +251,21 @@ def __getattr__(self, attr): if hasattr(self.obj, attr) and attr != '_cache': return self._make_wrapper(attr) - raise AttributeError("'%s' object has no attribute '%s'" % + raise AttributeError("%r object has no attribute %r" % (type(self).__name__, attr)) def __getitem__(self, key): raise NotImplementedError def _make_wrapper(self, name): + if name not in _apply_whitelist: + is_callable = callable(getattr(self.obj, name, None)) + kind = ' callable ' if is_callable else ' ' + msg = ("Cannot access{0}attribute {1!r} of {2!r} objects, try " + "using the 'apply' method".format(kind, name, + type(self).__name__)) + raise AttributeError(msg) + f = getattr(self.obj, name) if not isinstance(f, types.MethodType): return self.apply(lambda self: getattr(self, name)) diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 02eb4015c133f..46ab0fe022e78 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -9,7 +9,8 @@ from pandas.core.index import Index, MultiIndex from pandas.core.common import rands from pandas.core.api import Categorical, DataFrame -from pandas.core.groupby import GroupByError, SpecificationError, DataError +from pandas.core.groupby import (GroupByError, SpecificationError, DataError, + _apply_whitelist) from pandas.core.series import Series from pandas.util.testing import (assert_panel_equal, assert_frame_equal, assert_series_equal, assert_almost_equal, @@ -2696,8 +2697,40 @@ def test_filter_against_workaround(self): new_way = grouped.filter(lambda x: x['ints'].mean() > N/20) assert_frame_equal(new_way.sort_index(), old_way.sort_index()) + def test_groupby_whitelist(self): + from string import ascii_lowercase + letters = np.array(list(ascii_lowercase)) + N = 10 + random_letters = letters.take(np.random.randint(0, 26, N)) + df = DataFrame({'floats': N / 10 * Series(np.random.random(N)), + 'letters': Series(random_letters)}) + s = df.floats + + blacklist = ['eval', 'query', 'abs', 'shift', 'tshift', 'where', + 'mask', 'align', 'groupby', 'clip', 'astype', + 'at', 'combine', 'consolidate', 'convert_objects', + 'corr', 'corr_with', 'cov'] + to_methods = [method for method in dir(df) if method.startswith('to_')] + + blacklist.extend(to_methods) + + # e.g., to_csv + defined_but_not_allowed = ("(?:^Cannot.+{0!r}.+{1!r}.+try using the " + "'apply' method$)") + + # e.g., query, eval + not_defined = "(?:^{1!r} object has no attribute {0!r}$)" + fmt = defined_but_not_allowed + '|' + not_defined + for bl in blacklist: + for obj in (df, s): + gb = obj.groupby(df.letters) + msg = fmt.format(bl, type(gb).__name__) + with tm.assertRaisesRegexp(AttributeError, msg): + getattr(gb, bl) + + def assert_fp_equal(a, b): - assert((np.abs(a - b) < 1e-12).all()) + assert (np.abs(a - b) < 1e-12).all() def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
https://api.github.com/repos/pandas-dev/pandas/pulls/4887
2013-09-19T18:59:23Z
2013-09-27T17:02:55Z
2013-09-27T17:02:55Z
2014-06-19T00:53:18Z
BUG: bug in getitem with a duplicate index when using where (GH4879)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 4224880d3fde0..5a49f13cd8409 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -429,9 +429,11 @@ Bug Fixes ``ascending`` was being interpreted as ``True`` (:issue:`4839`, :issue:`4846`) - Fixed ``Panel.tshift`` not working. Added `freq` support to ``Panel.shift`` (:issue:`4853`) - - Fix an issue in TextFileReader w/ Python engine (i.e. PythonParser) + - Fix an issue in TextFileReader w/ Python engine (i.e. PythonParser) with thousands != "," (:issue:`4596`) - + - Bug in getitem with a duplicate index when using where (:issue:`4879`) + + pandas 0.12.0 ------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 70fcc2c9d9c0a..cf0afe4267f69 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1840,8 +1840,12 @@ def _getitem_column(self, key): if self.columns.is_unique: return self._get_item_cache(key) - # duplicate columns - return self._constructor(self._data.get(key)) + # duplicate columns & possible reduce dimensionaility + result = self._constructor(self._data.get(key)) + if result.columns.is_unique: + result = result[key] + + return result def _getitem_slice(self, key): return self._slice(key, axis=0) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 4b9fdb0422526..585b1c817ff19 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -401,7 +401,7 @@ def _astype(self, dtype, copy=False, raise_on_error=True, values=None, if values is None: values = com._astype_nansafe(self.values, dtype, copy=True) newb = make_block( - values, self.items, self.ref_items, ndim=self.ndim, + values, self.items, self.ref_items, ndim=self.ndim, placement=self._ref_locs, fastpath=True, dtype=dtype, klass=klass) except: if raise_on_error is True: @@ -716,7 +716,7 @@ def create_block(v, m, n, item, reshape=True): if inplace: return [self] - return [make_block(new_values, self.items, self.ref_items, fastpath=True)] + return [make_block(new_values, self.items, self.ref_items, placement=self._ref_locs, fastpath=True)] def interpolate(self, method='pad', axis=0, inplace=False, limit=None, fill_value=None, coerce=False, @@ -2853,12 +2853,13 @@ def _reindex_indexer_items(self, new_items, indexer, fill_value): # TODO: less efficient than I'd like item_order = com.take_1d(self.items.values, indexer) + new_axes = [new_items] + self.axes[1:] + new_blocks = [] + is_unique = new_items.is_unique # keep track of what items aren't found anywhere + l = np.arange(len(item_order)) mask = np.zeros(len(item_order), dtype=bool) - new_axes = [new_items] + self.axes[1:] - - new_blocks = [] for blk in self.blocks: blk_indexer = blk.items.get_indexer(item_order) selector = blk_indexer != -1 @@ -2872,12 +2873,19 @@ def _reindex_indexer_items(self, new_items, indexer, fill_value): new_block_items = new_items.take(selector.nonzero()[0]) new_values = com.take_nd(blk.values, blk_indexer[selector], axis=0, allow_fill=False) - new_blocks.append(make_block(new_values, new_block_items, - new_items, fastpath=True)) + placement = l[selector] if not is_unique else None + new_blocks.append(make_block(new_values, + new_block_items, + new_items, + placement=placement, + fastpath=True)) if not mask.all(): na_items = new_items[-mask] - na_block = self._make_na_block(na_items, new_items, + placement = l[-mask] if not is_unique else None + na_block = self._make_na_block(na_items, + new_items, + placement=placement, fill_value=fill_value) new_blocks.append(na_block) new_blocks = _consolidate(new_blocks, new_items) @@ -2943,7 +2951,7 @@ def reindex_items(self, new_items, indexer=None, copy=True, fill_value=None): return self.__class__(new_blocks, new_axes) - def _make_na_block(self, items, ref_items, fill_value=None): + def _make_na_block(self, items, ref_items, placement=None, fill_value=None): # TODO: infer dtypes other than float64 from fill_value if fill_value is None: @@ -2954,8 +2962,7 @@ def _make_na_block(self, items, ref_items, fill_value=None): dtype, fill_value = com._infer_dtype_from_scalar(fill_value) block_values = np.empty(block_shape, dtype=dtype) block_values.fill(fill_value) - na_block = make_block(block_values, items, ref_items) - return na_block + return make_block(block_values, items, ref_items, placement=placement) def take(self, indexer, new_index=None, axis=1, verify=True): if axis < 1: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index d216cebc1abf3..0bc454d6ef2bc 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3150,6 +3150,36 @@ def check(result, expected=None): expected = DataFrame([[1],[1],[1]],columns=['bar']) check(df,expected) + def test_column_dups_indexing(self): + + def check(result, expected=None): + if expected is not None: + assert_frame_equal(result,expected) + result.dtypes + str(result) + + # boolean indexing + # GH 4879 + dups = ['A', 'A', 'C', 'D'] + df = DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D'],dtype='float64') + expected = df[df.C > 6] + expected.columns = dups + df = DataFrame(np.arange(12).reshape(3,4), columns=dups,dtype='float64') + result = df[df.C > 6] + check(result,expected) + + # where + df = DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D'],dtype='float64') + expected = df[df > 6] + expected.columns = dups + df = DataFrame(np.arange(12).reshape(3,4), columns=dups,dtype='float64') + result = df[df > 6] + check(result,expected) + + # boolean with the duplicate raises + df = DataFrame(np.arange(12).reshape(3,4), columns=dups,dtype='float64') + self.assertRaises(ValueError, lambda : df[df.A > 6]) + def test_insert_benchmark(self): # from the vb_suite/frame_methods/frame_insert_columns N = 10 diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 3453e69ed72b6..aad9fb2f95483 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1233,9 +1233,10 @@ def test_mi_access(self): # GH 4146, not returning a block manager when selecting a unique index # from a duplicate index - expected = DataFrame([['a',1,1]],index=['A1'],columns=['h1','h3','h5'],).T + # as of 4879, this returns a Series (which is similar to what happens with a non-unique) + expected = Series(['a',1,1],index=['h1','h3','h5']) result = df2['A']['A1'] - assert_frame_equal(result,expected) + assert_series_equal(result,expected) # selecting a non_unique from the 2nd level expected = DataFrame([['d',4,4],['e',5,5]],index=Index(['B2','B2'],name='sub'),columns=['h1','h3','h5'],).T
raising previously as this was not handled properly closes #4879 ``` In [1]: df = DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D'],dtype='float64') In [2]: df Out[2]: A B C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 In [3]: df[df.C>6] Out[3]: A B C D 2 8 9 10 11 In [4]: df = DataFrame(np.arange(12).reshape(3,4), columns=['A', 'A', 'C', 'D'],dtype='float64') In [5]: df Out[5]: A A C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 In [6]: df[df.C>6] Out[6]: A A C D 2 8 9 10 11 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4881
2013-09-19T12:23:50Z
2013-09-19T12:50:15Z
2013-09-19T12:50:15Z
2014-06-20T21:01:35Z
CLN: clean up test plotting
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 45289dac44254..cb6ec3d648afa 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -67,17 +67,16 @@ def test_plot(self): _check_plot_works(self.series[:5].plot, kind='line') _check_plot_works(self.series[:5].plot, kind='barh') _check_plot_works(self.series[:10].plot, kind='barh') - - Series(randn(10)).plot(kind='bar', color='black') + _check_plot_works(Series(randn(10)).plot, kind='bar', color='black') # figsize and title import matplotlib.pyplot as plt plt.close('all') ax = self.series.plot(title='Test', figsize=(16, 8)) - self.assert_(ax.title.get_text() == 'Test') - self.assert_((np.round(ax.figure.get_size_inches()) - == np.array((16., 8.))).all()) + self.assertEqual(ax.title.get_text(), 'Test') + assert_array_equal(np.round(ax.figure.get_size_inches()), + np.array((16., 8.))) @slow def test_bar_colors(self): @@ -97,7 +96,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = conv.to_rgba(default_colors[i % len(default_colors)]) rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -109,7 +108,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = conv.to_rgba(custom_colors[i]) rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -124,7 +123,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = rgba_colors[i] rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -137,7 +136,7 @@ def test_bar_colors(self): for i, rect in enumerate(rects[::5]): xp = rgba_colors[i] rs = rect.get_facecolor() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -150,18 +149,18 @@ def test_bar_linewidth(self): # regular ax = df.plot(kind='bar', linewidth=2) for r in ax.patches: - self.assert_(r.get_linewidth() == 2) + self.assertEqual(r.get_linewidth(), 2) # stacked ax = df.plot(kind='bar', stacked=True, linewidth=2) for r in ax.patches: - self.assert_(r.get_linewidth() == 2) + self.assertEqual(r.get_linewidth(), 2) # subplots axes = df.plot(kind='bar', linewidth=2, subplots=True) for ax in axes: for r in ax.patches: - self.assert_(r.get_linewidth() == 2) + self.assertEqual(r.get_linewidth(), 2) @slow def test_bar_log(self): @@ -177,7 +176,7 @@ def test_rotation(self): df = DataFrame(randn(5, 5)) ax = df.plot(rot=30) for l in ax.get_xticklabels(): - self.assert_(l.get_rotation() == 30) + self.assertEqual(l.get_rotation(), 30) def test_irregular_datetime(self): rng = date_range('1/1/2000', '3/1/2000') @@ -186,7 +185,7 @@ def test_irregular_datetime(self): ax = ser.plot() xp = datetime(1999, 1, 1).toordinal() ax.set_xlim('1/1/1999', '1/1/2001') - self.assert_(xp == ax.get_xlim()[0]) + self.assertEqual(xp, ax.get_xlim()[0]) @slow def test_hist(self): @@ -205,8 +204,9 @@ def test_hist(self): fig, (ax1, ax2) = plt.subplots(1, 2) _check_plot_works(self.ts.hist, figure=fig, ax=ax1) _check_plot_works(self.ts.hist, figure=fig, ax=ax2) - self.assertRaises(ValueError, self.ts.hist, by=self.ts.index, - figure=fig) + + with tm.assertRaises(ValueError): + self.ts.hist(by=self.ts.index, figure=fig) @slow def test_hist_layout(self): @@ -216,8 +216,11 @@ def test_hist_layout(self): size=n)], 'height': random.normal(66, 4, size=n), 'weight': random.normal(161, 32, size=n)}) - self.assertRaises(ValueError, df.height.hist, layout=(1, 1)) - self.assertRaises(ValueError, df.height.hist, layout=[1, 1]) + with tm.assertRaises(ValueError): + df.height.hist(layout=(1, 1)) + + with tm.assertRaises(ValueError): + df.height.hist(layout=[1, 1]) @slow def test_hist_layout_with_by(self): @@ -231,10 +234,13 @@ def test_hist_layout_with_by(self): 'category': random.randint(4, size=n)}) _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1)) plt.close('all') + _check_plot_works(df.height.hist, by=df.gender, layout=(1, 2)) plt.close('all') + _check_plot_works(df.weight.hist, by=df.category, layout=(1, 4)) plt.close('all') + _check_plot_works(df.weight.hist, by=df.category, layout=(4, 1)) plt.close('all') @@ -250,19 +256,20 @@ def test_hist_no_overlap(self): fig = gcf() axes = fig.get_axes() self.assertEqual(len(axes), 2) - close('all') @slow def test_plot_fails_with_dupe_color_and_style(self): x = Series(randn(2)) - self.assertRaises(ValueError, x.plot, style='k--', color='k') + with tm.assertRaises(ValueError): + x.plot(style='k--', color='k') def test_plot_fails_when_ax_differs_from_figure(self): - from pylab import figure + from pylab import figure, close fig1 = figure() fig2 = figure() ax1 = fig1.add_subplot(111) - self.assertRaises(AssertionError, self.ts.hist, ax=ax1, figure=fig2) + with tm.assertRaises(AssertionError): + self.ts.hist(ax=ax1, figure=fig2) @slow def test_kde(self): @@ -311,7 +318,8 @@ def test_invalid_plot_data(self): kinds = 'line', 'bar', 'barh', 'kde', 'density' for kind in kinds: - self.assertRaises(TypeError, s.plot, kind=kind) + with tm.assertRaises(TypeError): + s.plot(kind=kind) @slow def test_valid_object_plot(self): @@ -326,11 +334,13 @@ def test_partially_invalid_plot_data(self): kinds = 'line', 'bar', 'barh', 'kde', 'density' for kind in kinds: - self.assertRaises(TypeError, s.plot, kind=kind) + with tm.assertRaises(TypeError): + s.plot(kind=kind) def test_invalid_kind(self): s = Series([1, 2]) - self.assertRaises(ValueError, s.plot, kind='aasdf') + with tm.assertRaises(ValueError): + s.plot(kind='aasdf') @slow def test_dup_datetime_index_plot(self): @@ -342,7 +352,6 @@ def test_dup_datetime_index_plot(self): _check_plot_works(s.plot) - class TestDataFramePlots(unittest.TestCase): @classmethod @@ -406,23 +415,21 @@ def test_plot(self): def test_nonnumeric_exclude(self): import matplotlib.pyplot as plt - plt.close('all') - df = DataFrame({'A': ["x", "y", "z"], 'B': [1, 2, 3]}) ax = df.plot() - self.assert_(len(ax.get_lines()) == 1) # B was plotted + self.assertEqual(len(ax.get_lines()), 1) # B was plotted @slow - def test_label(self): - import matplotlib.pyplot as plt - plt.close('all') + def test_implicit_label(self): df = DataFrame(randn(10, 3), columns=['a', 'b', 'c']) ax = df.plot(x='a', y='b') - self.assert_(ax.xaxis.get_label().get_text() == 'a') + self.assertEqual(ax.xaxis.get_label().get_text(), 'a') - plt.close('all') + @slow + def test_explicit_label(self): + df = DataFrame(randn(10, 3), columns=['a', 'b', 'c']) ax = df.plot(x='a', y='b', label='LABEL') - self.assert_(ax.xaxis.get_label().get_text() == 'LABEL') + self.assertEqual(ax.xaxis.get_label().get_text(), 'LABEL') @slow def test_plot_xy(self): @@ -449,9 +456,9 @@ def test_plot_xy(self): plt.close('all') ax = df.plot(x=1, y=2, title='Test', figsize=(16, 8)) - self.assert_(ax.title.get_text() == 'Test') - self.assert_((np.round(ax.figure.get_size_inches()) - == np.array((16., 8.))).all()) + self.assertEqual(ax.title.get_text(), 'Test') + assert_array_equal(np.round(ax.figure.get_size_inches()), + np.array((16., 8.))) # columns.inferred_type == 'mixed' # TODO add MultiIndex test @@ -541,19 +548,25 @@ def test_subplots(self): @slow def test_plot_bar(self): + from matplotlib.pylab import close df = DataFrame(randn(6, 4), index=list(string.ascii_letters[:6]), columns=['one', 'two', 'three', 'four']) _check_plot_works(df.plot, kind='bar') + close('all') _check_plot_works(df.plot, kind='bar', legend=False) + close('all') _check_plot_works(df.plot, kind='bar', subplots=True) + close('all') _check_plot_works(df.plot, kind='bar', stacked=True) + close('all') df = DataFrame(randn(10, 15), index=list(string.ascii_letters[:10]), columns=lrange(15)) _check_plot_works(df.plot, kind='bar') + close('all') df = DataFrame({'a': [0, 1], 'b': [1, 0]}) _check_plot_works(df.plot, kind='bar') @@ -608,14 +621,11 @@ def test_boxplot(self): _check_plot_works(df.boxplot) _check_plot_works(df.boxplot, column=['one', 'two']) - _check_plot_works(df.boxplot, column=['one', 'two'], - by='indic') + _check_plot_works(df.boxplot, column=['one', 'two'], by='indic') _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(lambda x: plotting.boxplot(x), df['one']) - + _check_plot_works(plotting.boxplot, df['one']) _check_plot_works(df.boxplot, notch=1) _check_plot_works(df.boxplot, by='indic', notch=1) @@ -633,7 +643,7 @@ def test_kde(self): self.assert_(ax.get_legend() is not None) axes = df.plot(kind='kde', logy=True, subplots=True) for ax in axes: - self.assert_(ax.get_yscale() == 'log') + self.assertEqual(ax.get_yscale(), 'log') @slow def test_hist(self): @@ -694,11 +704,13 @@ def test_hist(self): plt.close('all') ax = ser.hist(log=True) # scale of y must be 'log' - self.assert_(ax.get_yscale() == 'log') + self.assertEqual(ax.get_yscale(), 'log') plt.close('all') + # propagate attr exception from matplotlib.Axes.hist - self.assertRaises(AttributeError, ser.hist, foo='bar') + with tm.assertRaises(AttributeError): + ser.hist(foo='bar') @slow def test_hist_layout(self): @@ -716,14 +728,16 @@ def test_hist_layout(self): for layout_test in layout_to_expected_size: ax = df.hist(layout=layout_test['layout']) - self.assert_(len(ax) == layout_test['expected_size'][0]) - self.assert_(len(ax[0]) == layout_test['expected_size'][1]) + self.assertEqual(len(ax), layout_test['expected_size'][0]) + self.assertEqual(len(ax[0]), layout_test['expected_size'][1]) # layout too small for all 4 plots - self.assertRaises(ValueError, df.hist, layout=(1, 1)) + with tm.assertRaises(ValueError): + df.hist(layout=(1, 1)) # invalid format for layout - self.assertRaises(ValueError, df.hist, layout=(1,)) + with tm.assertRaises(ValueError): + df.hist(layout=(1,)) @slow def test_scatter(self): @@ -734,6 +748,7 @@ def test_scatter(self): def scat(**kwds): return plt.scatter_matrix(df, **kwds) + _check_plot_works(scat) _check_plot_works(scat, marker='+') _check_plot_works(scat, vmin=0) @@ -752,8 +767,10 @@ def scat2(x, y, by=None, ax=None, figsize=None): def test_andrews_curves(self): from pandas import read_csv from pandas.tools.plotting import andrews_curves - path = os.path.join(curpath(), 'data/iris.csv') + + path = os.path.join(curpath(), 'data', 'iris.csv') df = read_csv(path) + _check_plot_works(andrews_curves, df, 'Name') @slow @@ -761,7 +778,7 @@ def test_parallel_coordinates(self): from pandas import read_csv from pandas.tools.plotting import parallel_coordinates from matplotlib import cm - path = os.path.join(curpath(), 'data/iris.csv') + path = os.path.join(curpath(), 'data', 'iris.csv') df = read_csv(path) _check_plot_works(parallel_coordinates, df, 'Name') _check_plot_works(parallel_coordinates, df, 'Name', @@ -774,8 +791,8 @@ def test_parallel_coordinates(self): colors=['dodgerblue', 'aquamarine', 'seagreen']) _check_plot_works(parallel_coordinates, df, 'Name', colormap=cm.jet) - df = read_csv( - path, header=None, skiprows=1, names=[1, 2, 4, 8, 'Name']) + df = read_csv(path, header=None, skiprows=1, names=[1, 2, 4, 8, + 'Name']) _check_plot_works(parallel_coordinates, df, 'Name', use_columns=True) _check_plot_works(parallel_coordinates, df, 'Name', xticks=[1, 5, 25, 125]) @@ -785,7 +802,8 @@ def test_radviz(self): from pandas import read_csv from pandas.tools.plotting import radviz from matplotlib import cm - path = os.path.join(curpath(), 'data/iris.csv') + + path = os.path.join(curpath(), 'data', 'iris.csv') df = read_csv(path) _check_plot_works(radviz, df, 'Name') _check_plot_works(radviz, df, 'Name', colormap=cm.jet) @@ -803,10 +821,11 @@ def test_legend_name(self): ax = multi.plot() leg_title = ax.legend_.get_title() - self.assert_(leg_title.get_text(), 'group,individual') + self.assertEqual(leg_title.get_text(), 'group,individual') def _check_plot_fails(self, f, *args, **kwargs): - self.assertRaises(Exception, f, *args, **kwargs) + with tm.assertRaises(Exception): + f(*args, **kwargs) @slow def test_style_by_column(self): @@ -832,7 +851,6 @@ def test_line_colors(self): custom_colors = 'rgcby' - plt.close('all') df = DataFrame(randn(5, 5)) ax = df.plot(color=custom_colors) @@ -841,7 +859,7 @@ def test_line_colors(self): for i, l in enumerate(lines): xp = custom_colors[i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) tmp = sys.stderr sys.stderr = StringIO() @@ -850,7 +868,7 @@ def test_line_colors(self): ax2 = df.plot(colors=custom_colors) lines2 = ax2.get_lines() for l1, l2 in zip(lines, lines2): - self.assert_(l1.get_color(), l2.get_color()) + self.assertEqual(l1.get_color(), l2.get_color()) finally: sys.stderr = tmp @@ -864,7 +882,7 @@ def test_line_colors(self): for i, l in enumerate(lines): xp = rgba_colors[i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) plt.close('all') @@ -876,7 +894,7 @@ def test_line_colors(self): for i, l in enumerate(lines): xp = rgba_colors[i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) # make color a list if plotting one column frame # handles cases like df.plot(color='DodgerBlue') @@ -895,7 +913,7 @@ def test_default_color_cycle(self): for i, l in enumerate(lines): xp = plt.rcParams['axes.color_cycle'][i] rs = l.get_color() - self.assert_(xp == rs) + self.assertEqual(xp, rs) def test_unordered_ts(self): df = DataFrame(np.array([3.0, 2.0, 1.0]), @@ -907,13 +925,14 @@ def test_unordered_ts(self): xticks = ax.lines[0].get_xdata() self.assert_(xticks[0] < xticks[1]) ydata = ax.lines[0].get_ydata() - self.assert_(np.all(ydata == np.array([1.0, 2.0, 3.0]))) + assert_array_equal(ydata, np.array([1.0, 2.0, 3.0])) def test_all_invalid_plot_data(self): kinds = 'line', 'bar', 'barh', 'kde', 'density' df = DataFrame(list('abcd')) for kind in kinds: - self.assertRaises(TypeError, df.plot, kind=kind) + with tm.assertRaises(TypeError): + df.plot(kind=kind) @slow def test_partially_invalid_plot_data(self): @@ -921,11 +940,13 @@ def test_partially_invalid_plot_data(self): df = DataFrame(randn(10, 2), dtype=object) df[np.random.rand(df.shape[0]) > 0.5] = 'a' for kind in kinds: - self.assertRaises(TypeError, df.plot, kind=kind) + with tm.assertRaises(TypeError): + df.plot(kind=kind) def test_invalid_kind(self): df = DataFrame(randn(10, 2)) - self.assertRaises(ValueError, df.plot, kind='aasdf') + with tm.assertRaises(ValueError): + df.plot(kind='aasdf') class TestDataFrameGroupByPlots(unittest.TestCase): @@ -939,7 +960,8 @@ def setUpClass(cls): def tearDown(self): import matplotlib.pyplot as plt - plt.close('all') + for fignum in plt.get_fignums(): + plt.close(fignum) @slow def test_boxplot(self): @@ -955,36 +977,29 @@ def test_boxplot(self): grouped = df.groupby(level=1) _check_plot_works(grouped.boxplot) _check_plot_works(grouped.boxplot, subplots=False) + grouped = df.unstack(level=1).groupby(level=0, axis=1) _check_plot_works(grouped.boxplot) _check_plot_works(grouped.boxplot, subplots=False) def test_series_plot_color_kwargs(self): - # #1890 - import matplotlib.pyplot as plt - - plt.close('all') + # GH1890 ax = Series(np.arange(12) + 1).plot(color='green') line = ax.get_lines()[0] - self.assert_(line.get_color() == 'green') + self.assertEqual(line.get_color(), 'green') def test_time_series_plot_color_kwargs(self): # #1890 - import matplotlib.pyplot as plt - - plt.close('all') ax = Series(np.arange(12) + 1, index=date_range( '1/1/2000', periods=12)).plot(color='green') line = ax.get_lines()[0] - self.assert_(line.get_color() == 'green') + self.assertEqual(line.get_color(), 'green') def test_time_series_plot_color_with_empty_kwargs(self): import matplotlib as mpl - import matplotlib.pyplot as plt def_colors = mpl.rcParams['axes.color_cycle'] - plt.close('all') for i in range(3): ax = Series(np.arange(12) + 1, index=date_range('1/1/2000', periods=12)).plot() @@ -998,12 +1013,12 @@ def test_grouped_hist(self): df = DataFrame(randn(500, 2), columns=['A', 'B']) df['C'] = np.random.randint(0, 4, 500) axes = plotting.grouped_hist(df.A, by=df.C) - self.assert_(len(axes.ravel()) == 4) + self.assertEqual(len(axes.ravel()), 4) plt.close('all') axes = df.hist(by=df.C) - self.assert_(axes.ndim == 2) - self.assert_(len(axes.ravel()) == 4) + self.assertEqual(axes.ndim, 2) + self.assertEqual(len(axes.ravel()), 4) for ax in axes.ravel(): self.assert_(len(ax.patches) > 0) @@ -1022,12 +1037,13 @@ def test_grouped_hist(self): axes = plotting.grouped_hist(df.A, by=df.C, log=True) # scale of y must be 'log' for ax in axes.ravel(): - self.assert_(ax.get_yscale() == 'log') + self.assertEqual(ax.get_yscale(), 'log') plt.close('all') + # propagate attr exception from matplotlib.Axes.hist - self.assertRaises(AttributeError, plotting.grouped_hist, df.A, - by=df.C, foo='bar') + with tm.assertRaises(AttributeError): + plotting.grouped_hist(df.A, by=df.C, foo='bar') @slow def test_grouped_hist_layout(self): @@ -1057,49 +1073,67 @@ def test_grouped_hist_layout(self): layout=(4, 2)).shape, (4, 2)) @slow - def test_axis_shared(self): + def test_axis_share_x(self): # GH4089 - import matplotlib.pyplot as plt - def tick_text(tl): - return [x.get_text() for x in tl] - n = 100 - df = DataFrame({'gender': np.array(['Male', 'Female'])[random.randint(2, size=n)], + df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n), 'height': random.normal(66, 4, size=n), 'weight': random.normal(161, 32, size=n)}) ax1, ax2 = df.hist(column='height', by=df.gender, sharex=True) - self.assert_(ax1._shared_x_axes.joined(ax1, ax2)) + + # share x + self.assertTrue(ax1._shared_x_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_x_axes.joined(ax1, ax2)) + + # don't share y self.assertFalse(ax1._shared_y_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_x_axes.joined(ax1, ax2)) self.assertFalse(ax2._shared_y_axes.joined(ax1, ax2)) - plt.close('all') + @slow + def test_axis_share_y(self): + n = 100 + df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n), + 'height': random.normal(66, 4, size=n), + 'weight': random.normal(161, 32, size=n)}) ax1, ax2 = df.hist(column='height', by=df.gender, sharey=True) + + # share y + self.assertTrue(ax1._shared_y_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_y_axes.joined(ax1, ax2)) + + # don't share x self.assertFalse(ax1._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax1._shared_y_axes.joined(ax1, ax2)) self.assertFalse(ax2._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_y_axes.joined(ax1, ax2)) - plt.close('all') + @slow + def test_axis_share_xy(self): + n = 100 + df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n), + 'height': random.normal(66, 4, size=n), + 'weight': random.normal(161, 32, size=n)}) ax1, ax2 = df.hist(column='height', by=df.gender, sharex=True, sharey=True) - self.assert_(ax1._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax1._shared_y_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_x_axes.joined(ax1, ax2)) - self.assert_(ax2._shared_y_axes.joined(ax1, ax2)) + + # share both x and y + self.assertTrue(ax1._shared_x_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_x_axes.joined(ax1, ax2)) + + self.assertTrue(ax1._shared_y_axes.joined(ax1, ax2)) + self.assertTrue(ax2._shared_y_axes.joined(ax1, ax2)) def test_option_mpl_style(self): set_option('display.mpl_style', 'default') set_option('display.mpl_style', None) set_option('display.mpl_style', False) - try: + + with tm.assertRaises(ValueError): set_option('display.mpl_style', 'default2') - except ValueError: - pass def test_invalid_colormap(self): df = DataFrame(randn(3, 2), columns=['A', 'B']) - self.assertRaises(ValueError, df.plot, colormap='invalid_colormap') + + with tm.assertRaises(ValueError): + df.plot(colormap='invalid_colormap') def assert_is_valid_plot_return_object(objs): @@ -1141,6 +1175,7 @@ def _check_plot_works(f, *args, **kwargs): with ensure_clean() as path: plt.savefig(path) + plt.close(fig) def curpath(): diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index 87cb65601bdd9..a22d2a65248a9 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -1,9 +1,8 @@ -import os from datetime import datetime, timedelta, date, time import unittest import nose -from pandas.compat import range, lrange, zip +from pandas.compat import lrange, zip import numpy as np from numpy.testing.decorators import slow @@ -52,48 +51,49 @@ def setUp(self): columns=['A', 'B', 'C']) for x in idx] + def tearDown(self): + import matplotlib.pyplot as plt + for fignum in plt.get_fignums(): + plt.close(fignum) + @slow def test_ts_plot_with_tz(self): # GH2877 - index = date_range('1/1/2011', periods=2, freq='H', tz='Europe/Brussels') + index = date_range('1/1/2011', periods=2, freq='H', + tz='Europe/Brussels') ts = Series([188.5, 328.25], index=index) - ts.plot() + _check_plot_works(ts.plot) @slow def test_frame_inferred(self): # inferred freq import matplotlib.pyplot as plt - plt.close('all') idx = date_range('1/1/1987', freq='MS', periods=100) idx = DatetimeIndex(idx.values, freq=None) + df = DataFrame(np.random.randn(len(idx), 3), index=idx) - df.plot() + _check_plot_works(df.plot) # axes freq idx = idx[0:40] + idx[45:99] df2 = DataFrame(np.random.randn(len(idx), 3), index=idx) - df2.plot() - plt.close('all') + _check_plot_works(df2.plot) # N > 1 idx = date_range('2008-1-1 00:15:00', freq='15T', periods=10) idx = DatetimeIndex(idx.values, freq=None) df = DataFrame(np.random.randn(len(idx), 3), index=idx) - df.plot() + _check_plot_works(df.plot) - @slow def test_nonnumeric_exclude(self): import matplotlib.pyplot as plt - plt.close('all') idx = date_range('1/1/1987', freq='A', periods=3) df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]}, idx) - plt.close('all') ax = df.plot() # it works self.assert_(len(ax.get_lines()) == 1) #B was plotted - - plt.close('all') + plt.close(plt.gcf()) self.assertRaises(TypeError, df['A'].plot) @@ -101,30 +101,23 @@ def test_nonnumeric_exclude(self): def test_tsplot(self): from pandas.tseries.plotting import tsplot import matplotlib.pyplot as plt - plt.close('all') ax = plt.gca() ts = tm.makeTimeSeries() - tsplot(ts, plt.Axes.plot) f = lambda *args, **kwds: tsplot(s, plt.Axes.plot, *args, **kwds) - plt.close('all') for s in self.period_ser: _check_plot_works(f, s.index.freq, ax=ax, series=s) - plt.close('all') + for s in self.datetime_ser: _check_plot_works(f, s.index.freq.rule_code, ax=ax, series=s) - plt.close('all') - plt.close('all') ax = ts.plot(style='k') - self.assert_((0., 0., 0.) == ax.get_lines()[0].get_color()) + self.assertEqual((0., 0., 0.), ax.get_lines()[0].get_color()) - @slow def test_both_style_and_color(self): import matplotlib.pyplot as plt - plt.close('all') ts = tm.makeTimeSeries() self.assertRaises(ValueError, ts.plot, style='b-', color='#000099') @@ -143,11 +136,11 @@ def test_high_freq(self): def test_get_datevalue(self): from pandas.tseries.converter import get_datevalue self.assert_(get_datevalue(None, 'D') is None) - self.assert_(get_datevalue(1987, 'A') == 1987) - self.assert_(get_datevalue(Period(1987, 'A'), 'M') == - Period('1987-12', 'M').ordinal) - self.assert_(get_datevalue('1/1/1987', 'D') == - Period('1987-1-1', 'D').ordinal) + self.assertEqual(get_datevalue(1987, 'A'), 1987) + self.assertEqual(get_datevalue(Period(1987, 'A'), 'M'), + Period('1987-12', 'M').ordinal) + self.assertEqual(get_datevalue('1/1/1987', 'D'), + Period('1987-1-1', 'D').ordinal) @slow def test_line_plot_period_series(self): @@ -179,7 +172,6 @@ def test_line_plot_inferred_freq(self): ser = ser[[0, 3, 5, 6]] _check_plot_works(ser.plot) - @slow def test_fake_inferred_business(self): import matplotlib.pyplot as plt fig = plt.gcf() @@ -189,7 +181,7 @@ def test_fake_inferred_business(self): ts = Series(lrange(len(rng)), rng) ts = ts[:3].append(ts[5:]) ax = ts.plot() - self.assert_(not hasattr(ax, 'freq')) + self.assertFalse(hasattr(ax, 'freq')) @slow def test_plot_offset_freq(self): @@ -227,8 +219,8 @@ def test_uhf(self): for loc, label in zip(tlocs, tlabels): xp = conv._from_ordinal(loc).strftime('%H:%M:%S.%f') rs = str(label.get_text()) - if len(rs) != 0: - self.assert_(xp == rs) + if len(rs): + self.assertEqual(xp, rs) @slow def test_irreg_hf(self): @@ -255,7 +247,6 @@ def test_irreg_hf(self): diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() self.assert_((np.fabs(diffs[1:] - sec) < 1e-8).all()) - @slow def test_irregular_datetime64_repr_bug(self): import matplotlib.pyplot as plt ser = tm.makeTimeSeries() @@ -265,56 +256,52 @@ def test_irregular_datetime64_repr_bug(self): plt.clf() ax = fig.add_subplot(211) ret = ser.plot() - assert(ret is not None) + self.assert_(ret is not None) for rs, xp in zip(ax.get_lines()[0].get_xdata(), ser.index): - assert(rs == xp) + self.assertEqual(rs, xp) - @slow def test_business_freq(self): import matplotlib.pyplot as plt - plt.close('all') bts = tm.makePeriodSeries() ax = bts.plot() - self.assert_(ax.get_lines()[0].get_xydata()[0, 0], - bts.index[0].ordinal) + self.assertEqual(ax.get_lines()[0].get_xydata()[0, 0], + bts.index[0].ordinal) idx = ax.get_lines()[0].get_xdata() - self.assert_(PeriodIndex(data=idx).freqstr == 'B') + self.assertEqual(PeriodIndex(data=idx).freqstr, 'B') @slow def test_business_freq_convert(self): - import matplotlib.pyplot as plt - plt.close('all') n = tm.N tm.N = 300 bts = tm.makeTimeSeries().asfreq('BM') tm.N = n ts = bts.to_period('M') ax = bts.plot() - self.assert_(ax.get_lines()[0].get_xydata()[0, 0], ts.index[0].ordinal) + self.assertEqual(ax.get_lines()[0].get_xydata()[0, 0], + ts.index[0].ordinal) idx = ax.get_lines()[0].get_xdata() - self.assert_(PeriodIndex(data=idx).freqstr == 'M') + self.assertEqual(PeriodIndex(data=idx).freqstr, 'M') - @slow def test_nonzero_base(self): - import matplotlib.pyplot as plt - plt.close('all') - #GH2571 + # GH2571 idx = (date_range('2012-12-20', periods=24, freq='H') + timedelta(minutes=30)) df = DataFrame(np.arange(24), index=idx) ax = df.plot() rs = ax.get_lines()[0].get_xdata() - self.assert_(not Index(rs).is_normalized) + self.assertFalse(Index(rs).is_normalized) - @slow def test_dataframe(self): bts = DataFrame({'a': tm.makeTimeSeries()}) ax = bts.plot() idx = ax.get_lines()[0].get_xdata() + assert_array_equal(bts.index.to_period(), idx) @slow def test_axis_limits(self): + import matplotlib.pyplot as plt + def _test(ax): xlim = ax.get_xlim() ax.set_xlim(xlim[0] - 5, xlim[1] + 10) @@ -340,9 +327,7 @@ def _test(ax): result = ax.get_xlim() self.assertEqual(int(result[0]), expected[0].ordinal) self.assertEqual(int(result[1]), expected[1].ordinal) - - import matplotlib.pyplot as plt - plt.close('all') + plt.close(ax.get_figure()) ser = tm.makeTimeSeries() ax = ser.plot() @@ -354,7 +339,9 @@ def _test(ax): df = DataFrame({'a': ser, 'b': ser + 1}) axes = df.plot(subplots=True) - [_test(ax) for ax in axes] + + for ax in axes: + _test(ax) def test_get_finder(self): import pandas.tseries.converter as conv @@ -368,6 +355,7 @@ def test_get_finder(self): @slow def test_finder_daily(self): + import matplotlib.pyplot as plt xp = Period('1999-1-1', freq='B').ordinal day_lst = [10, 40, 252, 400, 950, 2750, 10000] for n in day_lst: @@ -377,35 +365,35 @@ def test_finder_daily(self): xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) - (vmin, vmax) = ax.get_xlim() + vmin, vmax = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) + plt.close(ax.get_figure()) @slow def test_finder_quarterly(self): import matplotlib.pyplot as plt xp = Period('1988Q1').ordinal yrs = [3.5, 11] - plt.close('all') for n in yrs: rng = period_range('1987Q2', periods=int(n * 4), freq='Q') ser = Series(np.random.randn(len(rng)), rng) ax = ser.plot() xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] - self.assert_(rs == xp) + self.assertEqual(rs, xp) (vmin, vmax) = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) + plt.close(ax.get_figure()) @slow def test_finder_monthly(self): import matplotlib.pyplot as plt xp = Period('Jan 1988').ordinal yrs = [1.15, 2.5, 4, 11] - plt.close('all') for n in yrs: rng = period_range('1987Q2', periods=int(n * 12), freq='M') ser = Series(np.random.randn(len(rng)), rng) @@ -413,28 +401,24 @@ def test_finder_monthly(self): xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] self.assert_(rs == xp) - (vmin, vmax) = ax.get_xlim() + vmin, vmax = ax.get_xlim() ax.set_xlim(vmin + 0.9, vmax) rs = xaxis.get_majorticklocs()[0] self.assertEqual(xp, rs) - plt.close('all') + plt.close(ax.get_figure()) - @slow def test_finder_monthly_long(self): - import matplotlib.pyplot as plt - plt.close('all') rng = period_range('1988Q1', periods=24 * 12, freq='M') ser = Series(np.random.randn(len(rng)), rng) ax = ser.plot() xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] xp = Period('1989Q1', 'M').ordinal - self.assert_(rs == xp) + self.assertEqual(rs, xp) @slow def test_finder_annual(self): import matplotlib.pyplot as plt - plt.close('all') xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170] for i, nyears in enumerate([5, 10, 19, 49, 99, 199, 599, 1001]): rng = period_range('1987', periods=nyears, freq='A') @@ -442,13 +426,11 @@ def test_finder_annual(self): ax = ser.plot() xaxis = ax.get_xaxis() rs = xaxis.get_majorticklocs()[0] - self.assert_(rs == Period(xp[i], freq='A').ordinal) - plt.close('all') + self.assertEqual(rs, Period(xp[i], freq='A').ordinal) + plt.close(ax.get_figure()) @slow def test_finder_minutely(self): - import matplotlib.pyplot as plt - plt.close('all') nminutes = 50 * 24 * 60 rng = date_range('1/1/1999', freq='Min', periods=nminutes) ser = Series(np.random.randn(len(rng)), rng) @@ -458,10 +440,7 @@ def test_finder_minutely(self): xp = Period('1/1/1999', freq='Min').ordinal self.assertEqual(rs, xp) - @slow def test_finder_hourly(self): - import matplotlib.pyplot as plt - plt.close('all') nhours = 23 rng = date_range('1/1/1999', freq='H', periods=nhours) ser = Series(np.random.randn(len(rng)), rng) @@ -474,40 +453,40 @@ def test_finder_hourly(self): @slow def test_gaps(self): import matplotlib.pyplot as plt - plt.close('all') + ts = tm.makeTimeSeries() ts[5:25] = np.nan ax = ts.plot() lines = ax.get_lines() - self.assert_(len(lines) == 1) + self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assert_(mask[5:25, 1].all()) + plt.close(ax.get_figure()) # irregular - plt.close('all') ts = tm.makeTimeSeries() ts = ts[[0, 1, 2, 5, 7, 9, 12, 15, 20]] ts[2:5] = np.nan ax = ts.plot() lines = ax.get_lines() - self.assert_(len(lines) == 1) + self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) mask = data.mask self.assert_(mask[2:5, 1].all()) + plt.close(ax.get_figure()) # non-ts - plt.close('all') idx = [0, 1, 2, 5, 7, 9, 12, 15, 20] ser = Series(np.random.randn(len(idx)), idx) ser[2:5] = np.nan ax = ser.plot() lines = ax.get_lines() - self.assert_(len(lines) == 1) + self.assertEqual(len(lines), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) @@ -516,8 +495,6 @@ def test_gaps(self): @slow def test_gap_upsample(self): - import matplotlib.pyplot as plt - plt.close('all') low = tm.makeTimeSeries() low[5:25] = np.nan ax = low.plot() @@ -526,8 +503,8 @@ def test_gap_upsample(self): s = Series(np.random.randn(len(idxh)), idxh) s.plot(secondary_y=True) lines = ax.get_lines() - self.assert_(len(lines) == 1) - self.assert_(len(ax.right_ax.get_lines()) == 1) + self.assertEqual(len(lines), 1) + self.assertEqual(len(ax.right_ax.get_lines()), 1) l = lines[0] data = l.get_xydata() tm.assert_isinstance(data, np.ma.core.MaskedArray) @@ -537,7 +514,7 @@ def test_gap_upsample(self): @slow def test_secondary_y(self): import matplotlib.pyplot as plt - plt.close('all') + ser = Series(np.random.randn(10)) ser2 = Series(np.random.randn(10)) ax = ser.plot(secondary_y=True).right_ax @@ -546,23 +523,21 @@ def test_secondary_y(self): l = ax.get_lines()[0] xp = Series(l.get_ydata(), l.get_xdata()) assert_series_equal(ser, xp) - self.assert_(ax.get_yaxis().get_ticks_position() == 'right') - self.assert_(not axes[0].get_yaxis().get_visible()) + self.assertEqual(ax.get_yaxis().get_ticks_position(), 'right') + self.assertFalse(axes[0].get_yaxis().get_visible()) + plt.close(fig) ax2 = ser2.plot() - self.assert_(ax2.get_yaxis().get_ticks_position() == 'left') + self.assertEqual(ax2.get_yaxis().get_ticks_position(), 'default') + plt.close(ax2.get_figure()) - plt.close('all') ax = ser2.plot() ax2 = ser.plot(secondary_y=True).right_ax self.assert_(ax.get_yaxis().get_visible()) - plt.close('all') - @slow def test_secondary_y_ts(self): import matplotlib.pyplot as plt - plt.close('all') idx = date_range('1/1/2000', periods=10) ser = Series(np.random.randn(10), idx) ser2 = Series(np.random.randn(10), idx) @@ -572,13 +547,14 @@ def test_secondary_y_ts(self): l = ax.get_lines()[0] xp = Series(l.get_ydata(), l.get_xdata()).to_timestamp() assert_series_equal(ser, xp) - self.assert_(ax.get_yaxis().get_ticks_position() == 'right') - self.assert_(not axes[0].get_yaxis().get_visible()) + self.assertEqual(ax.get_yaxis().get_ticks_position(), 'right') + self.assertFalse(axes[0].get_yaxis().get_visible()) + plt.close(fig) ax2 = ser2.plot() - self.assert_(ax2.get_yaxis().get_ticks_position() == 'left') + self.assertEqual(ax2.get_yaxis().get_ticks_position(), 'default') + plt.close(ax2.get_figure()) - plt.close('all') ax = ser2.plot() ax2 = ser.plot(secondary_y=True) self.assert_(ax.get_yaxis().get_visible()) @@ -588,50 +564,41 @@ def test_secondary_kde(self): _skip_if_no_scipy() import matplotlib.pyplot as plt - plt.close('all') ser = Series(np.random.randn(10)) ax = ser.plot(secondary_y=True, kind='density').right_ax fig = ax.get_figure() axes = fig.get_axes() - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'right') @slow def test_secondary_bar(self): - import matplotlib.pyplot as plt - plt.close('all') ser = Series(np.random.randn(10)) ax = ser.plot(secondary_y=True, kind='bar') fig = ax.get_figure() axes = fig.get_axes() - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'right') @slow def test_secondary_frame(self): - import matplotlib.pyplot as plt - plt.close('all') df = DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c']) axes = df.plot(secondary_y=['a', 'c'], subplots=True) - self.assert_(axes[0].get_yaxis().get_ticks_position() == 'right') - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'default') - self.assert_(axes[2].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[0].get_yaxis().get_ticks_position(), 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'default') + self.assertEqual(axes[2].get_yaxis().get_ticks_position(), 'right') @slow def test_secondary_bar_frame(self): - import matplotlib.pyplot as plt - plt.close('all') df = DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c']) axes = df.plot(kind='bar', secondary_y=['a', 'c'], subplots=True) - self.assert_(axes[0].get_yaxis().get_ticks_position() == 'right') - self.assert_(axes[1].get_yaxis().get_ticks_position() == 'default') - self.assert_(axes[2].get_yaxis().get_ticks_position() == 'right') + self.assertEqual(axes[0].get_yaxis().get_ticks_position(), 'right') + self.assertEqual(axes[1].get_yaxis().get_ticks_position(), 'default') + self.assertEqual(axes[2].get_yaxis().get_ticks_position(), 'right') - @slow def test_mixed_freq_regular_first(self): import matplotlib.pyplot as plt - plt.close('all') s1 = tm.makeTimeSeries() s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]] - s1.plot() + ax = s1.plot() ax2 = s2.plot(style='g') lines = ax2.get_lines() idx1 = lines[0].get_xdata() @@ -640,30 +607,24 @@ def test_mixed_freq_regular_first(self): self.assert_(idx2.equals(s2.index.to_period('B'))) left, right = ax2.get_xlim() pidx = s1.index.to_period() - self.assert_(left == pidx[0].ordinal) - self.assert_(right == pidx[-1].ordinal) - plt.close('all') + self.assertEqual(left, pidx[0].ordinal) + self.assertEqual(right, pidx[-1].ordinal) @slow def test_mixed_freq_irregular_first(self): import matplotlib.pyplot as plt - plt.close('all') s1 = tm.makeTimeSeries() s2 = s1[[0, 5, 10, 11, 12, 13, 14, 15]] s2.plot(style='g') ax = s1.plot() - self.assert_(not hasattr(ax, 'freq')) + self.assertFalse(hasattr(ax, 'freq')) lines = ax.get_lines() x1 = lines[0].get_xdata() assert_array_equal(x1, s2.index.asobject.values) x2 = lines[1].get_xdata() assert_array_equal(x2, s1.index.asobject.values) - plt.close('all') - @slow def test_mixed_freq_hf_first(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=365, freq='D') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -671,27 +632,26 @@ def test_mixed_freq_hf_first(self): high.plot() ax = low.plot() for l in ax.get_lines(): - self.assert_(PeriodIndex(data=l.get_xdata()).freq == 'D') + self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, 'D') @slow def test_mixed_freq_alignment(self): - import matplotlib.pyplot as plt ts_ind = date_range('2012-01-01 13:00', '2012-01-02', freq='H') ts_data = np.random.randn(12) ts = Series(ts_data, index=ts_ind) ts2 = ts.asfreq('T').interpolate() - plt.close('all') ax = ts.plot() ts2.plot(style='r') - self.assert_(ax.lines[0].get_xdata()[0] == ax.lines[1].get_xdata()[0]) + self.assertEqual(ax.lines[0].get_xdata()[0], + ax.lines[1].get_xdata()[0]) @slow def test_mixed_freq_lf_first(self): import matplotlib.pyplot as plt - plt.close('all') + idxh = date_range('1/1/1999', periods=365, freq='D') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -699,11 +659,11 @@ def test_mixed_freq_lf_first(self): low.plot(legend=True) ax = high.plot(legend=True) for l in ax.get_lines(): - self.assert_(PeriodIndex(data=l.get_xdata()).freq == 'D') + self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, 'D') leg = ax.get_legend() - self.assert_(len(leg.texts) == 2) + self.assertEqual(len(leg.texts), 2) + plt.close(ax.get_figure()) - plt.close('all') idxh = date_range('1/1/1999', periods=240, freq='T') idxl = date_range('1/1/1999', periods=4, freq='H') high = Series(np.random.randn(len(idxh)), idxh) @@ -711,9 +671,8 @@ def test_mixed_freq_lf_first(self): low.plot() ax = high.plot() for l in ax.get_lines(): - self.assert_(PeriodIndex(data=l.get_xdata()).freq == 'T') + self.assertEqual(PeriodIndex(data=l.get_xdata()).freq, 'T') - @slow def test_mixed_freq_irreg_period(self): ts = tm.makeTimeSeries() irreg = ts[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]] @@ -724,8 +683,6 @@ def test_mixed_freq_irreg_period(self): @slow def test_to_weekly_resampling(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=52, freq='W') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -737,8 +694,6 @@ def test_to_weekly_resampling(self): @slow def test_from_weekly_resampling(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=52, freq='W') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -763,9 +718,6 @@ def test_irreg_dtypes(self): @slow def test_time(self): - import matplotlib.pyplot as plt - plt.close('all') - t = datetime(1, 1, 1, 3, 30, 0) deltas = np.random.randint(1, 20, 3).cumsum() ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas]) @@ -783,7 +735,7 @@ def test_time(self): xp = l.get_text() if len(xp) > 0: rs = time(h, m, s).strftime('%H:%M:%S') - self.assert_(xp, rs) + self.assertEqual(xp, rs) # change xlim ax.set_xlim('1:30', '5:00') @@ -797,13 +749,10 @@ def test_time(self): xp = l.get_text() if len(xp) > 0: rs = time(h, m, s).strftime('%H:%M:%S') - self.assert_(xp, rs) + self.assertEqual(xp, rs) @slow def test_time_musec(self): - import matplotlib.pyplot as plt - plt.close('all') - t = datetime(1, 1, 1, 3, 30, 0) deltas = np.random.randint(1, 20, 3).cumsum() ts = np.array([(t + timedelta(microseconds=int(x))).time() @@ -823,12 +772,10 @@ def test_time_musec(self): xp = l.get_text() if len(xp) > 0: rs = time(h, m, s).strftime('%H:%M:%S.%f') - self.assert_(xp, rs) + self.assertEqual(xp, rs) @slow def test_secondary_upsample(self): - import matplotlib.pyplot as plt - plt.close('all') idxh = date_range('1/1/1999', periods=365, freq='D') idxl = date_range('1/1/1999', periods=12, freq='M') high = Series(np.random.randn(len(idxh)), idxh) @@ -836,9 +783,9 @@ def test_secondary_upsample(self): low.plot() ax = high.plot(secondary_y=True) for l in ax.get_lines(): - self.assert_(l.get_xdata().freq == 'D') + self.assertEqual(l.get_xdata().freq, 'D') for l in ax.right_ax.get_lines(): - self.assert_(l.get_xdata().freq == 'D') + self.assertEqual(l.get_xdata().freq, 'D') @slow def test_secondary_legend(self): @@ -851,54 +798,54 @@ def test_secondary_legend(self): df = tm.makeTimeDataFrame() ax = df.plot(secondary_y=['A', 'B']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) - self.assert_(leg.get_texts()[0].get_text() == 'A (right)') - self.assert_(leg.get_texts()[1].get_text() == 'B (right)') - self.assert_(leg.get_texts()[2].get_text() == 'C') - self.assert_(leg.get_texts()[3].get_text() == 'D') + self.assertEqual(len(leg.get_lines()), 4) + self.assertEqual(leg.get_texts()[0].get_text(), 'A (right)') + self.assertEqual(leg.get_texts()[1].get_text(), 'B (right)') + self.assertEqual(leg.get_texts()[2].get_text(), 'C') + self.assertEqual(leg.get_texts()[3].get_text(), 'D') self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) plt.clf() ax = fig.add_subplot(211) ax = df.plot(secondary_y=['A', 'C'], mark_right=False) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) - self.assert_(leg.get_texts()[0].get_text() == 'A') - self.assert_(leg.get_texts()[1].get_text() == 'B') - self.assert_(leg.get_texts()[2].get_text() == 'C') - self.assert_(leg.get_texts()[3].get_text() == 'D') + self.assertEqual(len(leg.get_lines()), 4) + self.assertEqual(leg.get_texts()[0].get_text(), 'A') + self.assertEqual(leg.get_texts()[1].get_text(), 'B') + self.assertEqual(leg.get_texts()[2].get_text(), 'C') + self.assertEqual(leg.get_texts()[3].get_text(), 'D') plt.clf() ax = df.plot(kind='bar', secondary_y=['A']) leg = ax.get_legend() - self.assert_(leg.get_texts()[0].get_text() == 'A (right)') - self.assert_(leg.get_texts()[1].get_text() == 'B') + self.assertEqual(leg.get_texts()[0].get_text(), 'A (right)') + self.assertEqual(leg.get_texts()[1].get_text(), 'B') plt.clf() ax = df.plot(kind='bar', secondary_y=['A'], mark_right=False) leg = ax.get_legend() - self.assert_(leg.get_texts()[0].get_text() == 'A') - self.assert_(leg.get_texts()[1].get_text() == 'B') + self.assertEqual(leg.get_texts()[0].get_text(), 'A') + self.assertEqual(leg.get_texts()[1].get_text(), 'B') plt.clf() ax = fig.add_subplot(211) df = tm.makeTimeDataFrame() ax = df.plot(secondary_y=['C', 'D']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) + self.assertEqual(len(leg.get_lines()), 4) self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) # non-ts df = tm.makeDataFrame() @@ -906,29 +853,28 @@ def test_secondary_legend(self): ax = fig.add_subplot(211) ax = df.plot(secondary_y=['A', 'B']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) + self.assertEqual(len(leg.get_lines()), 4) self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) plt.clf() ax = fig.add_subplot(211) ax = df.plot(secondary_y=['C', 'D']) leg = ax.get_legend() - self.assert_(len(leg.get_lines()) == 4) + self.assertEqual(len(leg.get_lines()), 4) self.assert_(ax.right_ax.get_legend() is None) colors = set() for line in leg.get_lines(): colors.add(line.get_color()) # TODO: color cycle problems - self.assert_(len(colors) == 4) + self.assertEqual(len(colors), 4) - @slow def test_format_date_axis(self): rng = date_range('1/1/2012', periods=12, freq='M') df = DataFrame(np.random.randn(len(rng), 3), rng) @@ -936,14 +882,15 @@ def test_format_date_axis(self): xaxis = ax.get_xaxis() for l in xaxis.get_ticklabels(): if len(l.get_text()) > 0: - self.assert_(l.get_rotation() == 30) + self.assertEqual(l.get_rotation(), 30) @slow def test_ax_plot(self): + import matplotlib.pyplot as plt + x = DatetimeIndex(start='2012-01-02', periods=10, freq='D') y = lrange(len(x)) - import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) lines = ax.plot(x, y, label='Y') @@ -971,39 +918,45 @@ def test_mpl_nopandas(self): assert_array_equal(np.array([x.toordinal() for x in dates]), line2.get_xydata()[:, 0]) + def _check_plot_works(f, freq=None, series=None, *args, **kwargs): import matplotlib.pyplot as plt fig = plt.gcf() - plt.clf() - ax = fig.add_subplot(211) - orig_ax = kwargs.pop('ax', plt.gca()) - orig_axfreq = getattr(orig_ax, 'freq', None) - - ret = f(*args, **kwargs) - assert(ret is not None) # do something more intelligent - - ax = kwargs.pop('ax', plt.gca()) - if series is not None: - dfreq = series.index.freq - if isinstance(dfreq, DateOffset): - dfreq = dfreq.rule_code - if orig_axfreq is None: - assert(ax.freq == dfreq) - - if freq is not None and orig_axfreq is None: - assert(ax.freq == freq) - - ax = fig.add_subplot(212) + try: - kwargs['ax'] = ax + plt.clf() + ax = fig.add_subplot(211) + orig_ax = kwargs.pop('ax', plt.gca()) + orig_axfreq = getattr(orig_ax, 'freq', None) + ret = f(*args, **kwargs) - assert(ret is not None) # do something more intelligent - except Exception: - pass + assert ret is not None # do something more intelligent + + ax = kwargs.pop('ax', plt.gca()) + if series is not None: + dfreq = series.index.freq + if isinstance(dfreq, DateOffset): + dfreq = dfreq.rule_code + if orig_axfreq is None: + assert ax.freq == dfreq + + if freq is not None and orig_axfreq is None: + assert ax.freq == freq + + ax = fig.add_subplot(212) + try: + kwargs['ax'] = ax + ret = f(*args, **kwargs) + assert ret is not None # do something more intelligent + except Exception: + pass + + with ensure_clean() as path: + plt.savefig(path) + finally: + plt.close(fig) - with ensure_clean() as path: - plt.savefig(path) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
Corrects tests of the form `self.assert_(x, y)` to `self.assertEqual(x, y)`. Also changes tests of the form `self.assert_(x == y)` to `self.assertEqual(x, y)`.
https://api.github.com/repos/pandas-dev/pandas/pulls/4876
2013-09-18T19:25:31Z
2013-09-18T20:41:31Z
2013-09-18T20:41:31Z
2014-06-13T05:16:05Z
ENG/BUG: Changed NDFrame.shift to work with arbitrary axis/ndims.
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 4758670517df0..e16c8f110323c 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -9087,7 +9087,6 @@ def test_shift(self): assertRaisesRegexp(ValueError, 'does not match PeriodIndex freq', ps.shift, freq='D') - # shift other axis # GH 6371 df = DataFrame(np.random.rand(10,5)) @@ -9095,6 +9094,15 @@ def test_shift(self): result = df.shift(1,axis=1) assert_frame_equal(result,expected) + def test_shift_columns(self): + df = tm.makeTimeDataFrame() + + shifted = df.shift(1, axis='columns') + self.assert_(shifted['A'].isnull().all()) + + self.assert_(shifted.columns.equals(df.columns)) + tm.assert_series_equal(shifted['B'], df['A']) + def test_shift_bool(self): df = DataFrame({'high': [True, False], 'low': [False, False]})
closes #4867. First part of changing `Panel.shift` is to make `NDFrame.shift` work with any axis and number of dimensions. Until Panel uses it, the only case of this is `DataFrame.shift(axis='columns')` which is added as a test.
https://api.github.com/repos/pandas-dev/pandas/pulls/4874
2013-09-18T14:47:33Z
2014-03-09T22:44:51Z
null
2014-07-13T22:56:30Z
FIX: iso date encoding year overflow
diff --git a/pandas/src/datetime/np_datetime_strings.c b/pandas/src/datetime/np_datetime_strings.c index 77ad8533f2831..9c78e995f4fe3 100644 --- a/pandas/src/datetime/np_datetime_strings.c +++ b/pandas/src/datetime/np_datetime_strings.c @@ -1148,7 +1148,7 @@ make_iso_8601_datetime(pandas_datetimestruct *dts, char *outstr, int outlen, #ifdef _WIN32 tmplen = _snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year); #else - tmplen = snprintf(substr, sublen, "%04" NPY_INT64_FMT, (long int)dts->year); + tmplen = snprintf(substr, sublen, "%04" NPY_INT64_FMT, (long long)dts->year); #endif /* If it ran out of space or there isn't space for the NULL terminator */ if (tmplen < 0 || tmplen > sublen) {
Fixes #4869
https://api.github.com/repos/pandas-dev/pandas/pulls/4871
2013-09-18T07:01:18Z
2013-09-18T12:03:41Z
2013-09-18T12:03:41Z
2014-07-16T08:29:00Z
TST: windows dtype 32-bit fixes
diff --git a/pandas/io/tests/test_clipboard.py b/pandas/io/tests/test_clipboard.py index 12c696f7076a4..f5b5ba745d83c 100644 --- a/pandas/io/tests/test_clipboard.py +++ b/pandas/io/tests/test_clipboard.py @@ -43,7 +43,7 @@ def check_round_trip_frame(self, data_type): data = self.data[data_type] data.to_clipboard() result = read_clipboard() - tm.assert_frame_equal(data, result) + tm.assert_frame_equal(data, result, check_dtype=False) def test_round_trip_frame(self): for dt in self.data_types: diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index aa989e9d785f8..45289dac44254 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -492,7 +492,7 @@ def test_xcompat(self): def test_unsorted_index(self): df = DataFrame({'y': np.arange(100)}, - index=np.arange(99, -1, -1)) + index=np.arange(99, -1, -1), dtype=np.int64) ax = df.plot() l = ax.get_lines()[0] rs = l.get_xydata()
Fix test failures related to incoorrect dtype, detail #4866.
https://api.github.com/repos/pandas-dev/pandas/pulls/4870
2013-09-18T06:00:10Z
2013-09-18T12:03:08Z
2013-09-18T12:03:08Z
2014-07-16T08:28:59Z
BUG: Fix for DateOffset's reprs. (GH4638)
diff --git a/doc/source/release.rst b/doc/source/release.rst index ce08a1ca0a175..34720c49b163b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -480,6 +480,8 @@ Bug Fixes - Fixed wrong check for overlapping in ``DatetimeIndex.union`` (:issue:`4564`) - Fixed conflict between thousands separator and date parser in csv_parser (:issue:`4678`) - Fix appending when dtypes are not the same (error showing mixing float/np.datetime64) (:issue:`4993`) + - Fix repr for DateOffset. No longer show duplicate entries in kwds. + Removed unused offset fields. (:issue:`4638`) pandas 0.12.0 ------------- diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index bef54a0b37f21..92ed1e415d11a 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -117,19 +117,31 @@ def __repr__(self): className = getattr(self, '_outputName', type(self).__name__) exclude = set(['n', 'inc']) attrs = [] - for attr in self.__dict__: + for attr in sorted(self.__dict__): if ((attr == 'kwds' and len(self.kwds) == 0) or attr.startswith('_')): continue - if attr not in exclude: - attrs.append('='.join((attr, repr(getattr(self, attr))))) + elif attr == 'kwds': + kwds_new = {} + for key in self.kwds: + if not hasattr(self, key): + kwds_new[key] = self.kwds[key] + if len(kwds_new) > 0: + attrs.append('='.join((attr, repr(kwds_new)))) + else: + if attr not in exclude: + attrs.append('='.join((attr, repr(getattr(self, attr))))) if abs(self.n) != 1: plural = 's' else: plural = '' + + n_str = "" + if self.n != 1: + n_str = "%s * " % self.n - out = '<%s ' % self.n + className + plural + out = '<%s' % n_str + className + plural if attrs: out += ': ' + ', '.join(attrs) out += '>' @@ -247,7 +259,7 @@ def __init__(self, n=1, **kwds): def rule_code(self): return 'B' - def __repr__(self): + def __repr__(self): #TODO: Figure out if this should be merged into DateOffset if hasattr(self, 'name') and len(self.name): return self.name @@ -261,8 +273,12 @@ def __repr__(self): plural = 's' else: plural = '' + + n_str = "" + if self.n != 1: + n_str = "%s * " % self.n - out = '<%s ' % self.n + className + plural + out = '<%s' % n_str + className + plural if attrs: out += ': ' + ', '.join(attrs) out += '>' @@ -741,7 +757,6 @@ def __init__(self, n=1, **kwds): self.n = n self.startingMonth = kwds.get('startingMonth', 3) - self.offset = BMonthEnd(3) self.kwds = kwds def isAnchored(self): @@ -803,7 +818,6 @@ def __init__(self, n=1, **kwds): self.n = n self.startingMonth = kwds.get('startingMonth', 3) - self.offset = BMonthBegin(3) self.kwds = kwds def isAnchored(self): @@ -855,7 +869,6 @@ def __init__(self, n=1, **kwds): self.n = n self.startingMonth = kwds.get('startingMonth', 3) - self.offset = MonthEnd(3) self.kwds = kwds def isAnchored(self): @@ -894,7 +907,6 @@ def __init__(self, n=1, **kwds): self.n = n self.startingMonth = kwds.get('startingMonth', 3) - self.offset = MonthBegin(3) self.kwds = kwds def isAnchored(self): diff --git a/pandas/tseries/tests/test_offsets.py b/pandas/tseries/tests/test_offsets.py index c248e0a5e0de3..5b4e3251683bb 100644 --- a/pandas/tseries/tests/test_offsets.py +++ b/pandas/tseries/tests/test_offsets.py @@ -150,10 +150,10 @@ def test_different_normalize_equals(self): self.assertEqual(offset, offset2) def test_repr(self): - assert repr(self.offset) == '<1 BusinessDay>' - assert repr(self.offset2) == '<2 BusinessDays>' + self.assertEqual(repr(self.offset), '<BusinessDay>') + assert repr(self.offset2) == '<2 * BusinessDays>' - expected = '<1 BusinessDay: offset=datetime.timedelta(1)>' + expected = '<BusinessDay: offset=datetime.timedelta(1)>' assert repr(self.offset + timedelta(1)) == expected def test_with_offset(self): @@ -324,10 +324,10 @@ def test_different_normalize_equals(self): self.assertEqual(offset, offset2) def test_repr(self): - assert repr(self.offset) == '<1 CustomBusinessDay>' - assert repr(self.offset2) == '<2 CustomBusinessDays>' + assert repr(self.offset) == '<CustomBusinessDay>' + assert repr(self.offset2) == '<2 * CustomBusinessDays>' - expected = '<1 BusinessDay: offset=datetime.timedelta(1)>' + expected = '<BusinessDay: offset=datetime.timedelta(1)>' assert repr(self.offset + timedelta(1)) == expected def test_with_offset(self): @@ -526,6 +526,11 @@ def assertOnOffset(offset, date, expected): class TestWeek(unittest.TestCase): + def test_repr(self): + self.assertEqual(repr(Week(weekday=0)), "<Week: weekday=0>") + self.assertEqual(repr(Week(n=-1, weekday=0)), "<-1 * Week: weekday=0>") + self.assertEqual(repr(Week(n=-2, weekday=0)), "<-2 * Weeks: weekday=0>") + def test_corner(self): self.assertRaises(ValueError, Week, weekday=7) assertRaisesRegexp(ValueError, "Day must be", Week, weekday=-1) @@ -598,6 +603,9 @@ def test_constructor(self): assertRaisesRegexp(ValueError, "^Day", WeekOfMonth, n=1, week=0, weekday=-1) assertRaisesRegexp(ValueError, "^Day", WeekOfMonth, n=1, week=0, weekday=7) + def test_repr(self): + self.assertEqual(repr(WeekOfMonth(weekday=1,week=2)), "<WeekOfMonth: week=2, weekday=1>") + def test_offset(self): date1 = datetime(2011, 1, 4) # 1st Tuesday of Month date2 = datetime(2011, 1, 11) # 2nd Tuesday of Month @@ -895,6 +903,11 @@ def test_onOffset(self): class TestBQuarterBegin(unittest.TestCase): + + def test_repr(self): + self.assertEqual(repr(BQuarterBegin()),"<BusinessQuarterBegin: startingMonth=3>") + self.assertEqual(repr(BQuarterBegin(startingMonth=3)), "<BusinessQuarterBegin: startingMonth=3>") + self.assertEqual(repr(BQuarterBegin(startingMonth=1)), "<BusinessQuarterBegin: startingMonth=1>") def test_isAnchored(self): self.assert_(BQuarterBegin(startingMonth=1).isAnchored()) @@ -981,6 +994,11 @@ def test_offset(self): class TestBQuarterEnd(unittest.TestCase): + def test_repr(self): + self.assertEqual(repr(BQuarterEnd()),"<BusinessQuarterEnd: startingMonth=3>") + self.assertEqual(repr(BQuarterEnd(startingMonth=3)), "<BusinessQuarterEnd: startingMonth=3>") + self.assertEqual(repr(BQuarterEnd(startingMonth=1)), "<BusinessQuarterEnd: startingMonth=1>") + def test_isAnchored(self): self.assert_(BQuarterEnd(startingMonth=1).isAnchored()) self.assert_(BQuarterEnd().isAnchored()) @@ -1083,6 +1101,11 @@ def test_onOffset(self): class TestQuarterBegin(unittest.TestCase): + def test_repr(self): + self.assertEqual(repr(QuarterBegin()), "<QuarterBegin: startingMonth=3>") + self.assertEqual(repr(QuarterBegin(startingMonth=3)), "<QuarterBegin: startingMonth=3>") + self.assertEqual(repr(QuarterBegin(startingMonth=1)),"<QuarterBegin: startingMonth=1>") + def test_isAnchored(self): self.assert_(QuarterBegin(startingMonth=1).isAnchored()) self.assert_(QuarterBegin().isAnchored()) @@ -1152,7 +1175,11 @@ def test_offset(self): class TestQuarterEnd(unittest.TestCase): - + def test_repr(self): + self.assertEqual(repr(QuarterEnd()), "<QuarterEnd: startingMonth=3>") + self.assertEqual(repr(QuarterEnd(startingMonth=3)), "<QuarterEnd: startingMonth=3>") + self.assertEqual(repr(QuarterEnd(startingMonth=1)), "<QuarterEnd: startingMonth=1>") + def test_isAnchored(self): self.assert_(QuarterEnd(startingMonth=1).isAnchored()) self.assert_(QuarterEnd().isAnchored())
closes #4638 Before: ``` In [22]: WeekOfMonth(weekday=1,week=2) Out[22]: <1 WeekOfMonth: week=2, kwds={'week': 2, 'weekday': 1}, weekday=1> In [32]: QuarterEnd() Out[32]: <1 QuarterEnd: startingMonth=3, offset=<3 MonthEnds>> In [40]: BQuarterBegin() Out[40]: <1 BusinessQuarterBegin: startingMonth=3, offset=<3 BusinessMonthBegins>> In [41]: BQuarterBegin(startingMonth=3) Out[41]: <1 BusinessQuarterBegin: startingMonth=3, kwds={'startingMonth': 3}, offset=<3 BusinessMonthBegins>> ``` after: ``` In [2]: WeekOfMonth(weekday=1,week=2) Out[2]: <1 WeekOfMonth: week=2, weekday=1> In [3]: QuarterEnd() Out[3]: <1 QuarterEnd: startingMonth=3> In [4]: BQuarterBegin() Out[4]: <1 BusinessQuarterBegin: startingMonth=3> In [5]: BQuarterBegin(startingMonth=3) Out[5]: <1 BusinessQuarterBegin: startingMonth=3> ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4868
2013-09-18T04:10:11Z
2013-09-27T03:50:38Z
2013-09-27T03:50:38Z
2014-07-16T08:28:56Z
Panel tshift 4853
diff --git a/doc/source/release.rst b/doc/source/release.rst index 793d52223b6f5..d747505593c94 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -428,6 +428,7 @@ Bug Fixes single column and passing a list for ``ascending``, the argument for ``ascending`` was being interpreted as ``True`` (:issue:`4839`, :issue:`4846`) + - Fixed ``Panel.tshift`` not working. Added `freq` support to ``Panel.shift`` (:issue:`4853`) pandas 0.12.0 ------------- diff --git a/pandas/core/datetools.py b/pandas/core/datetools.py index 228dc7574f8f3..91a29259d8f2f 100644 --- a/pandas/core/datetools.py +++ b/pandas/core/datetools.py @@ -35,3 +35,23 @@ isBusinessDay = BDay().onOffset isMonthEnd = MonthEnd().onOffset isBMonthEnd = BMonthEnd().onOffset + +def _resolve_offset(freq, kwds): + if 'timeRule' in kwds or 'offset' in kwds: + offset = kwds.get('offset', None) + offset = kwds.get('timeRule', offset) + if isinstance(offset, compat.string_types): + offset = getOffset(offset) + warn = True + else: + offset = freq + warn = False + + if warn: + import warnings + warnings.warn("'timeRule' and 'offset' parameters are deprecated," + " please use 'freq' instead", + FutureWarning) + + return offset + diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 78ef806a45dcb..70fcc2c9d9c0a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3497,55 +3497,6 @@ def diff(self, periods=1): new_data = self._data.diff(periods) return self._constructor(new_data) - def shift(self, periods=1, freq=None, **kwds): - """ - Shift the index of the DataFrame by desired number of periods with an - optional time freq - - Parameters - ---------- - periods : int - Number of periods to move, can be positive or negative - freq : DateOffset, timedelta, or time rule string, optional - Increment to use from datetools module or time rule (e.g. 'EOM') - - Notes - ----- - If freq is specified then the index values are shifted but the data - if not realigned - - Returns - ------- - shifted : DataFrame - """ - from pandas.core.series import _resolve_offset - - if periods == 0: - return self - - offset = _resolve_offset(freq, kwds) - - if isinstance(offset, compat.string_types): - offset = datetools.to_offset(offset) - - if offset is None: - indexer = com._shift_indexer(len(self), periods) - new_data = self._data.shift(indexer, periods) - elif isinstance(self.index, PeriodIndex): - orig_offset = datetools.to_offset(self.index.freq) - if offset == orig_offset: - new_data = self._data.copy() - new_data.axes[1] = self.index.shift(periods) - else: - msg = ('Given freq %s does not match PeriodIndex freq %s' % - (offset.rule_code, orig_offset.rule_code)) - raise ValueError(msg) - else: - new_data = self._data.copy() - new_data.axes[1] = self.index.shift(periods, offset) - - return self._constructor(new_data) - #---------------------------------------------------------------------- # Function application diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2f6bc13983f93..53d3687854cac 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11,8 +11,10 @@ import pandas.core.indexing as indexing from pandas.core.indexing import _maybe_convert_indices from pandas.tseries.index import DatetimeIndex +from pandas.tseries.period import PeriodIndex from pandas.core.internals import BlockManager import pandas.core.common as com +import pandas.core.datetools as datetools from pandas import compat, _np_version_under1p7 from pandas.compat import map, zip, lrange from pandas.core.common import (isnull, notnull, is_list_like, @@ -2667,7 +2669,40 @@ def cummin(self, axis=None, skipna=True): result = np.minimum.accumulate(y, axis) return self._wrap_array(result, self.axes, copy=False) - def tshift(self, periods=1, freq=None, **kwds): + def shift(self, periods=1, freq=None, axis=0, **kwds): + """ + Shift the index of the DataFrame by desired number of periods with an + optional time freq + + Parameters + ---------- + periods : int + Number of periods to move, can be positive or negative + freq : DateOffset, timedelta, or time rule string, optional + Increment to use from datetools module or time rule (e.g. 'EOM') + + Notes + ----- + If freq is specified then the index values are shifted but the data + if not realigned + + Returns + ------- + shifted : DataFrame + """ + if periods == 0: + return self + + if freq is None and not len(kwds): + block_axis = self._get_block_manager_axis(axis) + indexer = com._shift_indexer(len(self), periods) + new_data = self._data.shift(indexer, periods, axis=block_axis) + else: + return self.tshift(periods, freq, **kwds) + + return self._constructor(new_data) + + def tshift(self, periods=1, freq=None, axis=0, **kwds): """ Shift the time index, using the index's frequency if available @@ -2677,6 +2712,8 @@ def tshift(self, periods=1, freq=None, **kwds): Number of periods to move, can be positive or negative freq : DateOffset, timedelta, or time rule string, default None Increment to use from datetools module or time rule (e.g. 'EOM') + axis : int or basestring + Corresponds to the axis that contains the Index Notes ----- @@ -2686,19 +2723,45 @@ def tshift(self, periods=1, freq=None, **kwds): Returns ------- - shifted : Series + shifted : NDFrame """ + from pandas.core.datetools import _resolve_offset + + index = self._get_axis(axis) if freq is None: - freq = getattr(self.index, 'freq', None) + freq = getattr(index, 'freq', None) if freq is None: - freq = getattr(self.index, 'inferred_freq', None) + freq = getattr(index, 'inferred_freq', None) if freq is None: msg = 'Freq was not given and was not set in the index' raise ValueError(msg) - return self.shift(periods, freq, **kwds) + + if periods == 0: + return self + + offset = _resolve_offset(freq, kwds) + + if isinstance(offset, compat.string_types): + offset = datetools.to_offset(offset) + + block_axis = self._get_block_manager_axis(axis) + if isinstance(index, PeriodIndex): + orig_offset = datetools.to_offset(index.freq) + if offset == orig_offset: + new_data = self._data.copy() + new_data.axes[block_axis] = index.shift(periods) + else: + msg = ('Given freq %s does not match PeriodIndex freq %s' % + (offset.rule_code, orig_offset.rule_code)) + raise ValueError(msg) + else: + new_data = self._data.copy() + new_data.axes[block_axis] = index.shift(periods, offset) + + return self._constructor(new_data) def truncate(self, before=None, after=None, copy=True): """Function truncate a sorted DataFrame / Series before and/or after diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 11ce27b078b18..4b9fdb0422526 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -758,17 +758,27 @@ def diff(self, n): new_values = com.diff(self.values, n, axis=1) return [make_block(new_values, self.items, self.ref_items, ndim=self.ndim, fastpath=True)] - def shift(self, indexer, periods): + def shift(self, indexer, periods, axis=0): """ shift the block by periods, possibly upcast """ - new_values = self.values.take(indexer, axis=1) + new_values = self.values.take(indexer, axis=axis) # convert integer to float if necessary. need to do a lot more than # that, handle boolean etc also new_values, fill_value = com._maybe_upcast(new_values) - if periods > 0: - new_values[:, :periods] = fill_value + + # 1-d + if self.ndim == 1: + if periods > 0: + new_values[:periods] = fill_value + else: + new_values[periods:] = fill_value + + # 2-d else: - new_values[:, periods:] = fill_value + if periods > 0: + new_values[:, :periods] = fill_value + else: + new_values[:, periods:] = fill_value return [make_block(new_values, self.items, self.ref_items, ndim=self.ndim, fastpath=True)] def eval(self, func, other, raise_on_error=True, try_cast=False): @@ -1547,7 +1557,7 @@ def fillna(self, value, inplace=False, downcast=None): values = self.values if inplace else self.values.copy() return [ self.make_block(values.get_values(value), fill_value=value) ] - def shift(self, indexer, periods): + def shift(self, indexer, periods, axis=0): """ shift the block by periods """ new_values = self.values.to_dense().take(indexer) diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 6f02b49326e4d..45101b1e2afd5 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -1017,7 +1017,7 @@ def count(self, axis='major'): return self._wrap_result(result, axis) - def shift(self, lags, axis='major'): + def shift(self, lags, freq=None, axis='major'): """ Shift major or minor axis by specified number of leads/lags. Drops periods right now compared with DataFrame.shift @@ -1036,6 +1036,9 @@ def shift(self, lags, axis='major'): major_axis = self.major_axis minor_axis = self.minor_axis + if freq: + return self.tshift(lags, freq, axis=axis) + if lags > 0: vslicer = slice(None, -lags) islicer = slice(lags, None) @@ -1058,6 +1061,9 @@ def shift(self, lags, axis='major'): return self._constructor(values, items=items, major_axis=major_axis, minor_axis=minor_axis) + def tshift(self, periods=1, freq=None, axis='major', **kwds): + return super(Panel, self).tshift(periods, freq, axis, **kwds) + def truncate(self, before=None, after=None, axis='major'): """Function truncates a sorted Panel before and/or after some particular values on the requested axis diff --git a/pandas/core/series.py b/pandas/core/series.py index beb398dfe6fd0..9f7ab0cb0346b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -59,8 +59,6 @@ _np_version_under1p6 = LooseVersion(_np_version) < '1.6' _np_version_under1p7 = LooseVersion(_np_version) < '1.7' -_SHOW_WARNINGS = True - class _TimeOp(object): """ Wrapper around Series datetime/time/timedelta arithmetic operations. @@ -2917,62 +2915,6 @@ def last_valid_index(self): #---------------------------------------------------------------------- # Time series-oriented methods - def shift(self, periods=1, freq=None, copy=True, **kwds): - """ - Shift the index of the Series by desired number of periods with an - optional time offset - - Parameters - ---------- - periods : int - Number of periods to move, can be positive or negative - freq : DateOffset, timedelta, or offset alias string, optional - Increment to use from datetools module or time rule (e.g. 'EOM') - - Returns - ------- - shifted : Series - """ - if periods == 0: - return self.copy() - - offset = _resolve_offset(freq, kwds) - - if isinstance(offset, compat.string_types): - offset = datetools.to_offset(offset) - - def _get_values(): - values = self.values - if copy: - values = values.copy() - return values - - if offset is None: - dtype, fill_value = _maybe_promote(self.dtype) - new_values = pa.empty(len(self), dtype=dtype) - - if periods > 0: - new_values[periods:] = self.values[:-periods] - new_values[:periods] = fill_value - elif periods < 0: - new_values[:periods] = self.values[-periods:] - new_values[periods:] = fill_value - - return self._constructor(new_values, index=self.index, name=self.name) - elif isinstance(self.index, PeriodIndex): - orig_offset = datetools.to_offset(self.index.freq) - if orig_offset == offset: - return self._constructor( - _get_values(), self.index.shift(periods), - name=self.name) - msg = ('Given freq %s does not match PeriodIndex freq %s' % - (offset.rule_code, orig_offset.rule_code)) - raise ValueError(msg) - else: - return self._constructor(_get_values(), - index=self.index.shift(periods, offset), - name=self.name) - def asof(self, where): """ Return last good (non-NaN) value in TimeSeries if value is NaN for @@ -3317,26 +3259,6 @@ def _try_cast(arr, take_fast_path): return subarr -def _resolve_offset(freq, kwds): - if 'timeRule' in kwds or 'offset' in kwds: - offset = kwds.get('offset', None) - offset = kwds.get('timeRule', offset) - if isinstance(offset, compat.string_types): - offset = datetools.getOffset(offset) - warn = True - else: - offset = freq - warn = False - - if warn and _SHOW_WARNINGS: # pragma: no cover - import warnings - warnings.warn("'timeRule' and 'offset' parameters are deprecated," - " please use 'freq' instead", - FutureWarning) - - return offset - - # backwards compatiblity TimeSeries = Series diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py index 537b88db3c1f0..5cb29d717235d 100644 --- a/pandas/sparse/series.py +++ b/pandas/sparse/series.py @@ -605,7 +605,7 @@ def shift(self, periods, freq=None, **kwds): """ Analogous to Series.shift """ - from pandas.core.series import _resolve_offset + from pandas.core.datetools import _resolve_offset offset = _resolve_offset(freq, kwds) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index fc86a78ea684b..a498cca528043 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1323,6 +1323,44 @@ def test_shift(self): for i, f in compat.iteritems(self.panel))) assert_panel_equal(result, expected) + def test_tshift(self): + # PeriodIndex + ps = tm.makePeriodPanel() + shifted = ps.tshift(1) + unshifted = shifted.tshift(-1) + + assert_panel_equal(unshifted, ps) + + shifted2 = ps.tshift(freq='B') + assert_panel_equal(shifted, shifted2) + + shifted3 = ps.tshift(freq=bday) + assert_panel_equal(shifted, shifted3) + + assertRaisesRegexp(ValueError, 'does not match', ps.tshift, freq='M') + + # DatetimeIndex + panel = _panel + shifted = panel.tshift(1) + unshifted = shifted.tshift(-1) + + assert_panel_equal(panel, unshifted) + + shifted2 = panel.tshift(freq=panel.major_axis.freq) + assert_panel_equal(shifted, shifted2) + + inferred_ts = Panel(panel.values, + items=panel.items, + major_axis=Index(np.asarray(panel.major_axis)), + minor_axis=panel.minor_axis) + shifted = inferred_ts.tshift(1) + unshifted = shifted.tshift(-1) + assert_panel_equal(shifted, panel.tshift(1)) + assert_panel_equal(unshifted, inferred_ts) + + no_freq = panel.ix[:, [0, 5, 7], :] + self.assertRaises(ValueError, no_freq.tshift) + def test_multiindex_get(self): ind = MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1), ('b', 2)], names=['first', 'second']) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 686df18999850..b142adbd5b949 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -3550,13 +3550,11 @@ def test_shift(self): self.assertRaises(ValueError, ps.shift, freq='D') # legacy support - smod._SHOW_WARNINGS = False shifted4 = ps.shift(1, timeRule='B') assert_series_equal(shifted2, shifted4) shifted5 = ps.shift(1, offset=datetools.bday) assert_series_equal(shifted5, shifted4) - smod._SHOW_WARNINGS = True def test_tshift(self): # PeriodIndex diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 0718dc8926011..0481a522dabe8 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -460,12 +460,12 @@ def makeTimeDataFrame(nper=None): return DataFrame(data) -def getPeriodData(): - return dict((c, makePeriodSeries()) for c in getCols(K)) +def getPeriodData(nper=None): + return dict((c, makePeriodSeries(nper)) for c in getCols(K)) -def makePeriodFrame(): - data = getPeriodData() +def makePeriodFrame(nper=None): + data = getPeriodData(nper) return DataFrame(data) @@ -474,6 +474,10 @@ def makePanel(nper=None): data = dict((c, makeTimeDataFrame(nper)) for c in cols) return Panel.fromDict(data) +def makePeriodPanel(nper=None): + cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] + data = dict((c, makePeriodFrame(nper)) for c in cols) + return Panel.fromDict(data) def makePanel4D(nper=None): return Panel4D(dict(l1=makePanel(nper), l2=makePanel(nper),
closes https://github.com/pydata/pandas/issues/4853 I think I'm doing this right. I moved the `tshift` into generic and had `shift` offload to `tshift` if `freq` is found.
https://api.github.com/repos/pandas-dev/pandas/pulls/4864
2013-09-17T20:43:41Z
2013-09-18T13:40:29Z
2013-09-18T13:40:29Z
2014-07-16T08:28:52Z
BUG: Constrain date parsing from strings a little bit more #4601
diff --git a/doc/source/release.rst b/doc/source/release.rst index ffb792ca98da5..b71285758d53b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -433,6 +433,7 @@ Bug Fixes - Fix an issue in TextFileReader w/ Python engine (i.e. PythonParser) with thousands != "," (:issue:`4596`) - Bug in getitem with a duplicate index when using where (:issue:`4879`) + - Fix Type inference code coerces float column into datetime (:issue:`4601`) pandas 0.12.0 diff --git a/pandas/tests/test_tslib.py b/pandas/tests/test_tslib.py new file mode 100644 index 0000000000000..b9a7356412a10 --- /dev/null +++ b/pandas/tests/test_tslib.py @@ -0,0 +1,123 @@ +import unittest + +import numpy as np + +from pandas import tslib +from datetime import datetime + +class TestDatetimeParsingWrappers(unittest.TestCase): + def test_verify_datetime_bounds(self): + for year in (1, 1000, 1677, 2262, 5000): + dt = datetime(year, 1, 1) + self.assertRaises( + ValueError, + tslib.verify_datetime_bounds, + dt + ) + + for year in (1678, 2000, 2261): + tslib.verify_datetime_bounds(datetime(year, 1, 1)) + + def test_does_not_convert_mixed_integer(self): + bad_date_strings = ( + '-50000', + '999', + '123.1234', + 'm', + 'T' + ) + + for bad_date_string in bad_date_strings: + self.assertFalse( + tslib._does_string_look_like_datetime(bad_date_string) + ) + + good_date_strings = ( + '2012-01-01', + '01/01/2012', + 'Mon Sep 16, 2013', + '01012012', + '0101', + '1-1', + ) + + for good_date_string in good_date_strings: + self.assertTrue( + tslib._does_string_look_like_datetime(good_date_string) + ) + +class TestArrayToDatetime(unittest.TestCase): + def test_parsing_valid_dates(self): + arr = np.array(['01-01-2013', '01-02-2013'], dtype=object) + self.assert_( + np.array_equal( + tslib.array_to_datetime(arr), + np.array( + [ + '2013-01-01T00:00:00.000000000-0000', + '2013-01-02T00:00:00.000000000-0000' + ], + dtype='M8[ns]' + ) + ) + ) + + arr = np.array(['Mon Sep 16 2013', 'Tue Sep 17 2013'], dtype=object) + self.assert_( + np.array_equal( + tslib.array_to_datetime(arr), + np.array( + [ + '2013-09-16T00:00:00.000000000-0000', + '2013-09-17T00:00:00.000000000-0000' + ], + dtype='M8[ns]' + ) + ) + ) + + def test_number_looking_strings_not_into_datetime(self): + # #4601 + # These strings don't look like datetimes so they shouldn't be + # attempted to be converted + arr = np.array(['-352.737091', '183.575577'], dtype=object) + self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + + arr = np.array(['1', '2', '3', '4', '5'], dtype=object) + self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + + def test_dates_outside_of_datetime64_ns_bounds(self): + # These datetimes are outside of the bounds of the + # datetime64[ns] bounds, so they cannot be converted to + # datetimes + arr = np.array(['1/1/1676', '1/2/1676'], dtype=object) + self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + + arr = np.array(['1/1/2263', '1/2/2263'], dtype=object) + self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + + def test_coerce_of_invalid_datetimes(self): + arr = np.array(['01-01-2013', 'not_a_date', '1'], dtype=object) + + # Without coercing, the presence of any invalid dates prevents + # any values from being converted + self.assert_(np.array_equal(tslib.array_to_datetime(arr), arr)) + + # With coercing, the invalid dates becomes iNaT + self.assert_( + np.array_equal( + tslib.array_to_datetime(arr, coerce=True), + np.array( + [ + '2013-01-01T00:00:00.000000000-0000', + tslib.iNaT, + tslib.iNaT + ], + dtype='M8[ns]' + ) + ) + ) + +if __name__ == '__main__': + nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], + exit=False) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index fd97512b0528b..075102dd63100 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -317,7 +317,6 @@ class Timestamp(_Timestamp): _nat_strings = set(['NaT','nat','NAT','nan','NaN','NAN']) -_not_datelike_strings = set(['a','A','m','M','p','P','t','T']) class NaTType(_NaT): """(N)ot-(A)-(T)ime, the time equivalent of NaN""" @@ -841,6 +840,43 @@ def datetime_to_datetime64(ndarray[object] values): return result, inferred_tz +_not_datelike_strings = set(['a','A','m','M','p','P','t','T']) + +def verify_datetime_bounds(dt): + """Verify datetime.datetime is within the datetime64[ns] bounds.""" + if dt.year <= 1677 or dt.year >= 2262: + raise ValueError( + 'Given datetime not within valid datetime64[ns] bounds' + ) + return dt + +def _does_string_look_like_datetime(date_string): + if date_string.startswith('0'): + # Strings starting with 0 are more consistent with a + # date-like string than a number + return True + + try: + if float(date_string) < 1000: + return False + except ValueError: + pass + + if date_string in _not_datelike_strings: + return False + + return True + +def parse_datetime_string(date_string, verify_bounds=True, **kwargs): + if not _does_string_look_like_datetime(date_string): + raise ValueError('Given date string not likely a datetime.') + + dt = parse_date(date_string, **kwargs) + + if verify_bounds: + verify_datetime_bounds(dt) + + return dt def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, format=None, utc=None, coerce=False, unit=None): @@ -908,24 +944,15 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, &dts) _check_dts_bounds(iresult[i], &dts) except ValueError: - - # for some reason, dateutil parses some single letter len-1 strings into today's date - if len(val) == 1 and val in _not_datelike_strings: - if coerce: - iresult[i] = iNaT - continue - elif raise_: - raise try: - result[i] = parse_date(val, dayfirst=dayfirst) + result[i] = parse_datetime_string( + val, dayfirst=dayfirst + ) except Exception: if coerce: iresult[i] = iNaT continue raise TypeError - pandas_datetime_to_datetimestruct(iresult[i], PANDAS_FR_ns, - &dts) - _check_dts_bounds(iresult[i], &dts) except: if coerce: iresult[i] = iNaT @@ -946,7 +973,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, oresult[i] = 'NaT' continue try: - oresult[i] = parse_date(val, dayfirst=dayfirst) + oresult[i] = parse_datetime_string(val, dayfirst=dayfirst) except Exception: if raise_: raise
closes #4601 Currently dateutil will parse almost any string into a datetime. This change adds a filter in front of dateutil that will prevent it from parsing certain strings that don't look like datetimes: 1) Strings that parse to float values that are less than 1000 2) Certain special one character strings (this was already in there, this just moves that code) Additionally, this filters out datetimes that are out of range for the datetime64[ns] type. Currently any out-of-range datetimes will just overflow and be mapped to some random time within the bounds of datetime64[ns].
https://api.github.com/repos/pandas-dev/pandas/pulls/4863
2013-09-17T19:23:39Z
2013-09-20T22:34:04Z
2013-09-20T22:34:04Z
2014-06-22T11:10:12Z
TST: dtypes tests fix for 32-bit
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 6f6b3bf71c759..d216cebc1abf3 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -2743,7 +2743,7 @@ def test_constructor_generator(self): gen = ([ i, 'a'] for i in range(10)) result = DataFrame(gen) expected = DataFrame({ 0 : range(10), 1 : 'a' }) - assert_frame_equal(result, expected) + assert_frame_equal(result, expected, check_dtype=False) def test_constructor_list_of_dicts(self): data = [OrderedDict([['a', 1.5], ['b', 3], ['c', 4], ['d', 6]]), diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 0c862576b09a1..3453e69ed72b6 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1362,7 +1362,7 @@ def f(): ### frame ### - df_orig = DataFrame(np.arange(6).reshape(3,2),columns=['A','B']) + df_orig = DataFrame(np.arange(6).reshape(3,2),columns=['A','B'],dtype='int64') # iloc/iat raise df = df_orig.copy() diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c52fcad3d5111..686df18999850 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -355,8 +355,8 @@ def test_constructor_series(self): def test_constructor_iterator(self): - expected = Series(list(range(10))) - result = Series(range(10)) + expected = Series(list(range(10)),dtype='int64') + result = Series(range(10),dtype='int64') assert_series_equal(result, expected) def test_constructor_generator(self):
https://api.github.com/repos/pandas-dev/pandas/pulls/4860
2013-09-17T12:53:19Z
2013-09-17T13:06:25Z
2013-09-17T13:06:25Z
2014-07-16T08:28:50Z
TST: reproducing tests for subtle PyTables bug (disabled for now)
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 322b626acc0ad..ee438cb2cd45a 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2695,6 +2695,46 @@ def test_select_dtypes(self): expected = df.reindex(index=list(df.index)[0:10],columns=['A']) tm.assert_frame_equal(expected, result) + with ensure_clean(self.path) as store: + + # floats w/o NaN + df = DataFrame(dict(cols = range(11), values = range(11)),dtype='float64') + df['cols'] = (df['cols']+10).apply(str) + + store.append('df1',df,data_columns=True) + result = store.select( + 'df1', where='values>2.0') + expected = df[df['values']>2.0] + tm.assert_frame_equal(expected, result) + + # floats with NaN + df.iloc[0] = np.nan + expected = df[df['values']>2.0] + + store.append('df2',df,data_columns=True,index=False) + result = store.select( + 'df2', where='values>2.0') + tm.assert_frame_equal(expected, result) + + # https://github.com/PyTables/PyTables/issues/282 + # bug in selection when 0th row has a np.nan and an index + #store.append('df3',df,data_columns=True) + #result = store.select( + # 'df3', where='values>2.0') + #tm.assert_frame_equal(expected, result) + + # not in first position float with NaN ok too + df = DataFrame(dict(cols = range(11), values = range(11)),dtype='float64') + df['cols'] = (df['cols']+10).apply(str) + + df.iloc[1] = np.nan + expected = df[df['values']>2.0] + + store.append('df4',df,data_columns=True) + result = store.select( + 'df4', where='values>2.0') + tm.assert_frame_equal(expected, result) + def test_select_with_many_inputs(self): with ensure_clean(self.path) as store:
https://github.com/PyTables/PyTables/issues/282
https://api.github.com/repos/pandas-dev/pandas/pulls/4858
2013-09-17T01:02:48Z
2013-09-17T01:24:10Z
2013-09-17T01:24:10Z
2014-07-09T10:41:36Z
ENH: Added xlsxwriter as an ExcelWriter option.
diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt index 6a94d48ad7a5f..2e903102de7b1 100644 --- a/ci/requirements-2.7.txt +++ b/ci/requirements-2.7.txt @@ -8,6 +8,7 @@ numexpr==2.1 tables==2.3.1 matplotlib==1.1.1 openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 patsy==0.1.0 html5lib==1.0b2 diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.txt index a7e9d62e3549b..056b63bbb8591 100644 --- a/ci/requirements-2.7_LOCALE.txt +++ b/ci/requirements-2.7_LOCALE.txt @@ -2,6 +2,7 @@ python-dateutil pytz==2013b xlwt==0.7.5 openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 numpy==1.6.1 cython==0.19.1 diff --git a/ci/requirements-3.2.txt b/ci/requirements-3.2.txt index e907a2fa828f1..b689047019ed7 100644 --- a/ci/requirements-3.2.txt +++ b/ci/requirements-3.2.txt @@ -1,6 +1,7 @@ python-dateutil==2.1 pytz==2013b openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 numpy==1.6.2 cython==0.19.1 diff --git a/ci/requirements-3.3.txt b/ci/requirements-3.3.txt index eb1e725d98040..326098be5f7f4 100644 --- a/ci/requirements-3.3.txt +++ b/ci/requirements-3.3.txt @@ -1,6 +1,7 @@ python-dateutil==2.1 pytz==2013b openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 html5lib==1.0b2 numpy==1.7.1 diff --git a/doc/source/10min.rst b/doc/source/10min.rst index 58c5b54968614..705514ac0c364 100644 --- a/doc/source/10min.rst +++ b/doc/source/10min.rst @@ -695,13 +695,13 @@ Writing to an excel file .. ipython:: python - df.to_excel('foo.xlsx', sheet_name='sheet1') + df.to_excel('foo.xlsx', sheet_name='Sheet1') Reading from an excel file .. ipython:: python - pd.read_excel('foo.xlsx', 'sheet1', index_col=None, na_values=['NA']) + pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) .. ipython:: python :suppress: diff --git a/doc/source/install.rst b/doc/source/install.rst index 4472d844c1871..b1dcad9448cfd 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -100,6 +100,8 @@ Optional Dependencies * `openpyxl <http://packages.python.org/openpyxl/>`__, `xlrd/xlwt <http://www.python-excel.org/>`__ * openpyxl version 1.6.1 or higher * Needed for Excel I/O + * `XlsxWriter <https://pypi.python.org/pypi/XlsxWriter>`__ + * Alternative Excel writer. * `boto <https://pypi.python.org/pypi/boto>`__: necessary for Amazon S3 access. * One of `PyQt4 diff --git a/doc/source/io.rst b/doc/source/io.rst index b9581c37082bf..67492eddbac12 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -1654,7 +1654,7 @@ indices to be parsed. .. code-block:: python - read_excel('path_to_file.xls', Sheet1', parse_cols=[0, 2, 3], index_col=None, na_values=['NA']) + read_excel('path_to_file.xls', 'Sheet1', parse_cols=[0, 2, 3], index_col=None, na_values=['NA']) To write a DataFrame object to a sheet of an Excel file, you can use the ``to_excel`` instance method. The arguments are largely the same as ``to_csv`` @@ -1664,7 +1664,7 @@ written. For example: .. code-block:: python - df.to_excel('path_to_file.xlsx', sheet_name='sheet1') + df.to_excel('path_to_file.xlsx', sheet_name='Sheet1') Files with a ``.xls`` extension will be written using ``xlwt`` and those with a ``.xlsx`` extension will be written using ``openpyxl``. @@ -1677,8 +1677,8 @@ one can use the ExcelWriter class, as in the following example: .. code-block:: python writer = ExcelWriter('path_to_file.xlsx') - df1.to_excel(writer, sheet_name='sheet1') - df2.to_excel(writer, sheet_name='sheet2') + df1.to_excel(writer, sheet_name='Sheet1') + df2.to_excel(writer, sheet_name='Sheet2') writer.save() .. _io.excel.writers: @@ -1693,11 +1693,29 @@ Excel writer engines 1. the ``engine`` keyword argument 2. the filename extension (via the default specified in config options) -``pandas`` only supports ``openpyxl`` for ``.xlsx`` and ``.xlsm`` files and -``xlwt`` for ``.xls`` files. If you have multiple engines installed, you can choose the -engine to use by default via the options ``io.excel.xlsx.writer`` and -``io.excel.xls.writer``. +By default ``pandas`` only supports +`openpyxl <http://packages.python.org/openpyxl/>`__ as a writer for ``.xlsx`` +and ``.xlsm`` files and `xlwt <http://www.python-excel.org/>`__ as a writer for +``.xls`` files. If you have multiple engines installed, you can change the +default engine via the ``io.excel.xlsx.writer`` and ``io.excel.xls.writer`` +options. +For example if the optional `XlsxWriter <http://xlsxwriter.readthedocs.org>`__ +module is installed you can use it as a xlsx writer engine as follows: + +.. code-block:: python + + # By setting the 'engine' in the DataFrame and Panel 'to_excel()' methods. + df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', engine='xlsxwriter') + + # By setting the 'engine' in the ExcelWriter constructor. + writer = ExcelWriter('path_to_file.xlsx', engine='xlsxwriter') + + # Or via pandas configuration. + from pandas import set_option + set_option('io.excel.xlsx.writer', 'xlsxwriter') + + df.to_excel('path_to_file.xlsx', sheet_name='Sheet1') .. _io.hdf5: diff --git a/doc/source/release.rst b/doc/source/release.rst index f7755afe8caae..b71410a8f7e59 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -113,6 +113,9 @@ Improvements to existing features ``io.excel.xls.writer``. (:issue:`4745`, :issue:`4750`) - ``Panel.to_excel()`` now accepts keyword arguments that will be passed to its ``DataFrame``'s ``to_excel()`` methods. (:issue:`4750`) + - Added XlsxWriter as an optional ``ExcelWriter`` engine. This is about 5x + faster than the default openpyxl xlsx writer and is equivalent in speed + to the xlwt xls writer module. (:issue:`4542`) - allow DataFrame constructor to accept more list-like objects, e.g. list of ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`4297`, :issue:`4851`), thanks @lgautier diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 75f81d20926a1..20fe33226d7ca 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1356,7 +1356,7 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None, tupleize_cols=tupleize_cols) formatter.save() - def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='', + def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, cols=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None): """ @@ -1366,7 +1366,7 @@ def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='', ---------- excel_writer : string or ExcelWriter object File path or existing ExcelWriter - sheet_name : string, default 'sheet1' + sheet_name : string, default 'Sheet1' Name of sheet which will contain DataFrame na_rep : string, default '' Missing data representation @@ -1397,8 +1397,8 @@ def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='', to the existing workbook. This can be used to save different DataFrames to one workbook >>> writer = ExcelWriter('output.xlsx') - >>> df1.to_excel(writer,'sheet1') - >>> df2.to_excel(writer,'sheet2') + >>> df1.to_excel(writer,'Sheet1') + >>> df2.to_excel(writer,'Sheet2') >>> writer.save() """ from pandas.io.excel import ExcelWriter diff --git a/pandas/io/excel.py b/pandas/io/excel.py index f34c4f99a856d..6ce8eb697268b 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -596,6 +596,7 @@ def _convert_to_style(cls, style_dict, num_format_str=None): Parameters ---------- style_dict: style dictionary to convert + num_format_str: optional number format string """ import xlwt @@ -611,3 +612,95 @@ def _convert_to_style(cls, style_dict, num_format_str=None): register_writer(_XlwtWriter) + +class _XlsxWriter(ExcelWriter): + engine = 'xlsxwriter' + supported_extensions = ('.xlsx',) + + def __init__(self, path, **engine_kwargs): + # Use the xlsxwriter module as the Excel writer. + import xlsxwriter + + super(_XlsxWriter, self).__init__(path, **engine_kwargs) + + self.book = xlsxwriter.Workbook(path, **engine_kwargs) + + def save(self): + """ + Save workbook to disk. + """ + return self.book.close() + + def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0): + # Write the frame cells using xlsxwriter. + + sheet_name = self._get_sheet_name(sheet_name) + + if sheet_name in self.sheets: + wks = self.sheets[sheet_name] + else: + wks = self.book.add_worksheet(sheet_name) + self.sheets[sheet_name] = wks + + style_dict = {} + + for cell in cells: + val = _conv_value(cell.val) + + num_format_str = None + if isinstance(cell.val, datetime.datetime): + num_format_str = "YYYY-MM-DD HH:MM:SS" + if isinstance(cell.val, datetime.date): + num_format_str = "YYYY-MM-DD" + + stylekey = json.dumps(cell.style) + if num_format_str: + stylekey += num_format_str + + if stylekey in style_dict: + style = style_dict[stylekey] + else: + style = self._convert_to_style(cell.style, num_format_str) + style_dict[stylekey] = style + + if cell.mergestart is not None and cell.mergeend is not None: + wks.merge_range(startrow + cell.row, + startrow + cell.mergestart, + startcol + cell.col, + startcol + cell.mergeend, + val, style) + else: + wks.write(startrow + cell.row, + startcol + cell.col, + val, style) + + def _convert_to_style(self, style_dict, num_format_str=None): + """ + converts a style_dict to an xlsxwriter format object + Parameters + ---------- + style_dict: style dictionary to convert + num_format_str: optional number format string + """ + if style_dict is None: + return None + + # Create a XlsxWriter format object. + xl_format = self.book.add_format() + + # Map the cell font to XlsxWriter font properties. + if style_dict.get('font'): + font = style_dict['font'] + if font.get('bold'): + xl_format.set_bold() + + # Map the cell borders to XlsxWriter border properties. + if style_dict.get('borders'): + xl_format.set_border() + + if num_format_str is not None: + xl_format.set_num_format(num_format_str) + + return xl_format + +register_writer(_XlsxWriter) diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 00536026994c5..94f3e5a8cf746 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -16,9 +16,11 @@ register_writer ) from pandas.util.testing import ensure_clean +from pandas.core.config import set_option, get_option import pandas.util.testing as tm import pandas as pd + def _skip_if_no_xlrd(): try: import xlrd @@ -31,18 +33,25 @@ def _skip_if_no_xlrd(): def _skip_if_no_xlwt(): try: - import xlwt # NOQA + import xlwt # NOQA except ImportError: raise nose.SkipTest('xlwt not installed, skipping') def _skip_if_no_openpyxl(): try: - import openpyxl # NOQA + import openpyxl # NOQA except ImportError: raise nose.SkipTest('openpyxl not installed, skipping') +def _skip_if_no_xlsxwriter(): + try: + import xlsxwriter # NOQA + except ImportError: + raise nose.SkipTest('xlsxwriter not installed, skipping') + + def _skip_if_no_excelsuite(): _skip_if_no_xlrd() _skip_if_no_xlwt() @@ -268,15 +277,22 @@ def test_xlsx_table(self): class ExcelWriterBase(SharedItems): - # test cases to run with different extensions - # for each writer - # to add a writer test, define two things: - # 1. a check_skip function that skips your tests if your writer isn't - # installed - # 2. add a property ext, which is the file extension that your writer writes to + # Base class for test cases to run with different Excel writers. + # To add a writer test, define the following: + # 1. A check_skip function that skips your tests if your writer isn't + # installed. + # 2. Add a property ext, which is the file extension that your writer + # writes to. + # 3. Add a property engine_name, which is the name of the writer class. def setUp(self): self.check_skip() super(ExcelWriterBase, self).setUp() + self.option_name = 'io.excel.%s.writer' % self.ext + self.prev_engine = get_option(self.option_name) + set_option(self.option_name, self.engine_name) + + def tearDown(self): + set_option(self.option_name, self.prev_engine) def test_excel_sheet_by_name_raise(self): _skip_if_no_xlrd() @@ -790,6 +806,7 @@ def roundtrip(df, header=True, parser_hdr=0): class OpenpyxlTests(ExcelWriterBase, unittest.TestCase): ext = 'xlsx' + engine_name = 'openpyxl' check_skip = staticmethod(_skip_if_no_openpyxl) def test_to_excel_styleconverter(self): @@ -820,6 +837,7 @@ def test_to_excel_styleconverter(self): class XlwtTests(ExcelWriterBase, unittest.TestCase): ext = 'xls' + engine_name = 'xlwt' check_skip = staticmethod(_skip_if_no_xlwt) def test_to_excel_styleconverter(self): @@ -841,6 +859,52 @@ def test_to_excel_styleconverter(self): self.assertEquals(xlwt.Borders.THIN, xls_style.borders.left) self.assertEquals(xlwt.Alignment.HORZ_CENTER, xls_style.alignment.horz) + +class XlsxWriterTests(ExcelWriterBase, unittest.TestCase): + ext = 'xlsx' + engine_name = 'xlsxwriter' + check_skip = staticmethod(_skip_if_no_xlsxwriter) + + # Override test from the Superclass to use assertAlmostEqual on the + # floating point values read back in from the output XlsxWriter file. + def test_roundtrip_indexlabels(self): + _skip_if_no_xlrd() + ext = self.ext + path = '__tmp_to_excel_from_excel_indexlabels__.' + ext + + with ensure_clean(path) as path: + + self.frame['A'][:5] = nan + + self.frame.to_excel(path, 'test1') + self.frame.to_excel(path, 'test1', cols=['A', 'B']) + self.frame.to_excel(path, 'test1', header=False) + self.frame.to_excel(path, 'test1', index=False) + + # test index_label + frame = (DataFrame(np.random.randn(10, 2)) >= 0) + frame.to_excel(path, 'test1', index_label=['test']) + reader = ExcelFile(path) + recons = reader.parse('test1', index_col=0).astype(np.int64) + frame.index.names = ['test'] + self.assertEqual(frame.index.names, recons.index.names) + + frame = (DataFrame(np.random.randn(10, 2)) >= 0) + frame.to_excel( + path, 'test1', index_label=['test', 'dummy', 'dummy2']) + reader = ExcelFile(path) + recons = reader.parse('test1', index_col=0).astype(np.int64) + frame.index.names = ['test'] + self.assertEqual(frame.index.names, recons.index.names) + + frame = (DataFrame(np.random.randn(10, 2)) >= 0) + frame.to_excel(path, 'test1', index_label='test') + reader = ExcelFile(path) + recons = reader.parse('test1', index_col=0).astype(np.int64) + frame.index.names = ['test'] + self.assertAlmostEqual(frame.index.names, recons.index.names) + + class ExcelWriterEngineTests(unittest.TestCase): def test_ExcelWriter_dispatch(self): with tm.assertRaisesRegexp(ValueError, 'No engine'): diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index fc86a78ea684b..d725a3ff6f135 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1429,6 +1429,26 @@ def test_to_excel(self): recdf = reader.parse(str(item), index_col=0) assert_frame_equal(df, recdf) + def test_to_excel_xlsxwriter(self): + try: + import xlrd + import xlsxwriter + from pandas.io.excel import ExcelFile + except ImportError: + raise nose.SkipTest("Requires xlrd and xlsxwriter. Skipping test.") + + path = '__tmp__.xlsx' + with ensure_clean(path) as path: + self.panel.to_excel(path, engine='xlsxwriter') + try: + reader = ExcelFile(path) + except ImportError: + raise nose.SkipTest + + for item, df in compat.iteritems(self.panel): + recdf = reader.parse(str(item), index_col=0) + assert_frame_equal(df, recdf) + def test_dropna(self): p = Panel(np.random.randn(4, 5, 6), major_axis=list('abcde')) p.ix[:, ['b', 'd'], 0] = np.nan diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py index b7b4a936a1e90..d9c642372a9bb 100644 --- a/pandas/util/print_versions.py +++ b/pandas/util/print_versions.py @@ -104,6 +104,12 @@ def show_versions(): except: print("xlwt: Not installed") + try: + import xlsxwriter + print("xlsxwriter: %s" % xlsxwriter.__version__) + except: + print("xlsxwriter: Not installed") + try: import sqlalchemy print("sqlalchemy: %s" % sqlalchemy.__version__)
Added xlsxwriter as an optional writer engine. closes #4542.
https://api.github.com/repos/pandas-dev/pandas/pulls/4857
2013-09-16T21:35:00Z
2013-09-22T23:14:58Z
2013-09-22T23:14:58Z
2017-02-16T10:32:15Z
COMPAT: unicode compat issue fix (GH4854)
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 10e1464739203..a2531ebd43c82 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -180,6 +180,8 @@ class to receive bound method def u(s): return s + def u_safe(s): + return s else: string_types = basestring, integer_types = (int, long) @@ -190,6 +192,12 @@ def u(s): def u(s): return unicode(s, "unicode_escape") + def u_safe(s): + try: + return unicode(s, "unicode_escape") + except: + return s + string_and_binary_types = string_types + (binary_type,) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b79408a1bf8d2..5c1dd408f696c 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -29,7 +29,7 @@ import pandas.core.common as com from pandas.tools.merge import concat from pandas import compat -from pandas.compat import u, PY3, range, lrange +from pandas.compat import u_safe as u, PY3, range, lrange from pandas.io.common import PerformanceWarning from pandas.core.config import get_option from pandas.computation.pytables import Expr, maybe_expression
closes #4854
https://api.github.com/repos/pandas-dev/pandas/pulls/4856
2013-09-16T20:52:30Z
2013-09-16T22:49:08Z
2013-09-16T22:49:08Z
2014-07-07T14:19:37Z
CLN: _axis_len checking cleanup and better message
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index b9ffe788d183d..2f6bc13983f93 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -244,7 +244,7 @@ def _get_axis_number(self, axis): return self._AXIS_NUMBERS[axis] except: pass - raise ValueError('No axis named %s' % axis) + raise ValueError('No axis named {0} for object type {1}'.format(axis,type(self))) def _get_axis_name(self, axis): axis = self._AXIS_ALIASES.get(axis, axis) @@ -256,7 +256,7 @@ def _get_axis_name(self, axis): return self._AXIS_NAMES[axis] except: pass - raise ValueError('No axis named %s' % axis) + raise ValueError('No axis named {0} for object type {1}'.format(axis,type(self))) def _get_axis(self, axis): name = self._get_axis_name(axis) @@ -496,7 +496,7 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False): ------- renamed : type of caller """ - axis = self._AXIS_NAMES[axis] + axis = self._get_axis_name(axis) d = { 'copy' : copy, 'inplace' : inplace } d[axis] = mapper return self.rename(**d) @@ -1546,9 +1546,6 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, self._consolidate_inplace() axis = self._get_axis_number(axis) - if axis + 1 > self._AXIS_LEN: - raise ValueError( - "invalid axis passed for object type {0}".format(type(self))) method = com._clean_fill_method(method) if value is None:
https://api.github.com/repos/pandas-dev/pandas/pulls/4855
2013-09-16T20:30:07Z
2013-09-16T21:08:12Z
2013-09-16T21:08:12Z
2014-07-16T08:28:42Z
BUG: (GH4851) path for 0-dim arrays in DataFrame construction were incorrect
diff --git a/doc/source/release.rst b/doc/source/release.rst index 0ed1f39d72cb5..5c6af024f1663 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -114,7 +114,7 @@ Improvements to existing features - ``Panel.to_excel()`` now accepts keyword arguments that will be passed to its ``DataFrame``'s ``to_excel()`` methods. (:issue:`4750`) - allow DataFrame constructor to accept more list-like objects, e.g. list of - ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`42971`), + ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`4297`, :issue:`4851`), thanks @lgautier - DataFrame constructor now accepts a numpy masked record array (:issue:`3478`), thanks @jnothman diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f56b6bc00cf15..a51bfee371b89 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -429,7 +429,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, if index is None and isinstance(data[0], Series): index = _get_names_from_index(data) - if is_list_like(data[0]) and getattr(data[0],'ndim',0) <= 1: + if is_list_like(data[0]) and getattr(data[0],'ndim',1) == 1: arrays, columns = _to_arrays(data, columns, dtype=dtype) columns = _ensure_index(columns) @@ -4710,7 +4710,7 @@ def extract_index(data): elif isinstance(v, dict): have_dicts = True indexes.append(list(v.keys())) - elif is_list_like(v) and getattr(v,'ndim',0) <= 1: + elif is_list_like(v) and getattr(v,'ndim',1) == 1: have_raw_arrays = True raw_lengths.append(len(v)) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index a5c1941a7f2d3..ff4cf1ca821ce 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -2675,6 +2675,13 @@ def test_constructor_list_of_lists(self): self.assert_(com.is_integer_dtype(df['num'])) self.assert_(df['str'].dtype == np.object_) + # GH 4851 + # list of 0-dim ndarrays + expected = DataFrame({ 0: range(10) }) + data = [np.array(x) for x in range(10)] + result = DataFrame(data) + assert_frame_equal(result, expected) + def test_constructor_sequence_like(self): # GH 3783 # collections.Squence like
closes #4851
https://api.github.com/repos/pandas-dev/pandas/pulls/4852
2013-09-16T17:15:05Z
2013-09-16T17:36:54Z
2013-09-16T17:36:54Z
2014-07-16T08:28:38Z
BUG/ENH: provide better .loc based semantics for float based indicies, continuing not to fallback (related GH236)
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 9f238c22850b7..bc9dcdccfc2e1 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -1199,22 +1199,109 @@ numpy array. For instance, dflookup = DataFrame(np.random.rand(20,4), columns = ['A','B','C','D']) dflookup.lookup(list(range(0,10,2)), ['B','C','A','B','D']) -Setting values in mixed-type DataFrame --------------------------------------- +.. _indexing.float64index: -.. _indexing.mixed_type_setting: +Float64Index +------------ + +.. versionadded:: 0.13.0 -Setting values on a mixed-type DataFrame or Panel is supported when using -scalar values, though setting arbitrary vectors is not yet supported: +By default a ``Float64Index`` will be automatically created when passing floating, or mixed-integer-floating values in index creation. +This enables a pure label-based slicing paradigm that makes ``[],ix,loc`` for scalar indexing and slicing work exactly the +same. .. ipython:: python - df2 = df[:4] - df2['foo'] = 'bar' - print(df2) - df2.ix[2] = np.nan - print(df2) - print(df2.dtypes) + indexf = Index([1.5, 2, 3, 4.5, 5]) + indexf + sf = Series(range(5),index=indexf) + sf + +Scalar selection for ``[],.ix,.loc`` will always be label based. An integer will match an equal float index (e.g. ``3`` is equivalent to ``3.0``) + +.. ipython:: python + + sf[3] + sf[3.0] + sf.ix[3] + sf.ix[3.0] + sf.loc[3] + sf.loc[3.0] + +The only positional indexing is via ``iloc`` + +.. ipython:: python + + sf.iloc[3] + +A scalar index that is not found will raise ``KeyError`` + +Slicing is ALWAYS on the values of the index, for ``[],ix,loc`` and ALWAYS positional with ``iloc`` + +.. ipython:: python + + sf[2:4] + sf.ix[2:4] + sf.loc[2:4] + sf.iloc[2:4] + +In float indexes, slicing using floats is allowed + +.. ipython:: python + + sf[2.1:4.6] + sf.loc[2.1:4.6] + +In non-float indexes, slicing using floats will raise a ``TypeError`` + +.. code-block:: python + + In [1]: Series(range(5))[3.5] + TypeError: the label [3.5] is not a proper indexer for this index type (Int64Index) + + In [1]: Series(range(5))[3.5:4.5] + TypeError: the slice start [3.5] is not a proper indexer for this index type (Int64Index) + +Using a scalar float indexer will be deprecated in a future version, but is allowed for now. + +.. code-block:: python + + In [3]: Series(range(5))[3.0] + Out[3]: 3 + +Here is a typical use-case for using this type of indexing. Imagine that you have a somewhat +irregular timedelta-like indexing scheme, but the data is recorded as floats. This could for +example be millisecond offsets. + +.. ipython:: python + + dfir = concat([DataFrame(randn(5,2), + index=np.arange(5) * 250.0, + columns=list('AB')), + DataFrame(randn(6,2), + index=np.arange(4,10) * 250.1, + columns=list('AB'))]) + dfir + +Selection operations then will always work on a value basis, for all selection operators. + +.. ipython:: python + + dfir[0:1000.4] + dfir.loc[0:1001,'A'] + dfir.loc[1000.4] + +You could then easily pick out the first 1 second (1000 ms) of data then. + +.. ipython:: python + + dfir[0:1000] + +Of course if you need integer based selection, then use ``iloc`` + +.. ipython:: python + + dfir.iloc[0:5] .. _indexing.view_versus_copy: diff --git a/doc/source/release.rst b/doc/source/release.rst index eec2e91f0a755..e39116f9023e1 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -226,6 +226,10 @@ API Changes add top-level ``to_timedelta`` function - ``NDFrame`` now is compatible with Python's toplevel ``abs()`` function (:issue:`4821`). - raise a ``TypeError`` on invalid comparison ops on Series/DataFrame (e.g. integer/datetime) (:issue:`4968`) + - Added a new index type, ``Float64Index``. This will be automatically created when passing floating values in index creation. + This enables a pure label-based slicing paradigm that makes ``[],ix,loc`` for scalar indexing and slicing work exactly the same. + Indexing on other index types are preserved (and positional fallback for ``[],ix``), with the exception, that floating point slicing + on indexes on non ``Float64Index`` will raise a ``TypeError``, e.g. ``Series(range(5))[3.5:4.5]`` (:issue:`263`) Internal Refactoring ~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index bda6fa4cdf021..95e5ff62a2abd 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -116,6 +116,72 @@ Indexing API Changes p p.loc[:,:,'C'] +Float64Index API Change +~~~~~~~~~~~~~~~~~~~~~~~ + + - Added a new index type, ``Float64Index``. This will be automatically created when passing floating values in index creation. + This enables a pure label-based slicing paradigm that makes ``[],ix,loc`` for scalar indexing and slicing work exactly the + same. See :ref:`the docs<indexing.float64index>`, (:issue:`263`) + + Construction is by default for floating type values. + + .. ipython:: python + + index = Index([1.5, 2, 3, 4.5, 5]) + index + s = Series(range(5),index=index) + s + + Scalar selection for ``[],.ix,.loc`` will always be label based. An integer will match an equal float index (e.g. ``3`` is equivalent to ``3.0``) + + .. ipython:: python + + s[3] + s.ix[3] + s.loc[3] + + The only positional indexing is via ``iloc`` + + .. ipython:: python + + s.iloc[3] + + A scalar index that is not found will raise ``KeyError`` + + Slicing is ALWAYS on the values of the index, for ``[],ix,loc`` and ALWAYS positional with ``iloc`` + + .. ipython:: python + + s[2:4] + s.ix[2:4] + s.loc[2:4] + s.iloc[2:4] + + In float indexes, slicing using floats are allowed + + .. ipython:: python + + s[2.1:4.6] + s.loc[2.1:4.6] + + - Indexing on other index types are preserved (and positional fallback for ``[],ix``), with the exception, that floating point slicing + on indexes on non ``Float64Index`` will now raise a ``TypeError``. + + .. code-block:: python + + In [1]: Series(range(5))[3.5] + TypeError: the label [3.5] is not a proper indexer for this index type (Int64Index) + + In [1]: Series(range(5))[3.5:4.5] + TypeError: the slice start [3.5] is not a proper indexer for this index type (Int64Index) + + Using a scalar float indexer will be deprecated in a future version, but is allowed for now. + + .. code-block:: python + + In [3]: Series(range(5))[3.0] + Out[3]: 3 + HDFStore API Changes ~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/v0.4.x.txt b/doc/source/v0.4.x.txt index 249dec5fd647b..5333bb9ffb157 100644 --- a/doc/source/v0.4.x.txt +++ b/doc/source/v0.4.x.txt @@ -15,8 +15,7 @@ New Features with choice of join method (ENH56_) - :ref:`Added <indexing.get_level_values>` method ``get_level_values`` to ``MultiIndex`` (:issue:`188`) -- :ref:`Set <indexing.mixed_type_setting>` values in mixed-type - ``DataFrame`` objects via ``.ix`` indexing attribute (:issue:`135`) +- Set values in mixed-type ``DataFrame`` objects via ``.ix`` indexing attribute (:issue:`135`) - Added new ``DataFrame`` :ref:`methods <basics.dtypes>` ``get_dtype_counts`` and property ``dtypes`` (ENHdc_) - Added :ref:`ignore_index <merging.ignore_index>` option to diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py index 7dc2ebc3d54e1..3554b8a3f81e1 100755 --- a/pandas/computation/tests/test_eval.py +++ b/pandas/computation/tests/test_eval.py @@ -778,7 +778,7 @@ def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs): class TestAlignment(object): index_types = 'i', 'u', 'dt' - lhs_index_types = index_types + ('f', 's') # 'p' + lhs_index_types = index_types + ('s',) # 'p' def check_align_nested_unary_op(self, engine, parser): skip_if_no_ne(engine) diff --git a/pandas/core/api.py b/pandas/core/api.py index 14af72a2a762a..b4afe90d46842 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -8,7 +8,7 @@ from pandas.core.categorical import Categorical, Factor from pandas.core.format import (set_printoptions, reset_printoptions, set_eng_float_format) -from pandas.core.index import Index, Int64Index, MultiIndex +from pandas.core.index import Index, Int64Index, Float64Index, MultiIndex from pandas.core.series import Series, TimeSeries from pandas.core.frame import DataFrame diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0fd02c2bdc3a4..c98790fdc38ff 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2050,7 +2050,7 @@ def eval(self, expr, **kwargs): kwargs['local_dict'] = _ensure_scope(resolvers=resolvers, **kwargs) return _eval(expr, **kwargs) - def _slice(self, slobj, axis=0, raise_on_error=False): + def _slice(self, slobj, axis=0, raise_on_error=False, typ=None): axis = self._get_block_manager_axis(axis) new_data = self._data.get_slice( slobj, axis=axis, raise_on_error=raise_on_error) diff --git a/pandas/core/index.py b/pandas/core/index.py index 734a6ee15307d..7f136450daf6e 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -14,7 +14,7 @@ from pandas.util.decorators import cache_readonly, deprecate from pandas.core.common import isnull import pandas.core.common as com -from pandas.core.common import _values_from_object +from pandas.core.common import _values_from_object, is_float, is_integer from pandas.core.config import get_option @@ -49,10 +49,8 @@ def _shouldbe_timestamp(obj): or tslib.is_datetime64_array(obj) or tslib.is_timestamp_array(obj)) - _Identity = object - class Index(FrozenNDArray): """ @@ -160,8 +158,8 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, subarr = subarr.copy() elif np.isscalar(data): - raise TypeError('Index(...) must be called with a collection ' - 'of some kind, %s was passed' % repr(data)) + cls._scalar_data_error(data) + else: # other iterable of some kind subarr = com._asarray_tuplesafe(data, dtype=object) @@ -170,6 +168,8 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, inferred = lib.infer_dtype(subarr) if inferred == 'integer': return Int64Index(subarr.astype('i8'), copy=copy, name=name) + elif inferred in ['floating','mixed-integer-float']: + return Float64Index(subarr, copy=copy, name=name) elif inferred != 'string': if (inferred.startswith('datetime') or tslib.is_timestamp_array(subarr)): @@ -183,6 +183,30 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, subarr._set_names([name]) return subarr + # construction helpers + @classmethod + def _scalar_data_error(cls, data): + raise TypeError('{0}(...) must be called with a collection ' + 'of some kind, {1} was passed'.format(cls.__name__,repr(data))) + + @classmethod + def _string_data_error(cls, data): + raise TypeError('String dtype not supported, you may need ' + 'to explicitly cast to a numeric type') + + @classmethod + def _coerce_to_ndarray(cls, data): + + if not isinstance(data, np.ndarray): + if np.isscalar(data): + cls._scalar_data_error(data) + + # other iterable of some kind + if not isinstance(data, (list, tuple)): + data = list(data) + data = np.asarray(data) + return data + def __array_finalize__(self, obj): self._reset_identity() if not isinstance(obj, type(self)): @@ -374,12 +398,137 @@ def is_lexsorted_for_tuple(self, tup): def is_unique(self): return self._engine.is_unique + def is_integer(self): + return self.inferred_type in ['integer'] + + def is_floating(self): + return self.inferred_type in ['floating','mixed-integer-float'] + def is_numeric(self): return self.inferred_type in ['integer', 'floating'] + def is_mixed(self): + return 'mixed' in self.inferred_type + def holds_integer(self): return self.inferred_type in ['integer', 'mixed-integer'] + def _convert_scalar_indexer(self, key, typ=None): + """ convert a scalar indexer, right now we are converting floats -> ints + if the index supports it """ + + def to_int(): + ikey = int(key) + if ikey != key: + self._convert_indexer_error(key, 'label') + return ikey + + if typ == 'iloc': + if not (is_integer(key) or is_float(key)): + self._convert_indexer_error(key, 'label') + return to_int() + + if is_float(key): + return to_int() + + return key + + def _validate_slicer(self, key, f): + """ validate and raise if needed on a slice indexers according to the + passed in function """ + + if not f(key.start): + self._convert_indexer_error(key.start, 'slice start value') + if not f(key.stop): + self._convert_indexer_error(key.stop, 'slice stop value') + if not f(key.step): + self._convert_indexer_error(key.step, 'slice step value') + + def _convert_slice_indexer_iloc(self, key): + """ convert a slice indexer for iloc only """ + self._validate_slicer(key, lambda v: v is None or is_integer(v)) + return key + + def _convert_slice_indexer_getitem(self, key, is_index_slice=False): + """ called from the getitem slicers, determine how to treat the key + whether positional or not """ + if self.is_integer() or is_index_slice: + return key + return self._convert_slice_indexer(key) + + def _convert_slice_indexer(self, key, typ=None): + """ convert a slice indexer. disallow floats in the start/stop/step """ + + # validate slicers + def validate(v): + if v is None or is_integer(v): + return True + + # dissallow floats + elif is_float(v): + return False + + return True + + self._validate_slicer(key, validate) + + # figure out if this is a positional indexer + start, stop, step = key.start, key.stop, key.step + + def is_int(v): + return v is None or is_integer(v) + + is_null_slice = start is None and stop is None + is_index_slice = is_int(start) and is_int(stop) + is_positional = is_index_slice and not self.is_integer() + + if typ == 'iloc': + return self._convert_slice_indexer_iloc(key) + elif typ == 'getitem': + return self._convert_slice_indexer_getitem(key, is_index_slice=is_index_slice) + + # convert the slice to an indexer here + + # if we are mixed and have integers + try: + if is_positional and self.is_mixed(): + if start is not None: + i = self.get_loc(start) + if stop is not None: + j = self.get_loc(stop) + is_positional = False + except KeyError: + if self.inferred_type == 'mixed-integer-float': + raise + + if is_null_slice: + indexer = key + elif is_positional: + indexer = key + else: + try: + indexer = self.slice_indexer(start, stop, step) + except Exception: + if is_index_slice: + if self.is_integer(): + raise + else: + indexer = key + else: + raise + + return indexer + + def _convert_list_indexer(self, key, typ=None): + """ convert a list indexer. these should be locations """ + return key + + def _convert_indexer_error(self, key, msg=None): + if msg is None: + msg = 'label' + raise TypeError("the {0} [{1}] is not a proper indexer for this index type ({2})".format(msg, + key, + self.__class__.__name__)) def get_duplicates(self): from collections import defaultdict counter = defaultdict(lambda: 0) @@ -858,6 +1007,11 @@ def get_value(self, series, key): """ s = _values_from_object(series) k = _values_from_object(key) + + # prevent integer truncation bug in indexing + if is_float(k) and not self.is_floating(): + raise KeyError + try: return self._engine.get_value(s, k) except KeyError as e1: @@ -1323,6 +1477,11 @@ def slice_indexer(self, start=None, end=None, step=None): # return a slice if np.isscalar(start_slice) and np.isscalar(end_slice): + + # degenerate cases + if start is None and end is None: + return slice(None, None, step) + return slice(start_slice, end_slice, step) # loc indexers @@ -1488,22 +1647,13 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): if not isinstance(data, np.ndarray): if np.isscalar(data): - raise ValueError('Index(...) must be called with a collection ' - 'of some kind, %s was passed' % repr(data)) + cls._scalar_data_error(data) - if not isinstance(data, np.ndarray): - if np.isscalar(data): - raise ValueError('Index(...) must be called with a collection ' - 'of some kind, %s was passed' % repr(data)) - - # other iterable of some kind - if not isinstance(data, (list, tuple)): - data = list(data) - data = np.asarray(data) + data = cls._coerce_to_ndarray(data) if issubclass(data.dtype.type, compat.string_types): - raise TypeError('String dtype not supported, you may need ' - 'to explicitly cast to int') + cls._string_data_error(data) + elif issubclass(data.dtype.type, np.integer): # don't force the upcast as we may be dealing # with a platform int @@ -1524,8 +1674,8 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): data = np.asarray(data) if issubclass(data.dtype.type, compat.string_types): - raise TypeError('String dtype not supported, you may need ' - 'to explicitly cast to int') + cls._string_data_error(data) + elif issubclass(data.dtype.type, np.integer): # don't force the upcast as we may be dealing # with a platform int @@ -1581,6 +1731,123 @@ def _wrap_joined_index(self, joined, other): return Int64Index(joined, name=name) +class Float64Index(Index): + """ + Immutable ndarray implementing an ordered, sliceable set. The basic object + storing axis labels for all pandas objects. Float64Index is a special case of `Index` + with purely floating point labels. + + Parameters + ---------- + data : array-like (1-dimensional) + dtype : NumPy dtype (default: object) + copy : bool + Make a copy of input ndarray + name : object + Name to be stored in the index + + Note + ---- + An Index instance can **only** contain hashable objects + """ + + # when this is not longer object dtype this can be changed + #_engine_type = _index.Float64Engine + + def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False): + + if fastpath: + subarr = data.view(cls) + subarr.name = name + return subarr + + if not isinstance(data, np.ndarray): + if np.isscalar(data): + cls._scalar_data_error(data) + + data = cls._coerce_to_ndarray(data) + + if issubclass(data.dtype.type, compat.string_types): + cls._string_data_error(data) + + if dtype is None: + dtype = np.float64 + + try: + subarr = np.array(data, dtype=dtype, copy=copy) + except: + raise TypeError('Unsafe NumPy casting, you must ' + 'explicitly cast') + + # coerce to object for storage + if not subarr.dtype == np.object_: + subarr = subarr.astype(object) + + subarr = subarr.view(cls) + subarr.name = name + return subarr + + @property + def inferred_type(self): + return 'floating' + + def astype(self, dtype): + if np.dtype(dtype) != np.object_: + raise TypeError( + "Setting %s dtype to anything other than object is not supported" % self.__class__) + return Index(self.values,name=self.name,dtype=object) + + def _convert_scalar_indexer(self, key, typ=None): + + if typ == 'iloc': + return super(Float64Index, self)._convert_scalar_indexer(key, typ=typ) + return key + + def _convert_slice_indexer(self, key, typ=None): + """ convert a slice indexer, by definition these are labels + unless we are iloc """ + if typ == 'iloc': + return self._convert_slice_indexer_iloc(key) + elif typ == 'getitem': + pass + + # allow floats here + self._validate_slicer(key, lambda v: v is None or is_integer(v) or is_float(v)) + + # translate to locations + return self.slice_indexer(key.start,key.stop,key.step) + + def get_value(self, series, key): + """ we always want to get an index value, never a value """ + if not np.isscalar(key): + raise InvalidIndexError + + from pandas.core.indexing import _maybe_droplevels + from pandas.core.series import Series + + k = _values_from_object(key) + loc = self.get_loc(k) + new_values = series.values[loc] + if np.isscalar(new_values): + return new_values + + new_index = self[loc] + new_index = _maybe_droplevels(new_index, k) + return Series(new_values, index=new_index, name=series.name) + + def equals(self, other): + """ + Determines if two Index objects contain the same elements. + """ + if self is other: + return True + + try: + return np.array_equal(self, other) + except TypeError: + # e.g. fails in numpy 1.6 with DatetimeIndex #1681 + return False + class MultiIndex(Index): """ @@ -1801,6 +2068,14 @@ def __unicode__(self): def __len__(self): return len(self.labels[0]) + def _convert_slice_indexer(self, key, typ=None): + """ convert a slice indexer. disallow floats in the start/stop/step """ + + if typ == 'iloc': + return self._convert_slice_indexer_iloc(key) + + return super(MultiIndex,self)._convert_slice_indexer(key, typ=typ) + def _get_names(self): return FrozenList(level.name for level in self.levels) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index cb738df6966da..afbeb53d857e2 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -6,7 +6,7 @@ from pandas.compat import range, zip import pandas.compat as compat import pandas.core.common as com -from pandas.core.common import (_is_bool_indexer, +from pandas.core.common import (_is_bool_indexer, is_integer_dtype, ABCSeries, ABCDataFrame, ABCPanel) import pandas.lib as lib @@ -16,7 +16,7 @@ def get_indexers_list(): return [ - ('ix' ,_NDFrameIndexer), + ('ix' ,_IXIndexer ), ('iloc',_iLocIndexer ), ('loc' ,_LocIndexer ), ('at' ,_AtIndexer ), @@ -32,6 +32,7 @@ class IndexingError(Exception): class _NDFrameIndexer(object): + _valid_types = None _exception = KeyError def __init__(self, obj, name): @@ -68,8 +69,8 @@ def _get_label(self, label, axis=0): def _get_loc(self, key, axis=0): return self.obj._ixs(key, axis=axis) - def _slice(self, obj, axis=0, raise_on_error=False): - return self.obj._slice(obj, axis=axis, raise_on_error=raise_on_error) + def _slice(self, obj, axis=0, raise_on_error=False, typ=None): + return self.obj._slice(obj, axis=axis, raise_on_error=raise_on_error, typ=typ) def __setitem__(self, key, value): # kludgetastic @@ -92,8 +93,16 @@ def __setitem__(self, key, value): self._setitem_with_indexer(indexer, value) + def _has_valid_type(self, k, axis): + raise NotImplementedError() + def _has_valid_tuple(self, key): - pass + """ check the key for valid keys across my indexer """ + for i, k in enumerate(key): + if i >= self.obj.ndim: + raise IndexingError('Too many indexers') + if not self._has_valid_type(k,i): + raise ValueError("Location based indexing can only have [%s] types" % self._valid_types) def _convert_tuple(self, key, is_setter=False): keyidx = [] @@ -102,6 +111,17 @@ def _convert_tuple(self, key, is_setter=False): keyidx.append(idx) return tuple(keyidx) + def _convert_scalar_indexer(self, key, axis): + # if we are accessing via lowered dim, use the last dim + ax = self.obj._get_axis(min(axis,self.ndim-1)) + # a scalar + return ax._convert_scalar_indexer(key, typ=self.name) + + def _convert_slice_indexer(self, key, axis): + # if we are accessing via lowered dim, use the last dim + ax = self.obj._get_axis(min(axis,self.ndim-1)) + return ax._convert_slice_indexer(key, typ=self.name) + def _has_valid_setitem_indexer(self, indexer): return True @@ -228,7 +248,9 @@ def _setitem_with_indexer(self, indexer, value): # if we have a partial multiindex, then need to adjust the plane indexer here if len(labels) == 1 and isinstance(self.obj[labels[0]].index,MultiIndex): - index = self.obj[labels[0]].index + item = labels[0] + obj = self.obj[item] + index = obj.index idx = indexer[:info_axis][0] try: if idx in index: @@ -238,8 +260,19 @@ def _setitem_with_indexer(self, indexer, value): plane_indexer = tuple([idx]) + indexer[info_axis + 1:] lplane_indexer = _length_of_indexer(plane_indexer[0],index) + # require that we are setting the right number of values that we are indexing if is_list_like(value) and lplane_indexer != len(value): - raise ValueError("cannot set using a multi-index selection indexer with a different length than the value") + + if len(obj[idx]) != len(value): + raise ValueError("cannot set using a multi-index selection indexer with a different length than the value") + + # we can directly set the series here + # as we select a slice indexer on the mi + idx = index._convert_slice_indexer(idx) + obj = obj.copy() + obj._data = obj._data.setitem(tuple([idx]),value) + self.obj[item] = obj + return # non-mi else: @@ -546,7 +579,7 @@ def _convert_for_reindex(self, key, axis=0): # asarray can be unsafe, NumPy strings are weird keyarr = _asarray_tuplesafe(key) - if _is_integer_dtype(keyarr) and not _is_integer_index(labels): + if is_integer_dtype(keyarr) and not labels.is_integer(): keyarr = com._ensure_platform_int(keyarr) return labels.take(keyarr) @@ -610,6 +643,8 @@ def _getitem_lowerdim(self, tup): raise IndexingError('not applicable') def _getitem_axis(self, key, axis=0): + + self._has_valid_type(key, axis) labels = self.obj._get_axis(axis) if isinstance(key, slice): return self._get_slice_axis(key, axis=axis) @@ -626,10 +661,11 @@ def _getitem_axis(self, key, axis=0): try: return self._get_label(key, axis=axis) except (KeyError, TypeError): - if _is_integer_index(self.obj.index.levels[0]): + if self.obj.index.levels[0].is_integer(): raise - if not _is_integer_index(labels): + # this is the fallback! (for a non-float, non-integer index) + if not labels.is_floating() and not labels.is_integer(): return self._get_loc(key, axis=axis) return self._get_label(key, axis=axis) @@ -658,7 +694,7 @@ def _reindex(keys, level=None): # asarray can be unsafe, NumPy strings are weird keyarr = _asarray_tuplesafe(key) - if _is_integer_dtype(keyarr): + if is_integer_dtype(keyarr) and not labels.is_floating(): if labels.inferred_type != 'integer': keyarr = np.where(keyarr < 0, len(labels) + keyarr, keyarr) @@ -747,7 +783,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): - No, prefer label-based indexing """ labels = self.obj._get_axis(axis) - is_int_index = _is_integer_index(labels) + is_int_index = labels.is_integer() if com.is_integer(obj) and not is_int_index: @@ -765,52 +801,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): pass if isinstance(obj, slice): - ltype = labels.inferred_type - - # in case of providing all floats, use label-based indexing - float_slice = (labels.inferred_type == 'floating' - and _is_float_slice(obj)) - - # floats that are within tolerance of int used as positions - int_slice = _is_index_slice(obj) - - null_slice = obj.start is None and obj.stop is None - - # could have integers in the first level of the MultiIndex, - # in which case we wouldn't want to do position-based slicing - position_slice = (int_slice - and not ltype == 'integer' - and not isinstance(labels, MultiIndex) - and not float_slice) - - start, stop = obj.start, obj.stop - - # last ditch effort: if we are mixed and have integers - try: - if position_slice and 'mixed' in ltype: - if start is not None: - i = labels.get_loc(start) - if stop is not None: - j = labels.get_loc(stop) - position_slice = False - except KeyError: - if ltype == 'mixed-integer-float': - raise - - if null_slice or position_slice: - indexer = obj - else: - try: - indexer = labels.slice_indexer(start, stop, obj.step) - except Exception: - if _is_index_slice(obj): - if ltype == 'integer': - raise - indexer = obj - else: - raise - - return indexer + return self._convert_slice_indexer(obj, axis) elif _is_list_like(obj): if com._is_bool_indexer(obj): @@ -824,7 +815,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False): objarr = _asarray_tuplesafe(obj) # If have integer labels, defer to label-based indexing - if _is_integer_dtype(objarr) and not is_int_index: + if is_integer_dtype(objarr) and not is_int_index: if labels.inferred_type != 'integer': objarr = np.where(objarr < 0, len(labels) + objarr, objarr) @@ -879,74 +870,37 @@ def _get_slice_axis(self, slice_obj, axis=0): if not _need_slice(slice_obj): return obj + indexer = self._convert_slice_indexer(slice_obj, axis) - labels = obj._get_axis(axis) - - ltype = labels.inferred_type - - # in case of providing all floats, use label-based indexing - float_slice = (labels.inferred_type == 'floating' - and _is_float_slice(slice_obj)) + if isinstance(indexer, slice): + return self._slice(indexer, axis=axis, typ='iloc') + else: + return self.obj.take(indexer, axis=axis) - # floats that are within tolerance of int used as positions - int_slice = _is_index_slice(slice_obj) +class _IXIndexer(_NDFrameIndexer): + """ A primarily location based indexer, with integer fallback """ - null_slice = slice_obj.start is None and slice_obj.stop is None + def _has_valid_type(self, key, axis): + ax = self.obj._get_axis(axis) - # could have integers in the first level of the MultiIndex, - # in which case we wouldn't want to do position-based slicing - position_slice = (int_slice - and not ltype == 'integer' - and not isinstance(labels, MultiIndex) - and not float_slice) + if isinstance(key, slice): + return True - start, stop = slice_obj.start, slice_obj.stop + elif com._is_bool_indexer(key): + return True - # last ditch effort: if we are mixed and have integers - try: - if position_slice and 'mixed' in ltype: - if start is not None: - i = labels.get_loc(start) - if stop is not None: - j = labels.get_loc(stop) - position_slice = False - except KeyError: - if ltype == 'mixed-integer-float': - raise + elif _is_list_like(key): + return True - if null_slice or position_slice: - indexer = slice_obj else: - try: - indexer = labels.slice_indexer(start, stop, slice_obj.step) - except Exception: - if _is_index_slice(slice_obj): - if ltype == 'integer': - raise - indexer = slice_obj - else: - raise - if isinstance(indexer, slice): - return self._slice(indexer, axis=axis) - else: - return self.obj.take(indexer, axis=axis) + self._convert_scalar_indexer(key, axis) + + return True class _LocationIndexer(_NDFrameIndexer): - _valid_types = None _exception = Exception - def _has_valid_type(self, k, axis): - raise NotImplementedError() - - def _has_valid_tuple(self, key): - """ check the key for valid keys across my indexer """ - for i, k in enumerate(key): - if i >= self.obj.ndim: - raise ValueError('Too many indexers') - if not self._has_valid_type(k,i): - raise ValueError("Location based indexing can only have [%s] types" % self._valid_types) - def __getitem__(self, key): if type(key) is tuple: return self._getitem_tuple(key) @@ -974,7 +928,7 @@ def _get_slice_axis(self, slice_obj, axis=0): indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop, slice_obj.step) if isinstance(indexer, slice): - return self._slice(indexer, axis=axis) + return self._slice(indexer, axis=axis, typ='iloc') else: return self.obj.take(indexer, axis=axis) @@ -993,18 +947,28 @@ def _has_valid_type(self, key, axis): if isinstance(key, slice): - if key.start is not None: - if key.start not in ax: - raise KeyError("start bound [%s] is not the [%s]" % (key.start,self.obj._get_axis_name(axis))) - if key.stop is not None: - if key.stop not in ax: - raise KeyError("stop bound [%s] is not in the [%s]" % (key.stop,self.obj._get_axis_name(axis))) + if ax.is_floating(): + + # allowing keys to be slicers with no fallback + pass + + else: + if key.start is not None: + if key.start not in ax: + raise KeyError("start bound [%s] is not the [%s]" % (key.start,self.obj._get_axis_name(axis))) + if key.stop is not None: + if key.stop not in ax: + raise KeyError("stop bound [%s] is not in the [%s]" % (key.stop,self.obj._get_axis_name(axis))) elif com._is_bool_indexer(key): return True elif _is_list_like(key): + # mi is just a passthru + if isinstance(key, tuple) and isinstance(ax, MultiIndex): + return True + # require all elements in the index idx = _ensure_index(key) if not idx.isin(ax).all(): @@ -1014,18 +978,15 @@ def _has_valid_type(self, key, axis): else: - # if its empty we want a KeyError here - if not len(ax): - raise KeyError("The [%s] axis is empty" % self.obj._get_axis_name(axis)) + def error(): + raise KeyError("the label [%s] is not in the [%s]" % (key,self.obj._get_axis_name(axis))) + key = self._convert_scalar_indexer(key, axis) try: if not key in ax: - raise KeyError("the label [%s] is not in the [%s]" % (key,self.obj._get_axis_name(axis))) - except (TypeError): - - # if we have a weird type of key/ax - raise KeyError("the label [%s] is not in the [%s]" % (key,self.obj._get_axis_name(axis))) - + error() + except: + error() return True @@ -1045,6 +1006,7 @@ def _getitem_axis(self, key, axis=0): return self._getitem_iterable(key, axis=axis) else: + self._has_valid_type(key,axis) return self._get_label(key, axis=axis) class _iLocIndexer(_LocationIndexer): @@ -1092,11 +1054,12 @@ def _get_slice_axis(self, slice_obj, axis=0): return obj if isinstance(slice_obj, slice): - return self._slice(slice_obj, axis=axis, raise_on_error=True) + return self._slice(slice_obj, axis=axis, raise_on_error=True, typ='iloc') else: return self.obj.take(slice_obj, axis=axis) def _getitem_axis(self, key, axis=0): + if isinstance(key, slice): self._has_valid_type(key,axis) return self._get_slice_axis(key, axis=axis) @@ -1108,8 +1071,13 @@ def _getitem_axis(self, key, axis=0): # a single integer or a list of integers else: - if not (com.is_integer(key) or _is_list_like(key)): - raise ValueError("Cannot index by location index with a non-integer key") + if _is_list_like(key): + pass + else: + key = self._convert_scalar_indexer(key, axis) + + if not com.is_integer(key): + raise TypeError("Cannot index by location index with a non-integer key") return self._get_loc(key,axis=axis) @@ -1200,14 +1168,7 @@ def _convert_to_index_sliceable(obj, key): """ if we are index sliceable, then return my slicer, otherwise return None """ idx = obj.index if isinstance(key, slice): - idx_type = idx.inferred_type - if idx_type == 'floating': - indexer = obj.ix._convert_to_indexer(key, axis=0) - elif idx_type == 'integer' or _is_index_slice(key): - indexer = key - else: - indexer = obj.ix._convert_to_indexer(key, axis=0) - return indexer + return idx._convert_slice_indexer(key, typ='getitem') elif isinstance(key, compat.string_types): @@ -1237,31 +1198,7 @@ def _crit(v): return not both_none and (_crit(obj.start) and _crit(obj.stop)) -def _is_int_slice(obj): - def _is_valid_index(x): - return com.is_integer(x) - - def _crit(v): - return v is None or _is_valid_index(v) - - both_none = obj.start is None and obj.stop is None - - return not both_none and (_crit(obj.start) and _crit(obj.stop)) - - -def _is_float_slice(obj): - def _is_valid_index(x): - return com.is_float(x) - - def _crit(v): - return v is None or _is_valid_index(v) - - both_none = obj.start is None and obj.stop is None - - return not both_none and (_crit(obj.start) and _crit(obj.stop)) - - -class _SeriesIndexer(_NDFrameIndexer): +class _SeriesIndexer(_IXIndexer): """ Class to support fancy indexing, potentially using labels @@ -1286,7 +1223,7 @@ def _get_label(self, key, axis=0): def _get_loc(self, key, axis=0): return self.obj.values[key] - def _slice(self, indexer, axis=0): + def _slice(self, indexer, axis=0, typ=None): return self.obj._get_values(indexer) def _setitem_with_indexer(self, indexer, value): @@ -1389,15 +1326,6 @@ def _is_null_slice(obj): obj.stop is None and obj.step is None) -def _is_integer_dtype(arr): - return (issubclass(arr.dtype.type, np.integer) and - not arr.dtype.type == np.datetime64) - - -def _is_integer_index(index): - return index.inferred_type == 'integer' - - def _is_label_like(key): # select a label or row return not isinstance(key, slice) and not _is_list_like(key) @@ -1438,6 +1366,9 @@ def _maybe_droplevels(index, key): # we have dropped too much, so back out return original_index else: - index = index.droplevel(0) + try: + index = index.droplevel(0) + except: + pass return index diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 5f90eb9fa31a7..34b65f169b904 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -579,7 +579,7 @@ def _box_item_values(self, key, values): d = self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:]) return self._constructor_sliced(values, **d) - def _slice(self, slobj, axis=0, raise_on_error=False): + def _slice(self, slobj, axis=0, raise_on_error=False, typ=None): new_data = self._data.get_slice(slobj, axis=axis, raise_on_error=raise_on_error) diff --git a/pandas/core/series.py b/pandas/core/series.py index 942bb700a3718..bf5ec998c9963 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -901,7 +901,8 @@ def _ixs(self, i, axis=0): raise except: if isinstance(i, slice): - return self[i] + indexer = self.index._convert_slice_indexer(i,typ='iloc') + return self._get_values(indexer) else: label = self.index[i] if isinstance(label, Index): @@ -914,10 +915,10 @@ def _ixs(self, i, axis=0): def _is_mixed_type(self): return False - def _slice(self, slobj, axis=0, raise_on_error=False): + def _slice(self, slobj, axis=0, raise_on_error=False, typ=None): if raise_on_error: _check_slice_bounds(slobj, self.values) - + slobj = self.index._convert_slice_indexer(slobj,typ=typ or 'getitem') return self._constructor(self.values[slobj], index=self.index[slobj], name=self.name) @@ -935,7 +936,13 @@ def __getitem__(self, key): elif _is_bool_indexer(key): pass else: + + # we can try to coerce the indexer (or this will raise) + new_key = self.index._convert_scalar_indexer(key) + if type(new_key) != type(key): + return self.__getitem__(new_key) raise + except Exception: raise @@ -950,14 +957,7 @@ def __getitem__(self, key): def _get_with(self, key): # other: fancy integer or otherwise if isinstance(key, slice): - - idx_type = self.index.inferred_type - if idx_type == 'floating': - indexer = self.ix._convert_to_indexer(key, axis=0) - elif idx_type == 'integer' or _is_index_slice(key): - indexer = key - else: - indexer = self.ix._convert_to_indexer(key, axis=0) + indexer = self.index._convert_slice_indexer(key,typ='getitem') return self._get_values(indexer) else: if isinstance(key, tuple): @@ -980,7 +980,7 @@ def _get_with(self, key): key_type = lib.infer_dtype(key) if key_type == 'integer': - if self.index.inferred_type == 'integer': + if self.index.is_integer() or self.index.is_floating(): return self.reindex(key) else: return self._get_values(key) @@ -1080,10 +1080,7 @@ def _set_with_engine(self, key, value): def _set_with(self, key, value): # other: fancy integer or otherwise if isinstance(key, slice): - if self.index.inferred_type == 'integer' or _is_index_slice(key): - indexer = key - else: - indexer = self.ix._convert_to_indexer(key, axis=0) + indexer = self.index._convert_slice_indexer(key,typ='getitem') return self._set_values(indexer, value) else: if isinstance(key, tuple): @@ -2348,7 +2345,7 @@ def sort(self, axis=0, kind='quicksort', order=None, ascending=True): raise TypeError('This Series is a view of some other array, to ' 'sort in-place you must create a copy') - self[:] = sortedSeries + self._data = sortedSeries._data.copy() self.index = sortedSeries.index def sort_index(self, ascending=True): diff --git a/pandas/sparse/frame.py b/pandas/sparse/frame.py index 7d2571e6c3c74..a1b630dedaaab 100644 --- a/pandas/sparse/frame.py +++ b/pandas/sparse/frame.py @@ -374,7 +374,7 @@ def set_value(self, index, col, value): return dense.to_sparse(kind=self._default_kind, fill_value=self._default_fill_value) - def _slice(self, slobj, axis=0, raise_on_error=False): + def _slice(self, slobj, axis=0, raise_on_error=False, typ=None): if axis == 0: if raise_on_error: _check_slice_bounds(slobj, self.index) diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index e7a52756089cc..723bf022c3f48 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -1110,10 +1110,10 @@ def test_to_string_float_index(self): result = df.to_string() expected = (' 0\n' '1.5 0\n' - '2 1\n' - '3 2\n' - '4 3\n' - '5 4') + '2.0 1\n' + '3.0 2\n' + '4.0 3\n' + '5.0 4') self.assertEqual(result, expected) def test_to_string_ascii_error(self): diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 312b5aee18752..82be82ea57dae 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -1254,48 +1254,62 @@ def test_getitem_setitem_float_labels(self): assert_frame_equal(result, expected) self.assertEqual(len(result), 2) - # this should raise an exception - with tm.assertRaises(KeyError): - df.ix[1:2] - with tm.assertRaises(KeyError): - df.ix[1:2] = 0 + # loc_float changes this to work properly + result = df.ix[1:2] + expected = df.iloc[0:2] + assert_frame_equal(result, expected) + + df.ix[1:2] = 0 + result = df[1:2] + self.assert_((result==0).all().all()) # #2727 index = Index([1.0, 2.5, 3.5, 4.5, 5.0]) df = DataFrame(np.random.randn(5, 5), index=index) - # positional slicing! + # positional slicing only via iloc! + result = df.iloc[1.0:5] + expected = df.reindex([2.5, 3.5, 4.5, 5.0]) + assert_frame_equal(result, expected) + self.assertEqual(len(result), 4) + + result = df.iloc[4:5] + expected = df.reindex([5.0]) + assert_frame_equal(result, expected) + self.assertEqual(len(result), 1) + + cp = df.copy() + cp.iloc[1.0:5] = 0 + self.assert_((cp.iloc[1.0:5] == 0).values.all()) + self.assert_((cp.iloc[0:1] == df.iloc[0:1]).values.all()) + + cp = df.copy() + cp.iloc[4:5] = 0 + self.assert_((cp.iloc[4:5] == 0).values.all()) + self.assert_((cp.iloc[0:4] == df.iloc[0:4]).values.all()) + + # float slicing result = df.ix[1.0:5] + expected = df + assert_frame_equal(result, expected) + self.assertEqual(len(result), 5) + + result = df.ix[1.1:5] expected = df.reindex([2.5, 3.5, 4.5, 5.0]) assert_frame_equal(result, expected) self.assertEqual(len(result), 4) - # positional again - result = df.ix[4:5] + result = df.ix[4.51:5] expected = df.reindex([5.0]) assert_frame_equal(result, expected) self.assertEqual(len(result), 1) - # label-based result = df.ix[1.0:5.0] expected = df.reindex([1.0, 2.5, 3.5, 4.5, 5.0]) assert_frame_equal(result, expected) self.assertEqual(len(result), 5) cp = df.copy() - # positional slicing! - cp.ix[1.0:5] = 0 - self.assert_((cp.ix[1.0:5] == 0).values.all()) - self.assert_((cp.ix[0:1] == df.ix[0:1]).values.all()) - - cp = df.copy() - # positional again - cp.ix[4:5] = 0 - self.assert_((cp.ix[4:5] == 0).values.all()) - self.assert_((cp.ix[0:4] == df.ix[0:4]).values.all()) - - cp = df.copy() - # label-based cp.ix[1.0:5.0] = 0 self.assert_((cp.ix[1.0:5.0] == 0).values.all()) @@ -10064,15 +10078,15 @@ def test_reindex_with_nans(self): index=[100.0, 101.0, np.nan, 102.0, 103.0]) result = df.reindex(index=[101.0, 102.0, 103.0]) - expected = df.ix[[1, 3, 4]] + expected = df.iloc[[1, 3, 4]] assert_frame_equal(result, expected) result = df.reindex(index=[103.0]) - expected = df.ix[[4]] + expected = df.iloc[[4]] assert_frame_equal(result, expected) result = df.reindex(index=[101.0]) - expected = df.ix[[1]] + expected = df.iloc[[1]] assert_frame_equal(result, expected) def test_reindex_multi(self): diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index e3c9da3630975..857836fa698ce 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -12,7 +12,7 @@ import numpy as np from numpy.testing import assert_array_equal -from pandas.core.index import Index, Int64Index, MultiIndex, InvalidIndexError +from pandas.core.index import Index, Float64Index, Int64Index, MultiIndex, InvalidIndexError from pandas.core.frame import DataFrame from pandas.core.series import Series from pandas.util.testing import (assert_almost_equal, assertRaisesRegexp, @@ -654,6 +654,88 @@ def test_join_self(self): self.assert_(res is joined) +class TestFloat64Index(unittest.TestCase): + _multiprocess_can_split_ = True + + def setUp(self): + self.mixed = Float64Index([1.5, 2, 3, 4, 5]) + self.float = Float64Index(np.arange(5) * 2.5) + + def check_is_index(self, i): + self.assert_(isinstance(i, Index) and not isinstance(i, Float64Index)) + + def check_coerce(self, a, b, is_float_index=True): + self.assert_(a.equals(b)) + if is_float_index: + self.assert_(isinstance(b, Float64Index)) + else: + self.check_is_index(b) + + def test_constructor(self): + + # explicit construction + index = Float64Index([1,2,3,4,5]) + self.assert_(isinstance(index, Float64Index)) + self.assert_((index.values == np.array([1,2,3,4,5],dtype='float64')).all()) + index = Float64Index(np.array([1,2,3,4,5])) + self.assert_(isinstance(index, Float64Index)) + index = Float64Index([1.,2,3,4,5]) + self.assert_(isinstance(index, Float64Index)) + index = Float64Index(np.array([1.,2,3,4,5])) + self.assert_(isinstance(index, Float64Index)) + self.assert_(index.dtype == object) + + index = Float64Index(np.array([1.,2,3,4,5]),dtype=np.float32) + self.assert_(isinstance(index, Float64Index)) + self.assert_(index.dtype == object) + + index = Float64Index(np.array([1,2,3,4,5]),dtype=np.float32) + self.assert_(isinstance(index, Float64Index)) + self.assert_(index.dtype == object) + + # nan handling + result = Float64Index([np.nan, np.nan]) + self.assert_(pd.isnull(result.values).all()) + result = Float64Index(np.array([np.nan])) + self.assert_(pd.isnull(result.values).all()) + result = Index(np.array([np.nan])) + self.assert_(pd.isnull(result.values).all()) + + def test_constructor_invalid(self): + + # invalid + self.assertRaises(TypeError, Float64Index, 0.) + self.assertRaises(TypeError, Float64Index, ['a','b',0.]) + self.assertRaises(TypeError, Float64Index, [Timestamp('20130101')]) + + def test_constructor_coerce(self): + + self.check_coerce(self.mixed,Index([1.5, 2, 3, 4, 5])) + self.check_coerce(self.float,Index(np.arange(5) * 2.5)) + self.check_coerce(self.float,Index(np.array(np.arange(5) * 2.5, dtype=object))) + + def test_constructor_explicit(self): + + # these don't auto convert + self.check_coerce(self.float,Index((np.arange(5) * 2.5), dtype=object), + is_float_index=False) + self.check_coerce(self.mixed,Index([1.5, 2, 3, 4, 5],dtype=object), + is_float_index=False) + + def test_astype(self): + + result = self.float.astype(object) + self.assert_(result.equals(self.float)) + self.assert_(self.float.equals(result)) + self.check_is_index(result) + + i = self.mixed.copy() + i.name = 'foo' + result = i.astype(object) + self.assert_(result.equals(i)) + self.assert_(i.equals(result)) + self.check_is_index(result) + class TestInt64Index(unittest.TestCase): _multiprocess_can_split_ = True @@ -676,7 +758,7 @@ def test_constructor(self): self.assert_(np.array_equal(index, expected)) # scalar raise Exception - self.assertRaises(ValueError, Int64Index, 5) + self.assertRaises(TypeError, Int64Index, 5) # copy arr = self.index.values diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index ced4cbdc4dc36..0eab5ab834533 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -13,7 +13,7 @@ import pandas as pd import pandas.core.common as com from pandas.core.api import (DataFrame, Index, Series, Panel, notnull, isnull, - MultiIndex, DatetimeIndex, Timestamp) + MultiIndex, DatetimeIndex, Float64Index, Timestamp) from pandas.util.testing import (assert_almost_equal, assert_series_equal, assert_frame_equal, assert_panel_equal) from pandas import compat, concat @@ -1519,6 +1519,309 @@ def test_cache_updating(self): self.assert_("A+1" in panel.ix[0].columns) self.assert_("A+1" in panel.ix[1].columns) + def test_floating_index_doc_example(self): + + index = Index([1.5, 2, 3, 4.5, 5]) + s = Series(range(5),index=index) + self.assert_(s[3] == 2) + self.assert_(s.ix[3] == 2) + self.assert_(s.loc[3] == 2) + self.assert_(s.iloc[3] == 3) + + def test_floating_index(self): + + # related 236 + # scalar/slicing of a float index + s = Series(np.arange(5), index=np.arange(5) * 2.5) + + # label based slicing + result1 = s[1.0:3.0] + result2 = s.ix[1.0:3.0] + result3 = s.loc[1.0:3.0] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + + # exact indexing when found + result1 = s[5.0] + result2 = s.loc[5.0] + result3 = s.ix[5.0] + self.assert_(result1 == result2) + self.assert_(result1 == result3) + + result1 = s[5] + result2 = s.loc[5] + result3 = s.ix[5] + self.assert_(result1 == result2) + self.assert_(result1 == result3) + + self.assert_(s[5.0] == s[5]) + + # value not found (and no fallbacking at all) + + # scalar integers + self.assertRaises(KeyError, lambda : s.loc[4]) + self.assertRaises(KeyError, lambda : s.ix[4]) + self.assertRaises(KeyError, lambda : s[4]) + + # fancy floats/integers create the correct entry (as nan) + # fancy tests + expected = Series([2, 0], index=Float64Index([5.0, 0.0])) + for fancy_idx in [[5.0, 0.0], [5, 0], np.array([5.0, 0.0]), np.array([5, 0])]: + assert_series_equal(s[fancy_idx], expected) + assert_series_equal(s.loc[fancy_idx], expected) + assert_series_equal(s.ix[fancy_idx], expected) + + # all should return the same as we are slicing 'the same' + result1 = s.loc[2:5] + result2 = s.loc[2.0:5.0] + result3 = s.loc[2.0:5] + result4 = s.loc[2.1:5] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, result4) + + # previously this did fallback indexing + result1 = s[2:5] + result2 = s[2.0:5.0] + result3 = s[2.0:5] + result4 = s[2.1:5] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, result4) + + result1 = s.ix[2:5] + result2 = s.ix[2.0:5.0] + result3 = s.ix[2.0:5] + result4 = s.ix[2.1:5] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, result4) + + # combined test + result1 = s.loc[2:5] + result2 = s.ix[2:5] + result3 = s[2:5] + + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + + # list selection + result1 = s[[0.0,5,10]] + result2 = s.loc[[0.0,5,10]] + result3 = s.ix[[0.0,5,10]] + result4 = s.iloc[[0,2,4]] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, result4) + + result1 = s[[1.6,5,10]] + result2 = s.loc[[1.6,5,10]] + result3 = s.ix[[1.6,5,10]] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, Series([np.nan,2,4],index=[1.6,5,10])) + + result1 = s[[0,1,2]] + result2 = s.ix[[0,1,2]] + result3 = s.loc[[0,1,2]] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, Series([0.0,np.nan,np.nan],index=[0,1,2])) + + result1 = s.loc[[2.5, 5]] + result2 = s.ix[[2.5, 5]] + assert_series_equal(result1, result2) + assert_series_equal(result1, Series([1,2],index=[2.5,5.0])) + + result1 = s[[2.5]] + result2 = s.ix[[2.5]] + result3 = s.loc[[2.5]] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + assert_series_equal(result1, Series([1],index=[2.5])) + + def test_scalar_indexer(self): + # float indexing checked above + + def check_invalid(index, loc=None, iloc=None, ix=None, getitem=None): + + # related 236/4850 + # trying to access with a float index + s = Series(np.arange(len(index)),index=index) + + if iloc is None: + iloc = TypeError + self.assertRaises(iloc, lambda : s.iloc[3.5]) + if loc is None: + loc = TypeError + self.assertRaises(loc, lambda : s.loc[3.5]) + if ix is None: + ix = TypeError + self.assertRaises(ix, lambda : s.ix[3.5]) + if getitem is None: + getitem = TypeError + self.assertRaises(getitem, lambda : s[3.5]) + + for index in [ tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeIntIndex, + tm.makeDateIndex, tm.makePeriodIndex ]: + check_invalid(index()) + check_invalid(Index(np.arange(5) * 2.5),loc=KeyError, ix=KeyError, getitem=KeyError) + + def check_getitem(index): + + s = Series(np.arange(len(index)),index=index) + + # positional selection + result1 = s[5] + result2 = s[5.0] + result3 = s.iloc[5] + result4 = s.iloc[5.0] + + # by value + self.assertRaises(KeyError, lambda : s.loc[5]) + self.assertRaises(KeyError, lambda : s.loc[5.0]) + + # this is fallback, so it works + result5 = s.ix[5] + result6 = s.ix[5.0] + self.assert_(result1 == result2) + self.assert_(result1 == result3) + self.assert_(result1 == result4) + self.assert_(result1 == result5) + self.assert_(result1 == result6) + + # all index types except float/int + for index in [ tm.makeStringIndex, tm.makeUnicodeIndex, + tm.makeDateIndex, tm.makePeriodIndex ]: + check_getitem(index()) + + # exact indexing when found on IntIndex + s = Series(np.arange(10),dtype='int64') + + result1 = s[5.0] + result2 = s.loc[5.0] + result3 = s.ix[5.0] + result4 = s[5] + result5 = s.loc[5] + result6 = s.ix[5] + self.assert_(result1 == result2) + self.assert_(result1 == result3) + self.assert_(result1 == result4) + self.assert_(result1 == result5) + self.assert_(result1 == result6) + + def test_slice_indexer(self): + + def check_slicing_positional(index): + + s = Series(np.arange(len(index))+10,index=index) + + # these are all positional + result1 = s[2:5] + result2 = s.ix[2:5] + result3 = s.iloc[2:5] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + + # not in the index + self.assertRaises(KeyError, lambda : s.loc[2:5]) + + # make all float slicing fail + self.assertRaises(TypeError, lambda : s[2.0:5]) + self.assertRaises(TypeError, lambda : s[2.0:5.0]) + self.assertRaises(TypeError, lambda : s[2:5.0]) + + self.assertRaises(TypeError, lambda : s.ix[2.0:5]) + self.assertRaises(TypeError, lambda : s.ix[2.0:5.0]) + self.assertRaises(TypeError, lambda : s.ix[2:5.0]) + + self.assertRaises(KeyError, lambda : s.loc[2.0:5]) + self.assertRaises(KeyError, lambda : s.loc[2.0:5.0]) + self.assertRaises(KeyError, lambda : s.loc[2:5.0]) + + # these work for now + #self.assertRaises(TypeError, lambda : s.iloc[2.0:5]) + #self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0]) + #self.assertRaises(TypeError, lambda : s.iloc[2:5.0]) + + # all index types except int, float + for index in [ tm.makeStringIndex, tm.makeUnicodeIndex, + tm.makeDateIndex, tm.makePeriodIndex ]: + check_slicing_positional(index()) + + # int + index = tm.makeIntIndex() + s = Series(np.arange(len(index))+10,index) + + # this is positional + result1 = s[2:5] + result4 = s.iloc[2:5] + assert_series_equal(result1, result4) + + # these are all value based + result2 = s.ix[2:5] + result3 = s.loc[2:5] + result4 = s.loc[2.0:5] + result5 = s.loc[2.0:5.0] + result6 = s.loc[2:5.0] + assert_series_equal(result2, result3) + assert_series_equal(result2, result4) + assert_series_equal(result2, result5) + assert_series_equal(result2, result6) + + # make all float slicing fail + self.assertRaises(TypeError, lambda : s[2.0:5]) + self.assertRaises(TypeError, lambda : s[2.0:5.0]) + self.assertRaises(TypeError, lambda : s[2:5.0]) + + self.assertRaises(TypeError, lambda : s.ix[2.0:5]) + self.assertRaises(TypeError, lambda : s.ix[2.0:5.0]) + self.assertRaises(TypeError, lambda : s.ix[2:5.0]) + + # these work for now + #self.assertRaises(TypeError, lambda : s.iloc[2.0:5]) + #self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0]) + #self.assertRaises(TypeError, lambda : s.iloc[2:5.0]) + + # float + index = tm.makeFloatIndex() + s = Series(np.arange(len(index))+10,index=index) + + # these are all value based + result1 = s[2:5] + result2 = s.ix[2:5] + result3 = s.loc[2:5] + assert_series_equal(result1, result2) + assert_series_equal(result1, result3) + + # these are all valid + result1a = s[2.0:5] + result2a = s[2.0:5.0] + result3a = s[2:5.0] + assert_series_equal(result1a, result2a) + assert_series_equal(result1a, result3a) + + result1b = s.ix[2.0:5] + result2b = s.ix[2.0:5.0] + result3b = s.ix[2:5.0] + assert_series_equal(result1b, result2b) + assert_series_equal(result1b, result3b) + + result1c = s.loc[2.0:5] + result2c = s.loc[2.0:5.0] + result3c = s.loc[2:5.0] + assert_series_equal(result1c, result2c) + assert_series_equal(result1c, result3c) + + assert_series_equal(result1a, result1b) + assert_series_equal(result1a, result1c) + + # these work for now + #self.assertRaises(TypeError, lambda : s.iloc[2.0:5]) + #self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0]) + #self.assertRaises(TypeError, lambda : s.iloc[2:5.0]) + + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], diff --git a/pandas/tests/test_reshape.py b/pandas/tests/test_reshape.py index 161b740178a4d..c4e75fcb41d45 100644 --- a/pandas/tests/test_reshape.py +++ b/pandas/tests/test_reshape.py @@ -14,6 +14,7 @@ import numpy as np from pandas.util.testing import assert_frame_equal +from numpy.testing import assert_array_equal from pandas.core.reshape import melt, convert_dummies, lreshape, get_dummies import pandas.util.testing as tm @@ -195,11 +196,8 @@ def test_include_na(self): assert_frame_equal(res_na, exp_na) res_just_na = get_dummies([nan], dummy_na=True) - exp_just_na = DataFrame({nan: {0: 1.0}}) - # hack (NaN handling in assert_index_equal) - exp_just_na.columns = res_just_na.columns - assert_frame_equal(res_just_na, exp_just_na) - + exp_just_na = DataFrame(Series(1.0,index=[0]),columns=[nan]) + assert_array_equal(res_just_na.values, exp_just_na.values) class TestConvertDummies(unittest.TestCase): def test_convert_dummies(self): diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 6d3b052154147..98fa5c0a56ccd 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -909,12 +909,11 @@ def test_slice_can_reorder_not_uniquely_indexed(self): result = s[::-1] # it works! def test_slice_float_get_set(self): - result = self.ts[4.0:10.0] - expected = self.ts[4:10] - assert_series_equal(result, expected) - self.ts[4.0:10.0] = 0 - self.assert_((self.ts[4:10] == 0).all()) + self.assertRaises(TypeError, lambda : self.ts[4.0:10.0]) + def f(): + self.ts[4.0:10.0] = 0 + self.assertRaises(TypeError, f) self.assertRaises(TypeError, self.ts.__getitem__, slice(4.5, 10.0)) self.assertRaises(TypeError, self.ts.__setitem__, slice(4.5, 10.0), 0) @@ -932,6 +931,7 @@ def test_slice_floats2(self): self.assert_(len(s.ix[12.5:]) == 7) def test_slice_float64(self): + values = np.arange(10., 50., 2) index = Index(values) @@ -940,19 +940,19 @@ def test_slice_float64(self): s = Series(np.random.randn(20), index=index) result = s[start:end] - expected = s.ix[5:16] + expected = s.iloc[5:16] assert_series_equal(result, expected) - result = s.ix[start:end] + result = s.loc[start:end] assert_series_equal(result, expected) df = DataFrame(np.random.randn(20, 3), index=index) result = df[start:end] - expected = df.ix[5:16] + expected = df.iloc[5:16] tm.assert_frame_equal(result, expected) - result = df.ix[start:end] + result = df.loc[start:end] tm.assert_frame_equal(result, expected) def test_setitem(self): @@ -3254,6 +3254,13 @@ def test_value_counts_nunique(self): #self.assert_(result.index.dtype == 'timedelta64[ns]') self.assert_(result.index.dtype == 'int64') + # basics.rst doc example + series = Series(np.random.randn(500)) + series[20:500] = np.nan + series[10:20] = 5000 + result = series.nunique() + self.assert_(result == 11) + def test_unique(self): # 714 also, dtype=float diff --git a/pandas/util/testing.py b/pandas/util/testing.py index a5a96d3e03cac..b25f85c961798 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -393,23 +393,36 @@ def getCols(k): return string.ascii_uppercase[:k] -def makeStringIndex(k): +# make index +def makeStringIndex(k=10): return Index([rands(10) for _ in range(k)]) -def makeUnicodeIndex(k): +def makeUnicodeIndex(k=10): return Index([randu(10) for _ in range(k)]) -def makeIntIndex(k): +def makeIntIndex(k=10): return Index(lrange(k)) -def makeFloatIndex(k): +def makeFloatIndex(k=10): values = sorted(np.random.random_sample(k)) - np.random.random_sample(1) return Index(values * (10 ** np.random.randint(0, 9))) +def makeDateIndex(k=10): + dt = datetime(2000, 1, 1) + dr = bdate_range(dt, periods=k) + return DatetimeIndex(dr) + + +def makePeriodIndex(k=10): + dt = datetime(2000, 1, 1) + dr = PeriodIndex(start=dt, periods=k, freq='B') + return dr + +# make series def makeFloatSeries(): index = makeStringIndex(N) return Series(randn(N), index=index) @@ -431,41 +444,6 @@ def getSeriesData(): index = makeStringIndex(N) return dict((c, Series(randn(N), index=index)) for c in getCols(K)) - -def makeDataFrame(): - data = getSeriesData() - return DataFrame(data) - - -def getArangeMat(): - return np.arange(N * K).reshape((N, K)) - - -def getMixedTypeDict(): - index = Index(['a', 'b', 'c', 'd', 'e']) - - data = { - 'A': [0., 1., 2., 3., 4.], - 'B': [0., 1., 0., 1., 0.], - 'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'], - 'D': bdate_range('1/1/2009', periods=5) - } - - return index, data - - -def makeDateIndex(k): - dt = datetime(2000, 1, 1) - dr = bdate_range(dt, periods=k) - return DatetimeIndex(dr) - - -def makePeriodIndex(k): - dt = datetime(2000, 1, 1) - dr = PeriodIndex(start=dt, periods=k, freq='B') - return dr - - def makeTimeSeries(nper=None): if nper is None: nper = N @@ -490,6 +468,28 @@ def makeTimeDataFrame(nper=None): def getPeriodData(nper=None): return dict((c, makePeriodSeries(nper)) for c in getCols(K)) +# make frame +def makeDataFrame(): + data = getSeriesData() + return DataFrame(data) + + +def getArangeMat(): + return np.arange(N * K).reshape((N, K)) + + +def getMixedTypeDict(): + index = Index(['a', 'b', 'c', 'd', 'e']) + + data = { + 'A': [0., 1., 2., 3., 4.], + 'B': [0., 1., 0., 1., 0.], + 'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'], + 'D': bdate_range('1/1/2009', periods=5) + } + + return index, data + def makePeriodFrame(nper=None): data = getPeriodData(nper)
closes #236 - CLN: refactor all scalar/slicing code from core/indexing.py to core/index.py on a per-index basis - BUG: provide better `.loc` semantics on floating indicies - API: provide a implementation of `Float64Index` - BUG: raise on indexing with float keys on a non-float index provide better `loc` semantics on `Float64Index` ``` In [1]: s = Series(np.arange(5), index=np.arange(5) * 2.5) In [9]: s.index Out[9]: Float64Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=object) In [2]: s Out[2]: 0.0 0 2.5 1 5.0 2 7.5 3 10.0 4 dtype: int64 In [3]: # label based slicing In [4]: s[1.0:3.0] Out[4]: 2.5 1 dtype: int64 In [5]: s.ix[1.0:3.0] Out[5]: 2.5 1 dtype: int64 In [6]: s.loc[1.0:3.0] Out[6]: 2.5 1 dtype: int64 In [7]: # exact indexing when found In [8]: s[5.0] Out[8]: 2 In [9]: s.loc[5.0] Out[9]: 2 In [10]: s.ix[5.0] Out[10]: 2 In [11]: # non-fallback location based should raise this error (__getitem__,ix fallback here) In [12]: s.loc[4.0] KeyError: 'the label [4.0] is not in the [index]' In [13]: s[4.0] == s[4] Out[13]: True In [14]: s[4] == s[4] Out[14]: True # [],ix,s.ix[2:5] loc is clear about slicing on the values ONLY In [11]: s[2:5] Out[11]: 2.5 1 5.0 2 dtype: int64 In [12]: s.ix[2:5] Out[12]: 2.5 1 5.0 2 dtype: int64 In [2]: s.loc[2:5] Out[2]: 2.5 1 5.0 2 dtype: int64 In [15]: s.loc[2.0:5.0] Out[15]: 2.5 1 5.0 2 dtype: int64 In [16]: s.loc[2.0:5] Out[16]: 2.5 1 5.0 2 dtype: int64 In [17]: s.loc[2.1:5] Out[17]: 2.5 1 5.0 2 dtype: int64 ``` Float Slicing now raises when indexing by a non-integer slicer ``` In [1]: s = Series(np.arange(5)) In [2]: s Out[2]: 0 0 1 1 2 2 3 3 4 4 dtype: int64 In [3]: s[3.5] KeyError: In [4]: s.loc[3.5] KeyError: 'the label [3.5] is not in the [index]' In [5]: s.ix[3.5] KeyError: 'the label [3.5] is not in the [index]' In [6]: s.iloc[3.5] TypeError: the positional label [3.5] is not a proper indexer for this index type (Float64Index) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4850
2013-09-16T14:48:21Z
2013-09-25T20:08:12Z
2013-09-25T20:08:12Z
2014-07-05T04:36:06Z
DOC: isin Example for .13 release notes
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index bc9dcdccfc2e1..dc8c42fd11989 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -519,21 +519,14 @@ of the DataFrame): df[df['A'] > 0] -Consider the ``isin`` method of Series, which returns a boolean vector that is -true wherever the Series elements exist in the passed list. This allows you to -select rows where one or more columns have values you want: +List comprehensions and ``map`` method of Series can also be used to produce +more complex criteria: .. ipython:: python df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'], 'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'], 'c' : randn(7)}) - df2[df2['a'].isin(['one', 'two'])] - -List comprehensions and ``map`` method of Series can also be used to produce -more complex criteria: - -.. ipython:: python # only want 'two' or 'three' criterion = df2['a'].map(lambda x: x.startswith('t')) @@ -553,6 +546,26 @@ and :ref:`Advanced Indexing <indexing.advanced>` you may select along more than df2.loc[criterion & (df2['b'] == 'x'),'b':'c'] +.. _indexing.basics.indexing_isin: + +Indexing with isin +~~~~~~~~~~~~~~~~~~ + +Consider the ``isin`` method of Series, which returns a boolean vector that is +true wherever the Series elements exist in the passed list. This allows you to +select rows where one or more columns have values you want: + +.. ipython:: python + + s = Series(np.arange(5),index=np.arange(5)[::-1],dtype='int64') + + s + + s.isin([2, 4]) + + s[s.isin([2, 4])] + + DataFrame also has an ``isin`` method. When calling ``isin``, pass a set of values as either an array or dict. If values is an array, ``isin`` returns a DataFrame of booleans that is the same shape as the original DataFrame, with True @@ -585,6 +598,17 @@ You can also describe columns using integer location: df.isin(values, iloc=True) +Combine DataFrame's ``isin`` with the ``any()`` and ``all()`` methods to +quickly select subsets of your data that meet a given criteria. +To select a row where each column meets its own criterion: + +.. ipython:: python + + values = {'ids': ['a', 'b'], 'ids2': ['a', 'c'], 'vals': [1, 3]} + + row_mask = df.isin(values).all(1) + + df[row_mask] The :meth:`~pandas.DataFrame.where` Method and Masking ------------------------------------------------------ diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 1f9dc8d7dad81..090be81a3ee7c 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -516,6 +516,22 @@ Experimental For more details see the :ref:`indexing documentation on query <indexing.query>`. + - DataFrame now has an ``isin`` method that can be used to easily check whether the DataFrame's values are contained in an iterable. Use a dictionary if you'd like to check specific iterables for specific columns or rows. + + .. ipython:: python + + df = pd.DataFrame({'A': [1, 2, 3], 'B': ['d', 'e', 'f']}) + df.isin({'A': [1, 2], 'B': ['e', 'f']}) + + The ``isin`` method plays nicely with boolean indexing. To get the rows where each condition is met: + + .. ipython:: python + + mask = df.isin({'A': [1, 2], 'B': ['e', 'f']}) + df[mask.all(1)] + + See the :ref:`documentation<indexing.basics.indexing_isin>` for more. + .. _whatsnew_0130.refactoring: Internal Refactoring
I also fixed a few typos in a separate commit. I can remove that commit if they're going to cause conflicts. Also did I get the syntax correct for this link? > See :ref:`Boolean Indexing<indexing.boolean>` for more
https://api.github.com/repos/pandas-dev/pandas/pulls/4848
2013-09-16T13:39:44Z
2013-09-30T13:57:37Z
2013-09-30T13:57:37Z
2017-04-05T02:05:40Z
ENH: Added xlsxwriter as an ExcelWriter option.
diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt index 6a94d48ad7a5f..2e903102de7b1 100644 --- a/ci/requirements-2.7.txt +++ b/ci/requirements-2.7.txt @@ -8,6 +8,7 @@ numexpr==2.1 tables==2.3.1 matplotlib==1.1.1 openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 patsy==0.1.0 html5lib==1.0b2 diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.txt index a7e9d62e3549b..056b63bbb8591 100644 --- a/ci/requirements-2.7_LOCALE.txt +++ b/ci/requirements-2.7_LOCALE.txt @@ -2,6 +2,7 @@ python-dateutil pytz==2013b xlwt==0.7.5 openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 numpy==1.6.1 cython==0.19.1 diff --git a/ci/requirements-3.2.txt b/ci/requirements-3.2.txt index e907a2fa828f1..b689047019ed7 100644 --- a/ci/requirements-3.2.txt +++ b/ci/requirements-3.2.txt @@ -1,6 +1,7 @@ python-dateutil==2.1 pytz==2013b openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 numpy==1.6.2 cython==0.19.1 diff --git a/ci/requirements-3.3.txt b/ci/requirements-3.3.txt index eb1e725d98040..326098be5f7f4 100644 --- a/ci/requirements-3.3.txt +++ b/ci/requirements-3.3.txt @@ -1,6 +1,7 @@ python-dateutil==2.1 pytz==2013b openpyxl==1.6.2 +xlsxwriter==0.4.3 xlrd==0.9.2 html5lib==1.0b2 numpy==1.7.1 diff --git a/doc/source/10min.rst b/doc/source/10min.rst index 58c5b54968614..705514ac0c364 100644 --- a/doc/source/10min.rst +++ b/doc/source/10min.rst @@ -695,13 +695,13 @@ Writing to an excel file .. ipython:: python - df.to_excel('foo.xlsx', sheet_name='sheet1') + df.to_excel('foo.xlsx', sheet_name='Sheet1') Reading from an excel file .. ipython:: python - pd.read_excel('foo.xlsx', 'sheet1', index_col=None, na_values=['NA']) + pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) .. ipython:: python :suppress: diff --git a/doc/source/install.rst b/doc/source/install.rst index 4472d844c1871..b1dcad9448cfd 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -100,6 +100,8 @@ Optional Dependencies * `openpyxl <http://packages.python.org/openpyxl/>`__, `xlrd/xlwt <http://www.python-excel.org/>`__ * openpyxl version 1.6.1 or higher * Needed for Excel I/O + * `XlsxWriter <https://pypi.python.org/pypi/XlsxWriter>`__ + * Alternative Excel writer. * `boto <https://pypi.python.org/pypi/boto>`__: necessary for Amazon S3 access. * One of `PyQt4 diff --git a/doc/source/io.rst b/doc/source/io.rst index c29af29d2e63f..50d2323fcc8b0 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -1654,7 +1654,7 @@ indices to be parsed. .. code-block:: python - read_excel('path_to_file.xls', Sheet1', parse_cols=[0, 2, 3], index_col=None, na_values=['NA']) + read_excel('path_to_file.xls', 'Sheet1', parse_cols=[0, 2, 3], index_col=None, na_values=['NA']) To write a DataFrame object to a sheet of an Excel file, you can use the ``to_excel`` instance method. The arguments are largely the same as ``to_csv`` @@ -1664,7 +1664,7 @@ written. For example: .. code-block:: python - df.to_excel('path_to_file.xlsx', sheet_name='sheet1') + df.to_excel('path_to_file.xlsx', sheet_name='Sheet1') Files with a ``.xls`` extension will be written using ``xlwt`` and those with a ``.xlsx`` extension will be written using ``openpyxl``. @@ -1677,8 +1677,8 @@ one can use the ExcelWriter class, as in the following example: .. code-block:: python writer = ExcelWriter('path_to_file.xlsx') - df1.to_excel(writer, sheet_name='sheet1') - df2.to_excel(writer, sheet_name='sheet2') + df1.to_excel(writer, sheet_name='Sheet1') + df2.to_excel(writer, sheet_name='Sheet2') writer.save() .. _io.excel.writers: @@ -1693,11 +1693,29 @@ Excel writer engines 1. the ``engine`` keyword argument 2. the filename extension (via the default specified in config options) -``pandas`` only supports ``openpyxl`` for ``.xlsx`` and ``.xlsm`` files and -``xlwt`` for ``.xls`` files. If you have multiple engines installed, you can choose the -engine to use by default via the options ``io.excel.xlsx.writer`` and -``io.excel.xls.writer``. +By default ``pandas`` only supports +`openpyxl <http://packages.python.org/openpyxl/>`__ as a writer for ``.xlsx`` +and ``.xlsm`` files and `xlwt <http://www.python-excel.org/>`__ as a writer for +``.xls`` files. If you have multiple engines installed, you can change the +default engine via the ``io.excel.xlsx.writer`` and ``io.excel.xls.writer`` +options. +For example if the optional `XlsxWriter <http://xlsxwriter.readthedocs.org>`__ +module is installed you can use it as a xlsx writer engine as follows: + +.. code-block:: python + + # By setting the 'engine' in the DataFrame and Panel 'to_excel()' methods. + df.to_excel('path_to_file.xlsx', sheet_name='Sheet1', engine='xlsxwriter') + + # By setting the 'engine' in the ExcelWriter constructor. + writer = ExcelWriter('path_to_file.xlsx', engine='xlsxwriter') + + # Or via pandas configuration. + from pandas import set_option + set_option('io.excel.xlsx.writer', 'xlsxwriter') + + df.to_excel('path_to_file.xlsx', sheet_name='Sheet1') .. _io.hdf5: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f56b6bc00cf15..f8a4aa1eae68f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1357,7 +1357,7 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None, tupleize_cols=tupleize_cols) formatter.save() - def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='', + def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, cols=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None): """ @@ -1367,7 +1367,7 @@ def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='', ---------- excel_writer : string or ExcelWriter object File path or existing ExcelWriter - sheet_name : string, default 'sheet1' + sheet_name : string, default 'Sheet1' Name of sheet which will contain DataFrame na_rep : string, default '' Missing data representation @@ -1398,8 +1398,8 @@ def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='', to the existing workbook. This can be used to save different DataFrames to one workbook >>> writer = ExcelWriter('output.xlsx') - >>> df1.to_excel(writer,'sheet1') - >>> df2.to_excel(writer,'sheet2') + >>> df1.to_excel(writer,'Sheet1') + >>> df2.to_excel(writer,'Sheet2') >>> writer.save() """ from pandas.io.excel import ExcelWriter diff --git a/pandas/io/excel.py b/pandas/io/excel.py index f34c4f99a856d..6ce8eb697268b 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -596,6 +596,7 @@ def _convert_to_style(cls, style_dict, num_format_str=None): Parameters ---------- style_dict: style dictionary to convert + num_format_str: optional number format string """ import xlwt @@ -611,3 +612,95 @@ def _convert_to_style(cls, style_dict, num_format_str=None): register_writer(_XlwtWriter) + +class _XlsxWriter(ExcelWriter): + engine = 'xlsxwriter' + supported_extensions = ('.xlsx',) + + def __init__(self, path, **engine_kwargs): + # Use the xlsxwriter module as the Excel writer. + import xlsxwriter + + super(_XlsxWriter, self).__init__(path, **engine_kwargs) + + self.book = xlsxwriter.Workbook(path, **engine_kwargs) + + def save(self): + """ + Save workbook to disk. + """ + return self.book.close() + + def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0): + # Write the frame cells using xlsxwriter. + + sheet_name = self._get_sheet_name(sheet_name) + + if sheet_name in self.sheets: + wks = self.sheets[sheet_name] + else: + wks = self.book.add_worksheet(sheet_name) + self.sheets[sheet_name] = wks + + style_dict = {} + + for cell in cells: + val = _conv_value(cell.val) + + num_format_str = None + if isinstance(cell.val, datetime.datetime): + num_format_str = "YYYY-MM-DD HH:MM:SS" + if isinstance(cell.val, datetime.date): + num_format_str = "YYYY-MM-DD" + + stylekey = json.dumps(cell.style) + if num_format_str: + stylekey += num_format_str + + if stylekey in style_dict: + style = style_dict[stylekey] + else: + style = self._convert_to_style(cell.style, num_format_str) + style_dict[stylekey] = style + + if cell.mergestart is not None and cell.mergeend is not None: + wks.merge_range(startrow + cell.row, + startrow + cell.mergestart, + startcol + cell.col, + startcol + cell.mergeend, + val, style) + else: + wks.write(startrow + cell.row, + startcol + cell.col, + val, style) + + def _convert_to_style(self, style_dict, num_format_str=None): + """ + converts a style_dict to an xlsxwriter format object + Parameters + ---------- + style_dict: style dictionary to convert + num_format_str: optional number format string + """ + if style_dict is None: + return None + + # Create a XlsxWriter format object. + xl_format = self.book.add_format() + + # Map the cell font to XlsxWriter font properties. + if style_dict.get('font'): + font = style_dict['font'] + if font.get('bold'): + xl_format.set_bold() + + # Map the cell borders to XlsxWriter border properties. + if style_dict.get('borders'): + xl_format.set_border() + + if num_format_str is not None: + xl_format.set_num_format(num_format_str) + + return xl_format + +register_writer(_XlsxWriter) diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index a9822ea0b46c9..e55868f9bcd63 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -1,12 +1,7 @@ # pylint: disable=E1101 -from pandas.compat import StringIO, BytesIO, PY3, u, range, map -from datetime import datetime -from os.path import split as psplit -import csv +from pandas.compat import u, range, map import os -import sys -import re import unittest import nose @@ -14,55 +9,49 @@ from numpy import nan import numpy as np -from pandas import DataFrame, Series, Index, MultiIndex, DatetimeIndex -import pandas.io.parsers as parsers -from pandas.io.parsers import (read_csv, read_table, read_fwf, - TextParser, TextFileReader) +from pandas import DataFrame, Index, MultiIndex +from pandas.io.parsers import read_csv from pandas.io.excel import ( ExcelFile, ExcelWriter, read_excel, _XlwtWriter, _OpenpyxlWriter, register_writer ) -from pandas.util.testing import (assert_almost_equal, - assert_series_equal, - network, - ensure_clean) +from pandas.util.testing import ensure_clean +from pandas.core.config import set_option, get_option import pandas.util.testing as tm import pandas as pd -import pandas.lib as lib -from pandas import compat -from pandas.lib import Timestamp -from pandas.tseries.index import date_range -import pandas.tseries.tools as tools - -from numpy.testing.decorators import slow - -from pandas.parser import OverflowError def _skip_if_no_xlrd(): try: import xlrd ver = tuple(map(int, xlrd.__VERSION__.split(".")[:2])) if ver < (0, 9): - raise nose.SkipTest('xlrd not installed, skipping') + raise nose.SkipTest('xlrd < 0.9, skipping') except ImportError: raise nose.SkipTest('xlrd not installed, skipping') def _skip_if_no_xlwt(): try: - import xlwt + import xlwt # NOQA except ImportError: raise nose.SkipTest('xlwt not installed, skipping') def _skip_if_no_openpyxl(): try: - import openpyxl + import openpyxl # NOQA except ImportError: raise nose.SkipTest('openpyxl not installed, skipping') +def _skip_if_no_xlsxwriter(): + try: + import xlsxwriter # NOQA + except ImportError: + raise nose.SkipTest('xlsxwriter not installed, skipping') + + def _skip_if_no_excelsuite(): _skip_if_no_xlrd() _skip_if_no_xlwt() @@ -78,8 +67,7 @@ def _skip_if_no_excelsuite(): _mixed_frame['foo'] = 'bar' -class ExcelTests(unittest.TestCase): - +class SharedItems(object): def setUp(self): self.dirpath = tm.get_data_path() self.csv1 = os.path.join(self.dirpath, 'test1.csv') @@ -91,6 +79,13 @@ def setUp(self): self.tsframe = _tsframe.copy() self.mixed_frame = _mixed_frame.copy() + def read_csv(self, *args, **kwds): + kwds = kwds.copy() + kwds['engine'] = 'python' + return read_csv(*args, **kwds) + + +class ExcelReaderTests(SharedItems, unittest.TestCase): def test_parse_cols_int(self): _skip_if_no_openpyxl() _skip_if_no_xlrd() @@ -226,24 +221,6 @@ def test_excel_table_sheet_by_index(self): (self.xlsx1, self.csv1)]: self.check_excel_table_sheet_by_index(filename, csvfile) - def check_excel_sheet_by_name_raise(self, ext): - import xlrd - pth = os.path.join(self.dirpath, 'testit.{0}'.format(ext)) - - with ensure_clean(pth) as pth: - gt = DataFrame(np.random.randn(10, 2)) - gt.to_excel(pth) - xl = ExcelFile(pth) - df = xl.parse(0) - tm.assert_frame_equal(gt, df) - - self.assertRaises(xlrd.XLRDError, xl.parse, '0') - - def test_excel_sheet_by_name_raise(self): - _skip_if_no_xlrd() - _skip_if_no_xlwt() - for ext in ('xls', 'xlsx'): - self.check_excel_sheet_by_name_raise(ext) def test_excel_table(self): _skip_if_no_xlrd() @@ -276,7 +253,7 @@ def test_excel_read_buffer(self): pth = os.path.join(self.dirpath, 'test.xlsx') f = open(pth, 'rb') xl = ExcelFile(f) - df = xl.parse('Sheet1', index_col=0, parse_dates=True) + xl.parse('Sheet1', index_col=0, parse_dates=True) def test_xlsx_table(self): _skip_if_no_xlrd() @@ -298,32 +275,44 @@ def test_xlsx_table(self): tm.assert_frame_equal(df4, df.ix[:-1]) tm.assert_frame_equal(df4, df5) - def test_specify_kind_xls(self): - _skip_if_no_xlrd() - xlsx_file = os.path.join(self.dirpath, 'test.xlsx') - xls_file = os.path.join(self.dirpath, 'test.xls') - # succeeds with xlrd 0.8.0, weird - # self.assertRaises(Exception, ExcelFile, xlsx_file, kind='xls') +class ExcelWriterBase(SharedItems): + # Base class for test cases to run with different Excel writers. + # To add a writer test, define two things: + # 1. A check_skip function that skips your tests if your writer isn't + # installed. + # 2. Add a property ext, which is the file extension that your writer + # writes to. + # 3. Add a property engine_name, which is the name of the writer class. + def setUp(self): + self.check_skip() + super(ExcelWriterBase, self).setUp() + self.option_name = 'io.excel.%s.writer' % self.ext + self.prev_engine = get_option(self.option_name) + set_option(self.option_name, self.engine_name) - # ExcelFile(open(xls_file, 'rb'), kind='xls') - # self.assertRaises(Exception, ExcelFile, open(xlsx_file, 'rb'), - # kind='xls') + def tearDown(self): + set_option(self.option_name, self.prev_engine) - def read_csv(self, *args, **kwds): - kwds = kwds.copy() - kwds['engine'] = 'python' - return read_csv(*args, **kwds) + def test_excel_sheet_by_name_raise(self): + _skip_if_no_xlrd() + import xlrd + + ext = self.ext + pth = os.path.join(self.dirpath, 'testit.{0}'.format(ext)) - def test_excel_roundtrip_xls(self): - _skip_if_no_excelsuite() - self._check_extension('xls') + with ensure_clean(pth) as pth: + gt = DataFrame(np.random.randn(10, 2)) + gt.to_excel(pth) + xl = ExcelFile(pth) + df = xl.parse(0) + tm.assert_frame_equal(gt, df) - def test_excel_roundtrip_xlsx(self): - _skip_if_no_excelsuite() - self._check_extension('xlsx') + self.assertRaises(xlrd.XLRDError, xl.parse, '0') - def _check_extension(self, ext): + def test_roundtrip(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel__.' + ext with ensure_clean(path) as path: @@ -357,19 +346,9 @@ def _check_extension(self, ext): recons = read_excel(path, 'test1', index_col=0, na_values=[88,88.0]) tm.assert_frame_equal(self.frame, recons) - def test_excel_roundtrip_xls_mixed(self): + def test_mixed(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - - self._check_extension_mixed('xls') - - def test_excel_roundtrip_xlsx_mixed(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - - self._check_extension_mixed('xlsx') - - def _check_extension_mixed(self, ext): + ext = self.ext path = '__tmp_to_excel_from_excel_mixed__.' + ext with ensure_clean(path) as path: @@ -378,18 +357,10 @@ def _check_extension_mixed(self, ext): recons = reader.parse('test1', index_col=0) tm.assert_frame_equal(self.mixed_frame, recons) - def test_excel_roundtrip_xls_tsframe(self): - _skip_if_no_xlrd() - _skip_if_no_xlwt() - - self._check_extension_tsframe('xls') - def test_excel_roundtrip_xlsx_tsframe(self): - _skip_if_no_openpyxl() + def test_tsframe(self): _skip_if_no_xlrd() - self._check_extension_tsframe('xlsx') - - def _check_extension_tsframe(self, ext): + ext = self.ext path = '__tmp_to_excel_from_excel_tsframe__.' + ext df = tm.makeTimeDataFrame()[:5] @@ -400,15 +371,9 @@ def _check_extension_tsframe(self, ext): recons = reader.parse('test1') tm.assert_frame_equal(df, recons) - def test_excel_roundtrip_xls_int64(self): - _skip_if_no_excelsuite() - self._check_extension_int64('xls') - - def test_excel_roundtrip_xlsx_int64(self): - _skip_if_no_excelsuite() - self._check_extension_int64('xlsx') - - def _check_extension_int64(self, ext): + def test_int64(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_int64__.' + ext with ensure_clean(path) as path: @@ -426,15 +391,9 @@ def _check_extension_int64(self, ext): recons = reader.parse('test1').astype(np.int64) tm.assert_frame_equal(frame, recons, check_dtype=False) - def test_excel_roundtrip_xls_bool(self): - _skip_if_no_excelsuite() - self._check_extension_bool('xls') - - def test_excel_roundtrip_xlsx_bool(self): - _skip_if_no_excelsuite() - self._check_extension_bool('xlsx') - - def _check_extension_bool(self, ext): + def test_bool(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_bool__.' + ext with ensure_clean(path) as path: @@ -452,15 +411,9 @@ def _check_extension_bool(self, ext): recons = reader.parse('test1').astype(np.bool8) tm.assert_frame_equal(frame, recons) - def test_excel_roundtrip_xls_sheets(self): - _skip_if_no_excelsuite() - self._check_extension_sheets('xls') - - def test_excel_roundtrip_xlsx_sheets(self): - _skip_if_no_excelsuite() - self._check_extension_sheets('xlsx') - - def _check_extension_sheets(self, ext): + def test_sheets(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_sheets__.' + ext with ensure_clean(path) as path: @@ -485,15 +438,9 @@ def _check_extension_sheets(self, ext): np.testing.assert_equal('test1', reader.sheet_names[0]) np.testing.assert_equal('test2', reader.sheet_names[1]) - def test_excel_roundtrip_xls_colaliases(self): - _skip_if_no_excelsuite() - self._check_extension_colaliases('xls') - - def test_excel_roundtrip_xlsx_colaliases(self): - _skip_if_no_excelsuite() - self._check_extension_colaliases('xlsx') - - def _check_extension_colaliases(self, ext): + def test_colaliases(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_aliases__.' + ext with ensure_clean(path) as path: @@ -513,15 +460,9 @@ def _check_extension_colaliases(self, ext): xp.columns = col_aliases tm.assert_frame_equal(xp, rs) - def test_excel_roundtrip_xls_indexlabels(self): - _skip_if_no_excelsuite() - self._check_extension_indexlabels('xls') - - def test_excel_roundtrip_xlsx_indexlabels(self): - _skip_if_no_excelsuite() - self._check_extension_indexlabels('xlsx') - - def _check_extension_indexlabels(self, ext): + def test_roundtrip_indexlabels(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_indexlabels__.' + ext with ensure_clean(path) as path: @@ -557,7 +498,7 @@ def _check_extension_indexlabels(self, ext): self.assertEqual(frame.index.names, recons.index.names) # test index_labels in same row as column names - path = '%s.xls' % tm.rands(10) + path = '%s.%s' % (tm.rands(10), ext) with ensure_clean(path) as path: @@ -574,9 +515,8 @@ def _check_extension_indexlabels(self, ext): def test_excel_roundtrip_indexname(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - path = '%s.xls' % tm.rands(10) + path = '%s.%s' % (tm.rands(10), self.ext) df = DataFrame(np.random.randn(10, 4)) df.index.name = 'foo' @@ -592,10 +532,9 @@ def test_excel_roundtrip_indexname(self): def test_excel_roundtrip_datetime(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() # datetime.date, not sure what to test here exactly - path = '__tmp_excel_roundtrip_datetime__.xls' + path = '__tmp_excel_roundtrip_datetime__.' + self.ext tsf = self.tsframe.copy() with ensure_clean(path) as path: @@ -605,86 +544,22 @@ def test_excel_roundtrip_datetime(self): recons = reader.parse('test1') tm.assert_frame_equal(self.tsframe, recons) - def test_ExcelWriter_dispatch(self): - with tm.assertRaisesRegexp(ValueError, 'No engine'): - writer = ExcelWriter('nothing') - - _skip_if_no_openpyxl() - writer = ExcelWriter('apple.xlsx') - tm.assert_isinstance(writer, _OpenpyxlWriter) - - _skip_if_no_xlwt() - writer = ExcelWriter('apple.xls') - tm.assert_isinstance(writer, _XlwtWriter) - - - def test_register_writer(self): - # some awkward mocking to test out dispatch and such actually works - called_save = [] - called_write_cells = [] - class DummyClass(ExcelWriter): - called_save = False - called_write_cells = False - supported_extensions = ['test', 'xlsx', 'xls'] - engine = 'dummy' - - def save(self): - called_save.append(True) - - def write_cells(self, *args, **kwargs): - called_write_cells.append(True) - - def check_called(func): - func() - self.assert_(len(called_save) >= 1) - self.assert_(len(called_write_cells) >= 1) - del called_save[:] - del called_write_cells[:] - - register_writer(DummyClass) - writer = ExcelWriter('something.test') - tm.assert_isinstance(writer, DummyClass) - df = tm.makeCustomDataframe(1, 1) - panel = tm.makePanel() - func = lambda: df.to_excel('something.test') - check_called(func) - check_called(lambda: panel.to_excel('something.test')) - from pandas import set_option, get_option - val = get_option('io.excel.xlsx.writer') - set_option('io.excel.xlsx.writer', 'dummy') - check_called(lambda: df.to_excel('something.xlsx')) - check_called(lambda: df.to_excel('something.xls', engine='dummy')) - set_option('io.excel.xlsx.writer', val) - - - def test_to_excel_periodindex(self): - _skip_if_no_excelsuite() - - for ext in ['xls', 'xlsx']: - path = '__tmp_to_excel_periodindex__.' + ext - frame = self.tsframe - xp = frame.resample('M', kind='period') + _skip_if_no_xlrd() + path = '__tmp_to_excel_periodindex__.' + self.ext + frame = self.tsframe + xp = frame.resample('M', kind='period') - with ensure_clean(path) as path: - xp.to_excel(path, 'sht1') + with ensure_clean(path) as path: + xp.to_excel(path, 'sht1') - reader = ExcelFile(path) - rs = reader.parse('sht1', index_col=0, parse_dates=True) - tm.assert_frame_equal(xp, rs.to_period('M')) + reader = ExcelFile(path) + rs = reader.parse('sht1', index_col=0, parse_dates=True) + tm.assert_frame_equal(xp, rs.to_period('M')) def test_to_excel_multiindex(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - - self._check_excel_multiindex('xls') - - def test_to_excel_multiindex_xlsx(self): - _skip_if_no_xlrd() - _skip_if_no_openpyxl() - self._check_excel_multiindex('xlsx') - - def _check_excel_multiindex(self, ext): + ext = self.ext path = '__tmp_to_excel_multiindex__' + ext + '__.' + ext frame = self.frame @@ -708,15 +583,7 @@ def _check_excel_multiindex(self, ext): def test_to_excel_multiindex_dates(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - self._check_excel_multiindex_dates('xls') - - def test_to_excel_multiindex_xlsx_dates(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - self._check_excel_multiindex_dates('xlsx') - - def _check_excel_multiindex_dates(self, ext): + ext = self.ext path = '__tmp_to_excel_multiindex_dates__' + ext + '__.' + ext # try multiindex with dates @@ -742,83 +609,48 @@ def _check_excel_multiindex_dates(self, ext): self.tsframe.index = old_index # needed if setUP becomes classmethod def test_to_excel_float_format(self): - _skip_if_no_excelsuite() - for ext in ['xls', 'xlsx']: - filename = '__tmp_to_excel_float_format__.' + ext - df = DataFrame([[0.123456, 0.234567, 0.567567], - [12.32112, 123123.2, 321321.2]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - - with ensure_clean(filename) as filename: - df.to_excel(filename, 'test1', float_format='%.2f') - - reader = ExcelFile(filename) - rs = reader.parse('test1', index_col=None) - xp = DataFrame([[0.12, 0.23, 0.57], - [12.32, 123123.20, 321321.20]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - tm.assert_frame_equal(rs, xp) + _skip_if_no_xlrd() + ext = self.ext + filename = '__tmp_to_excel_float_format__.' + ext + df = DataFrame([[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + + with ensure_clean(filename) as filename: + df.to_excel(filename, 'test1', float_format='%.2f') + + reader = ExcelFile(filename) + rs = reader.parse('test1', index_col=None) + xp = DataFrame([[0.12, 0.23, 0.57], + [12.32, 123123.20, 321321.20]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + tm.assert_frame_equal(rs, xp) def test_to_excel_unicode_filename(self): - _skip_if_no_excelsuite() - - for ext in ['xls', 'xlsx']: - filename = u('\u0192u.') + ext - - try: - f = open(filename, 'wb') - except UnicodeEncodeError: - raise nose.SkipTest('no unicode file names on this system') - else: - f.close() - - df = DataFrame([[0.123456, 0.234567, 0.567567], - [12.32112, 123123.2, 321321.2]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - - with ensure_clean(filename) as filename: - df.to_excel(filename, 'test1', float_format='%.2f') - - reader = ExcelFile(filename) - rs = reader.parse('test1', index_col=None) - xp = DataFrame([[0.12, 0.23, 0.57], - [12.32, 123123.20, 321321.20]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - tm.assert_frame_equal(rs, xp) - - def test_to_excel_styleconverter(self): - _skip_if_no_xlwt() - _skip_if_no_openpyxl() - - import xlwt - import openpyxl - - hstyle = {"font": {"bold": True}, - "borders": {"top": "thin", - "right": "thin", - "bottom": "thin", - "left": "thin"}, - "alignment": {"horizontal": "center"}} - xls_style = _XlwtWriter._convert_to_style(hstyle) - self.assertTrue(xls_style.font.bold) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.top) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.right) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.bottom) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.left) - self.assertEquals(xlwt.Alignment.HORZ_CENTER, xls_style.alignment.horz) - - xlsx_style = _OpenpyxlWriter._convert_to_style(hstyle) - self.assertTrue(xlsx_style.font.bold) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.top.border_style) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.right.border_style) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.bottom.border_style) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.left.border_style) - self.assertEquals(openpyxl.style.Alignment.HORIZONTAL_CENTER, - xlsx_style.alignment.horizontal) + _skip_if_no_xlrd() + ext = self.ext + filename = u('\u0192u.') + ext + + try: + f = open(filename, 'wb') + except UnicodeEncodeError: + raise nose.SkipTest('no unicode file names on this system') + else: + f.close() + + df = DataFrame([[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + + with ensure_clean(filename) as filename: + df.to_excel(filename, 'test1', float_format='%.2f') + + reader = ExcelFile(filename) + rs = reader.parse('test1', index_col=None) + xp = DataFrame([[0.12, 0.23, 0.57], + [12.32, 123123.20, 321321.20]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + tm.assert_frame_equal(rs, xp) # def test_to_excel_header_styling_xls(self): @@ -921,14 +753,13 @@ def test_to_excel_styleconverter(self): # self.assertTrue(ws.cell(maddr).merged) # os.remove(filename) def test_excel_010_hemstring(self): - _skip_if_no_excelsuite() - + _skip_if_no_xlrd() from pandas.util.testing import makeCustomDataframe as mkdf # ensure limited functionality in 0.10 # override of #2370 until sorted out in 0.11 def roundtrip(df, header=True, parser_hdr=0): - path = '__tmp__test_xl_010_%s__.xls' % np.random.randint(1, 10000) + path = '__tmp__test_xl_010_%s__.%s' % (np.random.randint(1, 10000), self.ext) df.to_excel(path, header=header) with ensure_clean(path) as path: @@ -972,12 +803,168 @@ def roundtrip(df, header=True, parser_hdr=0): self.assertEqual(res.shape, (1, 2)) self.assertTrue(res.ix[0, 0] is not np.nan) + +class OpenpyxlTests(ExcelWriterBase, unittest.TestCase): + ext = 'xlsx' + engine_name = 'openpyxl' + check_skip = staticmethod(_skip_if_no_openpyxl) + + def test_to_excel_styleconverter(self): + _skip_if_no_openpyxl() + + import openpyxl + + hstyle = {"font": {"bold": True}, + "borders": {"top": "thin", + "right": "thin", + "bottom": "thin", + "left": "thin"}, + "alignment": {"horizontal": "center"}} + + xlsx_style = _OpenpyxlWriter._convert_to_style(hstyle) + self.assertTrue(xlsx_style.font.bold) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.top.border_style) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.right.border_style) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.bottom.border_style) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.left.border_style) + self.assertEquals(openpyxl.style.Alignment.HORIZONTAL_CENTER, + xlsx_style.alignment.horizontal) + + +class XlwtTests(ExcelWriterBase, unittest.TestCase): + ext = 'xls' + engine_name = 'xlwt' + check_skip = staticmethod(_skip_if_no_xlwt) + + def test_to_excel_styleconverter(self): + _skip_if_no_xlwt() + + import xlwt + + hstyle = {"font": {"bold": True}, + "borders": {"top": "thin", + "right": "thin", + "bottom": "thin", + "left": "thin"}, + "alignment": {"horizontal": "center"}} + xls_style = _XlwtWriter._convert_to_style(hstyle) + self.assertTrue(xls_style.font.bold) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.top) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.right) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.bottom) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.left) + self.assertEquals(xlwt.Alignment.HORZ_CENTER, xls_style.alignment.horz) + + +class XlsxWriterTests(ExcelWriterBase, unittest.TestCase): + ext = 'xlsx' + engine_name = 'xlsxwriter' + check_skip = staticmethod(_skip_if_no_xlsxwriter) + + # Override test from the Superclass to use assertAlmostEqual on the + # floating point values read back in from the output XlsxWriter file. + def test_roundtrip_indexlabels(self): + _skip_if_no_xlrd() + ext = self.ext + path = '__tmp_to_excel_from_excel_indexlabels__.' + ext + + with ensure_clean(path) as path: + + self.frame['A'][:5] = nan + + self.frame.to_excel(path, 'test1') + self.frame.to_excel(path, 'test1', cols=['A', 'B']) + self.frame.to_excel(path, 'test1', header=False) + self.frame.to_excel(path, 'test1', index=False) + + # test index_label + frame = (DataFrame(np.random.randn(10, 2)) >= 0) + frame.to_excel(path, 'test1', index_label=['test']) + reader = ExcelFile(path) + recons = reader.parse('test1', index_col=0).astype(np.int64) + frame.index.names = ['test'] + self.assertEqual(frame.index.names, recons.index.names) + + frame = (DataFrame(np.random.randn(10, 2)) >= 0) + frame.to_excel( + path, 'test1', index_label=['test', 'dummy', 'dummy2']) + reader = ExcelFile(path) + recons = reader.parse('test1', index_col=0).astype(np.int64) + frame.index.names = ['test'] + self.assertEqual(frame.index.names, recons.index.names) + + frame = (DataFrame(np.random.randn(10, 2)) >= 0) + frame.to_excel(path, 'test1', index_label='test') + reader = ExcelFile(path) + recons = reader.parse('test1', index_col=0).astype(np.int64) + frame.index.names = ['test'] + self.assertAlmostEqual(frame.index.names, recons.index.names) + + +class ExcelWriterEngineTests(unittest.TestCase): + def test_ExcelWriter_dispatch(self): + with tm.assertRaisesRegexp(ValueError, 'No engine'): + writer = ExcelWriter('nothing') + + _skip_if_no_openpyxl() + writer = ExcelWriter('apple.xlsx') + tm.assert_isinstance(writer, _OpenpyxlWriter) + + _skip_if_no_xlwt() + writer = ExcelWriter('apple.xls') + tm.assert_isinstance(writer, _XlwtWriter) + + + def test_register_writer(self): + # some awkward mocking to test out dispatch and such actually works + called_save = [] + called_write_cells = [] + class DummyClass(ExcelWriter): + called_save = False + called_write_cells = False + supported_extensions = ['test', 'xlsx', 'xls'] + engine = 'dummy' + + def save(self): + called_save.append(True) + + def write_cells(self, *args, **kwargs): + called_write_cells.append(True) + + def check_called(func): + func() + self.assert_(len(called_save) >= 1) + self.assert_(len(called_write_cells) >= 1) + del called_save[:] + del called_write_cells[:] + + register_writer(DummyClass) + writer = ExcelWriter('something.test') + tm.assert_isinstance(writer, DummyClass) + df = tm.makeCustomDataframe(1, 1) + panel = tm.makePanel() + func = lambda: df.to_excel('something.test') + check_called(func) + check_called(lambda: panel.to_excel('something.test')) + from pandas import set_option, get_option + val = get_option('io.excel.xlsx.writer') + set_option('io.excel.xlsx.writer', 'dummy') + check_called(lambda: df.to_excel('something.xlsx')) + check_called(lambda: df.to_excel('something.xls', engine='dummy')) + set_option('io.excel.xlsx.writer', val) + + +class ExcelLegacyTests(SharedItems, unittest.TestCase): def test_deprecated_from_parsers(self): # since 0.12 changed the import path import warnings - with warnings.catch_warnings() as w: + with warnings.catch_warnings(): warnings.filterwarnings(action='ignore', category=FutureWarning) _skip_if_no_xlrd() diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index fc86a78ea684b..3fad8124143ec 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1429,6 +1429,26 @@ def test_to_excel(self): recdf = reader.parse(str(item), index_col=0) assert_frame_equal(df, recdf) + def test_to_excel_xlsxwriter(self): + try: + import xlrd + import xlsxwriter + from pandas.io.excel import ExcelFile + except ImportError: + raise nose.SkipTest + + path = '__tmp__.xlsx' + with ensure_clean(path) as path: + self.panel.to_excel(path, engine='xlsxwriter') + try: + reader = ExcelFile(path) + except ImportError: + raise nose.SkipTest + + for item, df in compat.iteritems(self.panel): + recdf = reader.parse(str(item), index_col=0) + assert_frame_equal(df, recdf) + def test_dropna(self): p = Panel(np.random.randn(4, 5, 6), major_axis=list('abcde')) p.ix[:, ['b', 'd'], 0] = np.nan diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py index b7b4a936a1e90..d9c642372a9bb 100644 --- a/pandas/util/print_versions.py +++ b/pandas/util/print_versions.py @@ -104,6 +104,12 @@ def show_versions(): except: print("xlwt: Not installed") + try: + import xlsxwriter + print("xlsxwriter: %s" % xlsxwriter.__version__) + except: + print("xlsxwriter: Not installed") + try: import sqlalchemy print("sqlalchemy: %s" % sqlalchemy.__version__)
Added xlsxwriter as an optional writer engine. Issue #4542.
https://api.github.com/repos/pandas-dev/pandas/pulls/4847
2013-09-15T22:06:52Z
2013-09-16T21:34:10Z
null
2014-06-20T00:04:29Z
BUG: fix sort_index with one col and ascending list
diff --git a/doc/source/release.rst b/doc/source/release.rst index e4143e3f76a25..793d52223b6f5 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -424,6 +424,10 @@ Bug Fixes across different versions of matplotlib (:issue:`4789`) - Suppressed DeprecationWarning associated with internal calls issued by repr() (:issue:`4391`) - Fixed an issue with a duplicate index and duplicate selector with ``.loc`` (:issue:`4825`) + - Fixed an issue with ``DataFrame.sort_index`` where, when sorting by a + single column and passing a list for ``ascending``, the argument for + ``ascending`` was being interpreted as ``True`` (:issue:`4839`, + :issue:`4846`) pandas 0.12.0 ------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 75f81d20926a1..78ef806a45dcb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2856,7 +2856,7 @@ def sort_index(self, axis=0, by=None, ascending=True, inplace=False, Examples -------- - >>> result = df.sort_index(by=['A', 'B'], ascending=[1, 0]) + >>> result = df.sort_index(by=['A', 'B'], ascending=[True, False]) Returns ------- @@ -2875,6 +2875,9 @@ def sort_index(self, axis=0, by=None, ascending=True, inplace=False, raise ValueError('When sorting by column, axis must be 0 (rows)') if not isinstance(by, (tuple, list)): by = [by] + if com._is_sequence(ascending) and len(by) != len(ascending): + raise ValueError('Length of ascending (%d) != length of by' + ' (%d)' % (len(ascending), len(by))) if len(by) > 1: keys = [] @@ -2900,6 +2903,8 @@ def trans(v): raise ValueError('Cannot sort by duplicate column %s' % str(by)) indexer = k.argsort(kind=kind) + if isinstance(ascending, (tuple, list)): + ascending = ascending[0] if not ascending: indexer = indexer[::-1] elif isinstance(labels, MultiIndex): diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 752fc4c58ff3a..6f6b3bf71c759 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -8796,24 +8796,37 @@ def test_sort_index(self): expected = frame.ix[frame.index[indexer]] assert_frame_equal(sorted_df, expected) + sorted_df = frame.sort(columns='A', ascending=False) + assert_frame_equal(sorted_df, expected) + + # GH4839 + sorted_df = frame.sort(columns=['A'], ascending=[False]) + assert_frame_equal(sorted_df, expected) + # check for now sorted_df = frame.sort(columns='A') + assert_frame_equal(sorted_df, expected[::-1]) expected = frame.sort_index(by='A') assert_frame_equal(sorted_df, expected) - sorted_df = frame.sort(columns='A', ascending=False) - expected = frame.sort_index(by='A', ascending=False) - assert_frame_equal(sorted_df, expected) sorted_df = frame.sort(columns=['A', 'B'], ascending=False) expected = frame.sort_index(by=['A', 'B'], ascending=False) assert_frame_equal(sorted_df, expected) + sorted_df = frame.sort(columns=['A', 'B']) + assert_frame_equal(sorted_df, expected[::-1]) + self.assertRaises(ValueError, frame.sort_index, axis=2, inplace=True) + msg = 'When sorting by column, axis must be 0' with assertRaisesRegexp(ValueError, msg): frame.sort_index(by='A', axis=1) + msg = r'Length of ascending \(5\) != length of by \(2\)' + with assertRaisesRegexp(ValueError, msg): + frame.sort_index(by=['A', 'B'], axis=0, ascending=[True] * 5) + def test_sort_index_multicolumn(self): import random A = np.arange(5).repeat(20)
Fixes #4839. now actually checks the first element of the list
https://api.github.com/repos/pandas-dev/pandas/pulls/4846
2013-09-15T16:52:08Z
2013-09-17T05:40:41Z
2013-09-17T05:40:40Z
2014-06-29T21:06:36Z
BUG: Make lib.maybe_convert_objects work with uint64
diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 11ce27b078b18..365a6c43f7fb4 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3325,11 +3325,6 @@ def form_blocks(arrays, names, axes): else: datetime_items.append((i, k, v)) elif issubclass(v.dtype.type, np.integer): - if v.dtype == np.uint64: - # HACK #2355 definite overflow - if (v > 2 ** 63 - 1).any(): - object_items.append((i, k, v)) - continue int_items.append((i, k, v)) elif v.dtype == np.bool_: bool_items.append((i, k, v)) diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index e0bbc1a4e64c1..093b5cc6325f1 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -425,6 +425,31 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, else: return ints +def maybe_convert_uint64(ndarray[object] objects): + ''' + Try to convert objects into an array of uint64 + ''' + cdef: + Py_ssize_t i, n + ndarray[uint64_t] uints + bint cant_convert = 0 + object val + n = len(objects) + uints = np.empty(n, dtype='uint64') + for i from 0 <= i < n: + val = objects[i] + if not util.is_integer_object(val) or val < 0: + cant_convert = 1 + break + else: + uints[i] = val + + if cant_convert: + return objects + else: + return uints + + def maybe_convert_objects(ndarray[object] objects, bint try_float=0, bint safe=0, bint convert_datetime=0): ''' @@ -460,61 +485,60 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, onan = np.nan fnan = np.nan - for i from 0 <= i < n: - val = objects[i] - - if val is None: - seen_null = 1 - floats[i] = complexes[i] = fnan - elif util.is_bool_object(val): - seen_bool = 1 - bools[i] = val - elif util.is_float_object(val): - floats[i] = complexes[i] = val - seen_float = 1 - elif util.is_datetime64_object(val): - if convert_datetime: - idatetimes[i] = convert_to_tsobject(val, None, None).value - seen_datetime = 1 - else: + try: + for i from 0 <= i < n: + val = objects[i] + + if val is None: + seen_null = 1 + floats[i] = complexes[i] = fnan + elif util.is_bool_object(val): + seen_bool = 1 + bools[i] = val + elif util.is_float_object(val): + floats[i] = complexes[i] = val + seen_float = 1 + elif util.is_datetime64_object(val): + if convert_datetime: + idatetimes[i] = convert_to_tsobject(val, None, None).value + seen_datetime = 1 + else: + seen_object = 1 + # objects[i] = val.astype('O') + break + elif util.is_timedelta64_object(val): seen_object = 1 - # objects[i] = val.astype('O') break - elif util.is_timedelta64_object(val): - seen_object = 1 - break - elif util.is_integer_object(val): - seen_int = 1 - floats[i] = <float64_t> val - complexes[i] = <double complex> val - if not seen_null: - try: + elif util.is_integer_object(val): + seen_int = 1 + floats[i] = <float64_t> val + complexes[i] = <double complex> val + if not seen_null: ints[i] = val - except OverflowError: + elif util.is_complex_object(val): + complexes[i] = val + seen_complex = 1 + elif PyDateTime_Check(val) or util.is_datetime64_object(val): + if convert_datetime: + seen_datetime = 1 + idatetimes[i] = convert_to_tsobject(val, None, None).value + else: + seen_object = 1 + break + elif try_float and not util.is_string_object(val): + # this will convert Decimal objects + try: + floats[i] = float(val) + complexes[i] = complex(val) + seen_float = 1 + except Exception: seen_object = 1 break - elif util.is_complex_object(val): - complexes[i] = val - seen_complex = 1 - elif PyDateTime_Check(val) or util.is_datetime64_object(val): - if convert_datetime: - seen_datetime = 1 - idatetimes[i] = convert_to_tsobject(val, None, None).value else: seen_object = 1 break - elif try_float and not util.is_string_object(val): - # this will convert Decimal objects - try: - floats[i] = float(val) - complexes[i] = complex(val) - seen_float = 1 - except Exception: - seen_object = 1 - break - else: - seen_object = 1 - break + except OverflowError: + return maybe_convert_uint64(objects) seen_numeric = seen_complex or seen_float or seen_int diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index d216cebc1abf3..94d383b386ecf 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -55,6 +55,7 @@ import pandas.lib as lib from numpy.testing.decorators import slow +from nose.tools import assert_equal def _skip_if_no_scipy(): try: @@ -79,13 +80,13 @@ def _check_mixed_float(df, dtype = None): elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): - assert(df.dtypes['A'] == dtypes['A']) + assert_equal(df.dtypes['A'], dtypes['A']) if dtypes.get('B'): - assert(df.dtypes['B'] == dtypes['B']) + assert_equal(df.dtypes['B'], dtypes['B']) if dtypes.get('C'): - assert(df.dtypes['C'] == dtypes['C']) + assert_equal(df.dtypes['C'], dtypes['C']) if dtypes.get('D'): - assert(df.dtypes['D'] == dtypes['D']) + assert_equal(df.dtypes['D'], dtypes['D']) def _check_mixed_int(df, dtype = None): @@ -95,13 +96,13 @@ def _check_mixed_int(df, dtype = None): elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): - assert(df.dtypes['A'] == dtypes['A']) + assert_equal(df.dtypes['A'], dtypes['A']) if dtypes.get('B'): - assert(df.dtypes['B'] == dtypes['B']) + assert_equal(df.dtypes['B'], dtypes['B']) if dtypes.get('C'): - assert(df.dtypes['C'] == dtypes['C']) + assert_equal(df.dtypes['C'], dtypes['C']) if dtypes.get('D'): - assert(df.dtypes['D'] == dtypes['D']) + assert_equal(df.dtypes['D'], dtypes['D']) class CheckIndexing(object): @@ -2225,9 +2226,9 @@ def test_constructor_overflow_int64(self): dtype=np.uint64) result = DataFrame({'a': values}) - self.assert_(result['a'].dtype == object) + self.assert_(result['a'].dtype == np.dtype('uint64')) - # #2355 + # Now #2355 with #4845 fix. data_scores = [(6311132704823138710, 273), (2685045978526272070, 23), (8921811264899370420, 45), (long(17019687244989530680), 270), (long(9930107427299601010), 273)] @@ -2235,7 +2236,7 @@ def test_constructor_overflow_int64(self): data = np.zeros((len(data_scores),), dtype=dtype) data[:] = data_scores df_crawls = DataFrame(data) - self.assert_(df_crawls['uid'].dtype == object) + self.assert_(df_crawls['uid'].dtype == np.dtype('uint64')) def test_is_mixed_type(self): self.assert_(not self.frame._is_mixed_type) @@ -4437,7 +4438,7 @@ def test_arith_flex_frame(self): # overflow in the uint dtype = None if op in ['sub']: - dtype = dict(B = 'object', C = None) + dtype = dict(B = 'uint64', C = None) elif op in ['add','mul']: dtype = dict(C = None) assert_frame_equal(result, exp) @@ -10346,7 +10347,7 @@ def test_constructor_with_convert(self): df = DataFrame({'A' : [2**63] }) result = df['A'] - expected = Series(np.asarray([2**63], np.object_)) + expected = Series(np.asarray([2**63], np.uint64)) assert_series_equal(result, expected) df = DataFrame({'A' : [datetime(2005, 1, 1), True] }) diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py new file mode 100644 index 0000000000000..f7ea224096e72 --- /dev/null +++ b/pandas/tests/test_lib.py @@ -0,0 +1,41 @@ +import unittest +from datetime import datetime + +import pandas.lib as lib +import numpy as np + + +class TestLib(unittest.TestCase): + def test_maybe_convert_objects_uint64(self): + # GH4471 - array with objects too big for int64 + arr = np.array([2 ** 63 + 1], dtype=object) + result = lib.maybe_convert_objects(arr) + expected = np.array([2 ** 63 + 1], dtype='uint64') + self.assertEqual(result.dtype, np.dtype('uint64')) + np.testing.assert_array_equal(result, expected) + + arr2 = np.array([5, 2, 3, 4, 5, 1, 2, 3, 22, 1000, 2**63 + 5, + 2 ** 63 + 1000], dtype=object) + result = lib.maybe_convert_objects(arr2) + expected = arr2.copy().astype('uint64') + self.assertEqual(result.dtype, np.dtype('uint64')) + np.testing.assert_array_equal(result, expected) + + def test_maybe_convert_objects_uint64_unconvertible(self): + # can't convert because negative number + neg = np.array([-5, 2 ** 63 + 5, 3], dtype=object) + neg2 = np.array([2 ** 63 + 100, -3], dtype=object) + # can't convert because of datetime + dt = np.array([datetime(2011, 5, 3), 2 ** 63 + 2], dtype=object) + # can't convert because of complex + cmplx = np.array([2 ** 63 + 5, 1+3j, 22], dtype=object) + # can't convert b/c of float + flt = np.array([3.25, 1, 3, 2 ** 63 +4], dtype=object) + # can't convert b/c of nan + null = np.array([5, 2, 2 ** 63 + 2, np.nan], dtype=object) + null2 = np.array([np.nan, 2 ** 63 + 2], dtype=object) + for arr in (neg, neg2, dt, cmplx, flt, null, null2): + result = lib.maybe_convert_objects(arr.copy()) + self.assertEqual(result.dtype, np.object_) + np.testing.assert_array_equal(result, arr) +
Fixes #4471. Only when it's greater than uint64 max (and not negative, etc.)
https://api.github.com/repos/pandas-dev/pandas/pulls/4845
2013-09-15T15:32:48Z
2014-02-18T20:04:51Z
null
2014-06-19T20:46:34Z
TST: Cleanup Excel tests to make it easier to add and test additional writers
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index a9822ea0b46c9..00536026994c5 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -1,12 +1,7 @@ # pylint: disable=E1101 -from pandas.compat import StringIO, BytesIO, PY3, u, range, map -from datetime import datetime -from os.path import split as psplit -import csv +from pandas.compat import u, range, map import os -import sys -import re import unittest import nose @@ -14,51 +9,36 @@ from numpy import nan import numpy as np -from pandas import DataFrame, Series, Index, MultiIndex, DatetimeIndex -import pandas.io.parsers as parsers -from pandas.io.parsers import (read_csv, read_table, read_fwf, - TextParser, TextFileReader) +from pandas import DataFrame, Index, MultiIndex +from pandas.io.parsers import read_csv from pandas.io.excel import ( ExcelFile, ExcelWriter, read_excel, _XlwtWriter, _OpenpyxlWriter, register_writer ) -from pandas.util.testing import (assert_almost_equal, - assert_series_equal, - network, - ensure_clean) +from pandas.util.testing import ensure_clean import pandas.util.testing as tm import pandas as pd -import pandas.lib as lib -from pandas import compat -from pandas.lib import Timestamp -from pandas.tseries.index import date_range -import pandas.tseries.tools as tools - -from numpy.testing.decorators import slow - -from pandas.parser import OverflowError - def _skip_if_no_xlrd(): try: import xlrd ver = tuple(map(int, xlrd.__VERSION__.split(".")[:2])) if ver < (0, 9): - raise nose.SkipTest('xlrd not installed, skipping') + raise nose.SkipTest('xlrd < 0.9, skipping') except ImportError: raise nose.SkipTest('xlrd not installed, skipping') def _skip_if_no_xlwt(): try: - import xlwt + import xlwt # NOQA except ImportError: raise nose.SkipTest('xlwt not installed, skipping') def _skip_if_no_openpyxl(): try: - import openpyxl + import openpyxl # NOQA except ImportError: raise nose.SkipTest('openpyxl not installed, skipping') @@ -78,8 +58,7 @@ def _skip_if_no_excelsuite(): _mixed_frame['foo'] = 'bar' -class ExcelTests(unittest.TestCase): - +class SharedItems(object): def setUp(self): self.dirpath = tm.get_data_path() self.csv1 = os.path.join(self.dirpath, 'test1.csv') @@ -91,6 +70,13 @@ def setUp(self): self.tsframe = _tsframe.copy() self.mixed_frame = _mixed_frame.copy() + def read_csv(self, *args, **kwds): + kwds = kwds.copy() + kwds['engine'] = 'python' + return read_csv(*args, **kwds) + + +class ExcelReaderTests(SharedItems, unittest.TestCase): def test_parse_cols_int(self): _skip_if_no_openpyxl() _skip_if_no_xlrd() @@ -226,24 +212,6 @@ def test_excel_table_sheet_by_index(self): (self.xlsx1, self.csv1)]: self.check_excel_table_sheet_by_index(filename, csvfile) - def check_excel_sheet_by_name_raise(self, ext): - import xlrd - pth = os.path.join(self.dirpath, 'testit.{0}'.format(ext)) - - with ensure_clean(pth) as pth: - gt = DataFrame(np.random.randn(10, 2)) - gt.to_excel(pth) - xl = ExcelFile(pth) - df = xl.parse(0) - tm.assert_frame_equal(gt, df) - - self.assertRaises(xlrd.XLRDError, xl.parse, '0') - - def test_excel_sheet_by_name_raise(self): - _skip_if_no_xlrd() - _skip_if_no_xlwt() - for ext in ('xls', 'xlsx'): - self.check_excel_sheet_by_name_raise(ext) def test_excel_table(self): _skip_if_no_xlrd() @@ -276,7 +244,7 @@ def test_excel_read_buffer(self): pth = os.path.join(self.dirpath, 'test.xlsx') f = open(pth, 'rb') xl = ExcelFile(f) - df = xl.parse('Sheet1', index_col=0, parse_dates=True) + xl.parse('Sheet1', index_col=0, parse_dates=True) def test_xlsx_table(self): _skip_if_no_xlrd() @@ -298,32 +266,37 @@ def test_xlsx_table(self): tm.assert_frame_equal(df4, df.ix[:-1]) tm.assert_frame_equal(df4, df5) - def test_specify_kind_xls(self): - _skip_if_no_xlrd() - xlsx_file = os.path.join(self.dirpath, 'test.xlsx') - xls_file = os.path.join(self.dirpath, 'test.xls') - # succeeds with xlrd 0.8.0, weird - # self.assertRaises(Exception, ExcelFile, xlsx_file, kind='xls') +class ExcelWriterBase(SharedItems): + # test cases to run with different extensions + # for each writer + # to add a writer test, define two things: + # 1. a check_skip function that skips your tests if your writer isn't + # installed + # 2. add a property ext, which is the file extension that your writer writes to + def setUp(self): + self.check_skip() + super(ExcelWriterBase, self).setUp() - # ExcelFile(open(xls_file, 'rb'), kind='xls') - # self.assertRaises(Exception, ExcelFile, open(xlsx_file, 'rb'), - # kind='xls') + def test_excel_sheet_by_name_raise(self): + _skip_if_no_xlrd() + import xlrd - def read_csv(self, *args, **kwds): - kwds = kwds.copy() - kwds['engine'] = 'python' - return read_csv(*args, **kwds) + ext = self.ext + pth = os.path.join(self.dirpath, 'testit.{0}'.format(ext)) - def test_excel_roundtrip_xls(self): - _skip_if_no_excelsuite() - self._check_extension('xls') + with ensure_clean(pth) as pth: + gt = DataFrame(np.random.randn(10, 2)) + gt.to_excel(pth) + xl = ExcelFile(pth) + df = xl.parse(0) + tm.assert_frame_equal(gt, df) - def test_excel_roundtrip_xlsx(self): - _skip_if_no_excelsuite() - self._check_extension('xlsx') + self.assertRaises(xlrd.XLRDError, xl.parse, '0') - def _check_extension(self, ext): + def test_roundtrip(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel__.' + ext with ensure_clean(path) as path: @@ -357,19 +330,9 @@ def _check_extension(self, ext): recons = read_excel(path, 'test1', index_col=0, na_values=[88,88.0]) tm.assert_frame_equal(self.frame, recons) - def test_excel_roundtrip_xls_mixed(self): + def test_mixed(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - - self._check_extension_mixed('xls') - - def test_excel_roundtrip_xlsx_mixed(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - - self._check_extension_mixed('xlsx') - - def _check_extension_mixed(self, ext): + ext = self.ext path = '__tmp_to_excel_from_excel_mixed__.' + ext with ensure_clean(path) as path: @@ -378,18 +341,10 @@ def _check_extension_mixed(self, ext): recons = reader.parse('test1', index_col=0) tm.assert_frame_equal(self.mixed_frame, recons) - def test_excel_roundtrip_xls_tsframe(self): - _skip_if_no_xlrd() - _skip_if_no_xlwt() - - self._check_extension_tsframe('xls') - def test_excel_roundtrip_xlsx_tsframe(self): - _skip_if_no_openpyxl() + def test_tsframe(self): _skip_if_no_xlrd() - self._check_extension_tsframe('xlsx') - - def _check_extension_tsframe(self, ext): + ext = self.ext path = '__tmp_to_excel_from_excel_tsframe__.' + ext df = tm.makeTimeDataFrame()[:5] @@ -400,15 +355,9 @@ def _check_extension_tsframe(self, ext): recons = reader.parse('test1') tm.assert_frame_equal(df, recons) - def test_excel_roundtrip_xls_int64(self): - _skip_if_no_excelsuite() - self._check_extension_int64('xls') - - def test_excel_roundtrip_xlsx_int64(self): - _skip_if_no_excelsuite() - self._check_extension_int64('xlsx') - - def _check_extension_int64(self, ext): + def test_int64(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_int64__.' + ext with ensure_clean(path) as path: @@ -426,15 +375,9 @@ def _check_extension_int64(self, ext): recons = reader.parse('test1').astype(np.int64) tm.assert_frame_equal(frame, recons, check_dtype=False) - def test_excel_roundtrip_xls_bool(self): - _skip_if_no_excelsuite() - self._check_extension_bool('xls') - - def test_excel_roundtrip_xlsx_bool(self): - _skip_if_no_excelsuite() - self._check_extension_bool('xlsx') - - def _check_extension_bool(self, ext): + def test_bool(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_bool__.' + ext with ensure_clean(path) as path: @@ -452,15 +395,9 @@ def _check_extension_bool(self, ext): recons = reader.parse('test1').astype(np.bool8) tm.assert_frame_equal(frame, recons) - def test_excel_roundtrip_xls_sheets(self): - _skip_if_no_excelsuite() - self._check_extension_sheets('xls') - - def test_excel_roundtrip_xlsx_sheets(self): - _skip_if_no_excelsuite() - self._check_extension_sheets('xlsx') - - def _check_extension_sheets(self, ext): + def test_sheets(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_sheets__.' + ext with ensure_clean(path) as path: @@ -485,15 +422,9 @@ def _check_extension_sheets(self, ext): np.testing.assert_equal('test1', reader.sheet_names[0]) np.testing.assert_equal('test2', reader.sheet_names[1]) - def test_excel_roundtrip_xls_colaliases(self): - _skip_if_no_excelsuite() - self._check_extension_colaliases('xls') - - def test_excel_roundtrip_xlsx_colaliases(self): - _skip_if_no_excelsuite() - self._check_extension_colaliases('xlsx') - - def _check_extension_colaliases(self, ext): + def test_colaliases(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_aliases__.' + ext with ensure_clean(path) as path: @@ -513,15 +444,9 @@ def _check_extension_colaliases(self, ext): xp.columns = col_aliases tm.assert_frame_equal(xp, rs) - def test_excel_roundtrip_xls_indexlabels(self): - _skip_if_no_excelsuite() - self._check_extension_indexlabels('xls') - - def test_excel_roundtrip_xlsx_indexlabels(self): - _skip_if_no_excelsuite() - self._check_extension_indexlabels('xlsx') - - def _check_extension_indexlabels(self, ext): + def test_roundtrip_indexlabels(self): + _skip_if_no_xlrd() + ext = self.ext path = '__tmp_to_excel_from_excel_indexlabels__.' + ext with ensure_clean(path) as path: @@ -557,7 +482,7 @@ def _check_extension_indexlabels(self, ext): self.assertEqual(frame.index.names, recons.index.names) # test index_labels in same row as column names - path = '%s.xls' % tm.rands(10) + path = '%s.%s' % (tm.rands(10), ext) with ensure_clean(path) as path: @@ -574,9 +499,8 @@ def _check_extension_indexlabels(self, ext): def test_excel_roundtrip_indexname(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - path = '%s.xls' % tm.rands(10) + path = '%s.%s' % (tm.rands(10), self.ext) df = DataFrame(np.random.randn(10, 4)) df.index.name = 'foo' @@ -592,10 +516,9 @@ def test_excel_roundtrip_indexname(self): def test_excel_roundtrip_datetime(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() # datetime.date, not sure what to test here exactly - path = '__tmp_excel_roundtrip_datetime__.xls' + path = '__tmp_excel_roundtrip_datetime__.' + self.ext tsf = self.tsframe.copy() with ensure_clean(path) as path: @@ -605,86 +528,22 @@ def test_excel_roundtrip_datetime(self): recons = reader.parse('test1') tm.assert_frame_equal(self.tsframe, recons) - def test_ExcelWriter_dispatch(self): - with tm.assertRaisesRegexp(ValueError, 'No engine'): - writer = ExcelWriter('nothing') - - _skip_if_no_openpyxl() - writer = ExcelWriter('apple.xlsx') - tm.assert_isinstance(writer, _OpenpyxlWriter) - - _skip_if_no_xlwt() - writer = ExcelWriter('apple.xls') - tm.assert_isinstance(writer, _XlwtWriter) - - - def test_register_writer(self): - # some awkward mocking to test out dispatch and such actually works - called_save = [] - called_write_cells = [] - class DummyClass(ExcelWriter): - called_save = False - called_write_cells = False - supported_extensions = ['test', 'xlsx', 'xls'] - engine = 'dummy' - - def save(self): - called_save.append(True) - - def write_cells(self, *args, **kwargs): - called_write_cells.append(True) - - def check_called(func): - func() - self.assert_(len(called_save) >= 1) - self.assert_(len(called_write_cells) >= 1) - del called_save[:] - del called_write_cells[:] - - register_writer(DummyClass) - writer = ExcelWriter('something.test') - tm.assert_isinstance(writer, DummyClass) - df = tm.makeCustomDataframe(1, 1) - panel = tm.makePanel() - func = lambda: df.to_excel('something.test') - check_called(func) - check_called(lambda: panel.to_excel('something.test')) - from pandas import set_option, get_option - val = get_option('io.excel.xlsx.writer') - set_option('io.excel.xlsx.writer', 'dummy') - check_called(lambda: df.to_excel('something.xlsx')) - check_called(lambda: df.to_excel('something.xls', engine='dummy')) - set_option('io.excel.xlsx.writer', val) - - - def test_to_excel_periodindex(self): - _skip_if_no_excelsuite() - - for ext in ['xls', 'xlsx']: - path = '__tmp_to_excel_periodindex__.' + ext - frame = self.tsframe - xp = frame.resample('M', kind='period') + _skip_if_no_xlrd() + path = '__tmp_to_excel_periodindex__.' + self.ext + frame = self.tsframe + xp = frame.resample('M', kind='period') - with ensure_clean(path) as path: - xp.to_excel(path, 'sht1') + with ensure_clean(path) as path: + xp.to_excel(path, 'sht1') - reader = ExcelFile(path) - rs = reader.parse('sht1', index_col=0, parse_dates=True) - tm.assert_frame_equal(xp, rs.to_period('M')) + reader = ExcelFile(path) + rs = reader.parse('sht1', index_col=0, parse_dates=True) + tm.assert_frame_equal(xp, rs.to_period('M')) def test_to_excel_multiindex(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - - self._check_excel_multiindex('xls') - - def test_to_excel_multiindex_xlsx(self): - _skip_if_no_xlrd() - _skip_if_no_openpyxl() - self._check_excel_multiindex('xlsx') - - def _check_excel_multiindex(self, ext): + ext = self.ext path = '__tmp_to_excel_multiindex__' + ext + '__.' + ext frame = self.frame @@ -708,15 +567,7 @@ def _check_excel_multiindex(self, ext): def test_to_excel_multiindex_dates(self): _skip_if_no_xlrd() - _skip_if_no_xlwt() - self._check_excel_multiindex_dates('xls') - - def test_to_excel_multiindex_xlsx_dates(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - self._check_excel_multiindex_dates('xlsx') - - def _check_excel_multiindex_dates(self, ext): + ext = self.ext path = '__tmp_to_excel_multiindex_dates__' + ext + '__.' + ext # try multiindex with dates @@ -742,83 +593,48 @@ def _check_excel_multiindex_dates(self, ext): self.tsframe.index = old_index # needed if setUP becomes classmethod def test_to_excel_float_format(self): - _skip_if_no_excelsuite() - for ext in ['xls', 'xlsx']: - filename = '__tmp_to_excel_float_format__.' + ext - df = DataFrame([[0.123456, 0.234567, 0.567567], - [12.32112, 123123.2, 321321.2]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - - with ensure_clean(filename) as filename: - df.to_excel(filename, 'test1', float_format='%.2f') - - reader = ExcelFile(filename) - rs = reader.parse('test1', index_col=None) - xp = DataFrame([[0.12, 0.23, 0.57], - [12.32, 123123.20, 321321.20]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - tm.assert_frame_equal(rs, xp) + _skip_if_no_xlrd() + ext = self.ext + filename = '__tmp_to_excel_float_format__.' + ext + df = DataFrame([[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + + with ensure_clean(filename) as filename: + df.to_excel(filename, 'test1', float_format='%.2f') + + reader = ExcelFile(filename) + rs = reader.parse('test1', index_col=None) + xp = DataFrame([[0.12, 0.23, 0.57], + [12.32, 123123.20, 321321.20]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + tm.assert_frame_equal(rs, xp) def test_to_excel_unicode_filename(self): - _skip_if_no_excelsuite() - - for ext in ['xls', 'xlsx']: - filename = u('\u0192u.') + ext - - try: - f = open(filename, 'wb') - except UnicodeEncodeError: - raise nose.SkipTest('no unicode file names on this system') - else: - f.close() - - df = DataFrame([[0.123456, 0.234567, 0.567567], - [12.32112, 123123.2, 321321.2]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - - with ensure_clean(filename) as filename: - df.to_excel(filename, 'test1', float_format='%.2f') - - reader = ExcelFile(filename) - rs = reader.parse('test1', index_col=None) - xp = DataFrame([[0.12, 0.23, 0.57], - [12.32, 123123.20, 321321.20]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) - tm.assert_frame_equal(rs, xp) - - def test_to_excel_styleconverter(self): - _skip_if_no_xlwt() - _skip_if_no_openpyxl() - - import xlwt - import openpyxl - - hstyle = {"font": {"bold": True}, - "borders": {"top": "thin", - "right": "thin", - "bottom": "thin", - "left": "thin"}, - "alignment": {"horizontal": "center"}} - xls_style = _XlwtWriter._convert_to_style(hstyle) - self.assertTrue(xls_style.font.bold) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.top) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.right) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.bottom) - self.assertEquals(xlwt.Borders.THIN, xls_style.borders.left) - self.assertEquals(xlwt.Alignment.HORZ_CENTER, xls_style.alignment.horz) - - xlsx_style = _OpenpyxlWriter._convert_to_style(hstyle) - self.assertTrue(xlsx_style.font.bold) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.top.border_style) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.right.border_style) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.bottom.border_style) - self.assertEquals(openpyxl.style.Border.BORDER_THIN, - xlsx_style.borders.left.border_style) - self.assertEquals(openpyxl.style.Alignment.HORIZONTAL_CENTER, - xlsx_style.alignment.horizontal) + _skip_if_no_xlrd() + ext = self.ext + filename = u('\u0192u.') + ext + + try: + f = open(filename, 'wb') + except UnicodeEncodeError: + raise nose.SkipTest('no unicode file names on this system') + else: + f.close() + + df = DataFrame([[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + + with ensure_clean(filename) as filename: + df.to_excel(filename, 'test1', float_format='%.2f') + + reader = ExcelFile(filename) + rs = reader.parse('test1', index_col=None) + xp = DataFrame([[0.12, 0.23, 0.57], + [12.32, 123123.20, 321321.20]], + index=['A', 'B'], columns=['X', 'Y', 'Z']) + tm.assert_frame_equal(rs, xp) # def test_to_excel_header_styling_xls(self): @@ -921,14 +737,13 @@ def test_to_excel_styleconverter(self): # self.assertTrue(ws.cell(maddr).merged) # os.remove(filename) def test_excel_010_hemstring(self): - _skip_if_no_excelsuite() - + _skip_if_no_xlrd() from pandas.util.testing import makeCustomDataframe as mkdf # ensure limited functionality in 0.10 # override of #2370 until sorted out in 0.11 def roundtrip(df, header=True, parser_hdr=0): - path = '__tmp__test_xl_010_%s__.xls' % np.random.randint(1, 10000) + path = '__tmp__test_xl_010_%s__.%s' % (np.random.randint(1, 10000), self.ext) df.to_excel(path, header=header) with ensure_clean(path) as path: @@ -972,12 +787,120 @@ def roundtrip(df, header=True, parser_hdr=0): self.assertEqual(res.shape, (1, 2)) self.assertTrue(res.ix[0, 0] is not np.nan) + +class OpenpyxlTests(ExcelWriterBase, unittest.TestCase): + ext = 'xlsx' + check_skip = staticmethod(_skip_if_no_openpyxl) + + def test_to_excel_styleconverter(self): + _skip_if_no_openpyxl() + + import openpyxl + + hstyle = {"font": {"bold": True}, + "borders": {"top": "thin", + "right": "thin", + "bottom": "thin", + "left": "thin"}, + "alignment": {"horizontal": "center"}} + + xlsx_style = _OpenpyxlWriter._convert_to_style(hstyle) + self.assertTrue(xlsx_style.font.bold) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.top.border_style) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.right.border_style) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.bottom.border_style) + self.assertEquals(openpyxl.style.Border.BORDER_THIN, + xlsx_style.borders.left.border_style) + self.assertEquals(openpyxl.style.Alignment.HORIZONTAL_CENTER, + xlsx_style.alignment.horizontal) + + +class XlwtTests(ExcelWriterBase, unittest.TestCase): + ext = 'xls' + check_skip = staticmethod(_skip_if_no_xlwt) + + def test_to_excel_styleconverter(self): + _skip_if_no_xlwt() + + import xlwt + + hstyle = {"font": {"bold": True}, + "borders": {"top": "thin", + "right": "thin", + "bottom": "thin", + "left": "thin"}, + "alignment": {"horizontal": "center"}} + xls_style = _XlwtWriter._convert_to_style(hstyle) + self.assertTrue(xls_style.font.bold) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.top) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.right) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.bottom) + self.assertEquals(xlwt.Borders.THIN, xls_style.borders.left) + self.assertEquals(xlwt.Alignment.HORZ_CENTER, xls_style.alignment.horz) + +class ExcelWriterEngineTests(unittest.TestCase): + def test_ExcelWriter_dispatch(self): + with tm.assertRaisesRegexp(ValueError, 'No engine'): + writer = ExcelWriter('nothing') + + _skip_if_no_openpyxl() + writer = ExcelWriter('apple.xlsx') + tm.assert_isinstance(writer, _OpenpyxlWriter) + + _skip_if_no_xlwt() + writer = ExcelWriter('apple.xls') + tm.assert_isinstance(writer, _XlwtWriter) + + + def test_register_writer(self): + # some awkward mocking to test out dispatch and such actually works + called_save = [] + called_write_cells = [] + class DummyClass(ExcelWriter): + called_save = False + called_write_cells = False + supported_extensions = ['test', 'xlsx', 'xls'] + engine = 'dummy' + + def save(self): + called_save.append(True) + + def write_cells(self, *args, **kwargs): + called_write_cells.append(True) + + def check_called(func): + func() + self.assert_(len(called_save) >= 1) + self.assert_(len(called_write_cells) >= 1) + del called_save[:] + del called_write_cells[:] + + register_writer(DummyClass) + writer = ExcelWriter('something.test') + tm.assert_isinstance(writer, DummyClass) + df = tm.makeCustomDataframe(1, 1) + panel = tm.makePanel() + func = lambda: df.to_excel('something.test') + check_called(func) + check_called(lambda: panel.to_excel('something.test')) + from pandas import set_option, get_option + val = get_option('io.excel.xlsx.writer') + set_option('io.excel.xlsx.writer', 'dummy') + check_called(lambda: df.to_excel('something.xlsx')) + check_called(lambda: df.to_excel('something.xls', engine='dummy')) + set_option('io.excel.xlsx.writer', val) + + +class ExcelLegacyTests(SharedItems, unittest.TestCase): def test_deprecated_from_parsers(self): # since 0.12 changed the import path import warnings - with warnings.catch_warnings() as w: + with warnings.catch_warnings(): warnings.filterwarnings(action='ignore', category=FutureWarning) _skip_if_no_xlrd()
https://api.github.com/repos/pandas-dev/pandas/pulls/4844
2013-09-15T12:55:37Z
2013-09-15T22:27:34Z
2013-09-15T22:27:34Z
2014-07-16T08:28:24Z
CLN: replace rwproperty with regular property
diff --git a/doc/source/release.rst b/doc/source/release.rst index 62ca11b6cef0b..b3fb032493a18 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -287,6 +287,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Refactor of Series arithmetic with time-like objects (datetime/timedelta/time etc.) into a separate, cleaned up wrapper class. (:issue:`4613`) - Complex compat for ``Series`` with ``ndarray``. (:issue:`4819`) +- Removed unnecessary ``rwproperty`` from codebase in favor of builtin property. (:issue:`4843`) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e22202c65c140..c265d1590af95 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -24,7 +24,6 @@ from pandas.tslib import Timestamp from pandas import compat from pandas.compat import range, lrange, lmap, callable, map, zip -from pandas.util import rwproperty class Block(PandasObject): @@ -1450,22 +1449,22 @@ def shape(self): def itemsize(self): return self.dtype.itemsize - @rwproperty.getproperty + @property def fill_value(self): return self.values.fill_value - @rwproperty.setproperty + @fill_value.setter def fill_value(self, v): # we may need to upcast our fill to match our dtype if issubclass(self.dtype.type, np.floating): v = float(v) self.values.fill_value = v - @rwproperty.getproperty + @property def sp_values(self): return self.values.sp_values - @rwproperty.setproperty + @sp_values.setter def sp_values(self, v): # reset the sparse values self.values = SparseArray( diff --git a/pandas/core/series.py b/pandas/core/series.py index 7d3cce8c80f72..893483f0f2636 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -37,7 +37,6 @@ from pandas import compat from pandas.util.terminal import get_terminal_size from pandas.compat import zip, lzip, u, OrderedDict -from pandas.util import rwproperty import pandas.core.array as pa @@ -797,19 +796,19 @@ def __contains__(self, key): return key in self.index # complex - @rwproperty.getproperty + @property def real(self): return self.values.real - @rwproperty.setproperty + @real.setter def real(self, v): self.values.real = v - @rwproperty.getproperty + @property def imag(self): return self.values.imag - @rwproperty.setproperty + @imag.setter def imag(self, v): self.values.imag = v diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py index 21a054e6fe1a3..537b88db3c1f0 100644 --- a/pandas/sparse/series.py +++ b/pandas/sparse/series.py @@ -21,7 +21,6 @@ import pandas.index as _index from pandas import compat -from pandas.util import rwproperty from pandas.sparse.array import (make_sparse, _sparse_array_op, SparseArray) from pandas._sparse import BlockIndex, IntIndex @@ -213,11 +212,11 @@ def get_values(self): def block(self): return self._data._block - @rwproperty.getproperty + @property def fill_value(self): return self.block.fill_value - @rwproperty.setproperty + @fill_value.setter def fill_value(self, v): self.block.fill_value = v diff --git a/pandas/util/rwproperty.py b/pandas/util/rwproperty.py deleted file mode 100644 index 2d0dada68cc0e..0000000000000 --- a/pandas/util/rwproperty.py +++ /dev/null @@ -1,75 +0,0 @@ -# Read & write properties -# -# Copyright (c) 2006 by Philipp "philiKON" von Weitershausen -# philikon@philikon.de -# -# Freely distributable under the terms of the Zope Public License, v2.1. -# -# See rwproperty.txt for detailed explanations -# -import sys - -__all__ = ['getproperty', 'setproperty', 'delproperty'] - -class rwproperty(object): - - def __new__(cls, func): - name = func.__name__ - - # ugly, but common hack - frame = sys._getframe(1) - locals = frame.f_locals - - if name not in locals: - return cls.createProperty(func) - - oldprop = locals[name] - if isinstance(oldprop, property): - return cls.enhanceProperty(oldprop, func) - - raise TypeError("read & write properties cannot be mixed with " - "other attributes except regular property objects.") - - # this might not be particularly elegant, but it's easy on the eyes - - @staticmethod - def createProperty(func): - raise NotImplementedError - - @staticmethod - def enhanceProperty(oldprop, func): - raise NotImplementedError - -class getproperty(rwproperty): - - @staticmethod - def createProperty(func): - return property(func) - - @staticmethod - def enhanceProperty(oldprop, func): - return property(func, oldprop.fset, oldprop.fdel) - -class setproperty(rwproperty): - - @staticmethod - def createProperty(func): - return property(None, func) - - @staticmethod - def enhanceProperty(oldprop, func): - return property(oldprop.fget, func, oldprop.fdel) - -class delproperty(rwproperty): - - @staticmethod - def createProperty(func): - return property(None, None, func) - - @staticmethod - def enhanceProperty(oldprop, func): - return property(oldprop.fget, oldprop.fset, func) - -if __name__ == "__main__": - import doctest - doctest.testfile('rwproperty.txt')
2.6 added ability to use property-decorated function as decorator for setters and deleters, so pandas/util/rwproperty isn't necessary anymore.
https://api.github.com/repos/pandas-dev/pandas/pulls/4843
2013-09-15T04:59:45Z
2013-09-15T05:12:52Z
2013-09-15T05:12:52Z
2014-06-12T09:08:04Z
BUG: store datetime.date objects in HDFStore as ordinals rather then timetuples to avoid timezone issues (GH2852)
diff --git a/doc/source/release.rst b/doc/source/release.rst index ba7993bfed9bd..791fbc2c516b5 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -114,8 +114,10 @@ Improvements to existing features - ``Panel.to_excel()`` now accepts keyword arguments that will be passed to its ``DataFrame``'s ``to_excel()`` methods. (:issue:`4750`) - allow DataFrame constructor to accept more list-like objects, e.g. list of - ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`42971`) - - DataFrame constructor now accepts a numpy masked record array (:issue:`3478`) + ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`42971`), + thanks @lgautier + - DataFrame constructor now accepts a numpy masked record array (:issue:`3478`), + thanks @jnothman API Changes ~~~~~~~~~~~ @@ -168,6 +170,8 @@ API Changes with data_columns on the same axis - ``select_as_coordinates`` will now return an ``Int64Index`` of the resultant selection set - support ``timedelta64[ns]`` as a serialization type (:issue:`3577`) + - store `datetime.date` objects as ordinals rather then timetuples to avoid timezone issues (:issue:`2852`), + thanks @tavistmorph and @numpand - ``JSON`` - added ``date_unit`` parameter to specify resolution of timestamps. Options diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index d4c1eba1194ac..02548c9af7dc4 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -103,6 +103,8 @@ API changes - add the keyword ``dropna=True`` to ``append`` to change whether ALL nan rows are not written to the store (default is ``True``, ALL nan rows are NOT written), also settable via the option ``io.hdf.dropna_table`` (:issue:`4625`) + - store `datetime.date` objects as ordinals rather then timetuples to avoid timezone issues (:issue:`2852`), + thanks @tavistmorph and @numpand - Changes to how ``Index`` and ``MultiIndex`` handle metadata (``levels``, ``labels``, and ``names``) (:issue:`4039`): diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 9b6a230f6a551..c8224f761ce17 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1740,8 +1740,12 @@ def convert(self, values, nan_rep, encoding): elif dtype == u('timedelta64'): self.data = np.asarray(self.data, dtype='m8[ns]') elif dtype == u('date'): - self.data = np.array( - [date.fromtimestamp(v) for v in self.data], dtype=object) + try: + self.data = np.array( + [date.fromordinal(v) for v in data], dtype=object) + except (ValueError): + self.data = np.array( + [date.fromtimestamp(v) for v in self.data], dtype=object) elif dtype == u('datetime'): self.data = np.array( [datetime.fromtimestamp(v) for v in self.data], @@ -3769,7 +3773,7 @@ def _convert_index(index, encoding=None): return IndexCol(converted, 'datetime', _tables().Time64Col(), index_name=index_name) elif inferred_type == 'date': - converted = np.array([time.mktime(v.timetuple()) for v in values], + converted = np.array([v.toordinal() for v in values], dtype=np.int32) return IndexCol(converted, 'date', _tables().Time32Col(), index_name=index_name) @@ -3809,7 +3813,12 @@ def _unconvert_index(data, kind, encoding=None): index = np.array([datetime.fromtimestamp(v) for v in data], dtype=object) elif kind == u('date'): - index = np.array([date.fromtimestamp(v) for v in data], dtype=object) + try: + index = np.array( + [date.fromordinal(v) for v in data], dtype=object) + except (ValueError): + index = np.array( + [date.fromtimestamp(v) for v in self.data], dtype=object) elif kind in (u('integer'), u('float')): index = np.array(data) elif kind in (u('string')): @@ -4096,10 +4105,12 @@ def stringify(value): elif kind == u('timedelta64') or kind == u('timedelta'): v = _coerce_scalar_to_timedelta_type(v,unit='s').item() return TermValue(int(v), v, kind) - elif (isinstance(v, datetime) or hasattr(v, 'timetuple') - or kind == u('date')): + elif (isinstance(v, datetime) or hasattr(v, 'timetuple')): v = time.mktime(v.timetuple()) return TermValue(v, Timestamp(v), kind) + elif kind == u('date'): + v = v.toordinal() + return TermValue(v, Timestamp.fromordinal(v), kind) elif kind == u('integer'): v = int(float(v)) return TermValue(v, v, kind) diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 3f4ce72198215..861b4dd7567a0 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -1799,6 +1799,47 @@ def compare(a,b): result = store.select('df') assert_frame_equal(result,df) + def test_store_timezone(self): + # GH2852 + # issue storing datetime.date with a timezone as it resets when read back in a new timezone + + import platform + if platform.system() == "Windows": + raise nose.SkipTest("timezone setting not supported on windows") + + import datetime + import time + import os + + orig_tz = os.environ.get('TZ') + + def setTZ(tz): + if tz is None: + try: + del os.environ['TZ'] + except: + pass + else: + os.environ['TZ']=tz + time.tzset() + + try: + + with ensure_clean(self.path) as store: + + setTZ('EST5EDT') + today = datetime.date(2013,9,10) + df = DataFrame([1,2,3], index = [today, today, today]) + store['obj1'] = df + + setTZ('CST6CDT') + result = store['obj1'] + + assert_frame_equal(result, df) + + finally: + setTZ(orig_tz) + def test_append_with_timedelta(self): if _np_version_under1p7: raise nose.SkipTest("requires numpy >= 1.7")
closes #2852 thanks @tavistmorph and @numpand
https://api.github.com/repos/pandas-dev/pandas/pulls/4841
2013-09-14T21:08:45Z
2013-09-14T21:22:25Z
2013-09-14T21:22:25Z
2014-06-26T17:16:21Z
added documentationon pandas.datetime
diff --git a/doc/source/api.rst b/doc/source/api.rst index 538965d0be7ad..4348272030f3c 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -154,6 +154,13 @@ Top-level dealing with datetimes to_datetime +.. currentmodule:: pandas + +.. autosummary:: + :toctree: generated/ + + datetime + Standard moving window functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index 5dcb6c20be69d..814f56288c47d 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -211,6 +211,8 @@ Apply `Turning embeded lists into a multi-index frame <http://stackoverflow.com/questions/17349981/converting-pandas-dataframe-with-categorical-values-into-binary-values>`__ +.. _cookbook.timeseries: + Timeseries ---------- @@ -227,6 +229,56 @@ Turn a matrix with hours in columns and days in rows into a continous row sequen `How to rearrange a python pandas dataframe? <http://stackoverflow.com/questions/15432659/how-to-rearrange-a-python-pandas-dataframe>`__ +Working with timedate-based indices +___________________________________ + +The :func:`pd.datetime` allows for vectorised operations using datetime information stored in a :ref:`timeseries.datetimeindex`. + +Use cases are: + +* calculation of sunsunrise, sunset, daylength +* boolean test of working hours + +An example contributed by a savvy user at `Stackoverflow <http://stackoverflow.com/a/15839530>`_: + +.. ipython:: python + + import pandas as pd + + ###1) create a date column from indiviadual year, month, day columns + df = pd.DataFrame({"year": [1992, 2003, 2014], "month": [2,3,4], "day": [10,20,30]}) + df + + df["Date"] = df.apply(lambda x: pd.datetime(x['year'], x['month'], x['day']), axis=1) + df + + ###2) alternatively, use the equivalent to datetime.datetime.combine + import numpy as np + + #create a hourly timeseries + data_randints = np.random.randint(1, 10, 4000) + data_randints = data_randints.reshape(1000, 4) + ts = pd.Series(randn(1000), index=pd.date_range('1/1/2000', periods=1000, freq='H')) + df = pd.DataFrame(data_randints, index=ts.index, columns=['A', 'B', 'C', 'D']) + df.head() + + #only for examplary purposes: get the date & time from the df.index + # in real world, these would be read in or generated from different columns + df['date'] = df.index.date + df.head() + + df['time'] = df.index.time + df.head() + + #combine both: + df['datetime'] = df.apply((lambda x: pd.datetime.combine(x['date'], x['time'])), axis=1) + df.head() + + #the index could be set to the created column + df = df.set_index(['datetime']) + df.head() + + .. _cookbook.resample: Resampling
This is now a PR based on discussions in #4802
https://api.github.com/repos/pandas-dev/pandas/pulls/4840
2013-09-14T19:48:59Z
2013-09-20T17:18:15Z
null
2014-08-18T12:52:39Z
ENH: Better read_json error when handling bad keys
diff --git a/doc/source/release.rst b/doc/source/release.rst index f7755afe8caae..e4143e3f76a25 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -120,6 +120,8 @@ Improvements to existing features thanks @jnothman - ``__getitem__`` with ``tuple`` key (e.g., ``[:, 2]``) on ``Series`` without ``MultiIndex`` raises ``ValueError`` (:issue:`4759`, :issue:`4837`) + - ``read_json`` now raises a (more informative) ``ValueError`` when the dict + contains a bad key and ``orient='split'`` (:issue:`4730`, :issue:`4838`) API Changes ~~~~~~~~~~~ diff --git a/pandas/io/json.py b/pandas/io/json.py index 737ec1941b353..e3c85fae045d0 100644 --- a/pandas/io/json.py +++ b/pandas/io/json.py @@ -5,15 +5,14 @@ import pandas.json as _json from pandas.tslib import iNaT -from pandas.compat import long +from pandas.compat import long, u from pandas import compat, isnull from pandas import Series, DataFrame, to_datetime from pandas.io.common import get_filepath_or_buffer +import pandas.core.common as com loads = _json.loads dumps = _json.dumps - - ### interface to/from ### @@ -230,6 +229,14 @@ def __init__(self, json, orient, dtype=True, convert_axes=True, self.keep_default_dates = keep_default_dates self.obj = None + def check_keys_split(self, decoded): + "checks that dict has only the appropriate keys for orient='split'" + bad_keys = set(decoded.keys()).difference(set(self._split_keys)) + if bad_keys: + bad_keys = ", ".join(bad_keys) + raise ValueError(u("JSON data had unexpected key(s): %s") % + com.pprint_thing(bad_keys)) + def parse(self): # try numpy @@ -375,6 +382,8 @@ def _try_convert_dates(self): class SeriesParser(Parser): _default_orient = 'index' + _split_keys = ('name', 'index', 'data') + def _parse_no_numpy(self): @@ -385,6 +394,7 @@ def _parse_no_numpy(self): for k, v in compat.iteritems(loads( json, precise_float=self.precise_float))) + self.check_keys_split(decoded) self.obj = Series(dtype=None, **decoded) else: self.obj = Series( @@ -398,6 +408,7 @@ def _parse_numpy(self): decoded = loads(json, dtype=None, numpy=True, precise_float=self.precise_float) decoded = dict((str(k), v) for k, v in compat.iteritems(decoded)) + self.check_keys_split(decoded) self.obj = Series(**decoded) elif orient == "columns" or orient == "index": self.obj = Series(*loads(json, dtype=None, numpy=True, @@ -418,6 +429,7 @@ def _try_convert_types(self): class FrameParser(Parser): _default_orient = 'columns' + _split_keys = ('columns', 'index', 'data') def _parse_numpy(self): @@ -434,6 +446,7 @@ def _parse_numpy(self): decoded = loads(json, dtype=None, numpy=True, precise_float=self.precise_float) decoded = dict((str(k), v) for k, v in compat.iteritems(decoded)) + self.check_keys_split(decoded) self.obj = DataFrame(**decoded) elif orient == "values": self.obj = DataFrame(loads(json, dtype=None, numpy=True, @@ -456,6 +469,7 @@ def _parse_no_numpy(self): for k, v in compat.iteritems(loads( json, precise_float=self.precise_float))) + self.check_keys_split(decoded) self.obj = DataFrame(dtype=None, **decoded) elif orient == "index": self.obj = DataFrame( diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py index 108e779129672..c32fc08dab297 100644 --- a/pandas/io/tests/test_json/test_pandas.py +++ b/pandas/io/tests/test_json/test_pandas.py @@ -252,8 +252,8 @@ def test_frame_from_json_bad_data(self): json = StringIO('{"badkey":["A","B"],' '"index":["2","3"],' '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}') - self.assertRaises(TypeError, read_json, json, - orient="split") + with tm.assertRaisesRegexp(ValueError, r"unexpected key\(s\): badkey"): + read_json(json, orient="split") def test_frame_from_json_nones(self): df = DataFrame([[1, 2], [4, 5, 6]])
(in json data with orient=split) Fixes #4730.
https://api.github.com/repos/pandas-dev/pandas/pulls/4838
2013-09-14T02:58:30Z
2013-09-17T04:40:23Z
2013-09-17T04:40:23Z
2014-06-22T06:43:16Z
ENH: Better Exception when trying to set on Series with tuple-index.
diff --git a/doc/source/release.rst b/doc/source/release.rst index 791fbc2c516b5..62ca11b6cef0b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -118,6 +118,8 @@ Improvements to existing features thanks @lgautier - DataFrame constructor now accepts a numpy masked record array (:issue:`3478`), thanks @jnothman + - ``__getitem__`` with ``tuple`` key (e.g., ``[:, 2]``) on ``Series`` + without ``MultiIndex`` raises ``ValueError`` (:issue:`4759`, :issue:`4837`) API Changes ~~~~~~~~~~~ diff --git a/pandas/core/series.py b/pandas/core/series.py index 8d6591c3acd60..7d3cce8c80f72 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1050,6 +1050,8 @@ def __setitem__(self, key, value): return except TypeError as e: + if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): + raise ValueError("Can only tuple-index with a MultiIndex") # python 3 type errors should be raised if 'unorderable' in str(e): # pragma: no cover raise IndexError(key) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index d2d0bc39fbfc9..c52fcad3d5111 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -1025,10 +1025,10 @@ def test_setslice(self): def test_basic_getitem_setitem_corner(self): # invalid tuples, e.g. self.ts[:, None] vs. self.ts[:, 2] - self.assertRaises(Exception, self.ts.__getitem__, - (slice(None, None), 2)) - self.assertRaises(Exception, self.ts.__setitem__, - (slice(None, None), 2), 2) + with tm.assertRaisesRegexp(ValueError, 'tuple-index'): + self.ts[:, 2] + with tm.assertRaisesRegexp(ValueError, 'tuple-index'): + self.ts[:, 2] = 2 # weird lists. [slice(0, 5)] will work but not two slices result = self.ts[[slice(None, 5)]]
Closes #4759
https://api.github.com/repos/pandas-dev/pandas/pulls/4837
2013-09-14T02:38:04Z
2013-09-15T05:01:34Z
2013-09-15T05:01:34Z
2014-06-19T05:28:50Z
ENH: DataFrame constructor now accepts a numpy masked record array (GH3478)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 1d9fec688525a..ba7993bfed9bd 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -115,6 +115,7 @@ Improvements to existing features its ``DataFrame``'s ``to_excel()`` methods. (:issue:`4750`) - allow DataFrame constructor to accept more list-like objects, e.g. list of ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`42971`) + - DataFrame constructor now accepts a numpy masked record array (:issue:`3478`) API Changes ~~~~~~~~~~~ diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index f0a23b46373e9..d4c1eba1194ac 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -266,6 +266,7 @@ Enhancements ``ind``, passed to scipy.stats.gaussian_kde() (for scipy >= 0.11.0) to set the bandwidth, and to gkde.evaluate() to specify the indicies at which it is evaluated, respecttively. See scipy docs. + - DataFrame constructor now accepts a numpy masked record array (:issue:`3478`) .. _whatsnew_0130.refactoring: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index fb08c5eaa4822..f56b6bc00cf15 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -394,14 +394,22 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, elif isinstance(data, dict): mgr = self._init_dict(data, index, columns, dtype=dtype) elif isinstance(data, ma.MaskedArray): - mask = ma.getmaskarray(data) - if mask.any(): - data, fill_value = _maybe_upcast(data, copy=True) - data[mask] = fill_value + + # masked recarray + if isinstance(data, ma.mrecords.MaskedRecords): + mgr = _masked_rec_array_to_mgr(data, index, columns, dtype, copy) + + # a masked array else: - data = data.copy() - mgr = self._init_ndarray(data, index, columns, dtype=dtype, - copy=copy) + mask = ma.getmaskarray(data) + if mask.any(): + data, fill_value = _maybe_upcast(data, copy=True) + data[mask] = fill_value + else: + data = data.copy() + mgr = self._init_ndarray(data, index, columns, dtype=dtype, + copy=copy) + elif isinstance(data, (np.ndarray, Series)): if data.dtype.names: data_columns = list(data.dtype.names) @@ -1009,13 +1017,7 @@ def from_records(cls, data, index=None, exclude=None, columns=None, arr_columns.append(k) arrays.append(v) - # reorder according to the columns - if len(columns) and len(arr_columns): - indexer = _ensure_index( - arr_columns).get_indexer(columns) - arr_columns = _ensure_index( - [arr_columns[i] for i in indexer]) - arrays = [arrays[i] for i in indexer] + arrays, arr_columns = _reorder_arrays(arrays, arr_columns, columns) elif isinstance(data, (np.ndarray, DataFrame)): arrays, columns = _to_arrays(data, columns) @@ -4817,6 +4819,52 @@ def _to_arrays(data, columns, coerce_float=False, dtype=None): dtype=dtype) +def _masked_rec_array_to_mgr(data, index, columns, dtype, copy): + """ extract from a masked rec array and create the manager """ + + # essentially process a record array then fill it + fill_value = data.fill_value + fdata = ma.getdata(data) + if index is None: + index = _get_names_from_index(fdata) + if index is None: + index = _default_index(len(data)) + index = _ensure_index(index) + + if columns is not None: + columns = _ensure_index(columns) + arrays, arr_columns = _to_arrays(fdata, columns) + + # fill if needed + new_arrays = [] + for fv, arr, col in zip(fill_value, arrays, arr_columns): + mask = ma.getmaskarray(data[col]) + if mask.any(): + arr, fv = _maybe_upcast(arr, fill_value=fv, copy=True) + arr[mask] = fv + new_arrays.append(arr) + + # create the manager + arrays, arr_columns = _reorder_arrays(new_arrays, arr_columns, columns) + if columns is None: + columns = arr_columns + + mgr = _arrays_to_mgr(arrays, arr_columns, index, columns) + + if copy: + mgr = mgr.copy() + return mgr + +def _reorder_arrays(arrays, arr_columns, columns): + # reorder according to the columns + if columns is not None and len(columns) and arr_columns is not None and len(arr_columns): + indexer = _ensure_index( + arr_columns).get_indexer(columns) + arr_columns = _ensure_index( + [arr_columns[i] for i in indexer]) + arrays = [arrays[i] for i in indexer] + return arrays, arr_columns + def _list_to_arrays(data, columns, coerce_float=False, dtype=None): if len(data) > 0 and isinstance(data[0], tuple): content = list(lib.to_object_array_tuples(data).T) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 507c2055e1b68..201212d27c4b0 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -9,7 +9,8 @@ import csv import unittest import nose - +import functools +import itertools from pandas.compat import( map, zip, range, long, lrange, lmap, lzip, OrderedDict, cPickle as pickle, u, StringIO @@ -21,6 +22,7 @@ import numpy as np import numpy.ma as ma from numpy.testing import assert_array_equal +import numpy.ma.mrecords as mrecords import pandas as pan import pandas.core.nanops as nanops @@ -2510,6 +2512,50 @@ def test_constructor_maskedarray_nonfloat(self): self.assertEqual(True, frame['A'][1]) self.assertEqual(False, frame['C'][2]) + def test_constructor_mrecarray(self): + """ + Ensure mrecarray produces frame identical to dict of masked arrays + from GH3479 + + """ + assert_fr_equal = functools.partial(assert_frame_equal, + check_index_type=True, + check_column_type=True, + check_frame_type=True) + arrays = [ + ('float', np.array([1.5, 2.0])), + ('int', np.array([1, 2])), + ('str', np.array(['abc', 'def'])), + ] + for name, arr in arrays[:]: + arrays.append(('masked1_' + name, + np.ma.masked_array(arr, mask=[False, True]))) + arrays.append(('masked_all', np.ma.masked_all((2,)))) + arrays.append(('masked_none', + np.ma.masked_array([1.0, 2.5], mask=False))) + + # call assert_frame_equal for all selections of 3 arrays + for comb in itertools.combinations(arrays, 3): + names, data = zip(*comb) + mrecs = mrecords.fromarrays(data, names=names) + + # fill the comb + comb = dict([ (k, v.filled()) if hasattr(v,'filled') else (k, v) for k, v in comb ]) + + expected = DataFrame(comb,columns=names) + result = DataFrame(mrecs) + assert_fr_equal(result,expected) + + # specify columns + expected = DataFrame(comb,columns=names[::-1]) + result = DataFrame(mrecs, columns=names[::-1]) + assert_fr_equal(result,expected) + + # specify index + expected = DataFrame(comb,columns=names,index=[1,2]) + result = DataFrame(mrecs, index=[1,2]) + assert_fr_equal(result,expected) + def test_constructor_corner(self): df = DataFrame(index=[]) self.assertEqual(df.values.shape, (0, 0))
closes #3478
https://api.github.com/repos/pandas-dev/pandas/pulls/4836
2013-09-13T21:38:46Z
2013-09-14T20:34:53Z
2013-09-14T20:34:53Z
2014-07-16T08:28:13Z
io.pytables: handle start/stop in remove and select_coords
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b08be80dcb16a..f7f7be6c7a321 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -860,7 +860,7 @@ def remove(self, key, where=None, start=None, stop=None): raise KeyError('No object named %s in the file' % key) # remove the node - if where is None: + if where is None and start is None and stop is None: s.group._f_remove(recursive=True) # delete from the table @@ -2139,11 +2139,9 @@ def write(self, **kwargs): raise NotImplementedError( "cannot write on an abstract storer: sublcasses should implement") - def delete(self, where=None, **kwargs): - """support fully deleting the node in its entirety (only) - where - specification must be None - """ - if where is None: + def delete(self, where=None, start=None, stop=None, **kwargs): + """ support fully deleting the node in its entirety (only) - where specification must be None """ + if where is None and start is None and stop is None: self._handle.removeNode(self.group, recursive=True) return None @@ -3700,12 +3698,16 @@ def write_data_chunk(self, indexes, mask, values): except Exception as detail: raise TypeError("tables cannot write this data -> %s" % detail) - def delete(self, where=None, **kwargs): + def delete(self, where=None, start=None, stop=None, **kwargs): # delete all rows (and return the nrows) if where is None or not len(where): - nrows = self.nrows - self._handle.removeNode(self.group, recursive=True) + if start is None and stop is None: + nrows = self.nrows + self._handle.removeNode(self.group, recursive=True) + else: + nrows = self.table.removeRows(start=start, stop=stop) + self.table.flush() return nrows # infer the data kind @@ -3714,7 +3716,7 @@ def delete(self, where=None, **kwargs): # create the selection table = self.table - self.selection = Selection(self, where, **kwargs) + self.selection = Selection(self, where, start=start, stop=stop, **kwargs) values = self.selection.select_coords() # delete the rows in reverse order @@ -4297,7 +4299,7 @@ def select_coords(self): generate the selection """ if self.condition is None: - return np.arange(self.table.nrows) + return np.arange(0, self.table.nrows)[self.start:self.stop] return self.table.table.getWhereList(self.condition.format(), start=self.start, stop=self.stop, diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index f7d01cb1bec96..51e38bdab4469 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2158,6 +2158,68 @@ def test_remove_where(self): # self.assertRaises(ValueError, store.remove, # 'wp2', [('column', ['A', 'D'])]) + def test_remove_startstop(self): + + with ensure_clean_store(self.path) as store: + + wp = tm.makePanel() + + # start + store.put('wp1', wp, format='t') + n = store.remove('wp1', start=32) + assert(n == 120-32) + result = store.select('wp1') + expected = wp.reindex(major_axis=wp.major_axis[:32//4]) + assert_panel_equal(result, expected) + + store.put('wp2', wp, format='t') + n = store.remove('wp2', start=-32) + assert(n == 32) + result = store.select('wp2') + expected = wp.reindex(major_axis=wp.major_axis[:-32//4]) + assert_panel_equal(result, expected) + + # stop + store.put('wp3', wp, format='t') + n = store.remove('wp3', stop=32) + assert(n == 32) + result = store.select('wp3') + expected = wp.reindex(major_axis=wp.major_axis[32//4:]) + assert_panel_equal(result, expected) + + store.put('wp4', wp, format='t') + n = store.remove('wp4', stop=-32) + assert(n == 120-32) + result = store.select('wp4') + expected = wp.reindex(major_axis=wp.major_axis[-32//4:]) + assert_panel_equal(result, expected) + + # start n stop + store.put('wp5', wp, format='t') + n = store.remove('wp5', start=16, stop=-16) + assert(n == 120-32) + result = store.select('wp5') + expected = wp.reindex(major_axis=wp.major_axis[:16//4]+wp.major_axis[-16//4:]) + assert_panel_equal(result, expected) + + store.put('wp6', wp, format='t') + n = store.remove('wp6', start=16, stop=16) + assert(n == 0) + result = store.select('wp6') + expected = wp.reindex(major_axis=wp.major_axis) + assert_panel_equal(result, expected) + + # with where + date = wp.major_axis.take(np.arange(0,30,3)) + crit = Term('major_axis=date') + store.put('wp7', wp, format='t') + n = store.remove('wp7', where=[crit], stop=80) + assert(n == 28) + result = store.select('wp7') + expected = wp.reindex(major_axis=wp.major_axis-wp.major_axis[np.arange(0,20,3)]) + assert_panel_equal(result, expected) + + def test_remove_crit(self): with ensure_clean_store(self.path) as store:
I realized that the start/stop arguments to HDFStore.remove are ignored, so I have a patch to make them work as expected. Moreover I changed Selection.select_coords to also apply start and stop.
https://api.github.com/repos/pandas-dev/pandas/pulls/4835
2013-09-13T20:34:48Z
2014-02-08T14:50:32Z
null
2014-06-13T07:51:18Z
BUG: Fixed an issue with a duplicate index and duplicate selector with loc (GH4825)
diff --git a/doc/source/release.rst b/doc/source/release.rst index e164584674ae5..0ed1f39d72cb5 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -411,6 +411,7 @@ Bug Fixes - Fixed an issue related to ticklocs/ticklabels with log scale bar plots across different versions of matplotlib (:issue:`4789`) - Suppressed DeprecationWarning associated with internal calls issued by repr() (:issue:`4391`) + - Fixed an issue with a duplicate index and duplicate selector with ``.loc`` (:issue:`4825`) pandas 0.12.0 ------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 72196fcdad38d..4f5e6623e1512 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -701,6 +701,11 @@ def _reindex(keys, level=None): new_labels[cur_indexer] = cur_labels new_labels[missing_indexer] = missing_labels + # reindex with the specified axis + ndim = self.obj.ndim + if axis+1 > ndim: + raise AssertionError("invalid indexing error with non-unique index") + # a unique indexer if keyarr_is_unique: new_indexer = (Index(cur_indexer) + Index(missing_indexer)).values @@ -708,12 +713,15 @@ def _reindex(keys, level=None): # we have a non_unique selector, need to use the original indexer here else: - new_indexer = indexer - # reindex with the specified axis - ndim = self.obj.ndim - if axis+1 > ndim: - raise AssertionError("invalid indexing error with non-unique index") + # need to retake to have the same size as the indexer + rindexer = indexer.values + rindexer[~check] = 0 + result = self.obj.take(rindexer, axis=axis, convert=False) + + # reset the new indexer to account for the new size + new_indexer = np.arange(len(result)) + new_indexer[~check] = -1 result = result._reindex_with_indexers({ axis : [ new_labels, new_indexer ] }, copy=True, allow_dups=True) diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 4b17dd5ffd9db..0c862576b09a1 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1436,6 +1436,49 @@ def f(): p.loc[:,:,'C'] = Series([30,32],index=p_orig.items) assert_panel_equal(p,expected) + def test_series_partial_set(self): + # partial set with new index + # Regression from GH4825 + ser = Series([0.1, 0.2], index=[1, 2]) + + # loc + expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3]) + result = ser.loc[[3, 2, 3]] + assert_series_equal(result, expected) + + expected = Series([np.nan, np.nan, np.nan], index=[3, 3, 3]) + result = ser.loc[[3, 3, 3]] + assert_series_equal(result, expected) + + expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3]) + result = ser.loc[[2, 2, 3]] + assert_series_equal(result, expected) + + expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4]) + result = Series([0.1, 0.2, 0.3], index=[1,2,3]).loc[[3,4,4]] + assert_series_equal(result, expected) + + expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3]) + result = Series([0.1, 0.2, 0.3, 0.4], index=[1,2,3,4]).loc[[5,3,3]] + assert_series_equal(result, expected) + + expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4]) + result = Series([0.1, 0.2, 0.3, 0.4], index=[1,2,3,4]).loc[[5,4,4]] + assert_series_equal(result, expected) + + expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2]) + result = Series([0.1, 0.2, 0.3, 0.4], index=[4,5,6,7]).loc[[7,2,2]] + assert_series_equal(result, expected) + + expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5]) + result = Series([0.1, 0.2, 0.3, 0.4], index=[1,2,3,4]).loc[[4,5,5]] + assert_series_equal(result, expected) + + # iloc + expected = Series([0.2,0.2,0.1,0.1], index=[2,2,1,1]) + result = ser.iloc[[1,1,0,0]] + assert_series_equal(result, expected) + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
closes #4825 ``` In [1]: ser = Series([0.1, 0.2], index=[1, 2]) In [3]: ser Out[3]: 1 0.1 2 0.2 dtype: float64 In [4]: ser.loc[[3, 2, 3]] Out[4]: 3 NaN 2 0.2 3 NaN dtype: float64 In [5]: ser.loc[[3, 3, 3]] Out[5]: 3 NaN 3 NaN 3 NaN dtype: float64 In [6]: ser.loc[[2, 2, 3]] Out[6]: 2 0.2 2 0.2 3 NaN dtype: float64 In [7]: ser.iloc[[1,1,0,0]] Out[7]: 2 0.2 2 0.2 1 0.1 1 0.1 dtype: float64 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4833
2013-09-13T14:33:28Z
2013-09-16T12:56:55Z
2013-09-16T12:56:55Z
2014-07-15T19:42:48Z
BUG/VIS: correctly test for yaxis ticklocs across different versions of MPL
diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.txt index 70c398816f23c..a7e9d62e3549b 100644 --- a/ci/requirements-2.7_LOCALE.txt +++ b/ci/requirements-2.7_LOCALE.txt @@ -8,7 +8,7 @@ cython==0.19.1 bottleneck==0.6.0 numexpr==2.1 tables==2.3.1 -matplotlib==1.2.1 +matplotlib==1.3.0 patsy==0.1.0 html5lib==1.0b2 lxml==3.2.1 diff --git a/doc/source/release.rst b/doc/source/release.rst index 124661021f45c..1d9fec688525a 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -396,6 +396,8 @@ Bug Fixes - Fixed bug with reading compressed files in as ``bytes`` rather than ``str`` in Python 3. Simplifies bytes-producing file-handling in Python 3 (:issue:`3963`, :issue:`4785`). + - Fixed an issue related to ticklocs/ticklabels with log scale bar plots + across different versions of matplotlib (:issue:`4789`) pandas 0.12.0 ------------- diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 1583a3c0b52d9..aa989e9d785f8 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -2,6 +2,7 @@ import os import string import unittest +from distutils.version import LooseVersion from datetime import datetime, date, timedelta @@ -34,8 +35,9 @@ def setUpClass(cls): try: import matplotlib as mpl mpl.use('Agg', warn=False) + cls.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') except ImportError: - raise nose.SkipTest + raise nose.SkipTest("matplotlib not installed") def setUp(self): self.ts = tm.makeTimeSeries() @@ -161,6 +163,16 @@ def test_bar_linewidth(self): for r in ax.patches: self.assert_(r.get_linewidth() == 2) + @slow + def test_bar_log(self): + expected = np.array([1., 10., 100., 1000.]) + + if not self.mpl_le_1_2_1: + expected = np.hstack((.1, expected, 1e4)) + + ax = Series([200, 500]).plot(log=True, kind='bar') + assert_array_equal(ax.yaxis.get_ticklocs(), expected) + def test_rotation(self): df = DataFrame(randn(5, 5)) ax = df.plot(rot=30) @@ -342,8 +354,9 @@ def setUpClass(cls): try: import matplotlib as mpl mpl.use('Agg', warn=False) + cls.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') except ImportError: - raise nose.SkipTest + raise nose.SkipTest("matplotlib not installed") def tearDown(self): import matplotlib.pyplot as plt @@ -559,22 +572,31 @@ def test_bar_center(self): ax.patches[0].get_x() + ax.patches[0].get_width()) @slow - def test_bar_log(self): + def test_bar_log_no_subplots(self): # GH3254, GH3298 matplotlib/matplotlib#1882, #1892 # regressions in 1.2.1 + expected = np.array([1., 10.]) + + if not self.mpl_le_1_2_1: + expected = np.hstack((.1, expected, 100)) + # no subplots df = DataFrame({'A': [3] * 5, 'B': lrange(1, 6)}, index=lrange(5)) ax = df.plot(kind='bar', grid=True, log=True) - self.assertEqual(ax.yaxis.get_ticklocs()[0], 1.0) + assert_array_equal(ax.yaxis.get_ticklocs(), expected) + + @slow + def test_bar_log_subplots(self): + expected = np.array([1., 10., 100., 1000.]) + if not self.mpl_le_1_2_1: + expected = np.hstack((.1, expected, 1e4)) - p1 = Series([200, 500]).plot(log=True, kind='bar') - p2 = DataFrame([Series([200, 300]), + ax = DataFrame([Series([200, 300]), Series([300, 500])]).plot(log=True, kind='bar', subplots=True) - (p1.yaxis.get_ticklocs() == np.array([0.625, 1.625])) - (p2[0].yaxis.get_ticklocs() == np.array([1., 10., 100., 1000.])).all() - (p2[1].yaxis.get_ticklocs() == np.array([1., 10., 100., 1000.])).all() + assert_array_equal(ax[0].yaxis.get_ticklocs(), expected) + assert_array_equal(ax[1].yaxis.get_ticklocs(), expected) @slow def test_boxplot(self): diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 9f6f3b08ee508..ce75e755a313f 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -4,6 +4,7 @@ import warnings import re from contextlib import contextmanager +from distutils.version import LooseVersion import numpy as np @@ -1452,7 +1453,13 @@ def f(ax, x, y, w, start=None, log=self.log, **kwds): def _make_plot(self): import matplotlib as mpl + + # mpl decided to make their version string unicode across all Python + # versions for mpl >= 1.3 so we have to call str here for python 2 + mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') + colors = self._get_colors() + ncolors = len(colors) rects = [] labels = [] @@ -1466,19 +1473,18 @@ def _make_plot(self): ax = self._get_ax(i) label = com.pprint_thing(label) kwds = self.kwds.copy() - kwds['color'] = colors[i % len(colors)] + kwds['color'] = colors[i % ncolors] - start =0 + start = 0 if self.log: start = 1 if any(y < 1): # GH3254 - start = 0 if mpl.__version__ == "1.2.1" else None + start = 0 if mpl_le_1_2_1 else None if self.subplots: rect = bar_f(ax, self.ax_pos, y, self.bar_width, - start = start, - **kwds) + start=start, **kwds) ax.set_title(label) elif self.stacked: mask = y > 0 @@ -1489,8 +1495,7 @@ def _make_plot(self): neg_prior = neg_prior + np.where(mask, 0, y) else: rect = bar_f(ax, self.ax_pos + i * 0.75 / K, y, 0.75 / K, - start = start, - label=label, **kwds) + start=start, label=label, **kwds) rects.append(rect) if self.mark_right: labels.append(self._get_marked_label(label, i))
closes #4789
https://api.github.com/repos/pandas-dev/pandas/pulls/4832
2013-09-13T13:29:21Z
2013-09-14T20:31:47Z
2013-09-14T20:31:47Z
2014-07-16T08:28:07Z
TST: Add test case for 0.12 regression with loc from GH4825
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 7a993cbcf07f4..1cc8114de7656 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -704,6 +704,16 @@ def test_getitem_regression(self): result = s[lrange(5)] assert_series_equal(result, s) + def test_loc(self): + # Regression from GH4825 + ser = Series([0.1, 0.2], index=[1, 2]) + result = ser.loc[[2, 3, 2]] + expected = Series([0.2, np.nan, 0.2], index=[2, 3, 2]) + assert_series_equal(result, expected) + result = ser.loc[[2, 2, 3]] + expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3]) + assert_series_equal(result, expected) + def test_getitem_setitem_slice_bug(self): s = Series(lrange(10), lrange(10)) result = s[-12:]
Closes #4825.
https://api.github.com/repos/pandas-dev/pandas/pulls/4831
2013-09-13T11:20:06Z
2013-09-13T22:50:08Z
null
2014-06-24T19:39:00Z
BUG: Fix copy s.t. it always copies index/columns.
diff --git a/doc/source/release.rst b/doc/source/release.rst index 04908ee8c9e03..285cea7938f91 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -455,6 +455,8 @@ Bug Fixes - Tests for fillna on empty Series (:issue:`4346`), thanks @immerrr - Fixed a bug where ``ValueError`` wasn't correctly raised when column names weren't strings (:issue:`4956`) + - Fixed ``copy()`` to shallow copy axes/indices as well and thereby keep + separate metadata. (:issue:`4202`, :issue:`4830`) pandas 0.12.0 ------------- diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index e5071bb4484a6..ce07981793f7b 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1988,7 +1988,7 @@ def transform(self, func, *args, **kwargs): # broadcasting if isinstance(res, Series): - if res.index is obj.index: + if res.index.is_(obj.index): group.T.values[:] = res else: group.values[:] = res diff --git a/pandas/core/index.py b/pandas/core/index.py index f2a22580f16b4..734a6ee15307d 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -16,7 +16,6 @@ import pandas.core.common as com from pandas.core.common import _values_from_object from pandas.core.config import get_option -import warnings __all__ = ['Index'] @@ -27,6 +26,7 @@ def _indexOp(opname): Wrapper function for index comparison operations, to avoid code duplication. """ + def wrapper(self, other): func = getattr(self.view(np.ndarray), opname) result = func(other) @@ -54,6 +54,7 @@ def _shouldbe_timestamp(obj): class Index(FrozenNDArray): + """ Immutable ndarray implementing an ordered, sliceable set. The basic object storing axis labels for all pandas objects @@ -160,7 +161,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, elif np.isscalar(data): raise TypeError('Index(...) must be called with a collection ' - 'of some kind, %s was passed' % repr(data)) + 'of some kind, %s was passed' % repr(data)) else: # other iterable of some kind subarr = com._asarray_tuplesafe(data, dtype=object) @@ -171,7 +172,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, return Int64Index(subarr.astype('i8'), copy=copy, name=name) elif inferred != 'string': if (inferred.startswith('datetime') or - tslib.is_timestamp_array(subarr)): + tslib.is_timestamp_array(subarr)): from pandas.tseries.index import DatetimeIndex return DatetimeIndex(data, copy=copy, name=name, **kwargs) elif inferred == 'period': @@ -234,7 +235,7 @@ def to_series(self): useful with map for returning an indexer based on an index """ import pandas as pd - return pd.Series(self.values,index=self,name=self.name) + return pd.Series(self.values, index=self, name=self.name) def astype(self, dtype): return Index(self.values.astype(dtype), name=self.name, @@ -279,7 +280,7 @@ def _get_names(self): def _set_names(self, values): if len(values) != 1: raise ValueError('Length of new names must be 1, got %d' - % len(values)) + % len(values)) self.name = values[0] names = property(fset=_set_names, fget=_get_names) @@ -335,11 +336,11 @@ def _has_complex_internals(self): def summary(self, name=None): if len(self) > 0: head = self[0] - if hasattr(head,'format') and\ + if hasattr(head, 'format') and\ not isinstance(head, compat.string_types): head = head.format() tail = self[-1] - if hasattr(tail,'format') and\ + if hasattr(tail, 'format') and\ not isinstance(tail, compat.string_types): tail = tail.format() index_summary = ', %s to %s' % (com.pprint_thing(head), @@ -571,7 +572,7 @@ def to_native_types(self, slicer=None, **kwargs): def _format_native_types(self, na_rep='', **kwargs): """ actually format my specific types """ mask = isnull(self) - values = np.array(self,dtype=object,copy=True) + values = np.array(self, dtype=object, copy=True) values[mask] = na_rep return values.tolist() @@ -595,7 +596,7 @@ def identical(self, other): Similar to equals, but check that other comparable attributes are also equal """ return self.equals(other) and all( - ( getattr(self,c,None) == getattr(other,c,None) for c in self._comparables )) + (getattr(self, c, None) == getattr(other, c, None) for c in self._comparables)) def asof(self, label): """ @@ -886,7 +887,8 @@ def set_value(self, arr, key, value): Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ - self._engine.set_value(_values_from_object(arr), _values_from_object(key), value) + self._engine.set_value( + _values_from_object(arr), _values_from_object(key), value) def get_level_values(self, level): """ @@ -1357,7 +1359,7 @@ def slice_locs(self, start=None, end=None): # get_loc will return a boolean array for non_uniques # if we are not monotonic - if isinstance(start_slice,np.ndarray): + if isinstance(start_slice, np.ndarray): raise KeyError("cannot peform a slice operation " "on a non-unique non-monotonic index") @@ -1379,7 +1381,7 @@ def slice_locs(self, start=None, end=None): if not is_unique: # get_loc will return a boolean array for non_uniques - if isinstance(end_slice,np.ndarray): + if isinstance(end_slice, np.ndarray): raise KeyError("cannot perform a slice operation " "on a non-unique non-monotonic index") @@ -1447,6 +1449,7 @@ def drop(self, labels): class Int64Index(Index): + """ Immutable ndarray implementing an ordered, sliceable set. The basic object storing axis labels for all pandas objects. Int64Index is a special case of `Index` @@ -1579,6 +1582,7 @@ def _wrap_joined_index(self, joined, other): class MultiIndex(Index): + """ Implements multi-level, a.k.a. hierarchical, index object for pandas objects @@ -1625,7 +1629,6 @@ def __new__(cls, levels=None, labels=None, sortorder=None, names=None, if names is not None: subarr._set_names(names) - if sortorder is not None: subarr.sortorder = int(sortorder) else: @@ -1636,7 +1639,6 @@ def __new__(cls, levels=None, labels=None, sortorder=None, names=None, def _get_levels(self): return self._levels - def _set_levels(self, levels, copy=False): # This is NOT part of the levels property because it should be # externally not allowed to set levels. User beware if you change @@ -1686,7 +1688,7 @@ def _get_labels(self): def _set_labels(self, labels, copy=False): if len(labels) != self.nlevels: raise ValueError("Length of levels and labels must be the same.") - self._labels = FrozenList(_ensure_frozen(labs,copy=copy)._shallow_copy() + self._labels = FrozenList(_ensure_frozen(labs, copy=copy)._shallow_copy() for labs in labels) def set_labels(self, labels, inplace=False): @@ -1811,13 +1813,13 @@ def _set_names(self, values): values = list(values) if len(values) != self.nlevels: raise ValueError('Length of names (%d) must be same as level ' - '(%d)' % (len(values),self.nlevels)) + '(%d)' % (len(values), self.nlevels)) # set the name for name, level in zip(values, self.levels): level.rename(name, inplace=True) - - names = property(fset=_set_names, fget=_get_names, doc="Names of levels in MultiIndex") + names = property( + fset=_set_names, fget=_get_names, doc="Names of levels in MultiIndex") def _format_native_types(self, **kwargs): return self.tolist() @@ -1845,7 +1847,7 @@ def _get_level_number(self, level): count = self.names.count(level) if count > 1: raise ValueError('The name %s occurs multiple times, use a ' - 'level number' % level) + 'level number' % level) level = self.names.index(level) except ValueError: if not isinstance(level, int): @@ -1980,9 +1982,9 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False, formatted = lev.take(lab).format(formatter=formatter) # we have some NA - mask = lab==-1 + mask = lab == -1 if mask.any(): - formatted = np.array(formatted,dtype=object) + formatted = np.array(formatted, dtype=object) formatted[mask] = na_rep formatted = formatted.tolist() @@ -2000,7 +2002,6 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False, level.append(com.pprint_thing(name, escape_chars=('\t', '\r', '\n')) if name is not None else '') - level.extend(np.array(lev, dtype=object)) result_levels.append(level) @@ -2010,8 +2011,9 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False, if sparsify: sentinal = '' # GH3547 - # use value of sparsify as sentinal, unless it's an obvious "Truthey" value - if sparsify not in [True,1]: + # use value of sparsify as sentinal, unless it's an obvious + # "Truthey" value + if sparsify not in [True, 1]: sentinal = sparsify # little bit of a kludge job for #1217 result_levels = _sparsify(result_levels, @@ -2138,7 +2140,8 @@ def __contains__(self, key): def __reduce__(self): """Necessary for making this object picklable""" object_state = list(np.ndarray.__reduce__(self)) - subclass_state = (list(self.levels), list(self.labels), self.sortorder, list(self.names)) + subclass_state = (list(self.levels), list( + self.labels), self.sortorder, list(self.names)) object_state[2] = (object_state[2], subclass_state) return tuple(object_state) @@ -2490,7 +2493,8 @@ def reindex(self, target, method=None, level=None, limit=None, "with a method or limit") return self[target], target - raise Exception("cannot handle a non-takeable non-unique multi-index!") + raise Exception( + "cannot handle a non-takeable non-unique multi-index!") if not isinstance(target, MultiIndex): if indexer is None: @@ -2685,12 +2689,13 @@ def partial_selection(key): # here we have a completely specified key, but are using some partial string matching here # GH4758 - can_index_exactly = any([ l.is_all_dates and not isinstance(k,compat.string_types) for k, l in zip(key, self.levels) ]) - if any([ l.is_all_dates for k, l in zip(key, self.levels) ]) and not can_index_exactly: + can_index_exactly = any( + [l.is_all_dates and not isinstance(k, compat.string_types) for k, l in zip(key, self.levels)]) + if any([l.is_all_dates for k, l in zip(key, self.levels)]) and not can_index_exactly: indexer = slice(*self.slice_locs(key, key)) # we have a multiple selection here - if not indexer.stop-indexer.start == 1: + if not indexer.stop - indexer.start == 1: return partial_selection(key) key = tuple(self[indexer].tolist()[0]) @@ -2913,7 +2918,8 @@ def _assert_can_do_setop(self, other): def astype(self, dtype): if np.dtype(dtype) != np.object_: - raise TypeError("Setting %s dtype to anything other than object is not supported" % self.__class__) + raise TypeError( + "Setting %s dtype to anything other than object is not supported" % self.__class__) return self._shallow_copy() def insert(self, loc, item): @@ -2935,7 +2941,8 @@ def insert(self, loc, item): if not isinstance(item, tuple): item = (item,) + ('',) * (self.nlevels - 1) elif len(item) != self.nlevels: - raise ValueError('Item must have length equal to number of levels.') + raise ValueError( + 'Item must have length equal to number of levels.') new_levels = [] new_labels = [] @@ -2990,7 +2997,7 @@ def _wrap_joined_index(self, joined, other): # For utility purposes -def _sparsify(label_list, start=0,sentinal=''): +def _sparsify(label_list, start=0, sentinal=''): pivoted = lzip(*label_list) k = len(label_list) @@ -3031,7 +3038,7 @@ def _ensure_index(index_like, copy=False): if isinstance(index_like, list): if type(index_like) != list: index_like = list(index_like) - # #2200 ? + # 2200 ? converted, all_arrays = lib.clean_index_list(index_like) if len(converted) > 0 and all_arrays: @@ -3169,7 +3176,8 @@ def _get_consensus_names(indexes): # find the non-none names, need to tupleify to make # the set hashable, then reverse on return - consensus_names = set([ tuple(i.names) for i in indexes if all(n is not None for n in i.names) ]) + consensus_names = set([tuple(i.names) + for i in indexes if all(n is not None for n in i.names)]) if len(consensus_names) == 1: return list(list(consensus_names)[0]) return [None] * indexes[0].nlevels diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 3ab1bfb2c58ed..8fcb64e6d0eda 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2334,8 +2334,12 @@ def copy(self, deep=True): ------- copy : BlockManager """ - new_axes = list(self.axes) - return self.apply('copy', axes=new_axes, deep=deep, do_integrity_check=False) + if deep: + new_axes = [ax.view() for ax in self.axes] + else: + new_axes = list(self.axes) + return self.apply('copy', axes=new_axes, deep=deep, + ref_items=new_axes[0], do_integrity_check=False) def as_matrix(self, items=None): if len(self.blocks) == 0: diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py index 261443a95b111..ae981180022c7 100644 --- a/pandas/sparse/panel.py +++ b/pandas/sparse/panel.py @@ -235,19 +235,25 @@ def __setstate__(self, state): self._minor_axis = _ensure_index(com._unpickle_array(minor)) self._frames = frames - def copy(self): + def copy(self, deep=True): """ - Make a (shallow) copy of the sparse panel + Make a copy of the sparse panel Returns ------- copy : SparsePanel """ - return SparsePanel(self._frames.copy(), items=self.items, - major_axis=self.major_axis, - minor_axis=self.minor_axis, - default_fill_value=self.default_fill_value, - default_kind=self.default_kind) + + d = self._construct_axes_dict() + if deep: + new_data = dict((k, v.copy(deep=True)) for k, v in compat.iteritems(self._frames)) + d = dict((k, v.copy(deep=True)) for k, v in compat.iteritems(d)) + else: + new_data = self._frames.copy() + d['default_fill_value']=self.default_fill_value + d['default_kind']=self.default_kind + + return SparsePanel(new_data, **d) def to_frame(self, filter_observations=True): """ diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py index 5cb29d717235d..38003f0096df2 100644 --- a/pandas/sparse/series.py +++ b/pandas/sparse/series.py @@ -116,7 +116,7 @@ def __init__(self, data, index=None, sparse_index=None, kind='block', if is_sparse_array: if isinstance(data, SparseSeries) and index is None: - index = data.index + index = data.index.view() elif index is not None: assert(len(index) == len(data)) @@ -125,14 +125,14 @@ def __init__(self, data, index=None, sparse_index=None, kind='block', elif isinstance(data, SparseSeries): if index is None: - index = data.index + index = data.index.view() # extract the SingleBlockManager data = data._data elif isinstance(data, (Series, dict)): if index is None: - index = data.index + index = data.index.view() data = Series(data) data, sparse_index = make_sparse(data, kind=kind, @@ -150,7 +150,7 @@ def __init__(self, data, index=None, sparse_index=None, kind='block', if dtype is not None: data = data.astype(dtype) if index is None: - index = data.index + index = data.index.view() else: data = data.reindex(index, copy=False) @@ -520,7 +520,7 @@ def copy(self, deep=True): if deep: new_data = self._data.copy() - return self._constructor(new_data, index=self.index, + return self._constructor(new_data, sparse_index=self.sp_index, fill_value=self.fill_value, name=self.name) diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index 45543547fd64b..a74872c8f193f 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -787,7 +787,7 @@ def test_copy(self): cp = self.frame.copy() tm.assert_isinstance(cp, SparseDataFrame) assert_sp_frame_equal(cp, self.frame) - self.assert_(cp.index is self.frame.index) + self.assert_(cp.index.is_(self.frame.index)) def test_constructor(self): for col, series in compat.iteritems(self.frame): diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 0bc454d6ef2bc..7b753f5d6a367 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -1736,6 +1736,16 @@ class SafeForSparse(object): _multiprocess_can_split_ = True + def test_copy_index_name_checking(self): + # don't want to be able to modify the index stored elsewhere after + # making a copy + for attr in ('index', 'columns'): + ind = getattr(self.frame, attr) + ind.name = None + cp = self.frame.copy() + getattr(cp, attr).name = 'foo' + self.assert_(getattr(self.frame, attr).name is None) + def test_getitem_pop_assign_name(self): s = self.frame['A'] self.assertEqual(s.name, 'A') @@ -6040,16 +6050,6 @@ def test_copy(self): copy = self.mixed_frame.copy() self.assert_(copy._data is not self.mixed_frame._data) - # def test_copy_index_name_checking(self): - # # don't want to be able to modify the index stored elsewhere after - # # making a copy - - # self.frame.columns.name = None - # cp = self.frame.copy() - # cp.columns.name = 'foo' - - # self.assert_(self.frame.columns.name is None) - def _check_method(self, method='pearson', check_minp=False): if not check_minp: correls = self.frame.corr(method=method) @@ -7630,8 +7630,8 @@ def test_reindex(self): # corner cases - # Same index, copies values - newFrame = self.frame.reindex(self.frame.index) + # Same index, copies values but not index if copy=False + newFrame = self.frame.reindex(self.frame.index, copy=False) self.assert_(newFrame.index is self.frame.index) # length zero diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 3e7ec5c3a3c12..e3c9da3630975 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -202,7 +202,8 @@ def test_is_(self): self.assertFalse(ind.is_(ind[:])) self.assertFalse(ind.is_(ind.view(np.ndarray).view(Index))) self.assertFalse(ind.is_(np.array(range(10)))) - self.assertTrue(ind.is_(ind.view().base)) # quasi-implementation dependent + # quasi-implementation dependent + self.assertTrue(ind.is_(ind.view().base)) ind2 = ind.view() ind2.name = 'bob' self.assertTrue(ind.is_(ind2)) @@ -441,7 +442,7 @@ def test_is_all_dates(self): def test_summary(self): self._check_method_works(Index.summary) # GH3869 - ind = Index(['{other}%s',"~:{range}:0"], name='A') + ind = Index(['{other}%s', "~:{range}:0"], name='A') result = ind.summary() # shouldn't be formatted accidentally. self.assert_('~:{range}:0' in result) @@ -1182,8 +1183,8 @@ def test_astype(self): assert_copy(actual.labels, expected.labels) self.check_level_names(actual, expected.names) - assertRaisesRegexp(TypeError, "^Setting.*dtype.*object", self.index.astype, np.dtype(int)) - + with assertRaisesRegexp(TypeError, "^Setting.*dtype.*object"): + self.index.astype(np.dtype(int)) def test_constructor_single_level(self): single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']], @@ -1230,7 +1231,6 @@ def test_copy(self): self.assert_multiindex_copied(i_copy, self.index) - def test_shallow_copy(self): i_copy = self.index._shallow_copy() @@ -1497,10 +1497,11 @@ def test_slice_locs_with_type_mismatch(self): df = tm.makeCustomDataframe(5, 5) stacked = df.stack() idx = stacked.index - assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs, timedelta(seconds=30)) + with assertRaisesRegexp(TypeError, '^Level type mismatch'): + idx.slice_locs(timedelta(seconds=30)) # TODO: Try creating a UnicodeDecodeError in exception message - assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs, - df.index[1], (16, "a")) + with assertRaisesRegexp(TypeError, '^Level type mismatch'): + idx.slice_locs(df.index[1], (16, "a")) def test_slice_locs_not_sorted(self): index = MultiIndex(levels=[Index(lrange(4)), @@ -1672,7 +1673,7 @@ def test_format_sparse_config(self): warnings.filterwarnings('ignore', category=FutureWarning, module=".*format") - # #1538 + # GH1538 pd.set_option('display.multi_sparse', False) result = self.index.format() @@ -1734,11 +1735,11 @@ def test_identical(self): mi2 = self.index.copy() self.assert_(mi.identical(mi2)) - mi = mi.set_names(['new1','new2']) + mi = mi.set_names(['new1', 'new2']) self.assert_(mi.equals(mi2)) self.assert_(not mi.identical(mi2)) - mi2 = mi2.set_names(['new1','new2']) + mi2 = mi2.set_names(['new1', 'new2']) self.assert_(mi.identical(mi2)) def test_is_(self): @@ -1877,7 +1878,7 @@ def test_diff(self): expected.names = first.names self.assertEqual(first.names, result.names) assertRaisesRegexp(TypeError, "other must be a MultiIndex or a list" - " of tuples", first.diff, [1,2,3,4,5]) + " of tuples", first.diff, [1, 2, 3, 4, 5]) def test_from_tuples(self): assertRaisesRegexp(TypeError, 'Cannot infer number of levels from' diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index d3d4368d8028e..2c8394bfde285 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1195,11 +1195,11 @@ def test_count(self): result = frame.count(level='b') expect = self.frame.count(level=1) - assert_frame_equal(result, expect) + assert_frame_equal(result, expect, check_names=False) result = frame.count(level='a') expect = self.frame.count(level=0) - assert_frame_equal(result, expect) + assert_frame_equal(result, expect, check_names=False) series = self.series.copy() series.index.names = ['a', 'b'] diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index c78823779f6d0..a61212b341fa7 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -61,6 +61,13 @@ class SafeForLongAndSparse(object): def test_repr(self): foo = repr(self.panel) + def test_copy_names(self): + for attr in ('major_axis', 'minor_axis'): + getattr(self.panel, attr).name = None + cp = self.panel.copy() + getattr(cp, attr).name = 'foo' + self.assert_(getattr(self.panel, attr).name is None) + def test_iter(self): tm.equalContents(list(self.panel), self.panel.items) diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 4f7e75b401216..1ce909b57402f 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -762,11 +762,6 @@ def test_reindex(self): major=self.panel4d.major_axis, minor=self.panel4d.minor_axis) - assert(result.labels is self.panel4d.labels) - assert(result.items is self.panel4d.items) - assert(result.major_axis is self.panel4d.major_axis) - assert(result.minor_axis is self.panel4d.minor_axis) - # don't necessarily copy result = self.panel4d.reindex() assert_panel4d_equal(result,self.panel4d) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 60dd42865818c..b2c5782d56b1f 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -64,14 +64,17 @@ def test_copy_name(self): result = self.ts.copy() self.assertEquals(result.name, self.ts.name) - # def test_copy_index_name_checking(self): - # don't want to be able to modify the index stored elsewhere after - # making a copy + def test_copy_index_name_checking(self): + # don't want to be able to modify the index stored elsewhere after + # making a copy - # self.ts.index.name = None - # cp = self.ts.copy() - # cp.index.name = 'foo' - # self.assert_(self.ts.index.name is None) + self.ts.index.name = None + self.assert_(self.ts.index.name is None) + self.assert_(self.ts is self.ts) + cp = self.ts.copy() + cp.index.name = 'foo' + print(self.ts.index.name) + self.assert_(self.ts.index.name is None) def test_append_preserve_name(self): result = self.ts[:5].append(self.ts[5:]) @@ -4270,7 +4273,8 @@ def test_align_sameindex(self): def test_reindex(self): identity = self.series.reindex(self.series.index) - self.assertEqual(id(self.series.index), id(identity.index)) + self.assert_(np.may_share_memory(self.series.index, identity.index)) + self.assert_(identity.index.is_(self.series.index)) subIndex = self.series.index[10:20] subSeries = self.series.reindex(subIndex)
Fixes #4202 (and maybe some others too). Only copies index/columns with `deep=True` on `BlockManager`. Plus some tests...yay!
https://api.github.com/repos/pandas-dev/pandas/pulls/4830
2013-09-13T00:56:27Z
2013-09-24T03:43:59Z
2013-09-24T03:43:59Z
2014-06-13T02:11:01Z
ENH/API: allow DataFrame constructor to better accept list-like collections (GH3783,GH4297)
diff --git a/doc/source/release.rst b/doc/source/release.rst index c80ddd01cdf07..140c3bc836fdb 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -113,6 +113,8 @@ Improvements to existing features ``io.excel.xls.writer``. (:issue:`4745`, :issue:`4750`) - ``Panel.to_excel()`` now accepts keyword arguments that will be passed to its ``DataFrame``'s ``to_excel()`` methods. (:issue:`4750`) + - allow DataFrame constructor to accept more list-like objects, e.g. list of + ``collections.Sequence`` and ``array.Array`` objects (:issue:`3783`,:issue:`42971`) API Changes ~~~~~~~~~~~ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index bd601c5c8408e..fb08c5eaa4822 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -16,6 +16,7 @@ import sys import collections import warnings +import types from numpy import nan as NA import numpy as np @@ -24,7 +25,7 @@ from pandas.core.common import (isnull, notnull, PandasError, _try_sort, _default_index, _maybe_upcast, _is_sequence, _infer_dtype_from_scalar, _values_from_object, - _coerce_to_dtypes, _DATELIKE_DTYPES) + _coerce_to_dtypes, _DATELIKE_DTYPES, is_list_like) from pandas.core.generic import NDFrame from pandas.core.index import Index, MultiIndex, _ensure_index from pandas.core.indexing import (_NDFrameIndexer, _maybe_droplevels, @@ -413,12 +414,14 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, else: mgr = self._init_ndarray(data, index, columns, dtype=dtype, copy=copy) - elif isinstance(data, list): + elif isinstance(data, (list, types.GeneratorType)): + if isinstance(data, types.GeneratorType): + data = list(data) if len(data) > 0: if index is None and isinstance(data[0], Series): index = _get_names_from_index(data) - if isinstance(data[0], (list, tuple, collections.Mapping, Series)): + if is_list_like(data[0]) and getattr(data[0],'ndim',0) <= 1: arrays, columns = _to_arrays(data, columns, dtype=dtype) columns = _ensure_index(columns) @@ -4545,7 +4548,7 @@ def isin(self, values, iloc=False): else: - if not com.is_list_like(values): + if not is_list_like(values): raise TypeError("only list-like or dict-like objects are" " allowed to be passed to DataFrame.isin(), " "you passed a " @@ -4705,7 +4708,7 @@ def extract_index(data): elif isinstance(v, dict): have_dicts = True indexes.append(list(v.keys())) - elif isinstance(v, (list, tuple, np.ndarray)): + elif is_list_like(v) and getattr(v,'ndim',0) <= 1: have_raw_arrays = True raw_lengths.append(len(v)) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index c5af0b0d4d5c8..507c2055e1b68 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -2606,6 +2606,57 @@ def test_constructor_list_of_lists(self): self.assert_(com.is_integer_dtype(df['num'])) self.assert_(df['str'].dtype == np.object_) + def test_constructor_sequence_like(self): + # GH 3783 + # collections.Squence like + import collections + + class DummyContainer(collections.Sequence): + def __init__(self, lst): + self._lst = lst + def __getitem__(self, n): + return self._lst.__getitem__(n) + def __len__(self, n): + return self._lst.__len__() + + l = [DummyContainer([1, 'a']), DummyContainer([2, 'b'])] + columns = ["num", "str"] + result = DataFrame(l, columns=columns) + expected = DataFrame([[1,'a'],[2,'b']],columns=columns) + assert_frame_equal(result, expected, check_dtype=False) + + # GH 4297 + # support Array + import array + result = DataFrame.from_items([('A', array.array('i', range(10)))]) + expected = DataFrame({ 'A' : list(range(10)) }) + assert_frame_equal(result, expected, check_dtype=False) + + expected = DataFrame([ list(range(10)), list(range(10)) ]) + result = DataFrame([ array.array('i', range(10)), array.array('i',range(10)) ]) + assert_frame_equal(result, expected, check_dtype=False) + + def test_constructor_iterator(self): + + expected = DataFrame([ list(range(10)), list(range(10)) ]) + result = DataFrame([ range(10), range(10) ]) + assert_frame_equal(result, expected) + + def test_constructor_generator(self): + #related #2305 + + gen1 = (i for i in range(10)) + gen2 = (i for i in range(10)) + + expected = DataFrame([ list(range(10)), list(range(10)) ]) + result = DataFrame([ gen1, gen2 ]) + assert_frame_equal(result, expected) + + gen = ([ i, 'a'] for i in range(10)) + result = DataFrame(gen) + expected = DataFrame({ 0 : range(10), 1 : 'a' }) + assert_frame_equal(result, expected) + def test_constructor_list_of_dicts(self): data = [OrderedDict([['a', 1.5], ['b', 3], ['c', 4], ['d', 6]]), OrderedDict([['a', 1.5], ['b', 3], ['d', 6]]), diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 7a993cbcf07f4..d2d0bc39fbfc9 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -353,6 +353,12 @@ def test_constructor_series(self): assert_series_equal(s2, s1.sort_index()) + def test_constructor_iterator(self): + + expected = Series(list(range(10))) + result = Series(range(10)) + assert_series_equal(result, expected) + def test_constructor_generator(self): gen = (i for i in range(10))
closes #3783 closes #4297 related to #2305 (as now accept GeneratorType), but just convert to list, don't incrementally create the frame
https://api.github.com/repos/pandas-dev/pandas/pulls/4829
2013-09-13T00:51:20Z
2013-09-13T22:54:42Z
2013-09-13T22:54:41Z
2014-06-21T08:22:50Z
BUG: enhanced to_datetime with format '%Y%m%d' to handle NaT/nan better
diff --git a/doc/source/release.rst b/doc/source/release.rst index 5376e0396799e..101ec290a58cf 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -105,7 +105,7 @@ Improvements to existing features test to vbench (:issue:`4705` and :issue:`4722`) - Add ``axis`` and ``level`` keywords to ``where``, so that the ``other`` argument can now be an alignable pandas object. - - ``to_datetime`` with a format of 'YYYYMMDD' now parses much faster + - ``to_datetime`` with a format of '%Y%m%d' now parses much faster API Changes ~~~~~~~~~~~ diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index c9e643e25b761..d7ca9d9b371d4 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -845,9 +845,19 @@ def test_to_datetime_format_YYYYMMDD(self): assert_series_equal(result, expected) # with NaT + expected = Series([Timestamp("19801222"),Timestamp("19801222")] + [Timestamp("19810105")]*5) + expected[2] = np.nan s[2] = np.nan - self.assertRaises(ValueError, to_datetime, s,format='%Y%m%d') - self.assertRaises(ValueError, to_datetime, s.apply(str),format='%Y%m%d') + + result = to_datetime(s,format='%Y%m%d') + assert_series_equal(result, expected) + + # string with NaT + s = s.apply(str) + s[2] = 'nat' + result = to_datetime(s,format='%Y%m%d') + assert_series_equal(result, expected) + def test_to_datetime_format_microsecond(self): val = '01-Apr-2011 00:00:01.978' diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index cca4850c2c1bf..dd78bea385c61 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -106,8 +106,7 @@ def _convert_listlike(arg, box): # shortcut formatting here if format == '%Y%m%d': try: - carg = arg.astype(np.int64).astype(object) - result = lib.try_parse_year_month_day(carg/10000,carg/100 % 100, carg % 100) + result = _attempt_YYYYMMDD(arg) except: raise ValueError("cannot convert the input to '%Y%m%d' date format") @@ -144,6 +143,43 @@ def _convert_listlike(arg, box): class DateParseError(ValueError): pass +def _attempt_YYYYMMDD(arg): + """ try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like, + arg is a passed in as an object dtype, but could really be ints/strings with nan-like/or floats (e.g. with nan) """ + + def calc(carg): + # calculate the actual result + carg = carg.astype(object) + return lib.try_parse_year_month_day(carg/10000,carg/100 % 100, carg % 100) + + def calc_with_mask(carg,mask): + result = np.empty(carg.shape, dtype='M8[ns]') + iresult = result.view('i8') + iresult[-mask] = tslib.iNaT + result[mask] = calc(carg[mask].astype(np.float64).astype(np.int64)).astype('M8[ns]') + return result + + # try intlike / strings that are ints + try: + return calc(arg.astype(np.int64)) + except: + pass + + # a float with actual np.nan + try: + carg = arg.astype(np.float64) + return calc_with_mask(carg,com.notnull(carg)) + except: + pass + + # string with NaN-like + try: + mask = ~lib.ismember(arg, tslib._nat_strings) + return calc_with_mask(arg,mask) + except: + pass + + return None # patterns for quarters like '4Q2005', '05Q1' qpat1full = re.compile(r'(\d)Q(\d\d\d\d)') diff --git a/vb_suite/timeseries.py b/vb_suite/timeseries.py index 999c3869daf62..353d7afc63cb3 100644 --- a/vb_suite/timeseries.py +++ b/vb_suite/timeseries.py @@ -154,16 +154,7 @@ def date_range(start=None, end=None, periods=None, freq=None): timeseries_to_datetime_YYYYMMDD = \ Benchmark('to_datetime(strings,format="%Y%m%d")', setup, - start_date=datetime(2013, 9, 1)) - -setup = common_setup + """ -rng = date_range('1/1/2000', periods=10000, freq='D') -strings = Series(rng.year*10000+rng.month*100+rng.day,dtype=np.int64).apply(str) -""" - -timeseries_to_datetime_YYYYMMDD_old = \ - Benchmark('pandas.tslib.array_strptime(strings.values,"%Y%m%d")', setup, - start_date=datetime(2013, 9, 1)) + start_date=datetime(2012, 7, 1)) # ---- infer_freq # infer_freq
https://api.github.com/repos/pandas-dev/pandas/pulls/4828
2013-09-12T22:55:15Z
2013-09-12T23:46:46Z
2013-09-12T23:46:46Z
2014-07-16T08:27:57Z
PERF: much faster to_datetime performance with a format of '%Y%m%d'
diff --git a/doc/source/release.rst b/doc/source/release.rst index 75194f6877a6e..5376e0396799e 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -105,6 +105,7 @@ Improvements to existing features test to vbench (:issue:`4705` and :issue:`4722`) - Add ``axis`` and ``level`` keywords to ``where``, so that the ``other`` argument can now be an alignable pandas object. + - ``to_datetime`` with a format of 'YYYYMMDD' now parses much faster API Changes ~~~~~~~~~~~ diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index b5697a98de412..c9e643e25b761 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -834,6 +834,21 @@ def test_to_datetime_format(self): else: self.assert_(result.equals(expected)) + def test_to_datetime_format_YYYYMMDD(self): + s = Series([19801222,19801222] + [19810105]*5) + expected = Series([ Timestamp(x) for x in s.apply(str) ]) + + result = to_datetime(s,format='%Y%m%d') + assert_series_equal(result, expected) + + result = to_datetime(s.apply(str),format='%Y%m%d') + assert_series_equal(result, expected) + + # with NaT + s[2] = np.nan + self.assertRaises(ValueError, to_datetime, s,format='%Y%m%d') + self.assertRaises(ValueError, to_datetime, s.apply(str),format='%Y%m%d') + def test_to_datetime_format_microsecond(self): val = '01-Apr-2011 00:00:01.978' format = '%d-%b-%Y %H:%M:%S.%f' diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index 3087d54396691..cca4850c2c1bf 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -101,7 +101,19 @@ def _convert_listlike(arg, box): arg = com._ensure_object(arg) try: if format is not None: - result = tslib.array_strptime(arg, format) + result = None + + # shortcut formatting here + if format == '%Y%m%d': + try: + carg = arg.astype(np.int64).astype(object) + result = lib.try_parse_year_month_day(carg/10000,carg/100 % 100, carg % 100) + except: + raise ValueError("cannot convert the input to '%Y%m%d' date format") + + # fallback + if result is None: + result = tslib.array_strptime(arg, format) else: result = tslib.array_to_datetime(arg, raise_=errors == 'raise', utc=utc, dayfirst=dayfirst, diff --git a/vb_suite/timeseries.py b/vb_suite/timeseries.py index 4dd1dd2e96bdd..999c3869daf62 100644 --- a/vb_suite/timeseries.py +++ b/vb_suite/timeseries.py @@ -147,6 +147,24 @@ def date_range(start=None, end=None, periods=None, freq=None): Benchmark('to_datetime(strings)', setup, start_date=datetime(2012, 7, 11)) +setup = common_setup + """ +rng = date_range('1/1/2000', periods=10000, freq='D') +strings = Series(rng.year*10000+rng.month*100+rng.day,dtype=np.int64).apply(str) +""" + +timeseries_to_datetime_YYYYMMDD = \ + Benchmark('to_datetime(strings,format="%Y%m%d")', setup, + start_date=datetime(2013, 9, 1)) + +setup = common_setup + """ +rng = date_range('1/1/2000', periods=10000, freq='D') +strings = Series(rng.year*10000+rng.month*100+rng.day,dtype=np.int64).apply(str) +""" + +timeseries_to_datetime_YYYYMMDD_old = \ + Benchmark('pandas.tslib.array_strptime(strings.values,"%Y%m%d")', setup, + start_date=datetime(2013, 9, 1)) + # ---- infer_freq # infer_freq
``` In [1]: rng = date_range('1/1/2000', periods=10000, freq='D') In [2]: strings = Series(rng.year*10000+rng.month*100+rng.day,dtype=np.int64).apply(str) In [3]: %timeit pandas.tslib.array_strptime(strings.values,"%Y%m%d") 10 loops, best of 3: 42.9 ms per loop In [4]: %timeit pd.to_datetime(strings,format="%Y%m%d") 100 loops, best of 3: 9.21 ms per loop In [5]: (pd.to_datetime(strings,format="%Y%m%d") == pandas.tslib.array_strptime(strings.values,"%Y%m%d")).all() Out[5]: True ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4826
2013-09-12T17:07:14Z
2013-09-12T18:36:28Z
2013-09-12T18:36:28Z
2014-06-26T11:55:44Z
API: add is_beg_month/quarter/year, is_end_month/quarter/year accessors (#4565)
diff --git a/doc/source/api.rst b/doc/source/api.rst index 7918d6930341a..aa5c58652d550 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -1143,6 +1143,12 @@ Time/Date Components DatetimeIndex.tz DatetimeIndex.freq DatetimeIndex.freqstr + DatetimeIndex.is_month_start + DatetimeIndex.is_month_end + DatetimeIndex.is_quarter_start + DatetimeIndex.is_quarter_end + DatetiemIndex.is_year_start + DatetimeIndex.is_year_end Selecting ~~~~~~~~~ diff --git a/doc/source/release.rst b/doc/source/release.rst index 145100c110194..f54cc13a7d775 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -470,6 +470,10 @@ API Changes - ``DataFrame.apply`` will use the ``reduce`` argument to determine whether a ``Series`` or a ``DataFrame`` should be returned when the ``DataFrame`` is empty (:issue:`6007`). +- Add ``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, + ``is_year_start``, ``is_year_end`` accessors for ``DateTimeIndex``/``Timestamp`` which return a boolean array + of whether the timestamp(s) are at the start/end of the month/quarter/year defined by the + frequency of the ``DateTimeIndex``/``Timestamp`` (:issue:`4565`, :issue:`6998`)) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index e3070ff1507a2..1cae66fada587 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -408,6 +408,39 @@ regularity will result in a ``DatetimeIndex`` (but frequency is lost): .. _timeseries.offsets: +Time/Date Components +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are several time/date properties that one can access from ``Timestamp`` or a collection of timestamps like a ``DateTimeIndex``. + +.. csv-table:: + :header: "Property", "Description" + :widths: 15, 65 + + year, "The year of the datetime" + month,"The month of the datetime" + day,"The days of the datetime" + hour,"The hour of the datetime" + minute,"The minutes of the datetime" + second,"The seconds of the datetime" + microsecond,"The microseconds of the datetime" + nanosecond,"The nanoseconds of the datetime" + date,"Returns datetime.date" + time,"Returns datetime.time" + dayofyear,"The ordinal day of year" + weekofyear,"The week ordinal of the year" + week,"The week ordinal of the year" + dayofweek,"The day of the week with Monday=0, Sunday=6" + weekday,"The day of the week with Monday=0, Sunday=6" + quarter,"Quarter of the date: Jan=Mar = 1, Apr-Jun = 2, etc." + is_month_start,"Logical indicating if first day of month (defined by frequency)" + is_month_end,"Logical indicating if last day of month (defined by frequency)" + is_quarter_start,"Logical indicating if first day of quarter (defined by frequency)" + is_quarter_end,"Logical indicating if last day of quarter (defined by frequency)" + is_year_start,"Logical indicating if first day of year (defined by frequency)" + is_year_end,"Logical indicating if last day of year (defined by frequency)" + + DateOffset objects ------------------ diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt index 7962d21b85ecd..f281d40642063 100644 --- a/doc/source/v0.14.0.txt +++ b/doc/source/v0.14.0.txt @@ -89,6 +89,8 @@ API changes s.year s.index.year +- Add ``is_month_start``, ``is_month_end``, ``is_quarter_start``, ``is_quarter_end``, ``is_year_start``, ``is_year_end`` accessors for ``DateTimeIndex``/``Timestamp`` which return a boolean array of whether the timestamp(s) are at the start/end of the month/quarter/year defined by the frequency of the ``DateTimeIndex``/``Timestamp`` (:issue:`4565`, :issue:`6998`) + - More consistent behaviour for some groupby methods: groupby ``head`` and ``tail`` now act more like ``filter`` rather than an aggregation: diff --git a/pandas/core/base.py b/pandas/core/base.py index ec6a4ffbcefbb..1e9adb60f534e 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -336,3 +336,9 @@ def nunique(self): dayofyear = _field_accessor('dayofyear', "The ordinal day of the year") quarter = _field_accessor('quarter', "The quarter of the date") qyear = _field_accessor('qyear') + is_month_start = _field_accessor('is_month_start', "Logical indicating if first day of month (defined by frequency)") + is_month_end = _field_accessor('is_month_end', "Logical indicating if last day of month (defined by frequency)") + is_quarter_start = _field_accessor('is_quarter_start', "Logical indicating if first day of quarter (defined by frequency)") + is_quarter_end = _field_accessor('is_quarter_end', "Logical indicating if last day of quarter (defined by frequency)") + is_year_start = _field_accessor('is_year_start', "Logical indicating if first day of year (defined by frequency)") + is_year_end = _field_accessor('is_year_end', "Logical indicating if last day of year (defined by frequency)") diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 036a868fe0451..81b3d4631bfbf 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -214,7 +214,7 @@ def test_value_counts_unique_nunique(self): # freq must be specified because repeat makes freq ambiguous o = klass(np.repeat(values, range(1, len(o) + 1)), freq=o.freq) else: - o = klass(np.repeat(values, range(1, len(o) + 1))) + o = klass(np.repeat(values, range(1, len(o) + 1))) expected_s = Series(range(10, 0, -1), index=values[::-1], dtype='int64') tm.assert_series_equal(o.value_counts(), expected_s) @@ -246,7 +246,7 @@ def test_value_counts_unique_nunique(self): if isinstance(o, PeriodIndex): o = klass(np.repeat(values, range(1, len(o) + 1)), freq=o.freq) else: - o = klass(np.repeat(values, range(1, len(o) + 1))) + o = klass(np.repeat(values, range(1, len(o) + 1))) if isinstance(o, DatetimeIndex): # DatetimeIndex: nan is casted to Nat and included @@ -278,7 +278,7 @@ def test_value_counts_inferred(self): s = klass(s_values) expected = Series([4, 3, 2, 1], index=['b', 'a', 'd', 'c']) tm.assert_series_equal(s.value_counts(), expected) - + self.assert_numpy_array_equal(s.unique(), np.unique(s_values)) self.assertEquals(s.nunique(), 4) # don't sort, have to sort after the fact as not sorting is platform-dep @@ -410,7 +410,7 @@ def setUp(self): def test_ops_properties(self): self.check_ops_properties(['year','month','day','hour','minute','second','weekofyear','week','dayofweek','dayofyear','quarter']) - self.check_ops_properties(['date','time','microsecond','nanosecond'], lambda x: isinstance(x,DatetimeIndex)) + self.check_ops_properties(['date','time','microsecond','nanosecond', 'is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'], lambda x: isinstance(x,DatetimeIndex)) class TestPeriodIndexOps(Ops): _allowed = '_allow_period_index_ops' diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 6ac21e60ea7f3..a2e01c8110261 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -14,7 +14,7 @@ from pandas.compat import u from pandas.tseries.frequencies import ( infer_freq, to_offset, get_period_alias, - Resolution, get_reso_string) + Resolution, get_reso_string, get_offset) from pandas.tseries.offsets import DateOffset, generate_range, Tick, CDay from pandas.tseries.tools import parse_time_string, normalize_date from pandas.util.decorators import cache_readonly @@ -28,6 +28,7 @@ import pandas.algos as _algos import pandas.index as _index +from pandas.tslib import isleapyear def _utc(): import pytz @@ -43,7 +44,14 @@ def f(self): utc = _utc() if self.tz is not utc: values = self._local_timestamps() - return tslib.get_date_field(values, field) + if field in ['is_month_start', 'is_month_end', + 'is_quarter_start', 'is_quarter_end', + 'is_year_start', 'is_year_end']: + month_kw = self.freq.kwds.get('startingMonth', self.freq.kwds.get('month', 12)) if self.freq else 12 + freqstr = self.freqstr if self.freq else None + return tslib.get_start_end_field(values, field, freqstr, month_kw) + else: + return tslib.get_date_field(values, field) f.__name__ = name f.__doc__ = docstring return property(f) @@ -1439,6 +1447,12 @@ def freqstr(self): _weekday = _dayofweek _dayofyear = _field_accessor('dayofyear', 'doy') _quarter = _field_accessor('quarter', 'q') + _is_month_start = _field_accessor('is_month_start', 'is_month_start') + _is_month_end = _field_accessor('is_month_end', 'is_month_end') + _is_quarter_start = _field_accessor('is_quarter_start', 'is_quarter_start') + _is_quarter_end = _field_accessor('is_quarter_end', 'is_quarter_end') + _is_year_start = _field_accessor('is_year_start', 'is_year_start') + _is_year_end = _field_accessor('is_year_end', 'is_year_end') @property def _time(self): @@ -1774,6 +1788,7 @@ def to_julian_date(self): self.nanosecond/3600.0/1e+9 )/24.0) + def _generate_regular_range(start, end, periods, offset): if isinstance(offset, Tick): stride = offset.nanos @@ -1831,7 +1846,7 @@ def date_range(start=None, end=None, periods=None, freq='D', tz=None, Frequency strings can have multiples, e.g. '5H' tz : string or None Time zone name for returning localized DatetimeIndex, for example - Asia/Hong_Kong + Asia/Hong_Kong normalize : bool, default False Normalize start/end dates to midnight before generating date range name : str, default None diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index fc3ee993771d3..319eaee6d14df 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -1473,7 +1473,7 @@ def test_timestamp_fields(self): # extra fields from DatetimeIndex like quarter and week idx = tm.makeDateIndex(100) - fields = ['dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter'] + fields = ['dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter', 'is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end'] for f in fields: expected = getattr(idx, f)[-1] result = getattr(Timestamp(idx[-1]), f) @@ -2192,7 +2192,7 @@ def test_join_with_period_index(self): class TestDatetime64(tm.TestCase): """ - Also test supoprt for datetime64[ns] in Series / DataFrame + Also test support for datetime64[ns] in Series / DataFrame """ def setUp(self): @@ -2202,37 +2202,115 @@ def setUp(self): def test_datetimeindex_accessors(self): dti = DatetimeIndex( - freq='Q-JAN', start=datetime(1997, 12, 31), periods=100) + freq='D', start=datetime(1998, 1, 1), periods=365) self.assertEquals(dti.year[0], 1998) self.assertEquals(dti.month[0], 1) - self.assertEquals(dti.day[0], 31) + self.assertEquals(dti.day[0], 1) self.assertEquals(dti.hour[0], 0) self.assertEquals(dti.minute[0], 0) self.assertEquals(dti.second[0], 0) self.assertEquals(dti.microsecond[0], 0) - self.assertEquals(dti.dayofweek[0], 5) + self.assertEquals(dti.dayofweek[0], 3) - self.assertEquals(dti.dayofyear[0], 31) - self.assertEquals(dti.dayofyear[1], 120) + self.assertEquals(dti.dayofyear[0], 1) + self.assertEquals(dti.dayofyear[120], 121) - self.assertEquals(dti.weekofyear[0], 5) - self.assertEquals(dti.weekofyear[1], 18) + self.assertEquals(dti.weekofyear[0], 1) + self.assertEquals(dti.weekofyear[120], 18) self.assertEquals(dti.quarter[0], 1) - self.assertEquals(dti.quarter[1], 2) - - self.assertEquals(len(dti.year), 100) - self.assertEquals(len(dti.month), 100) - self.assertEquals(len(dti.day), 100) - self.assertEquals(len(dti.hour), 100) - self.assertEquals(len(dti.minute), 100) - self.assertEquals(len(dti.second), 100) - self.assertEquals(len(dti.microsecond), 100) - self.assertEquals(len(dti.dayofweek), 100) - self.assertEquals(len(dti.dayofyear), 100) - self.assertEquals(len(dti.weekofyear), 100) - self.assertEquals(len(dti.quarter), 100) + self.assertEquals(dti.quarter[120], 2) + + self.assertEquals(dti.is_month_start[0], True) + self.assertEquals(dti.is_month_start[1], False) + self.assertEquals(dti.is_month_start[31], True) + self.assertEquals(dti.is_quarter_start[0], True) + self.assertEquals(dti.is_quarter_start[90], True) + self.assertEquals(dti.is_year_start[0], True) + self.assertEquals(dti.is_year_start[364], False) + self.assertEquals(dti.is_month_end[0], False) + self.assertEquals(dti.is_month_end[30], True) + self.assertEquals(dti.is_month_end[31], False) + self.assertEquals(dti.is_month_end[364], True) + self.assertEquals(dti.is_quarter_end[0], False) + self.assertEquals(dti.is_quarter_end[30], False) + self.assertEquals(dti.is_quarter_end[89], True) + self.assertEquals(dti.is_quarter_end[364], True) + self.assertEquals(dti.is_year_end[0], False) + self.assertEquals(dti.is_year_end[364], True) + + self.assertEquals(len(dti.year), 365) + self.assertEquals(len(dti.month), 365) + self.assertEquals(len(dti.day), 365) + self.assertEquals(len(dti.hour), 365) + self.assertEquals(len(dti.minute), 365) + self.assertEquals(len(dti.second), 365) + self.assertEquals(len(dti.microsecond), 365) + self.assertEquals(len(dti.dayofweek), 365) + self.assertEquals(len(dti.dayofyear), 365) + self.assertEquals(len(dti.weekofyear), 365) + self.assertEquals(len(dti.quarter), 365) + self.assertEquals(len(dti.is_month_start), 365) + self.assertEquals(len(dti.is_month_end), 365) + self.assertEquals(len(dti.is_quarter_start), 365) + self.assertEquals(len(dti.is_quarter_end), 365) + self.assertEquals(len(dti.is_year_start), 365) + self.assertEquals(len(dti.is_year_end), 365) + + dti = DatetimeIndex( + freq='BQ-FEB', start=datetime(1998, 1, 1), periods=4) + + self.assertEquals(sum(dti.is_quarter_start), 0) + self.assertEquals(sum(dti.is_quarter_end), 4) + self.assertEquals(sum(dti.is_year_start), 0) + self.assertEquals(sum(dti.is_year_end), 1) + + # Ensure is_start/end accessors throw ValueError for CustomBusinessDay, CBD requires np >= 1.7 + if not _np_version_under1p7: + bday_egypt = offsets.CustomBusinessDay(weekmask='Sun Mon Tue Wed Thu') + dti = date_range(datetime(2013, 4, 30), periods=5, freq=bday_egypt) + self.assertRaises(ValueError, lambda: dti.is_month_start) + + dti = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03']) + + self.assertEquals(dti.is_month_start[0], 1) + + tests = [ + (Timestamp('2013-06-01', offset='M').is_month_start, 1), + (Timestamp('2013-06-01', offset='BM').is_month_start, 0), + (Timestamp('2013-06-03', offset='M').is_month_start, 0), + (Timestamp('2013-06-03', offset='BM').is_month_start, 1), + (Timestamp('2013-02-28', offset='Q-FEB').is_month_end, 1), + (Timestamp('2013-02-28', offset='Q-FEB').is_quarter_end, 1), + (Timestamp('2013-02-28', offset='Q-FEB').is_year_end, 1), + (Timestamp('2013-03-01', offset='Q-FEB').is_month_start, 1), + (Timestamp('2013-03-01', offset='Q-FEB').is_quarter_start, 1), + (Timestamp('2013-03-01', offset='Q-FEB').is_year_start, 1), + (Timestamp('2013-03-31', offset='QS-FEB').is_month_end, 1), + (Timestamp('2013-03-31', offset='QS-FEB').is_quarter_end, 0), + (Timestamp('2013-03-31', offset='QS-FEB').is_year_end, 0), + (Timestamp('2013-02-01', offset='QS-FEB').is_month_start, 1), + (Timestamp('2013-02-01', offset='QS-FEB').is_quarter_start, 1), + (Timestamp('2013-02-01', offset='QS-FEB').is_year_start, 1), + (Timestamp('2013-06-30', offset='BQ').is_month_end, 0), + (Timestamp('2013-06-30', offset='BQ').is_quarter_end, 0), + (Timestamp('2013-06-30', offset='BQ').is_year_end, 0), + (Timestamp('2013-06-28', offset='BQ').is_month_end, 1), + (Timestamp('2013-06-28', offset='BQ').is_quarter_end, 1), + (Timestamp('2013-06-28', offset='BQ').is_year_end, 0), + (Timestamp('2013-06-30', offset='BQS-APR').is_month_end, 0), + (Timestamp('2013-06-30', offset='BQS-APR').is_quarter_end, 0), + (Timestamp('2013-06-30', offset='BQS-APR').is_year_end, 0), + (Timestamp('2013-06-28', offset='BQS-APR').is_month_end, 1), + (Timestamp('2013-06-28', offset='BQS-APR').is_quarter_end, 1), + (Timestamp('2013-03-29', offset='BQS-APR').is_year_end, 1), + (Timestamp('2013-11-01', offset='AS-NOV').is_year_start, 1), + (Timestamp('2013-10-31', offset='AS-NOV').is_year_end, 1)] + + for ts, value in tests: + self.assertEquals(ts, value) + def test_nanosecond_field(self): dti = DatetimeIndex(np.arange(10)) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index e76a2d0cb6cf1..6d99d38049e5a 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -1,7 +1,7 @@ # cython: profile=False cimport numpy as np -from numpy cimport (int32_t, int64_t, import_array, ndarray, +from numpy cimport (int8_t, int32_t, int64_t, import_array, ndarray, NPY_INT64, NPY_DATETIME, NPY_TIMEDELTA) import numpy as np @@ -303,6 +303,30 @@ class Timestamp(_Timestamp): def asm8(self): return np.int64(self.value).view('M8[ns]') + @property + def is_month_start(self): + return self._get_start_end_field('is_month_start') + + @property + def is_month_end(self): + return self._get_start_end_field('is_month_end') + + @property + def is_quarter_start(self): + return self._get_start_end_field('is_quarter_start') + + @property + def is_quarter_end(self): + return self._get_start_end_field('is_quarter_end') + + @property + def is_year_start(self): + return self._get_start_end_field('is_year_start') + + @property + def is_year_end(self): + return self._get_start_end_field('is_year_end') + def tz_localize(self, tz): """ Convert naive Timestamp to local time zone @@ -725,6 +749,12 @@ cdef class _Timestamp(datetime): out = get_date_field(np.array([self.value], dtype=np.int64), field) return out[0] + cpdef _get_start_end_field(self, field): + month_kw = self.freq.kwds.get('startingMonth', self.freq.kwds.get('month', 12)) if self.freq else 12 + freqstr = self.freqstr if self.freq else None + out = get_start_end_field(np.array([self.value], dtype=np.int64), field, freqstr, month_kw) + return out[0] + cdef PyTypeObject* ts_type = <PyTypeObject*> Timestamp @@ -2298,6 +2328,225 @@ def get_date_field(ndarray[int64_t] dtindex, object field): raise ValueError("Field %s not supported" % field) +@cython.wraparound(False) +def get_start_end_field(ndarray[int64_t] dtindex, object field, object freqstr=None, int month_kw=12): + ''' + Given an int64-based datetime index return array of indicators + of whether timestamps are at the start/end of the month/quarter/year + (defined by frequency). + ''' + cdef: + _TSObject ts + Py_ssize_t i + int count = 0 + bint is_business = 0 + int end_month = 12 + int start_month = 1 + ndarray[int8_t] out + ndarray[int32_t, ndim=2] _month_offset + bint isleap + pandas_datetimestruct dts + int mo_off, dom, doy, dow, ldom + + _month_offset = np.array( + [[ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 ], + [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 ]], + dtype=np.int32 ) + + count = len(dtindex) + out = np.zeros(count, dtype='int8') + + if freqstr: + if freqstr == 'C': + raise ValueError("Custom business days is not supported by %s" % field) + is_business = freqstr[0] == 'B' + + # YearBegin(), BYearBegin() use month = starting month of year + # QuarterBegin(), BQuarterBegin() use startingMonth = starting month of year + # other offests use month, startingMonth as ending month of year. + + if (freqstr[0:2] in ['MS', 'QS', 'AS']) or (freqstr[1:3] in ['MS', 'QS', 'AS']): + end_month = 12 if month_kw == 1 else month_kw - 1 + start_month = month_kw + else: + end_month = month_kw + start_month = (end_month % 12) + 1 + else: + end_month = 12 + start_month = 1 + + if field == 'is_month_start': + if is_business: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + dom = dts.day + dow = ts_dayofweek(ts) + + if (dom == 1 and dow < 5) or (dom <= 3 and dow == 0): + out[i] = 1 + return out.view(bool) + else: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + dom = dts.day + + if dom == 1: + out[i] = 1 + return out.view(bool) + + elif field == 'is_month_end': + if is_business: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + isleap = is_leapyear(dts.year) + mo_off = _month_offset[isleap, dts.month - 1] + dom = dts.day + doy = mo_off + dom + ldom = _month_offset[isleap, dts.month] + dow = ts_dayofweek(ts) + + if (ldom == doy and dow < 5) or (dow == 4 and (ldom - doy <= 2)): + out[i] = 1 + return out.view(bool) + else: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + isleap = is_leapyear(dts.year) + mo_off = _month_offset[isleap, dts.month - 1] + dom = dts.day + doy = mo_off + dom + ldom = _month_offset[isleap, dts.month] + + if ldom == doy: + out[i] = 1 + return out.view(bool) + + elif field == 'is_quarter_start': + if is_business: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + dom = dts.day + dow = ts_dayofweek(ts) + + if ((dts.month - start_month) % 3 == 0) and ((dom == 1 and dow < 5) or (dom <= 3 and dow == 0)): + out[i] = 1 + return out.view(bool) + else: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + dom = dts.day + + if ((dts.month - start_month) % 3 == 0) and dom == 1: + out[i] = 1 + return out.view(bool) + + elif field == 'is_quarter_end': + if is_business: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + isleap = is_leapyear(dts.year) + mo_off = _month_offset[isleap, dts.month - 1] + dom = dts.day + doy = mo_off + dom + ldom = _month_offset[isleap, dts.month] + dow = ts_dayofweek(ts) + + if ((dts.month - end_month) % 3 == 0) and ((ldom == doy and dow < 5) or (dow == 4 and (ldom - doy <= 2))): + out[i] = 1 + return out.view(bool) + else: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + isleap = is_leapyear(dts.year) + mo_off = _month_offset[isleap, dts.month - 1] + dom = dts.day + doy = mo_off + dom + ldom = _month_offset[isleap, dts.month] + + if ((dts.month - end_month) % 3 == 0) and (ldom == doy): + out[i] = 1 + return out.view(bool) + + elif field == 'is_year_start': + if is_business: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + dom = dts.day + dow = ts_dayofweek(ts) + + if (dts.month == start_month) and ((dom == 1 and dow < 5) or (dom <= 3 and dow == 0)): + out[i] = 1 + return out.view(bool) + else: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + dom = dts.day + + if (dts.month == start_month) and dom == 1: + out[i] = 1 + return out.view(bool) + + elif field == 'is_year_end': + if is_business: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + isleap = is_leapyear(dts.year) + dom = dts.day + mo_off = _month_offset[isleap, dts.month - 1] + doy = mo_off + dom + dow = ts_dayofweek(ts) + ldom = _month_offset[isleap, dts.month] + + if (dts.month == end_month) and ((ldom == doy and dow < 5) or (dow == 4 and (ldom - doy <= 2))): + out[i] = 1 + return out.view(bool) + else: + for i in range(count): + if dtindex[i] == NPY_NAT: out[i] = -1; continue + + pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts) + ts = convert_to_tsobject(dtindex[i], None, None) + isleap = is_leapyear(dts.year) + mo_off = _month_offset[isleap, dts.month - 1] + dom = dts.day + doy = mo_off + dom + ldom = _month_offset[isleap, dts.month] + + if (dts.month == end_month) and (ldom == doy): + out[i] = 1 + return out.view(bool) + + raise ValueError("Field %s not supported" % field) + + cdef inline int m8_weekday(int64_t val): ts = convert_to_tsobject(val, None, None) return ts_dayofweek(ts) diff --git a/vb_suite/timeseries.py b/vb_suite/timeseries.py index 06ef99442b574..a3d4d4c7d40a5 100644 --- a/vb_suite/timeseries.py +++ b/vb_suite/timeseries.py @@ -303,3 +303,14 @@ def date_range(start=None, end=None, periods=None, freq=None): timeseries_custom_bmonthend_incr_n = \ Benchmark("date + 10 * cme",setup) + +#---------------------------------------------------------------------- +# month/quarter/year start/end accessors + +setup = common_setup + """ +N = 10000 +rng = date_range('1/1/1', periods=N, freq='B') +""" + +timeseries_is_month_start = Benchmark('rng.is_month_start', setup, + start_date=datetime(2014, 4, 1))
closes #4565
https://api.github.com/repos/pandas-dev/pandas/pulls/4823
2013-09-12T07:47:33Z
2014-04-29T23:41:57Z
2014-04-29T23:41:57Z
2014-06-19T15:50:34Z
ENH/CLN: support enhanced timedelta64 operations/conversions
diff --git a/doc/source/io.rst b/doc/source/io.rst index 1d3980e216587..da611c0375789 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2009,6 +2009,26 @@ space. These are in terms of the total number of rows in a table. Term('minor_axis', '=', ['A','B']) ], start=0, stop=10) +**Using timedelta64[ns]** + +.. versionadded:: 0.13 + +Beginning in 0.13.0, you can store and query using the ``timedelta64[ns]`` type. Terms can be +specified in the format: ``<float>(<unit>)``, where float may be signed (and fractional), and unit can be +``D,s,ms,us,ns`` for the timedelta. Here's an example: + +.. warning:: + + This requires ``numpy >= 1.7`` + +.. ipython:: python + + from datetime import timedelta + dftd = DataFrame(dict(A = Timestamp('20130101'), B = [ Timestamp('20130101') + timedelta(days=i,seconds=10) for i in range(10) ])) + dftd['C'] = dftd['A']-dftd['B'] + dftd + store.append('dftd',dftd,data_columns=True) + store.select('dftd',Term("C","<","-3.5D")) Indexing ~~~~~~~~ diff --git a/doc/source/release.rst b/doc/source/release.rst index 087d2880511d2..75194f6877a6e 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -156,6 +156,7 @@ API Changes - a column multi-index will be recreated properly (:issue:`4710`); raise on trying to use a multi-index with data_columns on the same axis - ``select_as_coordinates`` will now return an ``Int64Index`` of the resultant selection set + - support ``timedelta64[ns]`` as a serialization type (:issue:`3577`) - ``JSON`` - added ``date_unit`` parameter to specify resolution of timestamps. Options @@ -190,6 +191,8 @@ API Changes - provide automatic dtype conversions on _reduce operations (:issue:`3371`) - exclude non-numerics if mixed types with datelike in _reduce operations (:issue:`3371`) - default for ``tupleize_cols`` is now ``False`` for both ``to_csv`` and ``read_csv``. Fair warning in 0.12 (:issue:`3604`) + - moved timedeltas support to pandas.tseries.timedeltas.py; add timedeltas string parsing, + add top-level ``to_timedelta`` function Internal Refactoring ~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index 11f4ac9f487c2..5dbf1ce77bad8 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -1211,6 +1211,26 @@ Time Deltas & Conversions .. versionadded:: 0.13 +**string/integer conversion** + +Using the top-level ``to_timedelta``, you can convert a scalar or array from the standard +timedelta format (produced by ``to_csv``) into a timedelta type (``np.timedelta64`` in ``nanoseconds``). +It can also construct Series. + +.. warning:: + + This requires ``numpy >= 1.7`` + +.. ipython:: python + + to_timedelta('1 days 06:05:01.00003') + to_timedelta('15.5us') + to_timedelta(['1 days 06:05:01.00003','15.5us','nan']) + to_timedelta(np.arange(5),unit='s') + to_timedelta(np.arange(5),unit='d') + +**frequency conversion** + Timedeltas can be converted to other 'frequencies' by dividing by another timedelta. These operations yield ``float64`` dtyped Series. diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index caf218747bdfb..f0a23b46373e9 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -80,7 +80,7 @@ API changes See :ref:`here<io.hdf5-selecting_coordinates>` for an example. - allow a passed locations array or mask as a ``where`` condition (:issue:`4467`). See :ref:`here<io.hdf5-where_mask>` for an example. - + - support ``timedelta64[ns]`` as a serialization type (:issue:`3577`) - the ``format`` keyword now replaces the ``table`` keyword; allowed values are ``fixed(f)`` or ``table(t)`` the same defaults as prior < 0.13.0 remain, e.g. ``put`` implies 'fixed` or 'f' (Fixed) format and ``append`` imples 'table' or 't' (Table) format @@ -208,6 +208,21 @@ Enhancements - ``timedelta64[ns]`` operations + - Using the new top-level ``to_timedelta``, you can convert a scalar or array from the standard + timedelta format (produced by ``to_csv``) into a timedelta type (``np.timedelta64`` in ``nanoseconds``). + + .. warning:: + + This requires ``numpy >= 1.7`` + + .. ipython:: python + + to_timedelta('1 days 06:05:01.00003') + to_timedelta('15.5us') + to_timedelta(['1 days 06:05:01.00003','15.5us','nan']) + to_timedelta(np.arange(5),unit='s') + to_timedelta(np.arange(5),unit='d') + - A Series of dtype ``timedelta64[ns]`` can now be divided by another ``timedelta64[ns]`` object to yield a ``float64`` dtyped Series. This is frequency conversion. See :ref:`here<timeseries.timedeltas_convert>` for the docs. diff --git a/pandas/__init__.py b/pandas/__init__.py index a0edb397c28c1..03681d3fa5a3f 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -18,6 +18,19 @@ from datetime import datetime import numpy as np +# XXX: HACK for NumPy 1.5.1 to suppress warnings +try: + np.seterr(all='ignore') + # np.set_printoptions(suppress=True) +except Exception: # pragma: no cover + pass + +# numpy versioning +from distutils.version import LooseVersion +_np_version = np.version.short_version +_np_version_under1p6 = LooseVersion(_np_version) < '1.6' +_np_version_under1p7 = LooseVersion(_np_version) < '1.7' + from pandas.version import version as __version__ from pandas.info import __doc__ diff --git a/pandas/core/common.py b/pandas/core/common.py index ba7c6cc511933..b58bd92a4fd1f 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -11,7 +11,6 @@ import pandas.algos as algos import pandas.lib as lib import pandas.tslib as tslib -from distutils.version import LooseVersion from pandas import compat from pandas.compat import StringIO, BytesIO, range, long, u, zip, map from datetime import timedelta @@ -19,15 +18,6 @@ from pandas.core.config import get_option from pandas.core import array as pa - -# XXX: HACK for NumPy 1.5.1 to suppress warnings -try: - np.seterr(all='ignore') - # np.set_printoptions(suppress=True) -except Exception: # pragma: no cover - pass - - class PandasError(Exception): pass @@ -35,11 +25,6 @@ class PandasError(Exception): class AmbiguousIndexError(PandasError, KeyError): pass -# versioning -_np_version = np.version.short_version -_np_version_under1p6 = LooseVersion(_np_version) < '1.6' -_np_version_under1p7 = LooseVersion(_np_version) < '1.7' - _POSSIBLY_CAST_DTYPES = set([np.dtype(t) for t in ['M8[ns]', 'm8[ns]', 'O', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']]) @@ -704,34 +689,13 @@ def diff(arr, n, axis=0): return out_arr - -def _coerce_scalar_to_timedelta_type(r): - # kludgy here until we have a timedelta scalar - # handle the numpy < 1.7 case - - if is_integer(r): - r = timedelta(microseconds=r/1000) - - if _np_version_under1p7: - if not isinstance(r, timedelta): - raise AssertionError("Invalid type for timedelta scalar: %s" % type(r)) - if compat.PY3: - # convert to microseconds in timedelta64 - r = np.timedelta64(int(r.total_seconds()*1e9 + r.microseconds*1000)) - else: - return r - - if isinstance(r, timedelta): - r = np.timedelta64(r) - elif not isinstance(r, np.timedelta64): - raise AssertionError("Invalid type for timedelta scalar: %s" % type(r)) - return r.astype('timedelta64[ns]') - def _coerce_to_dtypes(result, dtypes): """ given a dtypes and a result set, coerce the result elements to the dtypes """ if len(result) != len(dtypes): raise AssertionError("_coerce_to_dtypes requires equal len arrays") + from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type + def conv(r,dtype): try: if isnull(r): @@ -1324,68 +1288,6 @@ def _possibly_convert_platform(values): return values - -def _possibly_cast_to_timedelta(value, coerce=True): - """ try to cast to timedelta64, if already a timedeltalike, then make - sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards, - don't force the conversion unless coerce is True - - if coerce='compat' force a compatibilty coercerion (to timedeltas) if needeed - """ - - # coercion compatability - if coerce == 'compat' and _np_version_under1p7: - - def convert(td, dtype): - - # we have an array with a non-object dtype - if hasattr(td,'item'): - td = td.astype(np.int64).item() - if td == tslib.iNaT: - return td - if dtype == 'm8[us]': - td *= 1000 - return td - - if td == tslib.compat_NaT: - return tslib.iNaT - - # convert td value to a nanosecond value - d = td.days - s = td.seconds - us = td.microseconds - - if dtype == 'object' or dtype == 'm8[ns]': - td = 1000*us + (s + d * 24 * 3600) * 10 ** 9 - else: - raise ValueError("invalid conversion of dtype in np < 1.7 [%s]" % dtype) - - return td - - # < 1.7 coercion - if not is_list_like(value): - value = np.array([ value ]) - - dtype = value.dtype - return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]') - - # deal with numpy not being able to handle certain timedelta operations - if isinstance(value, (ABCSeries, np.ndarray)) and value.dtype.kind == 'm': - if value.dtype != 'timedelta64[ns]': - value = value.astype('timedelta64[ns]') - return value - - # we don't have a timedelta, but we want to try to convert to one (but - # don't force it) - if coerce: - new_value = tslib.array_to_timedelta64( - _values_from_object(value).astype(object), coerce=False) - if new_value.dtype == 'i8': - value = np.array(new_value, dtype='timedelta64[ns]') - - return value - - def _possibly_cast_to_datetime(value, dtype, coerce=False): """ try to cast the array/value to a datetimelike dtype, converting float nan to iNaT """ @@ -1423,6 +1325,7 @@ def _possibly_cast_to_datetime(value, dtype, coerce=False): from pandas.tseries.tools import to_datetime value = to_datetime(value, coerce=coerce).values elif is_timedelta64: + from pandas.tseries.timedeltas import _possibly_cast_to_timedelta value = _possibly_cast_to_timedelta(value) except: pass @@ -1448,6 +1351,7 @@ def _possibly_cast_to_datetime(value, dtype, coerce=False): except: pass elif inferred_type in ['timedelta', 'timedelta64']: + from pandas.tseries.timedeltas import _possibly_cast_to_timedelta value = _possibly_cast_to_timedelta(value) return value diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 212e2bad563b6..b9ffe788d183d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -13,7 +13,7 @@ from pandas.tseries.index import DatetimeIndex from pandas.core.internals import BlockManager import pandas.core.common as com -from pandas import compat +from pandas import compat, _np_version_under1p7 from pandas.compat import map, zip, lrange from pandas.core.common import (isnull, notnull, is_list_like, _values_from_object, @@ -1908,7 +1908,7 @@ def abs(self): obj = np.abs(self) # suprimo numpy 1.6 hacking - if com._np_version_under1p7: + if _np_version_under1p7: if self.ndim == 1: if obj.dtype == 'm8[us]': obj = obj.astype('m8[ns]') diff --git a/pandas/core/series.py b/pandas/core/series.py index 4516fcfbaee8e..8d6591c3acd60 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -19,6 +19,7 @@ _asarray_tuplesafe, is_integer_dtype, _NS_DTYPE, _TD_DTYPE, _infer_dtype_from_scalar, is_list_like, _values_from_object, + _possibly_cast_to_datetime, _possibly_castable, _possibly_convert_platform, ABCSparseArray) from pandas.core.index import (Index, MultiIndex, InvalidIndexError, _ensure_index, _handle_legacy_indexes) @@ -32,6 +33,7 @@ from pandas.tseries.index import DatetimeIndex from pandas.tseries.period import PeriodIndex, Period from pandas.tseries.offsets import DateOffset +from pandas.tseries.timedeltas import _possibly_cast_to_timedelta from pandas import compat from pandas.util.terminal import get_terminal_size from pandas.compat import zip, lzip, u, OrderedDict @@ -142,7 +144,7 @@ def _convert_to_array(self, values, name=None): values = values.to_series() elif inferred_type in ('timedelta', 'timedelta64'): # have a timedelta, convert to to ns here - values = com._possibly_cast_to_timedelta(values, coerce=coerce) + values = _possibly_cast_to_timedelta(values, coerce=coerce) elif inferred_type == 'integer': # py3 compat where dtype is 'm' but is an integer if values.dtype.kind == 'm': @@ -160,7 +162,7 @@ def _convert_to_array(self, values, name=None): raise TypeError("cannot use a non-absolute DateOffset in " "datetime/timedelta operations [{0}]".format( ','.join([ com.pprint_thing(v) for v in values[mask] ]))) - values = com._possibly_cast_to_timedelta(os, coerce=coerce) + values = _possibly_cast_to_timedelta(os, coerce=coerce) else: raise TypeError("incompatible type [{0}] for a datetime/timedelta operation".format(pa.array(values).dtype)) @@ -3215,11 +3217,11 @@ def _try_cast(arr, take_fast_path): # perf shortcut as this is the most common case if take_fast_path: - if com._possibly_castable(arr) and not copy and dtype is None: + if _possibly_castable(arr) and not copy and dtype is None: return arr try: - arr = com._possibly_cast_to_datetime(arr, dtype) + arr = _possibly_cast_to_datetime(arr, dtype) subarr = pa.array(arr, dtype=dtype, copy=copy) except (ValueError, TypeError): if dtype is not None and raise_cast_failure: @@ -3266,9 +3268,9 @@ def _try_cast(arr, take_fast_path): subarr = lib.maybe_convert_objects(subarr) else: - subarr = com._possibly_convert_platform(data) + subarr = _possibly_convert_platform(data) - subarr = com._possibly_cast_to_datetime(subarr, dtype) + subarr = _possibly_cast_to_datetime(subarr, dtype) else: subarr = _try_cast(data, False) @@ -3285,7 +3287,7 @@ def _try_cast(arr, take_fast_path): dtype, value = _infer_dtype_from_scalar(value) else: # need to possibly convert the value here - value = com._possibly_cast_to_datetime(value, dtype) + value = _possibly_cast_to_datetime(value, dtype) subarr = pa.empty(len(index), dtype=dtype) subarr.fill(value) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 6759e07ed7935..9b6a230f6a551 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -17,7 +17,7 @@ import numpy as np import pandas from pandas import (Series, TimeSeries, DataFrame, Panel, Panel4D, Index, - MultiIndex, Int64Index, Timestamp) + MultiIndex, Int64Index, Timestamp, _np_version_under1p7) from pandas.sparse.api import SparseSeries, SparseDataFrame, SparsePanel from pandas.sparse.array import BlockIndex, IntIndex from pandas.tseries.api import PeriodIndex, DatetimeIndex @@ -29,6 +29,7 @@ from pandas.core.internals import BlockManager, make_block from pandas.core.reshape import block2d_to_blocknd, factor_indexer from pandas.core.index import _ensure_index +from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type import pandas.core.common as com from pandas.tools.merge import concat from pandas import compat @@ -1527,6 +1528,8 @@ def set_kind(self): self.kind = 'integer' elif dtype.startswith(u('date')): self.kind = 'datetime' + elif dtype.startswith(u('timedelta')): + self.kind = 'timedelta' elif dtype.startswith(u('bool')): self.kind = 'bool' else: @@ -1547,6 +1550,11 @@ def set_atom(self, block, existing_col, min_itemsize, nan_rep, info, encoding=No if inferred_type == 'datetime64': self.set_atom_datetime64(block) + elif dtype == 'timedelta64[ns]': + if _np_version_under1p7: + raise TypeError( + "timdelta64 is not supported under under numpy < 1.7") + self.set_atom_timedelta64(block) elif inferred_type == 'date': raise TypeError( "[date] is not implemented as a table column") @@ -1667,6 +1675,16 @@ def set_atom_datetime64(self, block, values=None): values = block.values.view('i8') self.set_data(values, 'datetime64') + def get_atom_timedelta64(self, block): + return _tables().Int64Col(shape=block.shape[0]) + + def set_atom_timedelta64(self, block, values=None): + self.kind = 'timedelta64' + self.typ = self.get_atom_timedelta64(block) + if values is None: + values = block.values.view('i8') + self.set_data(values, 'timedelta64') + @property def shape(self): return getattr(self.data, 'shape', None) @@ -1719,6 +1737,8 @@ def convert(self, values, nan_rep, encoding): else: self.data = np.asarray(self.data, dtype='M8[ns]') + elif dtype == u('timedelta64'): + self.data = np.asarray(self.data, dtype='m8[ns]') elif dtype == u('date'): self.data = np.array( [date.fromtimestamp(v) for v in self.data], dtype=object) @@ -1767,6 +1787,9 @@ def get_atom_data(self, block): def get_atom_datetime64(self, block): return _tables().Int64Col() + def get_atom_timedelta64(self, block): + return _tables().Int64Col() + class GenericDataIndexableCol(DataIndexableCol): @@ -2007,6 +2030,11 @@ def read_array(self, key): if dtype == u('datetime64'): ret = np.array(ret, dtype='M8[ns]') + elif dtype == u('timedelta64'): + if _np_version_under1p7: + raise TypeError( + "timedelta64 is not supported under under numpy < 1.7") + ret = np.array(ret, dtype='m8[ns]') if transposed: return ret.T @@ -2214,6 +2242,9 @@ def write_array(self, key, value, items=None): elif value.dtype.type == np.datetime64: self._handle.createArray(self.group, key, value.view('i8')) getattr(self.group, key)._v_attrs.value_type = 'datetime64' + elif value.dtype.type == np.timedelta64: + self._handle.createArray(self.group, key, value.view('i8')) + getattr(self.group, key)._v_attrs.value_type = 'timedelta64' else: if empty_array: self.write_array_empty(key, value) @@ -4000,7 +4031,9 @@ def eval(self): """ set the numexpr expression for this term """ if not self.is_valid: - raise ValueError("query term is not valid [%s]" % str(self)) + raise ValueError("query term is not valid [{0}]\n" + " all queries terms must include a reference to\n" + " either an axis (e.g. index or column), or a data_columns\n".format(str(self))) # convert values if we are in the table if self.is_in_table: @@ -4060,6 +4093,9 @@ def stringify(value): if v.tz is not None: v = v.tz_convert('UTC') return TermValue(v, v.value, kind) + elif kind == u('timedelta64') or kind == u('timedelta'): + v = _coerce_scalar_to_timedelta_type(v,unit='s').item() + return TermValue(int(v), v, kind) elif (isinstance(v, datetime) or hasattr(v, 'timetuple') or kind == u('date')): v = time.mktime(v.timetuple()) diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 7e5c3f9fff061..3f4ce72198215 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -22,7 +22,8 @@ assert_frame_equal, assert_series_equal) from pandas import concat, Timestamp -from pandas import compat +from pandas import compat, _np_version_under1p7 +from pandas.core import common as com from numpy.testing.decorators import slow @@ -1732,7 +1733,7 @@ def test_unimplemented_dtypes_table_columns(self): # this fails because we have a date in the object block...... self.assertRaises(TypeError, store.append, 'df_unimplemented', df) - def test_table_append_with_timezones(self): + def test_append_with_timezones(self): from datetime import timedelta @@ -1798,6 +1799,51 @@ def compare(a,b): result = store.select('df') assert_frame_equal(result,df) + def test_append_with_timedelta(self): + if _np_version_under1p7: + raise nose.SkipTest("requires numpy >= 1.7") + + # GH 3577 + # append timedelta + + from datetime import timedelta + df = DataFrame(dict(A = Timestamp('20130101'), B = [ Timestamp('20130101') + timedelta(days=i,seconds=10) for i in range(10) ])) + df['C'] = df['A']-df['B'] + df.ix[3:5,'C'] = np.nan + + with ensure_clean(self.path) as store: + + # table + _maybe_remove(store, 'df') + store.append('df',df,data_columns=True) + result = store.select('df') + assert_frame_equal(result,df) + + result = store.select('df',Term("C<100000")) + assert_frame_equal(result,df) + + result = store.select('df',Term("C","<",-3*86400)) + assert_frame_equal(result,df.iloc[3:]) + + result = store.select('df',Term("C","<",'-3D')) + assert_frame_equal(result,df.iloc[3:]) + + # a bit hacky here as we don't really deal with the NaT properly + + result = store.select('df',Term("C","<",'-500000s')) + result = result.dropna(subset=['C']) + assert_frame_equal(result,df.iloc[6:]) + + result = store.select('df',Term("C","<",'-3.5D')) + result = result.iloc[1:] + assert_frame_equal(result,df.iloc[4:]) + + # fixed + _maybe_remove(store, 'df2') + store.put('df2',df) + result = store.select('df2') + assert_frame_equal(result,df) + def test_remove(self): with ensure_clean(self.path) as store: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 723810a19d140..c5af0b0d4d5c8 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3248,9 +3248,10 @@ def test_operators_timedelta64(self): mixed['F'] = Timestamp('20130101') # results in an object array + from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type result = mixed.min() - expected = Series([com._coerce_scalar_to_timedelta_type(timedelta(seconds=5*60+5)), - com._coerce_scalar_to_timedelta_type(timedelta(days=-1)), + expected = Series([_coerce_scalar_to_timedelta_type(timedelta(seconds=5*60+5)), + _coerce_scalar_to_timedelta_type(timedelta(days=-1)), 'foo', 1, 1.0, diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 1f008354756bc..7a993cbcf07f4 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -14,7 +14,7 @@ import pandas as pd from pandas import (Index, Series, DataFrame, isnull, notnull, - bdate_range, date_range) + bdate_range, date_range, _np_version_under1p7) from pandas.core.index import MultiIndex from pandas.tseries.index import Timestamp, DatetimeIndex import pandas.core.config as cf @@ -2188,7 +2188,7 @@ def test_timedeltas_with_DateOffset(self): [Timestamp('20130101 9:06:00.005'), Timestamp('20130101 9:07:00.005')]) assert_series_equal(result, expected) - if not com._np_version_under1p7: + if not _np_version_under1p7: # operate with np.timedelta64 correctly result = s + np.timedelta64(1, 's') @@ -2292,7 +2292,7 @@ def test_timedelta64_operations_with_integers(self): self.assertRaises(TypeError, sop, s2.values) def test_timedelta64_conversions(self): - if com._np_version_under1p7: + if _np_version_under1p7: raise nose.SkipTest("cannot use 2 argument form of timedelta64 conversions with numpy < 1.7") startdate = Series(date_range('2013-01-01', '2013-01-03')) @@ -2317,7 +2317,7 @@ def test_timedelta64_equal_timedelta_supported_ops(self): 'm': 60 * 1000000, 's': 1000000, 'us': 1} def timedelta64(*args): - if com._np_version_under1p7: + if _np_version_under1p7: coeffs = np.array(args) terms = np.array([npy16_mappings[interval] for interval in intervals]) @@ -2426,7 +2426,7 @@ def test_timedelta64_functions(self): assert_series_equal(result, expected) def test_timedelta_fillna(self): - if com._np_version_under1p7: + if _np_version_under1p7: raise nose.SkipTest("timedelta broken in np 1.6.1") #GH 3371 @@ -2498,12 +2498,12 @@ def test_datetime64_fillna(self): assert_series_equal(result,expected) def test_sub_of_datetime_from_TimeSeries(self): - from pandas.core import common as com + from pandas.tseries.timedeltas import _possibly_cast_to_timedelta from datetime import datetime a = Timestamp(datetime(1993, 0o1, 0o7, 13, 30, 00)) b = datetime(1993, 6, 22, 13, 30) a = Series([a]) - result = com._possibly_cast_to_timedelta(np.abs(a - b)) + result = _possibly_cast_to_timedelta(np.abs(a - b)) self.assert_(result.dtype == 'timedelta64[ns]') def test_datetime64_with_index(self): diff --git a/pandas/tseries/api.py b/pandas/tseries/api.py index ead5a17c4fab1..c2cc3723802fc 100644 --- a/pandas/tseries/api.py +++ b/pandas/tseries/api.py @@ -7,5 +7,6 @@ from pandas.tseries.frequencies import infer_freq from pandas.tseries.period import Period, PeriodIndex, period_range, pnow from pandas.tseries.resample import TimeGrouper +from pandas.tseries.timedeltas import to_timedelta from pandas.lib import NaT import pandas.tseries.offsets as offsets diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index e91cad62e7dce..1572ca481d8a4 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -7,8 +7,7 @@ import numpy as np from pandas.core.common import (isnull, _NS_DTYPE, _INT64_DTYPE, - is_list_like,_possibly_cast_to_timedelta, - _values_from_object, _maybe_box) + is_list_like,_values_from_object, _maybe_box) from pandas.core.index import Index, Int64Index import pandas.compat as compat from pandas.compat import u diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py new file mode 100644 index 0000000000000..551507039112b --- /dev/null +++ b/pandas/tseries/tests/test_timedeltas.py @@ -0,0 +1,168 @@ +# pylint: disable-msg=E1101,W0612 + +from datetime import datetime, timedelta +import nose +import unittest + +import numpy as np +import pandas as pd + +from pandas import (Index, Series, DataFrame, isnull, notnull, + bdate_range, date_range, _np_version_under1p7) +import pandas.core.common as com +from pandas.compat import StringIO, lrange, range, zip, u, OrderedDict, long +from pandas import compat, to_timedelta, tslib +from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type as ct +from pandas.util.testing import (assert_series_equal, + assert_frame_equal, + assert_almost_equal, + ensure_clean) +import pandas.util.testing as tm + +def _skip_if_numpy_not_friendly(): + # not friendly for < 1.7 + if _np_version_under1p7: + raise nose.SkipTest("numpy < 1.7") + +class TestTimedeltas(unittest.TestCase): + _multiprocess_can_split_ = True + + def setUp(self): + pass + + def test_numeric_conversions(self): + _skip_if_numpy_not_friendly() + + self.assert_(ct(0) == np.timedelta64(0,'ns')) + self.assert_(ct(10) == np.timedelta64(10,'ns')) + self.assert_(ct(10,unit='ns') == np.timedelta64(10,'ns').astype('m8[ns]')) + + self.assert_(ct(10,unit='us') == np.timedelta64(10,'us').astype('m8[ns]')) + self.assert_(ct(10,unit='ms') == np.timedelta64(10,'ms').astype('m8[ns]')) + self.assert_(ct(10,unit='s') == np.timedelta64(10,'s').astype('m8[ns]')) + self.assert_(ct(10,unit='d') == np.timedelta64(10,'D').astype('m8[ns]')) + + def test_timedelta_conversions(self): + _skip_if_numpy_not_friendly() + + self.assert_(ct(timedelta(seconds=1)) == np.timedelta64(1,'s').astype('m8[ns]')) + self.assert_(ct(timedelta(microseconds=1)) == np.timedelta64(1,'us').astype('m8[ns]')) + self.assert_(ct(timedelta(days=1)) == np.timedelta64(1,'D').astype('m8[ns]')) + + def test_short_format_converters(self): + _skip_if_numpy_not_friendly() + + def conv(v): + return v.astype('m8[ns]') + + self.assert_(ct('10') == np.timedelta64(10,'ns')) + self.assert_(ct('10ns') == np.timedelta64(10,'ns')) + self.assert_(ct('100') == np.timedelta64(100,'ns')) + self.assert_(ct('100ns') == np.timedelta64(100,'ns')) + + self.assert_(ct('1000') == np.timedelta64(1000,'ns')) + self.assert_(ct('1000ns') == np.timedelta64(1000,'ns')) + self.assert_(ct('1000NS') == np.timedelta64(1000,'ns')) + + self.assert_(ct('10us') == np.timedelta64(10000,'ns')) + self.assert_(ct('100us') == np.timedelta64(100000,'ns')) + self.assert_(ct('1000us') == np.timedelta64(1000000,'ns')) + self.assert_(ct('1000Us') == np.timedelta64(1000000,'ns')) + self.assert_(ct('1000uS') == np.timedelta64(1000000,'ns')) + + self.assert_(ct('1ms') == np.timedelta64(1000000,'ns')) + self.assert_(ct('10ms') == np.timedelta64(10000000,'ns')) + self.assert_(ct('100ms') == np.timedelta64(100000000,'ns')) + self.assert_(ct('1000ms') == np.timedelta64(1000000000,'ns')) + + self.assert_(ct('-1s') == -np.timedelta64(1000000000,'ns')) + self.assert_(ct('1s') == np.timedelta64(1000000000,'ns')) + self.assert_(ct('10s') == np.timedelta64(10000000000,'ns')) + self.assert_(ct('100s') == np.timedelta64(100000000000,'ns')) + self.assert_(ct('1000s') == np.timedelta64(1000000000000,'ns')) + + self.assert_(ct('1d') == conv(np.timedelta64(1,'D'))) + self.assert_(ct('-1d') == -conv(np.timedelta64(1,'D'))) + self.assert_(ct('1D') == conv(np.timedelta64(1,'D'))) + self.assert_(ct('10D') == conv(np.timedelta64(10,'D'))) + self.assert_(ct('100D') == conv(np.timedelta64(100,'D'))) + self.assert_(ct('1000D') == conv(np.timedelta64(1000,'D'))) + self.assert_(ct('10000D') == conv(np.timedelta64(10000,'D'))) + + # space + self.assert_(ct(' 10000D ') == conv(np.timedelta64(10000,'D'))) + self.assert_(ct(' - 10000D ') == -conv(np.timedelta64(10000,'D'))) + + # invalid + self.assertRaises(ValueError, ct, '1foo') + self.assertRaises(ValueError, ct, 'foo') + + def test_full_format_converters(self): + _skip_if_numpy_not_friendly() + + def conv(v): + return v.astype('m8[ns]') + d1 = np.timedelta64(1,'D') + + self.assert_(ct('1days') == conv(d1)) + self.assert_(ct('1days,') == conv(d1)) + self.assert_(ct('- 1days,') == -conv(d1)) + + self.assert_(ct('00:00:01') == conv(np.timedelta64(1,'s'))) + self.assert_(ct('06:00:01') == conv(np.timedelta64(6*3600+1,'s'))) + self.assert_(ct('06:00:01.0') == conv(np.timedelta64(6*3600+1,'s'))) + self.assert_(ct('06:00:01.01') == conv(np.timedelta64(1000*(6*3600+1)+10,'ms'))) + + self.assert_(ct('- 1days, 00:00:01') == -conv(d1+np.timedelta64(1,'s'))) + self.assert_(ct('1days, 06:00:01') == conv(d1+np.timedelta64(6*3600+1,'s'))) + self.assert_(ct('1days, 06:00:01.01') == conv(d1+np.timedelta64(1000*(6*3600+1)+10,'ms'))) + + # invalid + self.assertRaises(ValueError, ct, '- 1days, 00') + + def test_nat_converters(self): + _skip_if_numpy_not_friendly() + + self.assert_(to_timedelta('nat') == tslib.iNaT) + self.assert_(to_timedelta('nan') == tslib.iNaT) + + def test_to_timedelta(self): + _skip_if_numpy_not_friendly() + + def conv(v): + return v.astype('m8[ns]') + d1 = np.timedelta64(1,'D') + + self.assert_(to_timedelta('1 days 06:05:01.00003') == conv(d1+np.timedelta64(6*3600+5*60+1,'s')+np.timedelta64(30,'us'))) + self.assert_(to_timedelta('15.5us') == conv(np.timedelta64(15500,'ns'))) + + # empty string + result = to_timedelta('') + self.assert_(result == tslib.iNaT) + + result = to_timedelta(['', '']) + self.assert_(isnull(result).all()) + + # pass thru + result = to_timedelta(np.array([np.timedelta64(1,'s')])) + expected = np.array([np.timedelta64(1,'s')]) + tm.assert_almost_equal(result,expected) + + # ints + result = np.timedelta64(0,'ns') + expected = to_timedelta(0) + self.assert_(result == expected) + + # Series + expected = Series([timedelta(days=1), timedelta(days=1, seconds=1)]) + result = to_timedelta(Series(['1d','1days 00:00:01'])) + tm.assert_series_equal(result, expected) + + # with units + result = Series([ np.timedelta64(0,'ns'), np.timedelta64(10,'s').astype('m8[ns]') ],dtype='m8[ns]') + expected = to_timedelta([0,10],unit='s') + tm.assert_series_equal(result, expected) + +if __name__ == '__main__': + nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], + exit=False) diff --git a/pandas/tseries/timedeltas.py b/pandas/tseries/timedeltas.py new file mode 100644 index 0000000000000..4d8633546e017 --- /dev/null +++ b/pandas/tseries/timedeltas.py @@ -0,0 +1,226 @@ +""" +timedelta support tools +""" + +import re +from datetime import timedelta + +import numpy as np +import pandas.tslib as tslib +from pandas import compat, _np_version_under1p7 +from pandas.core.common import (ABCSeries, is_integer, is_timedelta64_dtype, + _values_from_object, is_list_like) + +repr_timedelta = tslib.repr_timedelta64 +repr_timedelta64 = tslib.repr_timedelta64 + +def to_timedelta(arg, box=True, unit='ns'): + """ + Convert argument to timedelta + + Parameters + ---------- + arg : string, timedelta, array of strings (with possible NAs) + box : boolean, default True + If True returns a Series of the results, if False returns ndarray of values + unit : unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer/float number + + Returns + ------- + ret : timedelta64/arrays of timedelta64 if parsing succeeded + """ + if _np_version_under1p7: + raise ValueError("to_timedelta is not support for numpy < 1.7") + + def _convert_listlike(arg, box): + + if isinstance(arg, (list,tuple)): + arg = np.array(arg, dtype='O') + + if is_timedelta64_dtype(arg): + if box: + from pandas import Series + return Series(arg,dtype='m8[ns]') + return arg + + value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit) for r in arg ]) + if box: + from pandas import Series + value = Series(value,dtype='m8[ns]') + return value + + if arg is None: + return arg + elif isinstance(arg, ABCSeries): + from pandas import Series + values = _convert_listlike(arg.values, box=False) + return Series(values, index=arg.index, name=arg.name, dtype='m8[ns]') + elif is_list_like(arg): + return _convert_listlike(arg, box=box) + + return _convert_listlike([ arg ], box=False)[0] + +_short_search = re.compile( + "^\s*(?P<neg>-?)\s*(?P<value>\d*\.?\d*)\s*(?P<unit>d|s|ms|us|ns)?\s*$",re.IGNORECASE) +_full_search = re.compile( + "^\s*(?P<neg>-?)\s*(?P<days>\d+)?\s*(days|d)?,?\s*(?P<time>\d{2}:\d{2}:\d{2})?(?P<frac>\.\d+)?\s*$",re.IGNORECASE) +_nat_search = re.compile( + "^\s*(nat|nan)\s*$",re.IGNORECASE) +_whitespace = re.compile('^\s*$') + +def _coerce_scalar_to_timedelta_type(r, unit='ns'): + # kludgy here until we have a timedelta scalar + # handle the numpy < 1.7 case + + def conv(v): + if _np_version_under1p7: + return timedelta(microseconds=v/1000.0) + return np.timedelta64(v) + + if isinstance(r, compat.string_types): + converter = _get_string_converter(r, unit=unit) + r = converter() + r = conv(r) + elif r == tslib.iNaT: + return r + elif isinstance(r, np.timedelta64): + r = r.astype("m8[{0}]".format(unit.lower())) + elif is_integer(r): + r = tslib.cast_from_unit(r, unit) + r = conv(r) + + if _np_version_under1p7: + if not isinstance(r, timedelta): + raise AssertionError("Invalid type for timedelta scalar: %s" % type(r)) + if compat.PY3: + # convert to microseconds in timedelta64 + r = np.timedelta64(int(r.total_seconds()*1e9 + r.microseconds*1000)) + else: + return r + + if isinstance(r, timedelta): + r = np.timedelta64(r) + elif not isinstance(r, np.timedelta64): + raise AssertionError("Invalid type for timedelta scalar: %s" % type(r)) + return r.astype('timedelta64[ns]') + +def _get_string_converter(r, unit='ns'): + """ return a string converter for r to process the timedelta format """ + + # treat as a nan + if _whitespace.search(r): + def convert(r=None, unit=None): + return tslib.iNaT + return convert + + m = _short_search.search(r) + if m: + def convert(r=None, unit=unit, m=m): + if r is not None: + m = _short_search.search(r) + + gd = m.groupdict() + + r = float(gd['value']) + u = gd.get('unit') + if u is not None: + unit = u.lower() + if gd['neg']: + r *= -1 + return tslib.cast_from_unit(r, unit) + return convert + + m = _full_search.search(r) + if m: + def convert(r=None, unit=None, m=m): + if r is not None: + m = _full_search.search(r) + + gd = m.groupdict() + + # convert to seconds + value = float(gd['days'] or 0) * 86400 + + time = gd['time'] + if time: + (hh,mm,ss) = time.split(':') + value += float(hh)*3600 + float(mm)*60 + float(ss) + + frac = gd['frac'] + if frac: + value += float(frac) + + if gd['neg']: + value *= -1 + return tslib.cast_from_unit(value, 's') + return convert + + m = _nat_search.search(r) + if m: + def convert(r=None, unit=None, m=m): + return tslib.iNaT + return convert + + # no converter + raise ValueError("cannot create timedelta string converter") + +def _possibly_cast_to_timedelta(value, coerce=True): + """ try to cast to timedelta64, if already a timedeltalike, then make + sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards, + don't force the conversion unless coerce is True + + if coerce='compat' force a compatibilty coercerion (to timedeltas) if needeed + """ + + # coercion compatability + if coerce == 'compat' and _np_version_under1p7: + + def convert(td, dtype): + + # we have an array with a non-object dtype + if hasattr(td,'item'): + td = td.astype(np.int64).item() + if td == tslib.iNaT: + return td + if dtype == 'm8[us]': + td *= 1000 + return td + + if td == tslib.compat_NaT: + return tslib.iNaT + + # convert td value to a nanosecond value + d = td.days + s = td.seconds + us = td.microseconds + + if dtype == 'object' or dtype == 'm8[ns]': + td = 1000*us + (s + d * 24 * 3600) * 10 ** 9 + else: + raise ValueError("invalid conversion of dtype in np < 1.7 [%s]" % dtype) + + return td + + # < 1.7 coercion + if not is_list_like(value): + value = np.array([ value ]) + + dtype = value.dtype + return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]') + + # deal with numpy not being able to handle certain timedelta operations + if isinstance(value, (ABCSeries, np.ndarray)) and value.dtype.kind == 'm': + if value.dtype != 'timedelta64[ns]': + value = value.astype('timedelta64[ns]') + return value + + # we don't have a timedelta, but we want to try to convert to one (but + # don't force it) + if coerce: + new_value = tslib.array_to_timedelta64( + _values_from_object(value).astype(object), coerce=False) + if new_value.dtype == 'i8': + value = np.array(new_value, dtype='timedelta64[ns]') + + return value + diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 983d3385e8f85..fd97512b0528b 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -665,14 +665,14 @@ cdef convert_to_tsobject(object ts, object tz, object unit): if ts == NPY_NAT: obj.value = NPY_NAT else: - ts = ts * cast_from_unit(unit,None) + ts = ts * cast_from_unit(None,unit) obj.value = ts pandas_datetime_to_datetimestruct(ts, PANDAS_FR_ns, &obj.dts) elif util.is_float_object(ts): if ts != ts or ts == NPY_NAT: obj.value = NPY_NAT else: - ts = cast_from_unit(unit,ts) + ts = cast_from_unit(ts,unit) obj.value = ts pandas_datetime_to_datetimestruct(ts, PANDAS_FR_ns, &obj.dts) elif util.is_string_object(ts): @@ -852,7 +852,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, pandas_datetimestruct dts bint utc_convert = bool(utc) _TSObject _ts - int64_t m = cast_from_unit(unit,None) + int64_t m = cast_from_unit(None,unit) try: result = np.empty(n, dtype='M8[ns]') @@ -892,7 +892,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False, if val != val or val == iNaT: iresult[i] = iNaT else: - iresult[i] = cast_from_unit(unit,val) + iresult[i] = cast_from_unit(val,unit) else: try: if len(val) == 0: @@ -1276,10 +1276,10 @@ cdef inline _get_datetime64_nanos(object val): else: return ival -cdef inline int64_t cast_from_unit(object unit, object ts) except -1: +cpdef inline int64_t cast_from_unit(object ts, object unit) except -1: """ return a casting of the unit represented to nanoseconds round the fractional part of a float to our precision, p """ - if unit == 'D': + if unit == 'D' or unit == 'd': m = 1000000000L * 86400 p = 6 elif unit == 's': @@ -1303,7 +1303,9 @@ cdef inline int64_t cast_from_unit(object unit, object ts) except -1: # to avoid precision issues from float -> int base = <int64_t> ts frac = ts-base - return <int64_t> (base*m) + <int64_t> (round(frac,p)*m) + if p: + frac = round(frac,p) + return <int64_t> (base*m) + <int64_t> (frac*m) def cast_to_nanoseconds(ndarray arr): cdef:
closes .#3577 realted #3009 - ENH: add top-level `to_timedelta` to convert string/integer to timedeltas - TST: add pandas/tseries/tests/test_timedeltas.py - API: add full timedelta parsing and conversion to np.timedelta64[ns] - CLN: refactored locations of timedeltas to core/tseries/timedeltas (from a series of functions in core/common) - ENH: support timedelta64[ns] as a serialization type in HDFStore for query and append (GH3577)
https://api.github.com/repos/pandas-dev/pandas/pulls/4822
2013-09-12T00:05:21Z
2013-09-12T16:05:09Z
2013-09-12T16:05:09Z
2014-07-02T22:36:46Z
ENH: Allow abs to work with PandasObjects
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8eb6c858c0b29..212e2bad563b6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -560,6 +560,9 @@ def __nonzero__(self): __bool__ = __nonzero__ + def __abs__(self): + return self.abs() + #---------------------------------------------------------------------- # Array Interface diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index f9756858b5d85..723810a19d140 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3234,9 +3234,11 @@ def test_operators_timedelta64(self): # abs result = diffs.abs() + result2 = abs(diffs) expected = DataFrame(dict(A = df['A']-df['C'], B = df['B']-df['A'])) assert_frame_equal(result,expected) + assert_frame_equal(result2, expected) # mixed frame mixed = diffs.copy() diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 938025c450258..fc86a78ea684b 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -355,18 +355,24 @@ def test_get_value(self): def test_abs(self): result = self.panel.abs() + result2 = abs(self.panel) expected = np.abs(self.panel) self.assert_panel_equal(result, expected) + self.assert_panel_equal(result2, expected) df = self.panel['ItemA'] result = df.abs() + result2 = abs(df) expected = np.abs(df) assert_frame_equal(result, expected) + assert_frame_equal(result2, expected) s = df['A'] result = s.abs() + result2 = abs(s) expected = np.abs(s) assert_series_equal(result, expected) + assert_series_equal(result2, expected) class CheckIndexing(object):
Add `__abs__` method so that you can use the toplevel `abs()` with PandasObjects. I note there aren't that many existing test cases for abs. At some point we might want to think about that. Also related #4819 cc @thisch
https://api.github.com/repos/pandas-dev/pandas/pulls/4821
2013-09-11T23:38:26Z
2013-09-11T23:49:00Z
2013-09-11T23:49:00Z
2014-06-25T20:28:51Z
API: Complex compat for Series with ndarray. (GH4819)
diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index 0b0023f533705..5dcb6c20be69d 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -116,7 +116,7 @@ panelnd The :ref:`panelnd<dsintro.panelnd>` docs. `Construct a 5D panelnd -http://stackoverflow.com/questions/18748598/why-my-panelnd-factory-throwing-a-keyerror`__ +<http://stackoverflow.com/questions/18748598/why-my-panelnd-factory-throwing-a-keyerror>`__ .. _cookbook.missing_data: diff --git a/doc/source/release.rst b/doc/source/release.rst index fd724af9917d2..087d2880511d2 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -265,6 +265,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility - Refactor of Series arithmetic with time-like objects (datetime/timedelta/time etc.) into a separate, cleaned up wrapper class. (:issue:`4613`) +- Complex compat for ``Series`` with ``ndarray``. (:issue:`4819`) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/series.py b/pandas/core/series.py index 32f6765b5d84d..577e0a8b57930 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -35,6 +35,7 @@ from pandas import compat from pandas.util.terminal import get_terminal_size from pandas.compat import zip, lzip, u, OrderedDict +from pandas.util import rwproperty import pandas.core.array as pa @@ -793,6 +794,23 @@ def __array_wrap__(self, result): def __contains__(self, key): return key in self.index + # complex + @rwproperty.getproperty + def real(self): + return self.values.real + + @rwproperty.setproperty + def real(self, v): + self.values.real = v + + @rwproperty.getproperty + def imag(self): + return self.values.imag + + @rwproperty.setproperty + def imag(self, v): + self.values.imag = v + # coercion __float__ = _coerce_method(float) __long__ = _coerce_method(int) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 7f8fa1019261f..1f008354756bc 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2814,6 +2814,19 @@ def f(x): expected = Series(1,index=range(10),dtype='float64') #assert_series_equal(result,expected) + def test_complexx(self): + + # GH4819 + # complex access for ndarray compat + a = np.arange(5) + b = Series(a + 4j*a) + tm.assert_almost_equal(a,b.real) + tm.assert_almost_equal(4*a,b.imag) + + b.real = np.arange(5)+5 + tm.assert_almost_equal(a+5,b.real) + tm.assert_almost_equal(4*a,b.imag) + def test_underlying_data_conversion(self): # GH 4080
closes #4819
https://api.github.com/repos/pandas-dev/pandas/pulls/4820
2013-09-11T21:06:26Z
2013-09-11T21:23:29Z
2013-09-11T21:23:29Z
2014-06-23T07:11:10Z
TST: tests for GH4812 (already fixed in master)
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index 1c6c4eae8d279..6ad69a466ba03 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -284,6 +284,17 @@ def test_resample_ohlc_dataframe(self): # dupe columns fail atm # df.columns = ['PRICE', 'PRICE'] + def test_resample_dup_index(self): + + # GH 4812 + # dup columns with resample raising + df = DataFrame(np.random.randn(4,12),index=[2000,2000,2000,2000],columns=[ Period(year=2000,month=i+1,freq='M') for i in range(12) ]) + df.iloc[3,:] = np.nan + result = df.resample('Q',axis=1) + expected = df.groupby(lambda x: int((x.month-1)/3),axis=1).mean() + expected.columns = [ Period(year=2000,quarter=i+1,freq='Q') for i in range(4) ] + assert_frame_equal(result, expected) + def test_resample_reresample(self): dti = DatetimeIndex( start=datetime(2005, 1, 1), end=datetime(2005, 1, 10),
closes #4812 was already fixed!
https://api.github.com/repos/pandas-dev/pandas/pulls/4813
2013-09-11T17:19:26Z
2013-09-13T00:08:05Z
2013-09-13T00:08:05Z
2014-06-19T21:26:34Z
CLN: removed need for Coordinates in HDFStore tables / added doc section
diff --git a/doc/source/io.rst b/doc/source/io.rst index 3a284062a2ec9..1d3980e216587 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2118,6 +2118,22 @@ These do not currently accept the ``where`` selector (coming soon) store.select_column('df_dc', 'index') store.select_column('df_dc', 'string') +.. _io.hdf5-selecting_coordinates: + +**Selecting coordinates** + +Sometimes you want to get the coordinates (a.k.a the index locations) of your query. This returns an +``Int64Index`` of the resulting locations. These coordinates can also be passed to subsequent +``where`` operations. + +.. ipython:: python + + df_coord = DataFrame(np.random.randn(1000,2),index=date_range('20000101',periods=1000)) + store.append('df_coord',df_coord) + c = store.select_as_coordinates('df_coord','index>20020101') + c.summary() + store.select('df_coord',where=c) + .. _io.hdf5-where_mask: **Selecting using a where mask** diff --git a/doc/source/release.rst b/doc/source/release.rst index a23aa2fcebc12..ce9c8d6319c46 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -155,6 +155,7 @@ API Changes the ``Storer`` format has been renamed to ``Fixed`` - a column multi-index will be recreated properly (:issue:`4710`); raise on trying to use a multi-index with data_columns on the same axis + - ``select_as_coordinates`` will now return an ``Int64Index`` of the resultant selection set - ``JSON`` - added ``date_unit`` parameter to specify resolution of timestamps. Options diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 3431d82219856..caf218747bdfb 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -76,6 +76,8 @@ API changes duplicate rows from a table (:issue:`4367`) - removed the ``warn`` argument from ``open``. Instead a ``PossibleDataLossError`` exception will be raised if you try to use ``mode='w'`` with an OPEN file handle (:issue:`4367`) + - ``select_as_coordinates`` will now return an ``Int64Index`` of the resultant selection set + See :ref:`here<io.hdf5-selecting_coordinates>` for an example. - allow a passed locations array or mask as a ``where`` condition (:issue:`4467`). See :ref:`here<io.hdf5-where_mask>` for an example. diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d445ce8b797b5..6759e07ed7935 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -565,7 +565,7 @@ def func(_start, _stop): def select_as_coordinates(self, key, where=None, start=None, stop=None, **kwargs): """ - return the selection as a Coordinates. + return the selection as an Index Parameters ---------- @@ -3071,7 +3071,7 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs): # create the selection self.selection = Selection( self, where=where, start=start, stop=stop, **kwargs) - return Coordinates(self.selection.select_coords(), group=self.group, where=where) + return Index(self.selection.select_coords()) def read_column(self, column, where=None, **kwargs): """ return a single column from the table, generally only indexables are interesting """ @@ -4106,28 +4106,6 @@ def tostring(self, encoding): return self.converted -class Coordinates(object): - - """ holds a returned coordinates list, useful to select the same rows from different tables - - coordinates : holds the array of coordinates - group : the source group - where : the source where - """ - - def __init__(self, values, group, where, **kwargs): - self.values = values - self.group = group - self.where = where - - def __len__(self): - return len(self.values) - - def __getitem__(self, key): - """ return a new coordinates object, sliced by the key """ - return Coordinates(self.values[key], self.group, self.where) - - class Selection(object): """ @@ -4151,11 +4129,7 @@ def __init__(self, table, where=None, start=None, stop=None, **kwargs): self.terms = None self.coordinates = None - # a coordinate - if isinstance(where, Coordinates): - self.coordinates = where.values - - elif com.is_list_like(where): + if com.is_list_like(where): # see if we have a passed coordinate like try: diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 48a2150758a3f..7e5c3f9fff061 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2879,6 +2879,7 @@ def test_coordinates(self): result = store.select('df', where=c) expected = df.ix[3:4, :] tm.assert_frame_equal(result, expected) + self.assert_(isinstance(c, Index)) # multiple tables _maybe_remove(store, 'df1')
CLN: removed need for Coordinates, instead return an Index of the coordinates DOC: added section on select_as_coordinates
https://api.github.com/repos/pandas-dev/pandas/pulls/4809
2013-09-11T00:14:48Z
2013-09-11T00:25:20Z
2013-09-11T00:25:20Z
2014-07-16T08:27:38Z
BUG: Fixed an issue with a duplicate index and assignment with a dtype change (GH4686)
diff --git a/doc/source/release.rst b/doc/source/release.rst index a23aa2fcebc12..121ff505aa23c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -376,6 +376,7 @@ Bug Fixes - Fix bugs in indexing in a Series with a duplicate index (:issue:`4548`, :issue:`4550`) - Fixed bug with reading compressed files with ``read_fwf`` in Python 3. (:issue:`3963`) + - Fixed an issue with a duplicate index and assignment with a dtype change (:issue:`4686`) pandas 0.12.0 ------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 91be4f42c17e4..e22202c65c140 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1797,11 +1797,13 @@ def _reset_ref_locs(self): def _rebuild_ref_locs(self): """ take _ref_locs and set the individual block ref_locs, skipping Nones no effect on a unique index """ - if self._ref_locs is not None: + if getattr(self,'_ref_locs',None) is not None: item_count = 0 for v in self._ref_locs: if v is not None: block, item_loc = v + if block._ref_locs is None: + block.reset_ref_locs() block._ref_locs[item_loc] = item_count item_count += 1 @@ -2595,11 +2597,11 @@ def _set_item(item, arr): self.delete(item) loc = _possibly_convert_to_indexer(loc) - for i, (l, arr) in enumerate(zip(loc, value)): + for i, (l, k, arr) in enumerate(zip(loc, subset, value)): # insert the item self.insert( - l, item, arr[None, :], allow_duplicates=True) + l, k, arr[None, :], allow_duplicates=True) # reset the _ref_locs on indiviual blocks # rebuild ref_locs diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 18ee89fbc5c66..4b17dd5ffd9db 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1292,6 +1292,24 @@ def test_astype_assignment_with_iloc(self): result = df.get_dtype_counts().sort_index() expected = Series({ 'int64' : 4, 'float64' : 1, 'object' : 2 }).sort_index() + def test_astype_assignment_with_dups(self): + + # GH 4686 + # assignment with dups that has a dtype change + df = DataFrame( + np.arange(3).reshape((1,3)), + columns=pd.MultiIndex.from_tuples( + [('A', '1'), ('B', '1'), ('A', '2')] + ), + dtype=object + ) + index = df.index.copy() + + df['A'] = df['A'].astype(np.float64) + result = df.get_dtype_counts().sort_index() + expected = Series({ 'float64' : 2, 'object' : 1 }).sort_index() + self.assert_(df.index.equals(index)) + def test_dups_loc(self): # GH4726
closes #4686
https://api.github.com/repos/pandas-dev/pandas/pulls/4806
2013-09-10T19:26:27Z
2013-09-10T19:54:07Z
2013-09-10T19:54:07Z
2014-07-03T22:52:42Z
ENH: Series constructor converts dicts with tuples in keys to MultiIndex
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index 3e11552be3612..0e449cb35eaaa 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -761,6 +761,7 @@ This is equivalent to the following .. _basics.reindexing: + Reindexing and altering labels ------------------------------ diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index c1b8044ea305b..aeb6ba7eaca25 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -1593,7 +1593,10 @@ can think of ``MultiIndex`` an array of tuples where each tuple is unique. A ``MultiIndex`` can be created from a list of arrays (using ``MultiIndex.from_arrays``), an array of tuples (using ``MultiIndex.from_tuples``), or a crossed set of iterables (using -``MultiIndex.from_product``). +``MultiIndex.from_product``). The ``Index`` constructor will attempt to return +a ``MultiIndex`` when it is passed a list of tuples. The following examples +demo different ways to initialize MultiIndexes. + .. ipython:: python @@ -1601,7 +1604,10 @@ can think of ``MultiIndex`` an array of tuples where each tuple is unique. A ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) tuples - index = MultiIndex.from_tuples(tuples, names=['first', 'second']) + + multi_index = MultiIndex.from_tuples(tuples, names=['first', 'second']) + multi_index + s = Series(randn(8), index=index) s diff --git a/doc/source/release.rst b/doc/source/release.rst index c0d4c0c73296f..b05d6fef69f7a 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -53,6 +53,9 @@ pandas 0.14.0 New features ~~~~~~~~~~~~ +- ``Index`` returns a MultiIndex if passed a list of tuples + ``DataFrame(dict)`` and ``Series(dict)`` create ``MultiIndex`` + columns and index where applicable (:issue:`4187`) - Hexagonal bin plots from ``DataFrame.plot`` with ``kind='hexbin'`` (:issue:`5478`) - Added the ``sym_diff`` method to ``Index`` (:issue:`5543`) - Added ``to_julian_date`` to ``TimeStamp`` and ``DatetimeIndex``. The Julian @@ -214,6 +217,8 @@ Bug Fixes ~~~~~~~~~ - Bug in Series ValueError when index doesn't match data (:issue:`6532`) +- Prevent segfault due to MultiIndex not being supported in HDFStore table + format (:issue:`1848`) - Bug in ``pd.DataFrame.sort_index`` where mergesort wasn't stable when ``ascending=False`` (:issue:`6399`) - Bug in ``pd.tseries.frequencies.to_offset`` when argument has leading zeroes (:issue:`6391`) - Bug in version string gen. for dev versions with shallow clones / install from tarball (:issue:`6127`) diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt index 057f83bff44f2..748d5e74c8166 100644 --- a/doc/source/v0.14.0.txt +++ b/doc/source/v0.14.0.txt @@ -346,6 +346,18 @@ Deprecations Enhancements ~~~~~~~~~~~~ +- DataFrame and Series will create MultiIndex if passed a list of tuples + + .. ipython:: python + + Series({('a', 'b'): 1, ('a', 'a'): 0, + ('a', 'c'): 2, ('b', 'a'): 3, ('b', 'b'): 4}) + pandas.DataFrame({('a', 'b'): {('A', 'B'): 1, ('A', 'C'): 2}, + ('a', 'a'): {('A', 'C'): 3, ('A', 'B'): 4}, + ('a', 'c'): {('A', 'B'): 5, ('A', 'C'): 6}, + ('b', 'a'): {('A', 'C'): 7, ('A', 'B'): 8}, + ('b', 'b'): {('A', 'D'): 9, ('A', 'B'): 10}}) + - ``DataFrame.to_latex`` now takes a longtable keyword, which if True will return a table in a longtable environment. (:issue:`6617`) - ``pd.read_clipboard`` will, if 'sep' is unspecified, try to detect data copied from a spreadsheet and parse accordingly. (:issue:`6223`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5ecdd4d8b351d..5d3a92227977b 100755 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -316,9 +316,9 @@ def _init_dict(self, data, index, columns, dtype=None): else: keys = list(data.keys()) if not isinstance(data, OrderedDict): - keys = _try_sort(list(data.keys())) + keys = _try_sort(keys) columns = data_names = Index(keys) - arrays = [data[k] for k in columns] + arrays = [data[k] for k in keys] return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) @@ -4512,7 +4512,7 @@ def extract_index(data): index = None if len(data) == 0: index = Index([]) - elif len(data) > 0 and index is None: + elif len(data) > 0: raw_lengths = [] indexes = [] diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 996a691eca082..4f5bf3ff5b6cd 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1157,8 +1157,7 @@ def groups(self): else: to_groupby = lzip(*(ping.grouper for ping in self.groupings)) to_groupby = Index(to_groupby) - - return self.axis.groupby(to_groupby) + return self.axis.groupby(to_groupby.values) @cache_readonly def group_info(self): diff --git a/pandas/core/index.py b/pandas/core/index.py index 3213f288be4b3..e15ca83256269 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -71,6 +71,8 @@ class Index(IndexOpsMixin, FrozenNDArray): Make a copy of input ndarray name : object Name to be stored in the index + tupleize_cols : bool (default: True) + When True, attempt to create a MultiIndex if possible Notes ----- @@ -99,7 +101,7 @@ class Index(IndexOpsMixin, FrozenNDArray): _engine_type = _index.ObjectEngine def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, - **kwargs): + tupleize_cols=True, **kwargs): # no class inference! if fastpath: @@ -139,8 +141,19 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, elif np.isscalar(data): cls._scalar_data_error(data) - else: + if tupleize_cols and isinstance(data, list) and data: + try: + sorted(data) + has_mixed_types = False + except (TypeError, UnicodeDecodeError): + has_mixed_types = True # python3 only + if isinstance(data[0], tuple) and not has_mixed_types: + try: + return MultiIndex.from_tuples( + data, names=name or kwargs.get('names')) + except (TypeError, KeyError): + pass # python2 - MultiIndex fails on mixed types # other iterable of some kind subarr = com._asarray_tuplesafe(data, dtype=object) @@ -808,7 +821,8 @@ def identical(self, other): """ return (self.equals(other) and all((getattr(self, c, None) == getattr(other, c, None) - for c in self._comparables))) + for c in self._comparables)) and + type(self) == type(other)) def asof(self, label): """ @@ -1755,11 +1769,11 @@ def insert(self, loc, item): ------- new_index : Index """ - index = np.asarray(self) - # because numpy is fussy with tuples - item_idx = Index([item], dtype=index.dtype) - new_index = np.concatenate((index[:loc], item_idx, index[loc:])) - return Index(new_index, name=self.name) + _self = np.asarray(self) + item_idx = Index([item], dtype=self.dtype).values + idx = np.concatenate( + (_self[:loc], item_idx, _self[loc:])) + return Index(idx, name=self.name) def drop(self, labels): """ diff --git a/pandas/core/series.py b/pandas/core/series.py index 47721ab371c3b..5fd42fb38622a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -22,9 +22,9 @@ _values_from_object, _possibly_cast_to_datetime, _possibly_castable, _possibly_convert_platform, + _try_sort, ABCSparseArray, _maybe_match_name, _ensure_object, SettingWithCopyError) - from pandas.core.index import (Index, MultiIndex, InvalidIndexError, _ensure_index, _handle_legacy_indexes) from pandas.core.indexing import ( @@ -180,7 +180,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None, if isinstance(data, OrderedDict): index = Index(data) else: - index = Index(sorted(data)) + index = Index(_try_sort(data)) try: if isinstance(index, DatetimeIndex): # coerce back to datetime objects for lookup diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index 046fa3887a32d..eac1e0373f24d 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -58,6 +58,8 @@ def infer_dtype(object _values): _values = list(_values) values = list_to_object_array(_values) + values = getattr(values, 'values', values) + val_kind = values.dtype.type if val_kind in _TYPE_MAP: return _TYPE_MAP[val_kind] @@ -1029,6 +1031,8 @@ def fast_multiget(dict mapping, ndarray keys, default=np.nan): # kludge, for Series return np.empty(0, dtype='f8') + keys = getattr(keys, 'values', keys) + for i in range(n): val = util.get_value_1d(keys, i) if val in mapping: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 1bbcba0e4caad..86ebad3bc216e 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -181,12 +181,12 @@ def test_getitem_list(self): # tuples df = DataFrame(randn(8, 3), columns=Index([('foo', 'bar'), ('baz', 'qux'), - ('peek', 'aboo')], name='sth')) + ('peek', 'aboo')], name=['sth', 'sth2'])) result = df[[('foo', 'bar'), ('baz', 'qux')]] expected = df.ix[:, :2] assert_frame_equal(result, expected) - self.assertEqual(result.columns.name, 'sth') + self.assertEqual(result.columns.names, ['sth', 'sth2']) def test_setitem_list(self): @@ -2490,6 +2490,31 @@ def test_constructor_dict_of_tuples(self): expected = DataFrame(dict((k, list(v)) for k, v in compat.iteritems(data))) assert_frame_equal(result, expected, check_dtype=False) + def test_constructor_dict_multiindex(self): + check = lambda result, expected: tm.assert_frame_equal( + result, expected, check_dtype=True, check_index_type=True, + check_column_type=True, check_names=True) + d = {('a', 'a'): {('i', 'i'): 0, ('i', 'j'): 1, ('j', 'i'): 2}, + ('b', 'a'): {('i', 'i'): 6, ('i', 'j'): 5, ('j', 'i'): 4}, + ('b', 'c'): {('i', 'i'): 7, ('i', 'j'): 8, ('j', 'i'): 9}} + _d = sorted(d.items()) + df = DataFrame(d) + expected = DataFrame( + [x[1] for x in _d], + index=MultiIndex.from_tuples([x[0] for x in _d])).T + expected.index = MultiIndex.from_tuples(expected.index) + check(df, expected) + + d['z'] = {'y': 123., ('i', 'i'): 111, ('i', 'j'): 111, ('j', 'i'): 111} + _d.insert(0, ('z', d['z'])) + expected = DataFrame( + [x[1] for x in _d], + index=Index([x[0] for x in _d], tupleize_cols=False)).T + expected.index = Index(expected.index, tupleize_cols=False) + df = DataFrame(d) + df = df.reindex(columns=expected.columns, index=expected.index) + check(df, expected) + 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) @@ -2913,8 +2938,8 @@ class CustomDict(dict): def test_constructor_ragged(self): data = {'A': randn(10), 'B': randn(8)} - assertRaisesRegexp(ValueError, 'arrays must all be same length', - DataFrame, data) + with assertRaisesRegexp(ValueError, 'arrays must all be same length'): + DataFrame(data) def test_constructor_scalar(self): idx = Index(lrange(3)) @@ -12042,7 +12067,8 @@ def test_index_namedtuple(self): IndexType = namedtuple("IndexType", ["a", "b"]) idx1 = IndexType("foo", "bar") idx2 = IndexType("baz", "bof") - index = Index([idx1, idx2], name="composite_index") + index = Index([idx1, idx2], + name="composite_index", tupleize_cols=False) df = DataFrame([(1, 2), (3, 4)], index=index, columns=["A", "B"]) self.assertEqual(df.ix[IndexType("foo", "bar")]["A"], 1) diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index c6c405306afb8..2280ee4e22c57 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -48,7 +48,8 @@ def setUp(self): intIndex = tm.makeIntIndex(100), floatIndex = tm.makeFloatIndex(100), empty = Index([]), - tuples = Index(lzip(['foo', 'bar', 'baz'], [1, 2, 3])), + tuples = MultiIndex.from_tuples(lzip(['foo', 'bar', 'baz'], + [1, 2, 3])) ) for name, ind in self.indices.items(): setattr(self, name, ind) @@ -230,6 +231,10 @@ def test_identical(self): i2 = i2.rename('foo') self.assert_(i1.identical(i2)) + i3 = Index([('a', 'a'), ('a', 'b'), ('b', 'a')]) + i4 = Index([('a', 'a'), ('a', 'b'), ('b', 'a')], tupleize_cols=False) + self.assertFalse(i3.identical(i4)) + def test_is_(self): ind = Index(range(10)) self.assertTrue(ind.is_(ind)) @@ -987,18 +992,24 @@ def test_equals(self): self.assert_(same_values.equals(self.index)) def test_identical(self): + i = Index(self.index.copy()) + self.assertTrue(i.identical(self.index)) - i = self.index.copy() - same_values = Index(i, dtype=object) - self.assert_(i.identical(same_values)) + same_values_different_type = Index(i, dtype=object) + self.assertFalse(i.identical(same_values_different_type)) - i = self.index.copy() + i = self.index.copy(dtype=object) i = i.rename('foo') same_values = Index(i, dtype=object) - self.assert_(same_values.identical(self.index)) + self.assertTrue(same_values.identical(self.index.copy(dtype=object))) self.assertFalse(i.identical(self.index)) - self.assert_(Index(same_values, name='foo').identical(i)) + self.assertTrue(Index(same_values, name='foo', dtype=object + ).identical(i)) + + self.assertFalse( + self.index.copy(dtype=object) + .identical(self.index.copy(dtype='int64'))) def test_get_indexer(self): target = Int64Index(np.arange(10)) @@ -2210,6 +2221,12 @@ def test_identical(self): mi2 = mi2.set_names(['new1', 'new2']) self.assert_(mi.identical(mi2)) + mi3 = Index(mi.tolist(), names=mi.names) + mi4 = Index(mi.tolist(), names=mi.names, tupleize_cols=False) + self.assert_(mi.identical(mi3)) + self.assert_(not mi.identical(mi4)) + self.assert_(mi.equals(mi4)) + def test_is_(self): mi = MultiIndex.from_tuples(lzip(range(10), range(10))) self.assertTrue(mi.is_(mi)) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 95b7b6ace4e2d..377df1e4417f5 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -633,6 +633,26 @@ def test_constructor_dict(self): expected.ix[1] = 1 assert_series_equal(result, expected) + def test_constructor_dict_multiindex(self): + check = lambda result, expected: tm.assert_series_equal( + result, expected, check_dtype=True, check_index_type=True, + check_series_type=True) + d = {('a', 'a'): 0., ('b', 'a'): 1., ('b', 'c'): 2.} + _d = sorted(d.items()) + ser = Series(d) + expected = Series([x[1] for x in _d], + index=MultiIndex.from_tuples([x[0] for x in _d])) + check(ser, expected) + + d['z'] = 111. + _d.insert(0, ('z', d['z'])) + ser = Series(d) + expected = Series( + [x[1] for x in _d], + index=Index([x[0] for x in _d], tupleize_cols=False)) + ser = ser.reindex(index=expected.index) + check(ser, expected) + def test_constructor_subclass_dict(self): data = tm.TestSubDict((x, 10.0 * x) for x in range(10)) series = Series(data)
closes #3323 related #4187 related #1848 Hi, I'd love for Series (and DataFrame) initialized with a dict to automatically create the MultiIndex. See below example. Desired Result: ``` In [1]: pandas.Series({('a', 'b'): 1, ('a', 'a'): 0, ('a', 'c'): 2, ('b', 'a'): 3, ('b', 'b'): 4}) Out[1]: a a 0 b 1 c 2 b a 3 b 4 dtype: int64 In [2]: ``` Current result: ``` In [1]: pandas.Series({('a', 'b'): 1, ('a', 'a'): 0, ('a', 'c'): 2, ('b', 'a'): 3, ('b', 'b'): 4}) Out[1]: (a, a) 0 (a, b) 1 (a, c) 2 (b, a) 3 (b, b) 4 dtype: int64 In [2]: ``` Is this something I can go ahead and update tests for? It seems like we should have it. Also, what are your thoughts about adding this to the DataFrame constructor as well? Thanks, Alex
https://api.github.com/repos/pandas-dev/pandas/pulls/4805
2013-09-10T18:58:31Z
2014-04-09T23:32:01Z
null
2014-06-19T23:22:31Z
CLN: move align out of series consolidating into core/generic.py
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d5c265dcf93a0..d6daa467752a9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2202,7 +2202,7 @@ def last(self, offset): return self.ix[start:] def align(self, other, join='outer', axis=None, level=None, copy=True, - fill_value=np.nan, method=None, limit=None, fill_axis=0): + fill_value=None, method=None, limit=None, fill_axis=0): """ Align two object on their axes with the specified join method for each axis Index @@ -2288,35 +2288,51 @@ def _align_series(self, other, join='outer', axis=None, level=None, fill_axis=0): from pandas import DataFrame - fdata = self._data - if axis == 0: - join_index = self.index - lidx, ridx = None, None - if not self.index.equals(other.index): - join_index, lidx, ridx = self.index.join(other.index, how=join, - return_indexers=True) + # series/series compat + if isinstance(self, ABCSeries) and isinstance(other, ABCSeries): + if axis: + raise ValueError('cannot align series to a series other than axis 0') - if lidx is not None: - fdata = fdata.reindex_indexer(join_index, lidx, axis=1) - elif axis == 1: - join_index = self.columns - lidx, ridx = None, None - if not self.columns.equals(other.index): - join_index, lidx, ridx = \ - self.columns.join(other.index, how=join, - return_indexers=True) + join_index, lidx, ridx = self.index.join(other.index, how=join, + level=level, + return_indexers=True) + + left_result = self._reindex_indexer(join_index, lidx, copy) + right_result = other._reindex_indexer(join_index, ridx, copy) - if lidx is not None: - fdata = fdata.reindex_indexer(join_index, lidx, axis=0) else: - raise ValueError('Must specify axis=0 or 1') - if copy and fdata is self._data: - fdata = fdata.copy() + # one has > 1 ndim + fdata = self._data + if axis == 0: + join_index = self.index + lidx, ridx = None, None + if not self.index.equals(other.index): + join_index, lidx, ridx = self.index.join(other.index, how=join, + return_indexers=True) + + if lidx is not None: + fdata = fdata.reindex_indexer(join_index, lidx, axis=1) + elif axis == 1: + join_index = self.columns + lidx, ridx = None, None + if not self.columns.equals(other.index): + join_index, lidx, ridx = \ + self.columns.join(other.index, how=join, + return_indexers=True) + + if lidx is not None: + fdata = fdata.reindex_indexer(join_index, lidx, axis=0) + else: + raise ValueError('Must specify axis=0 or 1') + + if copy and fdata is self._data: + fdata = fdata.copy() - left_result = DataFrame(fdata) - right_result = other if ridx is None else other.reindex(join_index) + left_result = DataFrame(fdata) + right_result = other if ridx is None else other.reindex(join_index) + # fill fill_na = notnull(fill_value) or (method is not None) if fill_na: return (left_result.fillna(fill_value, method=method, limit=limit, diff --git a/pandas/core/series.py b/pandas/core/series.py index 3f93f210ad4cf..32f6765b5d84d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2667,45 +2667,6 @@ def apply(self, func, convert_dtype=True, args=(), **kwds): else: return self._constructor(mapped, index=self.index, name=self.name) - def align(self, other, join='outer', axis=None, level=None, copy=True, - fill_value=None, method=None, limit=None): - """ - Align two Series object with the specified join method - - Parameters - ---------- - other : Series - join : {'outer', 'inner', 'left', 'right'}, default 'outer' - axis : None, alignment axis (is 0 for Series) - level : int or name - Broadcast across a level, matching Index values on the - passed MultiIndex level - copy : boolean, default True - Always return new objects. If copy=False and no reindexing is - required, the same object will be returned (for better performance) - fill_value : object, default None - method : str, default 'pad' - limit : int, default None - fill_value, method, inplace, limit are passed to fillna - - Returns - ------- - (left, right) : (Series, Series) - Aligned Series - """ - join_index, lidx, ridx = self.index.join(other.index, how=join, - level=level, - return_indexers=True) - - left = self._reindex_indexer(join_index, lidx, copy) - right = other._reindex_indexer(join_index, ridx, copy) - fill_na = (fill_value is not None) or (method is not None) - if fill_na: - return (left.fillna(fill_value, method=method, limit=limit), - right.fillna(fill_value, method=method, limit=limit)) - else: - return left, right - def _reindex_indexer(self, new_index, indexer, copy): if indexer is None: if copy: diff --git a/pandas/sparse/frame.py b/pandas/sparse/frame.py index d8f6d531a6983..7d2571e6c3c74 100644 --- a/pandas/sparse/frame.py +++ b/pandas/sparse/frame.py @@ -573,11 +573,14 @@ def _reindex_columns(self, columns, copy, level, fill_value, limit=None, return SparseDataFrame(sdict, index=self.index, columns=columns, default_fill_value=self._default_fill_value) - def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, limit=None, copy=False): + def _reindex_with_indexers(self, reindexers, method=None, fill_value=None, limit=None, copy=False): if method is not None or limit is not None: raise NotImplementedError("cannot reindex with a method or limit with sparse") + if fill_value is None: + fill_value = np.nan + index, row_indexer = reindexers.get(0, (None, None)) columns, col_indexer = reindexers.get(1, (None, None))
https://api.github.com/repos/pandas-dev/pandas/pulls/4800
2013-09-10T13:58:15Z
2013-09-10T14:29:35Z
2013-09-10T14:29:35Z
2014-07-16T08:27:34Z
CLN: move clip to core/generic (adds to Panel as well), related to (GH2747)
diff --git a/doc/source/api.rst b/doc/source/api.rst index 9cf10d3f0780d..538965d0be7ad 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -708,6 +708,9 @@ Computations / Descriptive Stats :toctree: generated/ Panel.abs + Panel.clip + Panel.clip_lower + Panel.clip_upper Panel.count Panel.cummax Panel.cummin diff --git a/doc/source/release.rst b/doc/source/release.rst index 4f02fdbbfe97a..a23aa2fcebc12 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -260,6 +260,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue:`4605`), and adds ``rename`` with the same signature for ``Panel`` - Series (for index) / Panel (for items) now as attribute access to its elements (:issue:`1903`) +- Refactor ``clip`` methods to core/generic.py (:issue:`4798`) - Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility - Refactor of Series arithmetic with time-like objects (datetime/timedelta/time etc.) into a separate, cleaned up wrapper class. (:issue:`4613`) diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index a38ff2fa6d457..3431d82219856 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -353,8 +353,9 @@ and behaviors. Series formerly subclassed directly from ``ndarray``. (:issue:`40 - Refactor ``Series.reindex`` to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing on a Series to work - ``Series.copy`` no longer accepts the ``order`` parameter and is now consistent with ``NDFrame`` copy -- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue`4605`), and adds ``rename`` +- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue:`4605`), and adds ``rename`` with the same signature for ``Panel`` +- Refactor ``clip`` methods to core/generic.py (:issue:`4798`) - Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility - ``Series`` (for index) / ``Panel`` (for items) now allow attribute access to its elements (:issue:`1903`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 71d7f826781df..2b0e18c0c5524 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4396,47 +4396,6 @@ def f(arr): data = self._get_numeric_data() if numeric_only else self return data.apply(f, axis=axis) - - def clip(self, lower=None, upper=None): - """ - Trim values at input threshold(s) - - Parameters - ---------- - lower : float, default None - upper : float, default None - - Returns - ------- - clipped : DataFrame - """ - - # GH 2747 (arguments were reversed) - if lower is not None and upper is not None: - lower, upper = min(lower, upper), max(lower, upper) - - return self.apply(lambda x: x.clip(lower=lower, upper=upper)) - - def clip_upper(self, threshold): - """ - Trim values above threshold - - Returns - ------- - clipped : DataFrame - """ - return self.apply(lambda x: x.clip_upper(threshold)) - - def clip_lower(self, threshold): - """ - Trim values below threshold - - Returns - ------- - clipped : DataFrame - """ - return self.apply(lambda x: x.clip_lower(threshold)) - def rank(self, axis=0, numeric_only=None, method='average', na_option='keep', ascending=True): """ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2919790300bc3..d5c265dcf93a0 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1920,6 +1920,68 @@ def f(x): return obj + def clip(self, lower=None, upper=None, out=None): + """ + Trim values at input threshold(s) + + Parameters + ---------- + lower : float, default None + upper : float, default None + + Returns + ------- + clipped : Series + """ + if out is not None: # pragma: no cover + raise Exception('out argument is not supported yet') + + # GH 2747 (arguments were reversed) + if lower is not None and upper is not None: + lower, upper = min(lower, upper), max(lower, upper) + + result = self + if lower is not None: + result = result.clip_lower(lower) + if upper is not None: + result = result.clip_upper(upper) + + return result + + def clip_upper(self, threshold): + """ + Return copy of input with values above given value truncated + + See also + -------- + clip + + Returns + ------- + clipped : same type as input + """ + if isnull(threshold): + raise ValueError("Cannot use an NA value as a clip threshold") + + return self.where((self <= threshold) | isnull(self), threshold) + + def clip_lower(self, threshold): + """ + Return copy of the input with values below given value truncated + + See also + -------- + clip + + Returns + ------- + clipped : same type as input + """ + if isnull(threshold): + raise ValueError("Cannot use an NA value as a clip threshold") + + return self.where((self >= threshold) | isnull(self), threshold) + def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False): """ diff --git a/pandas/core/series.py b/pandas/core/series.py index ef8c630a7bde8..3f93f210ad4cf 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2102,64 +2102,6 @@ def autocorr(self): """ return self.corr(self.shift(1)) - def clip(self, lower=None, upper=None, out=None): - """ - Trim values at input threshold(s) - - Parameters - ---------- - lower : float, default None - upper : float, default None - - Returns - ------- - clipped : Series - """ - if out is not None: # pragma: no cover - raise Exception('out argument is not supported yet') - - result = self - if lower is not None: - result = result.clip_lower(lower) - if upper is not None: - result = result.clip_upper(upper) - - return result - - def clip_upper(self, threshold): - """ - Return copy of series with values above given value truncated - - See also - -------- - clip - - Returns - ------- - clipped : Series - """ - if isnull(threshold): - raise ValueError("Cannot use an NA value as a clip threshold") - - return self.where((self <= threshold) | isnull(self), threshold) - - def clip_lower(self, threshold): - """ - Return copy of series with values below given value truncated - - See also - -------- - clip - - Returns - ------- - clipped : Series - """ - if isnull(threshold): - raise ValueError("Cannot use an NA value as a clip threshold") - - return self.where((self >= threshold) | isnull(self), threshold) - def dot(self, other): """ Matrix multiplication with DataFrame or inner-product with Series objects
https://api.github.com/repos/pandas-dev/pandas/pulls/4798
2013-09-10T13:33:57Z
2013-09-10T14:05:33Z
2013-09-10T14:05:33Z
2014-06-17T05:06:46Z
CLN: default for tupleize_cols is now False for both to_csv and read_csv. Fair warning in 0.12 (GH3604)
diff --git a/doc/source/io.rst b/doc/source/io.rst index 67cbe35144461..3a284062a2ec9 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -153,7 +153,7 @@ They can take a number of arguments: time and lower memory usage. - ``mangle_dupe_cols``: boolean, default True, then duplicate columns will be specified as 'X.0'...'X.N', rather than 'X'...'X' - - ``tupleize_cols``: boolean, default True, if False, convert a list of tuples + - ``tupleize_cols``: boolean, default False, if False, convert a list of tuples to a multi-index of columns, otherwise, leave the column index as a list of tuples .. ipython:: python @@ -860,19 +860,16 @@ Reading columns with a ``MultiIndex`` By specifying list of row locations for the ``header`` argument, you can read in a ``MultiIndex`` for the columns. Specifying non-consecutive -rows will skip the interveaning rows. +rows will skip the interveaning rows. In order to have the pre-0.13 behavior +of tupleizing columns, specify ``tupleize_cols=True``. .. ipython:: python from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4) - df.to_csv('mi.csv',tupleize_cols=False) + df.to_csv('mi.csv') print open('mi.csv').read() - pd.read_csv('mi.csv',header=[0,1,2,3],index_col=[0,1],tupleize_cols=False) - -Note: The default behavior in 0.12 remains unchanged (``tupleize_cols=True``) from prior versions, -but starting with 0.13, the default *to* write and read multi-index columns will be in the new -format (``tupleize_cols=False``) + pd.read_csv('mi.csv',header=[0,1,2,3],index_col=[0,1]) Note: If an ``index_col`` is not specified (e.g. you don't have an index, or wrote it with ``df.to_csv(..., index=False``), then any ``names`` on the columns index will be *lost*. @@ -966,7 +963,7 @@ function takes a number of arguments. Only the first is required. - ``sep`` : Field delimiter for the output file (default ",") - ``encoding``: a string representing the encoding to use if the contents are non-ascii, for python versions prior to 3 - - ``tupleize_cols``: boolean, default True, if False, write as a list of tuples, + - ``tupleize_cols``: boolean, default False, if False, write as a list of tuples, otherwise write in an expanded line format suitable for ``read_csv`` Writing a formatted string diff --git a/doc/source/release.rst b/doc/source/release.rst index de7aa675380b7..4f02fdbbfe97a 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -188,6 +188,7 @@ API Changes a list can be passed to ``to_replace`` (:issue:`4743`). - provide automatic dtype conversions on _reduce operations (:issue:`3371`) - exclude non-numerics if mixed types with datelike in _reduce operations (:issue:`3371`) + - default for ``tupleize_cols`` is now ``False`` for both ``to_csv`` and ``read_csv``. Fair warning in 0.12 (:issue:`3604`) Internal Refactoring ~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/format.py b/pandas/core/format.py index 6b4dc979d5279..92fcfaa5f2f9c 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -787,7 +787,7 @@ def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None, cols=None, header=True, index=True, index_label=None, mode='w', nanRep=None, encoding=None, quoting=None, line_terminator='\n', chunksize=None, engine=None, - tupleize_cols=True, quotechar='"'): + tupleize_cols=False, quotechar='"'): self.engine = engine # remove for 0.13 self.obj = obj diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 52d3a15d8d184..71d7f826781df 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1191,7 +1191,7 @@ def from_csv(cls, path, header=0, sep=',', index_col=0, is used. Different default from read_table parse_dates : boolean, default True Parse dates. Different default from read_table - tupleize_cols : boolean, default True + tupleize_cols : boolean, default False write multi_index columns as a list of tuples (if True) or new (expanded format) if False) @@ -1208,7 +1208,7 @@ def from_csv(cls, path, header=0, sep=',', index_col=0, from pandas.io.parsers import read_table return read_table(path, header=header, sep=sep, parse_dates=parse_dates, index_col=index_col, - encoding=encoding, tupleize_cols=False) + encoding=encoding, tupleize_cols=tupleize_cols) def to_sparse(self, fill_value=None, kind='block'): """ @@ -1291,7 +1291,7 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None, cols=None, header=True, index=True, index_label=None, mode='w', nanRep=None, encoding=None, quoting=None, line_terminator='\n', chunksize=None, - tupleize_cols=True, **kwds): + tupleize_cols=False, **kwds): r"""Write DataFrame to a comma-separated values (csv) file Parameters @@ -1331,7 +1331,7 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None, defaults to csv.QUOTE_MINIMAL chunksize : int or None rows to write at a time - tupleize_cols : boolean, default True + tupleize_cols : boolean, default False write multi_index columns as a list of tuples (if True) or new (expanded format) if False) """ diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index e1b09eb76415f..06940e3bb2b4c 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -247,7 +247,7 @@ def _read(filepath_or_buffer, kwds): 'squeeze': False, 'compression': None, 'mangle_dupe_cols': True, - 'tupleize_cols':True, + 'tupleize_cols':False, } @@ -336,7 +336,7 @@ def parser_f(filepath_or_buffer, encoding=None, squeeze=False, mangle_dupe_cols=True, - tupleize_cols=True, + tupleize_cols=False, ): # Alias sep -> delimiter. @@ -656,7 +656,7 @@ def __init__(self, kwds): self.na_fvalues = kwds.get('na_fvalues') self.true_values = kwds.get('true_values') self.false_values = kwds.get('false_values') - self.tupleize_cols = kwds.get('tupleize_cols',True) + self.tupleize_cols = kwds.get('tupleize_cols',False) self._date_conv = _make_date_converter(date_parser=self.date_parser, dayfirst=self.dayfirst) diff --git a/pandas/parser.pyx b/pandas/parser.pyx index 8b90e76fa4bf3..b97929023adb6 100644 --- a/pandas/parser.pyx +++ b/pandas/parser.pyx @@ -310,7 +310,7 @@ cdef class TextReader: skip_footer=0, verbose=False, mangle_dupe_cols=True, - tupleize_cols=True): + tupleize_cols=False): self.parser = parser_new() self.parser.chunksize = tokenize_chunksize
closes #3604
https://api.github.com/repos/pandas-dev/pandas/pulls/4797
2013-09-10T12:09:34Z
2013-09-10T13:07:33Z
2013-09-10T13:07:33Z
2014-07-08T08:55:34Z
BUG: pickle failing on FrozenList, when using MultiIndex (GH4788)
diff --git a/pandas/core/base.py b/pandas/core/base.py index a57af06f24cc9..a2f7f04053b9f 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -108,6 +108,9 @@ def __mul__(self, other): __imul__ = __mul__ + def __reduce__(self): + return self.__class__, (list(self),) + def __hash__(self): return hash(tuple(self)) diff --git a/pandas/core/index.py b/pandas/core/index.py index 2b5f761026924..b561d7637c0c3 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -2109,7 +2109,7 @@ def __contains__(self, key): def __reduce__(self): """Necessary for making this object picklable""" object_state = list(np.ndarray.__reduce__(self)) - subclass_state = (self.levels, self.labels, self.sortorder, self.names) + subclass_state = (list(self.levels), list(self.labels), self.sortorder, list(self.names)) object_state[2] = (object_state[2], subclass_state) return tuple(object_state) diff --git a/pandas/io/api.py b/pandas/io/api.py index 2c8f8d1c893e2..94deb51ab4b18 100644 --- a/pandas/io/api.py +++ b/pandas/io/api.py @@ -10,4 +10,4 @@ from pandas.io.html import read_html from pandas.io.sql import read_sql from pandas.io.stata import read_stata -from pandas.io.pickle import read_pickle +from pandas.io.pickle import read_pickle, to_pickle diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py index af1b333312309..97633873e7b40 100644 --- a/pandas/io/pickle.py +++ b/pandas/io/pickle.py @@ -39,8 +39,7 @@ def try_read(path, encoding=None): # the param try: with open(path,'rb') as fh: - with open(path,'rb') as fh: - return pc.load(fh, encoding=encoding, compat=False) + return pc.load(fh, encoding=encoding, compat=False) except: with open(path,'rb') as fh: return pc.load(fh, encoding=encoding, compat=True) diff --git a/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle b/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle index 6b471d55b1642..e057576b6894b 100644 Binary files a/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle and b/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle differ diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_AMD64_windows_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_AMD64_windows_2.7.3.pickle new file mode 100644 index 0000000000000..1001c0f470122 Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_AMD64_windows_2.7.3.pickle differ diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_i686_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_i686_linux_2.7.3.pickle deleted file mode 100644 index 17061f6b7dc0f..0000000000000 Binary files a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_i686_linux_2.7.3.pickle and /dev/null differ diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle index 470d3e89c433d..3049e94791581 100644 Binary files a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle and b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle differ diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/x86_64_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/x86_64_linux_2.7.3.pickle deleted file mode 100644 index e8c1e52078f7c..0000000000000 Binary files a/pandas/io/tests/data/legacy_pickle/0.12.0/x86_64_linux_2.7.3.pickle and /dev/null differ diff --git a/pandas/io/tests/data/legacy_pickle/0.13.0/0.12.0-300-g6ffed43_x86_64_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.13.0/0.12.0-300-g6ffed43_x86_64_linux_2.7.3.pickle deleted file mode 100644 index 93e1f3e6c9607..0000000000000 Binary files a/pandas/io/tests/data/legacy_pickle/0.13.0/0.12.0-300-g6ffed43_x86_64_linux_2.7.3.pickle and /dev/null differ diff --git a/pandas/io/tests/generate_legacy_pickles.py b/pandas/io/tests/generate_legacy_pickles.py index f54a67b7f76cf..05e5d68379b09 100644 --- a/pandas/io/tests/generate_legacy_pickles.py +++ b/pandas/io/tests/generate_legacy_pickles.py @@ -77,16 +77,23 @@ def create_data(): index = dict(int = Index(np.arange(10)), date = date_range('20130101',periods=10)) - mi = dict(reg = MultiIndex.from_tuples(list(zip([['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], + mi = dict(reg2 = MultiIndex.from_tuples(tuple(zip(*[['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']])), names=['first', 'second'])) series = dict(float = Series(data['A']), int = Series(data['B']), mixed = Series(data['E']), - ts = TimeSeries(np.arange(10).astype(np.int64),index=date_range('20130101',periods=10))) + ts = TimeSeries(np.arange(10).astype(np.int64),index=date_range('20130101',periods=10)), + mi = Series(np.arange(5).astype(np.float64),index=MultiIndex.from_tuples(tuple(zip(*[[1,1,2,2,2], + [3,4,3,4,5]])), + names=['one','two']))) frame = dict(float = DataFrame(dict(A = series['float'], B = series['float'] + 1)), int = DataFrame(dict(A = series['int'] , B = series['int'] + 1)), - mixed = DataFrame(dict([ (k,data[k]) for k in ['A','B','C','D']]))) + mixed = DataFrame(dict([ (k,data[k]) for k in ['A','B','C','D']])), + mi = DataFrame(dict(A = np.arange(5).astype(np.float64), B = np.arange(5).astype(np.int64)), + index=MultiIndex.from_tuples(tuple(zip(*[['bar','bar','baz','baz','baz'], + ['one','two','one','two','three']])), + names=['first','second']))) panel = dict(float = Panel(dict(ItemA = frame['float'], ItemB = frame['float']+1))) diff --git a/pandas/io/tests/test_pickle.py b/pandas/io/tests/test_pickle.py index 92231d2ef094f..167eed95fd5a6 100644 --- a/pandas/io/tests/test_pickle.py +++ b/pandas/io/tests/test_pickle.py @@ -15,15 +15,34 @@ from pandas import Index from pandas.sparse.tests import test_sparse from pandas import compat +from pandas.compat import u from pandas.util.misc import is_little_endian import pandas +def _read_pickle(vf, encoding=None, compat=False): + from pandas.compat import pickle_compat as pc + with open(vf,'rb') as fh: + pc.load(fh, encoding=encoding, compat=compat) + class TestPickle(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): from pandas.io.tests.generate_legacy_pickles import create_data self.data = create_data() + self.path = u('__%s__.pickle' % tm.rands(10)) + + def compare_element(self, typ, result, expected): + if isinstance(expected,Index): + self.assert_(expected.equals(result)) + return + + if typ.startswith('sp_'): + comparator = getattr(test_sparse,"assert_%s_equal" % typ) + comparator(result,expected,exact_indices=False) + else: + comparator = getattr(tm,"assert_%s_equal" % typ) + comparator(result,expected) def compare(self, vf): @@ -36,19 +55,12 @@ def compare(self, vf): for typ, dv in data.items(): for dt, result in dv.items(): - - expected = self.data[typ][dt] - - if isinstance(expected,Index): - self.assert_(expected.equals(result)) + try: + expected = self.data[typ][dt] + except (KeyError): continue - if typ.startswith('sp_'): - comparator = getattr(test_sparse,"assert_%s_equal" % typ) - comparator(result,expected,exact_indices=False) - else: - comparator = getattr(tm,"assert_%s_equal" % typ) - comparator(result,expected) + self.compare_element(typ, result, expected) def read_pickles(self, version): if not is_little_endian(): @@ -68,8 +80,18 @@ def test_read_pickles_0_11_0(self): def test_read_pickles_0_12_0(self): self.read_pickles('0.12.0') - def test_read_pickles_0_13_0(self): - self.read_pickles('0.13.0') + def test_round_trip_current(self): + + for typ, dv in self.data.items(): + + for dt, expected in dv.items(): + + with tm.ensure_clean(self.path) as path: + + pd.to_pickle(expected,path) + + result = pd.read_pickle(path) + self.compare_element(typ, result, expected) if __name__ == '__main__': import nose diff --git a/setup.py b/setup.py index f04b39f864ecf..b7df339daf75a 100755 --- a/setup.py +++ b/setup.py @@ -527,7 +527,6 @@ def pxd(name): 'tests/data/legacy_pickle/0.10.1/*.pickle', 'tests/data/legacy_pickle/0.11.0/*.pickle', 'tests/data/legacy_pickle/0.12.0/*.pickle', - 'tests/data/legacy_pickle/0.13.0/*.pickle', 'tests/data/*.csv', 'tests/data/*.dta', 'tests/data/*.txt',
closes #4788
https://api.github.com/repos/pandas-dev/pandas/pulls/4791
2013-09-09T23:04:09Z
2013-09-10T13:05:46Z
2013-09-10T13:05:46Z
2014-06-26T18:22:27Z
BUG: Fix read_fwf with compressed files.
diff --git a/doc/source/release.rst b/doc/source/release.rst index f32ea44ed6242..53c50100072f9 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -369,6 +369,8 @@ Bug Fixes - Bug in ``iloc`` with a slice index failing (:issue:`4771`) - Incorrect error message with no colspecs or width in ``read_fwf``. (:issue:`4774`) - Fix bugs in indexing in a Series with a duplicate index (:issue:`4548`, :issue:`4550`) + - Fixed bug with reading compressed files with ``read_fwf`` in Python 3. + (:issue:`3963`) pandas 0.12.0 ------------- diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index f05b0a676cde4..e1b09eb76415f 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -14,6 +14,7 @@ from pandas.core.frame import DataFrame import datetime import pandas.core.common as com +from pandas.core.config import get_option from pandas import compat from pandas.io.date_converters import generic_parser from pandas.io.common import get_filepath_or_buffer @@ -1921,11 +1922,14 @@ class FixedWidthReader(object): """ A reader of fixed-width lines. """ - def __init__(self, f, colspecs, filler, thousands=None): + def __init__(self, f, colspecs, filler, thousands=None, encoding=None): self.f = f self.colspecs = colspecs self.filler = filler # Empty characters between fields. self.thousands = thousands + if encoding is None: + encoding = get_option('display.encoding') + self.encoding = encoding if not ( isinstance(colspecs, (tuple, list))): raise AssertionError() @@ -1937,11 +1941,20 @@ def __init__(self, f, colspecs, filler, thousands=None): isinstance(colspec[1], int) ): raise AssertionError() - def next(self): - line = next(self.f) - # Note: 'colspecs' is a sequence of half-open intervals. - return [line[fromm:to].strip(self.filler or ' ') - for (fromm, to) in self.colspecs] + if compat.PY3: + def next(self): + line = next(self.f) + if isinstance(line, bytes): + line = line.decode(self.encoding) + # Note: 'colspecs' is a sequence of half-open intervals. + return [line[fromm:to].strip(self.filler or ' ') + for (fromm, to) in self.colspecs] + else: + def next(self): + line = next(self.f) + # Note: 'colspecs' is a sequence of half-open intervals. + return [line[fromm:to].strip(self.filler or ' ') + for (fromm, to) in self.colspecs] # Iterator protocol in Python 3 uses __next__() __next__ = next @@ -1959,7 +1972,8 @@ def __init__(self, f, **kwds): PythonParser.__init__(self, f, **kwds) def _make_reader(self, f): - self.data = FixedWidthReader(f, self.colspecs, self.delimiter) + self.data = FixedWidthReader(f, self.colspecs, self.delimiter, + encoding=self.encoding) ##### deprecations in 0.12 ##### diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 9d751de6645ce..f872ddd793935 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -2028,6 +2028,31 @@ def test_fwf_regression(self): res = df.loc[:,c] self.assert_(len(res)) + def test_fwf_compression(self): + try: + import gzip + import bz2 + except ImportError: + raise nose.SkipTest("Need gzip and bz2 to run this test") + + data = """1111111111 + 2222222222 + 3333333333""".strip() + widths = [5, 5] + names = ['one', 'two'] + expected = read_fwf(StringIO(data), widths=widths, names=names) + if compat.PY3: + data = bytes(data, encoding='utf-8') + for comp_name, compresser in [('gzip', gzip.GzipFile), + ('bz2', bz2.BZ2File)]: + with tm.ensure_clean() as path: + tmp = compresser(path, mode='wb') + tmp.write(data) + tmp.close() + result = read_fwf(path, widths=widths, names=names, + compression=comp_name) + tm.assert_frame_equal(result, expected) + def test_verbose_import(self): text = """a,b,c,d one,1,2,3
Fixes #3963. `gzip` and `bz2` both now return `bytes` rather than `str` in Python 3, so need to check for bytes and decode as necessary. replacing #4783
https://api.github.com/repos/pandas-dev/pandas/pulls/4784
2013-09-09T04:46:13Z
2013-09-09T12:27:12Z
2013-09-09T12:27:12Z
2014-06-19T08:29:24Z
BUG: Fix input bytes conversion in Py3 to return str
diff --git a/doc/source/release.rst b/doc/source/release.rst index 140c3bc836fdb..124661021f45c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -393,6 +393,9 @@ Bug Fixes - Fixed bug with reading compressed files with ``read_fwf`` in Python 3. (:issue:`3963`) - Fixed an issue with a duplicate index and assignment with a dtype change (:issue:`4686`) + - Fixed bug with reading compressed files in as ``bytes`` rather than ``str`` + in Python 3. Simplifies bytes-producing file-handling in Python 3 + (:issue:`3963`, :issue:`4785`). pandas 0.12.0 ------------- diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 1b5939eb98417..12c929cd59820 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -36,6 +36,7 @@ import types PY3 = (sys.version_info[0] >= 3) +PY3_2 = sys.version_info[:2] == (3, 2) try: import __builtin__ as builtins diff --git a/pandas/core/common.py b/pandas/core/common.py index b58bd92a4fd1f..34aaa08b57171 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -5,6 +5,7 @@ import re import codecs import csv +import sys from numpy.lib.format import read_array, write_array import numpy as np @@ -1858,27 +1859,42 @@ def next(self): def _get_handle(path, mode, encoding=None, compression=None): + """Gets file handle for given path and mode. + NOTE: Under Python 3.2, getting a compressed file handle means reading in the entire file, + decompressing it and decoding it to ``str`` all at once and then wrapping it in a StringIO. + """ if compression is not None: - if encoding is not None: - raise ValueError('encoding + compression not yet supported') + if encoding is not None and not compat.PY3: + msg = 'encoding + compression not yet supported in Python 2' + raise ValueError(msg) if compression == 'gzip': import gzip - return gzip.GzipFile(path, 'rb') + f = gzip.GzipFile(path, 'rb') elif compression == 'bz2': import bz2 - return bz2.BZ2File(path, 'rb') + + f = bz2.BZ2File(path, 'rb') else: raise ValueError('Unrecognized compression type: %s' % compression) - - if compat.PY3: # pragma: no cover - if encoding: - f = open(path, mode, encoding=encoding) - else: - f = open(path, mode, errors='replace') + if compat.PY3_2: + # gzip and bz2 don't work with TextIOWrapper in 3.2 + encoding = encoding or get_option('display.encoding') + f = StringIO(f.read().decode(encoding)) + elif compat.PY3: + from io import TextIOWrapper + f = TextIOWrapper(f, encoding=encoding) + return f else: - f = open(path, mode) + if compat.PY3: + if encoding: + f = open(path, mode, encoding=encoding) + else: + f = open(path, mode, errors='replace') + else: + f = open(path, mode) + return f if compat.PY3: # pragma: no cover diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 06940e3bb2b4c..5554bef4acf98 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1175,13 +1175,36 @@ def count_empty_vals(vals): return sum([1 for v in vals if v == '' or v is None]) -def _wrap_compressed(f, compression): +def _wrap_compressed(f, compression, encoding=None): + """wraps compressed fileobject in a decompressing fileobject + NOTE: For all files in Python 3.2 and for bzip'd files under all Python + versions, this means reading in the entire file and then re-wrapping it in + StringIO. + """ compression = compression.lower() + encoding = encoding or get_option('display.encoding') if compression == 'gzip': import gzip - return gzip.GzipFile(fileobj=f) + + f = gzip.GzipFile(fileobj=f) + if compat.PY3_2: + # 3.2's gzip doesn't support read1 + f = StringIO(f.read().decode(encoding)) + elif compat.PY3: + from io import TextIOWrapper + + f = TextIOWrapper(f) + return f elif compression == 'bz2': - raise ValueError('Python cannot read bz2 data from file handle') + 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) + return f else: raise ValueError('do not recognize compression method %s' % compression) @@ -1235,7 +1258,12 @@ def __init__(self, f, **kwds): f = com._get_handle(f, 'r', encoding=self.encoding, compression=self.compression) elif self.compression: - f = _wrap_compressed(f, self.compression) + f = _wrap_compressed(f, self.compression, self.encoding) + # in Python 3, convert BytesIO or fileobjects passed with an encoding + elif compat.PY3 and isinstance(f, compat.BytesIO): + from io import TextIOWrapper + + f = TextIOWrapper(f, encoding=self.encoding) if hasattr(f, 'readline'): self._make_reader(f) @@ -1321,14 +1349,9 @@ class MyDialect(csv.Dialect): def _read(): line = next(f) pat = re.compile(sep) - if (compat.PY3 and isinstance(line, bytes)): - yield pat.split(line.decode('utf-8').strip()) - for line in f: - yield pat.split(line.decode('utf-8').strip()) - else: + yield pat.split(line.strip()) + for line in f: yield pat.split(line.strip()) - for line in f: - yield pat.split(line.strip()) reader = _read() self.data = reader diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index f872ddd793935..fb2b3fdd33bf1 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=E1101 from datetime import datetime @@ -2043,8 +2044,8 @@ def test_fwf_compression(self): expected = read_fwf(StringIO(data), widths=widths, names=names) if compat.PY3: data = bytes(data, encoding='utf-8') - for comp_name, compresser in [('gzip', gzip.GzipFile), - ('bz2', bz2.BZ2File)]: + comps = [('gzip', gzip.GzipFile), ('bz2', bz2.BZ2File)] + for comp_name, compresser in comps: with tm.ensure_clean() as path: tmp = compresser(path, mode='wb') tmp.write(data) @@ -2053,6 +2054,18 @@ def test_fwf_compression(self): compression=comp_name) tm.assert_frame_equal(result, expected) + def test_BytesIO_input(self): + if not compat.PY3: + raise nose.SkipTest("Bytes-related test - only needs to work on Python 3") + result = pd.read_fwf(BytesIO("שלום\nשלום".encode('utf8')), widths=[2,2]) + expected = pd.DataFrame([["של", "ום"]], columns=["של", "ום"]) + tm.assert_frame_equal(result, expected) + data = BytesIO("שלום::1234\n562::123".encode('cp1255')) + result = pd.read_table(data, sep="::", engine='python', + encoding='cp1255') + expected = pd.DataFrame([[562, 123]], columns=["שלום","1234"]) + tm.assert_frame_equal(result, expected) + def test_verbose_import(self): text = """a,b,c,d one,1,2,3
Fixes #3963, #4785 Fixed bug with reading compressed files in as `bytes` (`gzip` and `bz2` both now return `bytes` rather than `str` in Python 3) rather than `str` in Python 3, as well as the lack of conversion of `BytesIO`. Now, `_get_handle` and `_wrap_compressed` both wrap in an `io.TextIOWrapper`, so that the parsers work internally only with `str` in Python 3. In Python 3.2, has to read the entire file in first (because `gzip` and `bz2` files both lack a `read1()` method in 3.2) Also adds support for passing fileobjects with compression == 'bz2'.
https://api.github.com/repos/pandas-dev/pandas/pulls/4783
2013-09-09T03:45:05Z
2013-09-14T01:59:59Z
2013-09-14T01:59:59Z
2014-06-19T08:30:04Z
ENH: Add axis and level keywords to where, so that the other argument can now be an alignable pandas object.
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index e3a069960ab6b..d2fd11ee43615 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -625,6 +625,18 @@ This can be done intuitively like so: df2[df2 < 0] = 0 df2 +By default, ``where`` returns a modified copy of the data. There is an +optional parameter ``inplace`` so that the original data can be modified +without creating a copy: + +.. ipython:: python + + df_orig = df.copy() + df_orig.where(df > 0, -df, inplace=True); + df_orig + +**alignment** + Furthermore, ``where`` aligns the input boolean condition (ndarray or DataFrame), such that partial selection with setting is possible. This is analagous to partial setting via ``.ix`` (but on the contents rather than the axis labels) @@ -635,24 +647,30 @@ partial setting via ``.ix`` (but on the contents rather than the axis labels) df2[ df2[1:4] > 0 ] = 3 df2 -By default, ``where`` returns a modified copy of the data. There is an -optional parameter ``inplace`` so that the original data can be modified -without creating a copy: +.. versionadded:: 0.13 + +Where can also accept ``axis`` and ``level`` parameters to align the input when +performing the ``where``. .. ipython:: python - df_orig = df.copy() + df2 = df.copy() + df2.where(df2>0,df2['A'],axis='index') - df_orig.where(df > 0, -df, inplace=True); +This is equivalent (but faster than) the following. - df_orig +.. ipython:: python + + df2 = df.copy() + df.apply(lambda x, y: x.where(x>0,y), y=df['A']) + +**mask** ``mask`` is the inverse boolean operation of ``where``. .. ipython:: python s.mask(s >= 0) - df.mask(df >= 0) Take Methods diff --git a/doc/source/missing_data.rst b/doc/source/missing_data.rst index 0c8efb4e905ec..6b63032a6c659 100644 --- a/doc/source/missing_data.rst +++ b/doc/source/missing_data.rst @@ -205,6 +205,33 @@ To remind you, these are the available filling methods: With time series data, using pad/ffill is extremely common so that the "last known value" is available at every time point. +Filling with a PandasObject +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 0.12 + +You can also fill using a direct assignment with an alignable object. The +use case of this is to fill a DataFrame with the mean of that column. + +.. ipython:: python + + df = DataFrame(np.random.randn(10,3)) + df.iloc[3:5,0] = np.nan + df.iloc[4:6,1] = np.nan + df.iloc[5:8,2] = np.nan + df + + df.fillna(df.mean()) + +.. versionadded:: 0.13 + +Same result as above, but is aligning the 'fill' value which is +a Series in this case. + +.. ipython:: python + + df.where(pd.notnull(df),df.mean(),axis='columns') + .. _missing_data.dropna: Dropping axis labels with missing data: dropna diff --git a/doc/source/release.rst b/doc/source/release.rst index f32ea44ed6242..70c520b6831bc 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -102,6 +102,8 @@ Improvements to existing features tests/test_frame, tests/test_multilevel (:issue:`4732`). - Performance improvement of timesesies plotting with PeriodIndex and added test to vbench (:issue:`4705` and :issue:`4722`) + - Add ``axis`` and ``level`` keywords to ``where``, so that the ``other`` argument + can now be an alignable pandas object. API Changes ~~~~~~~~~~~ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f4c5eb808689c..2919790300bc3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2173,6 +2173,8 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, from pandas import DataFrame, Series method = com._clean_fill_method(method) + if axis is not None: + axis = self._get_axis_number(axis) if isinstance(other, DataFrame): return self._align_frame(other, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, @@ -2262,7 +2264,8 @@ def _align_series(self, other, join='outer', axis=None, level=None, else: return left_result, right_result - def where(self, cond, other=np.nan, inplace=False, try_cast=False, raise_on_error=True): + def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, + try_cast=False, raise_on_error=True): """ Return an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other. @@ -2273,6 +2276,8 @@ def where(self, cond, other=np.nan, inplace=False, try_cast=False, raise_on_erro other : scalar or DataFrame inplace : boolean, default False Whether to perform the operation in place on the data + axis : alignment axis if needed, default None + level : alignment level if needed, default None try_cast : boolean, default False try to cast the result back to the input type (if possible), raise_on_error : boolean, default True @@ -2306,15 +2311,17 @@ def where(self, cond, other=np.nan, inplace=False, try_cast=False, raise_on_erro # align with me if other.ndim <= self.ndim: - _, other = self.align(other, join='left', fill_value=np.nan) + _, other = self.align(other, join='left', + axis=axis, level=level, + fill_value=np.nan) # if we are NOT aligned, raise as we cannot where index - if not all([ other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes) ]): + if axis is None and not all([ other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes) ]): raise InvalidIndexError # slice me out of the other else: - raise NotImplemented + raise NotImplemented("cannot align with a bigger dimensional PandasObject") elif is_list_like(other): @@ -2386,11 +2393,11 @@ def where(self, cond, other=np.nan, inplace=False, try_cast=False, raise_on_erro if inplace: # we may have different type blocks come out of putmask, so # reconstruct the block manager - self._data = self._data.putmask(cond, other, inplace=True) + self._data = self._data.putmask(cond, other, align=axis is None, inplace=True) else: new_data = self._data.where( - other, cond, raise_on_error=raise_on_error, try_cast=try_cast) + other, cond, align=axis is None, raise_on_error=raise_on_error, try_cast=try_cast) return self._constructor(new_data) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 1716980813cea..91be4f42c17e4 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -593,22 +593,40 @@ def setitem(self, indexer, value): return [ self ] - def putmask(self, mask, new, inplace=False): + def putmask(self, mask, new, align=True, inplace=False): """ putmask the data to the block; it is possible that we may create a new dtype of block - return the resulting block(s) """ + return the resulting block(s) + + Parameters + ---------- + mask : the condition to respect + new : a ndarray/object + align : boolean, perform alignment on other/cond, default is True + inplace : perform inplace modification, default is False + + Returns + ------- + a new block(s), the result of the putmask + """ new_values = self.values if inplace else self.values.copy() # may need to align the new if hasattr(new, 'reindex_axis'): - axis = getattr(new, '_info_axis_number', 0) - new = new.reindex_axis(self.items, axis=axis, copy=False).values.T + if align: + axis = getattr(new, '_info_axis_number', 0) + new = new.reindex_axis(self.items, axis=axis, copy=False).values.T + else: + new = new.values.T # may need to align the mask if hasattr(mask, 'reindex_axis'): - axis = getattr(mask, '_info_axis_number', 0) - mask = mask.reindex_axis( - self.items, axis=axis, copy=False).values.T + if align: + axis = getattr(mask, '_info_axis_number', 0) + mask = mask.reindex_axis( + self.items, axis=axis, copy=False).values.T + else: + mask = mask.values.T # if we are passed a scalar None, convert it here if not is_list_like(new) and isnull(new): @@ -616,6 +634,11 @@ def putmask(self, mask, new, inplace=False): if self._can_hold_element(new): new = self._try_cast(new) + + # pseudo-broadcast + if isinstance(new,np.ndarray) and new.ndim == self.ndim-1: + new = np.repeat(new,self.shape[-1]).reshape(self.shape) + np.putmask(new_values, mask, new) # maybe upcast me @@ -842,7 +865,7 @@ def handle_error(): return [make_block(result, self.items, self.ref_items, ndim=self.ndim, fastpath=True)] - def where(self, other, cond, raise_on_error=True, try_cast=False): + def where(self, other, cond, align=True, raise_on_error=True, try_cast=False): """ evaluate the block; return result block(s) from the result @@ -850,6 +873,7 @@ def where(self, other, cond, raise_on_error=True, try_cast=False): ---------- other : a ndarray/object cond : the condition to respect + align : boolean, perform alignment on other/cond raise_on_error : if True, raise when I can't perform the function, False by default (and just return the data that we had coming in) @@ -862,21 +886,30 @@ def where(self, other, cond, raise_on_error=True, try_cast=False): # see if we can align other if hasattr(other, 'reindex_axis'): - axis = getattr(other, '_info_axis_number', 0) - other = other.reindex_axis(self.items, axis=axis, copy=True).values + if align: + axis = getattr(other, '_info_axis_number', 0) + other = other.reindex_axis(self.items, axis=axis, copy=True).values + else: + other = other.values # make sure that we can broadcast is_transposed = False if hasattr(other, 'ndim') and hasattr(values, 'ndim'): if values.ndim != other.ndim or values.shape == other.shape[::-1]: - values = values.T - is_transposed = True + + # pseodo broadcast (its a 2d vs 1d say and where needs it in a specific direction) + if other.ndim >= 1 and values.ndim-1 == other.ndim and values.shape[0] != other.shape[0]: + other = _block_shape(other).T + else: + values = values.T + is_transposed = True # see if we can align cond if not hasattr(cond, 'shape'): raise ValueError( "where must have a condition that is ndarray like") - if hasattr(cond, 'reindex_axis'): + + if align and hasattr(cond, 'reindex_axis'): axis = getattr(cond, '_info_axis_number', 0) cond = cond.reindex_axis(self.items, axis=axis, copy=True).values else: diff --git a/pandas/core/series.py b/pandas/core/series.py index 4f67fb1afdd5f..ef8c630a7bde8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2725,7 +2725,7 @@ def apply(self, func, convert_dtype=True, args=(), **kwds): else: return self._constructor(mapped, index=self.index, name=self.name) - def align(self, other, join='outer', level=None, copy=True, + def align(self, other, join='outer', axis=None, level=None, copy=True, fill_value=None, method=None, limit=None): """ Align two Series object with the specified join method @@ -2734,6 +2734,7 @@ def align(self, other, join='outer', level=None, copy=True, ---------- other : Series join : {'outer', 'inner', 'left', 'right'}, default 'outer' + axis : None, alignment axis (is 0 for Series) level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index cefe15952d329..f9756858b5d85 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -7931,6 +7931,35 @@ def test_where_none(self): expected = DataFrame({'series': Series([0,1,2,3,4,5,6,7,np.nan,np.nan]) }) assert_frame_equal(df, expected) + def test_where_align(self): + + def create(): + df = DataFrame(np.random.randn(10,3)) + df.iloc[3:5,0] = np.nan + df.iloc[4:6,1] = np.nan + df.iloc[5:8,2] = np.nan + return df + + # series + df = create() + expected = df.fillna(df.mean()) + result = df.where(pd.notnull(df),df.mean(),axis='columns') + assert_frame_equal(result, expected) + + df.where(pd.notnull(df),df.mean(),inplace=True,axis='columns') + assert_frame_equal(df, expected) + + df = create().fillna(0) + expected = df.apply(lambda x, y: x.where(x>0,y), y=df[0]) + result = df.where(df>0,df[0],axis='index') + assert_frame_equal(result, expected) + + # frame + df = create() + expected = df.fillna(1) + result = df.where(pd.notnull(df),DataFrame(1,index=df.index,columns=df.columns)) + assert_frame_equal(result, expected) + def test_mask(self): df = DataFrame(np.random.randn(5, 3)) cond = df > 0
So traditionally a fillna that does the means of the columns is an apply operation ``` In [1]: df = DataFrame(np.random.randn(10,3)) In [2]: df.iloc[3:5,0] = np.nan In [3]: df.iloc[4:6,1] = np.nan In [4]: df.iloc[5:8,2] = np.nan In [5]: df Out[5]: 0 1 2 0 0.096030 0.197451 1.645981 1 -0.443437 0.359204 -0.382563 2 0.613981 1.418754 -0.589935 3 0.000000 0.449953 -0.308414 4 0.000000 0.000000 -0.471054 5 -2.350309 0.000000 0.000000 6 -0.218522 0.498207 0.000000 7 0.478238 0.399154 0.000000 8 0.895854 0.230992 0.025799 9 0.085675 2.189373 -0.946990 ``` The following currently fails in 0.12 as where is finicky about how it broadcasts ``` In [4]: df.where(df>0,df[0],axis='index') ValueError: other must be the same shape as self when an ndarray ``` Adding `axis` and `level` arguments to `where` (which uses align under the hood), now enables the `other` object to be a Series/DataFrame (as well as a scalar) without a whole bunch of alignment/broadcasting. This also should be quite a bit faster. ``` IIn [6]: df.where(df>0,df[0],axis='index') Out[6]: 0 1 2 0 0.096030 0.197451 1.645981 1 -0.443437 0.359204 -0.443437 2 0.613981 1.418754 0.613981 3 0.000000 0.449953 0.000000 4 0.000000 0.000000 0.000000 5 -2.350309 -2.350309 -2.350309 6 -0.218522 0.498207 -0.218522 7 0.478238 0.399154 0.478238 8 0.895854 0.230992 0.025799 9 0.085675 2.189373 0.085675 ``` This works in 0.12. ``` In [7]: df.apply(lambda x, y: x.where(x>0,y), y=df[0]) Out[7]: 0 1 2 0 0.096030 0.197451 1.645981 1 -0.443437 0.359204 -0.443437 2 0.613981 1.418754 0.613981 3 0.000000 0.449953 0.000000 4 0.000000 0.000000 0.000000 5 -2.350309 -2.350309 -2.350309 6 -0.218522 0.498207 -0.218522 7 0.478238 0.399154 0.478238 8 0.895854 0.230992 0.025799 9 0.085675 2.189373 0.085675 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4781
2013-09-09T03:05:55Z
2013-09-10T11:34:51Z
2013-09-10T11:34:51Z
2014-06-12T07:40:42Z
TST/BUG: duplicate indexing ops with a Series using where and inplace add buggy (GH4550/GH4548)
diff --git a/doc/source/release.rst b/doc/source/release.rst index cac49a53e8fc5..f32ea44ed6242 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -368,6 +368,7 @@ Bug Fixes - Bug in concatenation with duplicate columns across dtypes not merging with axis=0 (:issue:`4771`) - Bug in ``iloc`` with a slice index failing (:issue:`4771`) - Incorrect error message with no colspecs or width in ``read_fwf``. (:issue:`4774`) + - Fix bugs in indexing in a Series with a duplicate index (:issue:`4548`, :issue:`4550`) pandas 0.12.0 ------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 58e1fbc4f177d..f4c5eb808689c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7,7 +7,7 @@ import pandas as pd from pandas.core.base import PandasObject -from pandas.core.index import Index, MultiIndex, _ensure_index +from pandas.core.index import Index, MultiIndex, _ensure_index, InvalidIndexError import pandas.core.indexing as indexing from pandas.core.indexing import _maybe_convert_indices from pandas.tseries.index import DatetimeIndex @@ -2308,6 +2308,10 @@ def where(self, cond, other=np.nan, inplace=False, try_cast=False, raise_on_erro _, other = self.align(other, join='left', fill_value=np.nan) + # if we are NOT aligned, raise as we cannot where index + if not all([ other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes) ]): + raise InvalidIndexError + # slice me out of the other else: raise NotImplemented diff --git a/pandas/core/series.py b/pandas/core/series.py index 5579e60ceb90e..4f67fb1afdd5f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1037,9 +1037,13 @@ def __setitem__(self, key, value): if _is_bool_indexer(key): key = _check_bool_indexer(self.index, key) - self.where(~key, value, inplace=True) - else: - self._set_with(key, value) + try: + self.where(~key, value, inplace=True) + return + except (InvalidIndexError): + pass + + self._set_with(key, value) def _set_with_engine(self, key, value): values = self.values diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index b0911ed10be20..7f8fa1019261f 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -1373,6 +1373,26 @@ def test_where_inplace(self): rs.where(cond, -s, inplace=True) assert_series_equal(rs, s.where(cond, -s)) + def test_where_dups(self): + # GH 4550 + # where crashes with dups in index + s1 = Series(list(range(3))) + s2 = Series(list(range(3))) + comb = pd.concat([s1,s2]) + result = comb.where(comb < 2) + expected = Series([0,1,np.nan,0,1,np.nan],index=[0,1,2,0,1,2]) + assert_series_equal(result, expected) + + # GH 4548 + # inplace updating not working with dups + comb[comb<1] = 5 + expected = Series([5,1,2,5,1,2],index=[0,1,2,0,1,2]) + assert_series_equal(comb, expected) + + comb[comb<2] += 10 + expected = Series([5,11,2,5,11,2],index=[0,1,2,0,1,2]) + assert_series_equal(comb, expected) + def test_mask(self): s = Series(np.random.randn(5)) cond = s > 0
closes #4550,#4548 ``` In [1]: s = pd.concat([Series(list(range(3))),Series(list(range(3)))]) In [2]: s Out[2]: 0 0 1 1 2 2 0 0 1 1 2 2 dtype: int64 In [3]: s.where(s<2) Out[3]: 0 0 1 1 2 NaN 0 0 1 1 2 NaN dtype: float64 In [4]: s[s<1] = 5 In [5]: s Out[5]: 0 5 1 1 2 2 0 5 1 1 2 2 dtype: int64 In [6]: s[s<2] += 10 In [7]: s Out[7]: 0 5 1 11 2 2 0 5 1 11 2 2 dtype: int64 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4779
2013-09-09T01:51:08Z
2013-09-09T02:03:15Z
2013-09-09T02:03:14Z
2014-06-15T21:16:42Z
BLD: windows builds failing in pandas.json (#4764)
diff --git a/pandas/src/ujson/lib/ultrajsonenc.c b/pandas/src/ujson/lib/ultrajsonenc.c index 4106ed6b73fcf..15d92d42f6753 100644 --- a/pandas/src/ujson/lib/ultrajsonenc.c +++ b/pandas/src/ujson/lib/ultrajsonenc.c @@ -549,7 +549,7 @@ int Buffer_AppendDoubleUnchecked(JSOBJ obj, JSONObjectEncoder *enc, double value { precision_str[0] = '%'; precision_str[1] = '.'; -#ifdef _WIN32 +#if defined(_WIN32) && defined(_MSC_VER) sprintf_s(precision_str+2, sizeof(precision_str)-2, "%ug", enc->doublePrecision); enc->offset += sprintf_s(str, enc->end - enc->offset, precision_str, neg ? -value : value); #else
https://api.github.com/repos/pandas-dev/pandas/pulls/4778
2013-09-09T00:59:50Z
2013-09-18T02:36:50Z
2013-09-18T02:36:50Z
2014-07-16T08:27:15Z
PERF: refactor tokenizer to give compiler branching hints. (OSX testers wanted)
diff --git a/pandas/src/parser/tokenizer.c b/pandas/src/parser/tokenizer.c index 45b8b9263e9cd..98be17d34d8ff 100644 --- a/pandas/src/parser/tokenizer.c +++ b/pandas/src/parser/tokenizer.c @@ -686,26 +686,63 @@ int tokenize_delimited(parser_t *self, size_t line_limit) i, c, self->file_lines + 1, self->line_fields[self->lines], self->state)); - switch(self->state) { - - case START_RECORD: - // start of record - + // prioritize the common cases before going to a switch statement + if (self->state == IN_FIELD) { + /* in unquoted field */ if (c == '\n') { - // \n\r possible? + END_FIELD(); END_LINE(); - break; + /* self->state = START_RECORD; */ } else if (c == '\r') { + END_FIELD(); self->state = EAT_CRNL; - break; } + else if (c == self->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == self->delimiter) { + // End of field. End of line not reached yet + END_FIELD(); + self->state = START_FIELD; + } + else if (c == self->commentchar) { + END_FIELD(); + self->state = EAT_COMMENT; + } + else { + /* normal character - save in field */ + PUSH_CHAR(c); + } + } else if (self->state == IN_QUOTED_FIELD) { + // In many files this branch won't be taken, but in quoted-field heavy files + // this will be very hot and omission means a disproportionate panelty. + // Try to strike a balance. - /* normal character - handle as START_FIELD */ - self->state = START_FIELD; - /* fallthru */ - - case START_FIELD: + /* in quoted field */ + if (c == self->escapechar) { + /* Possible escape character */ + self->state = ESCAPE_IN_QUOTED_FIELD; + } + else if (c == self->quotechar && + self->quoting != QUOTE_NONE) { + if (self->doublequote) { + /* doublequote; " represented by "" */ + self->state = QUOTE_IN_QUOTED_FIELD; + } + else { + /* end of quote part of field */ + self->state = IN_FIELD; + } + } + else { + /* normal character - save in field */ + PUSH_CHAR(c); + } + } else if (self->state == START_FIELD) { + start_field_label: /* expecting field */ + if (c == '\n') { END_FIELD(); END_LINE(); @@ -743,66 +780,28 @@ int tokenize_delimited(parser_t *self, size_t line_limit) PUSH_CHAR(c); self->state = IN_FIELD; } - break; - - case ESCAPED_CHAR: - /* if (c == '\0') */ - /* c = '\n'; */ - - PUSH_CHAR(c); - self->state = IN_FIELD; - break; + } else if (self->state == START_RECORD) { + // start of record - case IN_FIELD: - /* in unquoted field */ if (c == '\n') { - END_FIELD(); + // \n\r possible? END_LINE(); - /* self->state = START_RECORD; */ } else if (c == '\r') { - END_FIELD(); self->state = EAT_CRNL; - } - else if (c == self->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == self->delimiter) { - // End of field. End of line not reached yet - END_FIELD(); + } else { + /* normal character - handle as START_FIELD */ self->state = START_FIELD; + /* fallthru */ + goto start_field_label; } - else if (c == self->commentchar) { - END_FIELD(); - self->state = EAT_COMMENT; - } - else { - /* normal character - save in field */ - PUSH_CHAR(c); - } - break; + } else switch(self->state) { - case IN_QUOTED_FIELD: - /* in quoted field */ - if (c == self->escapechar) { - /* Possible escape character */ - self->state = ESCAPE_IN_QUOTED_FIELD; - } - else if (c == self->quotechar && - self->quoting != QUOTE_NONE) { - if (self->doublequote) { - /* doublequote; " represented by "" */ - self->state = QUOTE_IN_QUOTED_FIELD; - } - else { - /* end of quote part of field */ - self->state = IN_FIELD; - } - } - else { - /* normal character - save in field */ - PUSH_CHAR(c); - } + case ESCAPED_CHAR: + /* if (c == '\0') */ + /* c = '\n'; */ + + PUSH_CHAR(c); + self->state = IN_FIELD; break; case ESCAPE_IN_QUOTED_FIELD: @@ -940,18 +939,54 @@ int tokenize_delim_customterm(parser_t *self, size_t line_limit) i, c, self->file_lines + 1, self->line_fields[self->lines], self->state)); - switch(self->state) { - case START_RECORD: - // start of record + // prioritize the common cases before going to a switch statement + if (self->state == IN_FIELD) { + /* in unquoted field */ if (c == self->lineterminator) { - // \n\r possible? + END_FIELD(); END_LINE(); - break; + /* self->state = START_RECORD; */ + } + else if (c == self->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == self->delimiter) { + // End of field. End of line not reached yet + END_FIELD(); + self->state = START_FIELD; + } + else if (c == self->commentchar) { + END_FIELD(); + self->state = EAT_COMMENT; + } + else { + /* normal character - save in field */ + PUSH_CHAR(c); + } + } else if (self->state == IN_QUOTED_FIELD) { + /* in quoted field */ + if (c == self->escapechar) { + /* Possible escape character */ + self->state = ESCAPE_IN_QUOTED_FIELD; + } + else if (c == self->quotechar && + self->quoting != QUOTE_NONE) { + if (self->doublequote) { + /* doublequote; " represented by "" */ + self->state = QUOTE_IN_QUOTED_FIELD; + } + else { + /* end of quote part of field */ + self->state = IN_FIELD; + } } - /* normal character - handle as START_FIELD */ - self->state = START_FIELD; - /* fallthru */ - case START_FIELD: + else { + /* normal character - save in field */ + PUSH_CHAR(c); + } + } else if (self->state == START_FIELD) { + start_field_label: /* expecting field */ if (c == self->lineterminator) { END_FIELD(); @@ -987,7 +1022,18 @@ int tokenize_delim_customterm(parser_t *self, size_t line_limit) PUSH_CHAR(c); self->state = IN_FIELD; } - break; + } else if (self->state == START_RECORD) { + // start of record + if (c == self->lineterminator) { + // \n\r possible? + END_LINE(); + } else { + /* normal character - handle as START_FIELD */ + self->state = START_FIELD; + /* fallthru */ + goto start_field_label; + } + } else switch(self->state) { case ESCAPED_CHAR: /* if (c == '\0') */ @@ -997,55 +1043,6 @@ int tokenize_delim_customterm(parser_t *self, size_t line_limit) self->state = IN_FIELD; break; - case IN_FIELD: - /* in unquoted field */ - if (c == self->lineterminator) { - END_FIELD(); - END_LINE(); - /* self->state = START_RECORD; */ - } - else if (c == self->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == self->delimiter) { - // End of field. End of line not reached yet - END_FIELD(); - self->state = START_FIELD; - } - else if (c == self->commentchar) { - END_FIELD(); - self->state = EAT_COMMENT; - } - else { - /* normal character - save in field */ - PUSH_CHAR(c); - } - break; - - case IN_QUOTED_FIELD: - /* in quoted field */ - if (c == self->escapechar) { - /* Possible escape character */ - self->state = ESCAPE_IN_QUOTED_FIELD; - } - else if (c == self->quotechar && - self->quoting != QUOTE_NONE) { - if (self->doublequote) { - /* doublequote; " represented by "" */ - self->state = QUOTE_IN_QUOTED_FIELD; - } - else { - /* end of quote part of field */ - self->state = IN_FIELD; - } - } - else { - /* normal character - save in field */ - PUSH_CHAR(c); - } - break; - case ESCAPE_IN_QUOTED_FIELD: PUSH_CHAR(c); self->state = IN_QUOTED_FIELD; @@ -1141,37 +1138,57 @@ int tokenize_whitespace(parser_t *self, size_t line_limit) i, c, self->file_lines + 1, self->line_fields[self->lines], self->state)); - switch(self->state) { - - case EAT_WHITESPACE: - if (!IS_WHITESPACE(c)) { - // END_FIELD(); - self->state = START_FIELD; - // Fall through to subsequent state - } else { - // if whitespace char, keep slurping - break; - } - - case START_RECORD: - // start of record + // prioritize the common cases before going to a switch statement + if (self->state == IN_FIELD) { + /* in unquoted field */ if (c == '\n') { - // \n\r possible? + END_FIELD(); END_LINE(); - break; + /* self->state = START_RECORD; */ } else if (c == '\r') { + END_FIELD(); self->state = EAT_CRNL; - break; - } else if (IS_WHITESPACE(c)) { + } + else if (c == self->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (IS_WHITESPACE(c)) { + // End of field. End of line not reached yet END_FIELD(); self->state = EAT_WHITESPACE; - break; - } else { - /* normal character - handle as START_FIELD */ - self->state = START_FIELD; } - /* fallthru */ - case START_FIELD: + else if (c == self->commentchar) { + END_FIELD(); + self->state = EAT_COMMENT; + } + else { + /* normal character - save in field */ + PUSH_CHAR(c); + } + } else if (self->state == IN_QUOTED_FIELD) { + /* in quoted field */ + if (c == self->escapechar) { + /* Possible escape character */ + self->state = ESCAPE_IN_QUOTED_FIELD; + } + else if (c == self->quotechar && + self->quoting != QUOTE_NONE) { + if (self->doublequote) { + /* doublequote; " represented by "" */ + self->state = QUOTE_IN_QUOTED_FIELD; + } + else { + /* end of quote part of field */ + self->state = IN_FIELD; + } + } + else { + /* normal character - save in field */ + PUSH_CHAR(c); + } + } else if (self->state == START_FIELD) { + start_field_label: /* expecting field */ if (c == '\n') { END_FIELD(); @@ -1209,66 +1226,43 @@ int tokenize_whitespace(parser_t *self, size_t line_limit) PUSH_CHAR(c); self->state = IN_FIELD; } - break; - - case ESCAPED_CHAR: - /* if (c == '\0') */ - /* c = '\n'; */ - - PUSH_CHAR(c); - self->state = IN_FIELD; - break; - - case IN_FIELD: - /* in unquoted field */ + } else if (self->state == START_RECORD) { + start_record_label: + // start of record if (c == '\n') { - END_FIELD(); + // \n\r possible? END_LINE(); - /* self->state = START_RECORD; */ } else if (c == '\r') { - END_FIELD(); self->state = EAT_CRNL; - } - else if (c == self->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (IS_WHITESPACE(c)) { - // End of field. End of line not reached yet + } else if (IS_WHITESPACE(c)) { END_FIELD(); self->state = EAT_WHITESPACE; - } - else if (c == self->commentchar) { - END_FIELD(); - self->state = EAT_COMMENT; - } - else { - /* normal character - save in field */ - PUSH_CHAR(c); - } - break; - case IN_QUOTED_FIELD: - /* in quoted field */ - if (c == self->escapechar) { - /* Possible escape character */ - self->state = ESCAPE_IN_QUOTED_FIELD; - } - else if (c == self->quotechar && - self->quoting != QUOTE_NONE) { - if (self->doublequote) { - /* doublequote; " represented by "" */ - self->state = QUOTE_IN_QUOTED_FIELD; - } - else { - /* end of quote part of field */ - self->state = IN_FIELD; - } + } else { + /* normal character - handle as START_FIELD */ + self->state = START_FIELD; + /* fallthru */ + goto start_field_label; } - else { - /* normal character - save in field */ - PUSH_CHAR(c); + } else switch(self->state) { + + case EAT_WHITESPACE: + if (!IS_WHITESPACE(c)) { + // END_FIELD(); + self->state = START_FIELD; + // Fall through to subsequent state + goto start_record_label; + } else { + // if whitespace char, keep slurping + break; } + + case ESCAPED_CHAR: + /* if (c == '\0') */ + /* c = '\n'; */ + + PUSH_CHAR(c); + self->state = IN_FIELD; break; case ESCAPE_IN_QUOTED_FIELD: diff --git a/vb_suite/parser.py b/vb_suite/parser.py index 50d37f37708e7..e81e635c1700a 100644 --- a/vb_suite/parser.py +++ b/vb_suite/parser.py @@ -79,3 +79,34 @@ cmd = "read_table(StringIO(data), sep=',', header=None, parse_dates=[1])" sdate = datetime(2012, 5, 7) read_table_multiple_date_baseline = Benchmark(cmd, setup, start_date=sdate) + +# 09/2013, c-parser does not support multichar delim so this is slow. track it. +setup = common_setup + """ +from cStringIO import StringIO +data = '''\ +KORD::19990127 19:00:00::18:56:00::0.8100::2.8100::7.2000::0.0000::280.0000 +KORD::19990127 20:00:00::19:56:00::0.0100::2.2100::7.2000::0.0000::260.0000 +KORD::19990127 21:00:00::20:56:00::-0.5900::2.2100::5.7000::0.0000::280.0000 +KORD::19990127 21:00:00::21:18:00::-0.9900::2.0100::3.6000::0.0000::270.0000 +KORD::19990127 22:00:00::21:56:00::-0.5900::1.7100::5.1000::0.0000::290.0000 +''' +data = data * 200 +""" +cmd = "read_table(StringIO(data), sep='::', header=None, parse_dates=False)" +sdate = datetime(2012, 5, 7) +read_table_multichar_delim = Benchmark(cmd, setup, start_date=sdate) + +setup = common_setup + """ +from cStringIO import StringIO +data = '''\ +KORD,19990127 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000 +KORD,19990127 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000 +KORD,19990127 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000 +KORD,19990127 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000 +KORD,19990127 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000 +''' +data = data * 50000 +""" +cmd = "read_table(StringIO(data), sep=',', header=None, parse_dates=False)" +sdate = datetime(2012, 5, 7) +read_table_multiple_long = Benchmark(cmd, setup, start_date=sdate)
Included vbench shows ~12% improvement. I've seen 15-20% on movielens, 8% on FEC. I've encountered no regressions on any dataset I tried. Tested with gcc 4.6,4.7,4.8 on linux, results from OSX+clang would be useful: `./test_perf.sh -H -r read_table_multiple_long` before and after. Second VB commit is unrelated. Will merge in a couple of days or so, if all is quiet.
https://api.github.com/repos/pandas-dev/pandas/pulls/4777
2013-09-08T23:21:55Z
2013-09-10T13:50:23Z
null
2014-06-14T23:47:58Z
DOC: correction of example in unstack docstring
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a3eb3ea54c784..9f30c3e7f5255 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3280,28 +3280,38 @@ def unstack(self, level=-1): Parameters ---------- - level : int, string, or list of these, default last level + level : int, string, or list of these, default -1 (last level) Level(s) of index to unstack, can pass level name + See also + -------- + DataFrame.pivot : Pivot a table based on column values. + DataFrame.stack : Pivot a level of the column labels (inverse operation + from `unstack`). + Examples -------- + >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), + ... ('two', 'a'), ('two', 'b')]) + >>> s = pd.Series(np.arange(1.0, 5.0), index=index) >>> s - one a 1. - one b 2. - two a 3. - two b 4. + one a 1 + b 2 + two a 3 + b 4 + dtype: float64 >>> s.unstack(level=-1) a b - one 1. 2. - two 3. 4. + one 1 2 + two 3 4 - >>> df = s.unstack(level=0) - >>> df + >>> s.unstack(level=0) one two - a 1. 2. - b 3. 4. + a 1 3 + b 2 4 + >>> df = s.unstack(level=0) >>> df.unstack() one a 1. b 3.
There is an error in the example of the `unstack` docstring (http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.unstack.html ): ``` >>> df = s.unstack(level=0) >>> df one two a 1. 2. b 3. 4 ``` should be ``` one two a 1. 3. b 2. 4 ``` So this PR fixes that, but in the same time I did some other adjustments. Mainly: - added a "see also" - added in the example the code to create the series, so one can run the example him/herself
https://api.github.com/repos/pandas-dev/pandas/pulls/4776
2013-09-08T16:56:25Z
2013-09-20T22:18:14Z
2013-09-20T22:18:14Z
2014-07-16T08:27:13Z
DOC: some stylistic improvements to docstring rendering in documentation
diff --git a/doc/source/themes/nature_with_gtoc/static/nature.css_t b/doc/source/themes/nature_with_gtoc/static/nature.css_t index 2e0bed922c1e6..61b0e2cce5e5a 100644 --- a/doc/source/themes/nature_with_gtoc/static/nature.css_t +++ b/doc/source/themes/nature_with_gtoc/static/nature.css_t @@ -178,6 +178,10 @@ div.body h4 { font-size: 110%; background-color: #D8DEE3; } div.body h5 { font-size: 100%; background-color: #D8DEE3; } div.body h6 { font-size: 100%; background-color: #D8DEE3; } +p.rubric { + border-bottom: 1px solid rgb(201, 201, 201); +} + a.headerlink { color: #c60f0f; font-size: 0.8em; @@ -231,10 +235,10 @@ p.admonition-title:after { pre { padding: 10px; - background-color: White; + background-color: rgb(250,250,250); color: #222; line-height: 1.2em; - border: 1px solid #C6C9CB; + border: 1px solid rgb(201,201,201); font-size: 1.1em; margin: 1.5em 0 1.5em 0; -webkit-box-shadow: 1px 1px 1px #d8d8d8; @@ -258,3 +262,49 @@ div.viewcode-block:target { border-top: 1px solid #ac9; border-bottom: 1px solid #ac9; } + + +/** + * Styling for field lists + */ + + /* grey highlighting of 'parameter' and 'returns' field */ +table.field-list { + border-collapse: separate; + border-spacing: 10px; + margin-left: 1px; + /* border-left: 5px solid rgb(238, 238, 238) !important; */ +} + +table.field-list th.field-name { + /* display: inline-block; */ + padding: 1px 8px 1px 5px; + white-space: nowrap; + background-color: rgb(238, 238, 238); +} + +/* italic font for parameter types */ +table.field-list td.field-body > p { + font-style: italic; +} + +table.field-list td.field-body > p > strong { + font-style: normal; +} + +/* reduced space around parameter description */ +td.field-body blockquote { + border-left: none; + margin: 0em 0em 0.3em; + padding-left: 30px; +} + + +/** + * See also + */ + +div.seealso dd { + margin-top: 0; + margin-bottom: 0; +}
This is a PR with some stylistic improvements to the docstring rendering in the documentation. The incentive was that I found the reference (docstring) documentation not always clearly organised. Things I changed (mainly copied from the new numpy/scipy docs): - reduced space around parameter description - italic font for parameter types - assure that colon after "Parameters" is on same line and some grey background in Parameter field to highlight the - "See also" box: put link and description on same line - light background color in code examples - line under Notes and Examples section headers You can see the result here: http://jorisvandenbossche.github.io/example-pandas-docs/html-docstring-rendering/generated/pandas.DataFrame.apply.html#pandas.DataFrame.apply and compare with the original: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html#pandas.DataFrame.apply Each of the points is of course debatable and I can change some of them back. Maybe the grey background of the code cells (this also applies to the tutorial docs) and the grey highlighting of the "parameter" and "returns" field (this can alse be the full block as in eg http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape) is maybe the most debatable. Style is of course always subjective :-) So what do you think?
https://api.github.com/repos/pandas-dev/pandas/pulls/4775
2013-09-08T16:16:49Z
2013-09-20T22:21:44Z
2013-09-20T22:21:44Z
2014-07-16T08:27:12Z
BUG: read_fwf: incorrect error message with no colspecs or widths
diff --git a/doc/source/release.rst b/doc/source/release.rst index 96527d0161687..66ac9d813f056 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -335,6 +335,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Bug in setting with ``loc/ix`` a single indexer with a multi-index axis and a numpy array, related to (:issue:`3777`) - Bug in concatenation with duplicate columns across dtypes not merging with axis=0 (:issue:`4771`) - Bug in ``iloc`` with a slice index failing (:issue:`4771`) + - Incorrect error message with no colspecs or width in ``read_fwf``. (:issue:`4774`) pandas 0.12 =========== diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 8cf7eaa1b19e3..f05b0a676cde4 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -414,7 +414,9 @@ def parser_f(filepath_or_buffer, @Appender(_read_fwf_doc) def read_fwf(filepath_or_buffer, colspecs=None, widths=None, **kwds): # Check input arguments. - if bool(colspecs is None) == bool(widths is None): + if colspecs is None and widths is None: + raise ValueError("Must specify either colspecs or widths") + elif colspecs is not None and widths is not None: raise ValueError("You must specify only one of 'widths' and " "'colspecs'") diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 6668cfd73a6b7..9d751de6645ce 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -1995,8 +1995,11 @@ def test_fwf(self): StringIO(data3), colspecs=colspecs, delimiter='~', header=None) tm.assert_frame_equal(df, expected) - self.assertRaises(ValueError, read_fwf, StringIO(data3), - colspecs=colspecs, widths=[6, 10, 10, 7]) + with tm.assertRaisesRegexp(ValueError, "must specify only one of"): + read_fwf(StringIO(data3), colspecs=colspecs, widths=[6, 10, 10, 7]) + + with tm.assertRaisesRegexp(ValueError, "Must specify either"): + read_fwf(StringIO(data3)) def test_fwf_regression(self): # GH 3594
https://api.github.com/repos/pandas-dev/pandas/pulls/4774
2013-09-08T01:57:55Z
2013-09-08T03:14:03Z
2013-09-08T03:14:03Z
2014-06-12T14:15:28Z
TST: add dups on both index tests for HDFStore
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 0a9e6855f094a..d445ce8b797b5 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -667,7 +667,7 @@ def func(_start, _stop): axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0] # concat and return - return concat(objs, axis=axis, verify_integrity=True).consolidate() + return concat(objs, axis=axis, verify_integrity=False).consolidate() if iterator or chunksize is not None: return TableIterator(self, func, nrows=nrows, start=start, stop=stop, chunksize=chunksize, auto_close=auto_close) diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index e9f4cf7d0f96f..48a2150758a3f 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2342,6 +2342,16 @@ def test_select_with_dups(self): result = store.select('df',columns=['B','A']) assert_frame_equal(result,expected,by_blocks=True) + # duplicates on both index and columns + with ensure_clean(self.path) as store: + store.append('df',df) + store.append('df',df) + + expected = df.loc[:,['B','A']] + expected = concat([expected, expected]) + result = store.select('df',columns=['B','A']) + assert_frame_equal(result,expected,by_blocks=True) + def test_wide_table_dups(self): wp = tm.makePanel() with ensure_clean(self.path) as store:
https://api.github.com/repos/pandas-dev/pandas/pulls/4773
2013-09-07T21:02:33Z
2013-09-07T21:18:52Z
2013-09-07T21:18:52Z
2014-07-16T08:27:09Z
BUG: Bug in concatenation with duplicate columns across dtypes not merging with axis=0 (GH4771)
diff --git a/doc/source/release.rst b/doc/source/release.rst index e12e6c91d46d0..930f100fd86dc 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -331,6 +331,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Bug in multi-indexing with a partial string selection as one part of a MultIndex (:issue:`4758`) - Bug with reindexing on the index with a non-unique index will now raise ``ValueError`` (:issue:`4746`) - Bug in setting with ``loc/ix`` a single indexer with a multi-index axis and a numpy array, related to (:issue:`3777`) + - Bug in concatenation with duplicate columns across dtypes not merging with axis=0 (:issue:`4771`) + - Bug in ``iloc`` with a slice index failing (:issue:`4771`) pandas 0.12 =========== diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 57db36b252e3c..e27430b06c45c 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2174,7 +2174,7 @@ def get_slice(self, slobj, axis=0, raise_on_error=False): placement=blk._ref_locs) new_blocks = [newb] else: - return self.reindex_items(new_items) + return self.reindex_items(new_items, indexer=np.arange(len(self.items))[slobj]) else: new_blocks = self._slice_blocks(slobj, axis) diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index d6088c2d72525..18ee89fbc5c66 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -16,7 +16,7 @@ MultiIndex, DatetimeIndex, Timestamp) from pandas.util.testing import (assert_almost_equal, assert_series_equal, assert_frame_equal, assert_panel_equal) -from pandas import compat +from pandas import compat, concat import pandas.util.testing as tm import pandas.lib as lib @@ -359,6 +359,29 @@ def test_iloc_getitem_slice(self): self.check_result('slice', 'iloc', slice(1,3), 'ix', { 0 : [2,4], 1: [3,6], 2: [4,8] }, typs = ['ints']) self.check_result('slice', 'iloc', slice(1,3), 'indexer', slice(1,3), typs = ['labels','mixed','ts','floats','empty'], fails = IndexError) + def test_iloc_getitem_slice_dups(self): + + df1 = DataFrame(np.random.randn(10,4),columns=['A','A','B','B']) + df2 = DataFrame(np.random.randint(0,10,size=20).reshape(10,2),columns=['A','C']) + + # axis=1 + df = concat([df1,df2],axis=1) + assert_frame_equal(df.iloc[:,:4],df1) + assert_frame_equal(df.iloc[:,4:],df2) + + df = concat([df2,df1],axis=1) + assert_frame_equal(df.iloc[:,:2],df2) + assert_frame_equal(df.iloc[:,2:],df1) + + assert_frame_equal(df.iloc[:,0:3],concat([df2,df1.iloc[:,[0]]],axis=1)) + + # axis=0 + df = concat([df,df],axis=0) + assert_frame_equal(df.iloc[0:10,:2],df2) + assert_frame_equal(df.iloc[0:10,2:],df1) + assert_frame_equal(df.iloc[10:,:2],df2) + assert_frame_equal(df.iloc[10:,2:],df1) + def test_iloc_getitem_out_of_bounds(self): # out-of-bounds slice diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py index 765dbc07b464f..d7fedecdb0ef2 100644 --- a/pandas/tools/merge.py +++ b/pandas/tools/merge.py @@ -649,6 +649,7 @@ def __init__(self, data_list, join_index, indexers, axis=1, copy=True): for data, indexer in zip(data_list, indexers): if not data.is_consolidated(): data = data.consolidate() + data._set_ref_locs() self.units.append(_JoinUnit(data.blocks, indexer)) self.join_index = join_index @@ -682,7 +683,6 @@ def get_result(self): blockmaps = self._prepare_blocks() kinds = _get_merge_block_kinds(blockmaps) - result_is_unique = self.result_axes[0].is_unique result_blocks = [] # maybe want to enable flexible copying <-- what did I mean? @@ -692,23 +692,28 @@ def get_result(self): if klass in mapping: klass_blocks.extend((unit, b) for b in mapping[klass]) res_blk = self._get_merged_block(klass_blocks) - - # if we have a unique result index, need to clear the _ref_locs - # a non-unique is set as we are creating - if result_is_unique: - res_blk.set_ref_locs(None) - result_blocks.append(res_blk) return BlockManager(result_blocks, self.result_axes) def _get_merged_block(self, to_merge): if len(to_merge) > 1: + + # placement set here return self._merge_blocks(to_merge) else: unit, block = to_merge[0] - return unit.reindex_block(block, self.axis, - self.result_items, copy=self.copy) + blk = unit.reindex_block(block, self.axis, + self.result_items, copy=self.copy) + + # set placement / invalidate on a unique result + if self.result_items.is_unique and blk._ref_locs is not None: + if not self.copy: + blk = blk.copy() + blk.set_ref_locs(None) + + return blk + def _merge_blocks(self, merge_chunks): """ @@ -736,7 +741,18 @@ def _merge_blocks(self, merge_chunks): # does not sort new_block_items = _concat_indexes([b.items for _, b in merge_chunks]) - return make_block(out, new_block_items, self.result_items) + + # need to set placement if we have a non-unique result + # calculate by the existing placement plus the offset in the result set + placement = None + if not self.result_items.is_unique: + nchunks = len(merge_chunks) + offsets = np.array([0] + [ len(self.result_items) / nchunks ] * (nchunks-1)).cumsum() + placement = [] + for (unit, blk), offset in zip(merge_chunks,offsets): + placement.extend(blk.ref_locs+offset) + + return make_block(out, new_block_items, self.result_items, placement=placement) class _JoinUnit(object): @@ -992,6 +1008,7 @@ def _prepare_blocks(self): blockmaps = [] for data in reindexed_data: data = data.consolidate() + data._set_ref_locs() blockmaps.append(data.get_block_map(typ='dict')) return blockmaps, reindexed_data @@ -1063,7 +1080,10 @@ def _concat_blocks(self, blocks): # or maybe would require performance test) raise PandasError('dtypes are not consistent throughout ' 'DataFrames') - return make_block(concat_values, blocks[0].items, self.new_axes[0]) + return make_block(concat_values, + blocks[0].items, + self.new_axes[0], + placement=blocks[0]._ref_locs) else: offsets = np.r_[0, np.cumsum([len(x._data.axes[0]) for diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index 5cfe22781f362..f7eb3c125db61 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -1396,6 +1396,54 @@ def test_crossed_dtypes_weird_corner(self): [df, df2], keys=['one', 'two'], names=['first', 'second']) self.assertEqual(result.index.names, ('first', 'second')) + def test_dups_index(self): + # GH 4771 + + # single dtypes + df = DataFrame(np.random.randint(0,10,size=40).reshape(10,4),columns=['A','A','C','C']) + + result = concat([df,df],axis=1) + assert_frame_equal(result.iloc[:,:4],df) + assert_frame_equal(result.iloc[:,4:],df) + + result = concat([df,df],axis=0) + assert_frame_equal(result.iloc[:10],df) + assert_frame_equal(result.iloc[10:],df) + + # multi dtypes + df = concat([DataFrame(np.random.randn(10,4),columns=['A','A','B','B']), + DataFrame(np.random.randint(0,10,size=20).reshape(10,2),columns=['A','C'])], + axis=1) + + result = concat([df,df],axis=1) + assert_frame_equal(result.iloc[:,:6],df) + assert_frame_equal(result.iloc[:,6:],df) + + result = concat([df,df],axis=0) + assert_frame_equal(result.iloc[:10],df) + assert_frame_equal(result.iloc[10:],df) + + # append + result = df.iloc[0:8,:].append(df.iloc[8:]) + assert_frame_equal(result, df) + + result = df.iloc[0:8,:].append(df.iloc[8:9]).append(df.iloc[9:10]) + assert_frame_equal(result, df) + + expected = concat([df,df],axis=0) + result = df.append(df) + assert_frame_equal(result, expected) + + def test_join_dups(self): + df = concat([DataFrame(np.random.randn(10,4),columns=['A','A','B','B']), + DataFrame(np.random.randint(0,10,size=20).reshape(10,2),columns=['A','C'])], + axis=1) + + expected = concat([df,df],axis=1) + result = df.join(df,rsuffix='_2') + result.columns = expected.columns + assert_frame_equal(result, expected) + def test_handle_empty_objects(self): df = DataFrame(np.random.randn(10, 4), columns=list('abcd'))
closes #4771 TST/BUG: Bug in iloc with a slice index failing (GH4771)
https://api.github.com/repos/pandas-dev/pandas/pulls/4772
2013-09-07T19:16:11Z
2013-09-07T20:57:14Z
2013-09-07T20:57:14Z
2014-06-13T14:32:04Z
REF/BUG/ENH/API: refactor read_html to use TextParser
diff --git a/doc/source/release.rst b/doc/source/release.rst index 4f4681b112664..78236bbf821dd 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -167,6 +167,8 @@ Improvements to existing features - Improve support for converting R datasets to pandas objects (more informative index for timeseries and numeric, support for factors, dist, and high-dimensional arrays). + - :func:`~pandas.read_html` now supports the ``parse_dates``, + ``tupleize_cols`` and ``thousands`` parameters (:issue:`4770`). API Changes ~~~~~~~~~~~ @@ -373,6 +375,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` ``core/generic.py`` (:issue:`4435`). - Refactor cum objects to core/generic.py (:issue:`4435`), note that these have a more numpy-like function signature. + - :func:`~pandas.read_html` now uses ``TextParser`` to parse HTML data from + bs4/lxml (:issue:`4770`). .. _release.bug_fixes-0.13.0: @@ -538,6 +542,15 @@ Bug Fixes - Make sure series-series boolean comparions are label based (:issue:`4947`) - Bug in multi-level indexing with a Timestamp partial indexer (:issue:`4294`) - Tests/fix for multi-index construction of an all-nan frame (:isue:`4078`) + - Fixed a bug where :func:`~pandas.read_html` wasn't correctly inferring + values of tables with commas (:issue:`5029`) + - Fixed a bug where :func:`~pandas.read_html` wasn't providing a stable + ordering of returned tables (:issue:`4770`, :issue:`5029`). + - Fixed a bug where :func:`~pandas.read_html` was incorrectly parsing when + passed ``index_col=0`` (:issue:`5066`). + - Fixed a bug where :func:`~pandas.read_html` was incorrectly infering the + type of headers (:issue:`5048`). + pandas 0.12.0 ------------- diff --git a/pandas/io/html.py b/pandas/io/html.py index df94e0ffa2e79..96bedbf390af6 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -7,15 +7,18 @@ import re import numbers import collections +import warnings from distutils.version import LooseVersion import numpy as np -from pandas import DataFrame, MultiIndex, isnull from pandas.io.common import _is_url, urlopen, parse_url -from pandas.compat import range, lrange, lmap, u, map -from pandas import compat +from pandas.io.parsers import TextParser +from pandas.compat import (lrange, lmap, u, string_types, iteritems, text_type, + raise_with_traceback) +from pandas.core import common as com +from pandas import Series try: @@ -45,7 +48,7 @@ ############# # READ HTML # ############# -_RE_WHITESPACE = re.compile(r'([\r\n]+|\s{2,})') +_RE_WHITESPACE = re.compile(r'[\r\n]+|\s{2,}') def _remove_whitespace(s, regex=_RE_WHITESPACE): @@ -67,7 +70,7 @@ def _remove_whitespace(s, regex=_RE_WHITESPACE): return regex.sub(' ', s.strip()) -def _get_skiprows_iter(skiprows): +def _get_skiprows(skiprows): """Get an iterator given an integer, slice or container. Parameters @@ -80,11 +83,6 @@ def _get_skiprows_iter(skiprows): TypeError * If `skiprows` is not a slice, integer, or Container - Raises - ------ - TypeError - * If `skiprows` is not a slice, integer, or Container - Returns ------- it : iterable @@ -92,13 +90,12 @@ def _get_skiprows_iter(skiprows): """ if isinstance(skiprows, slice): return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1) - elif isinstance(skiprows, numbers.Integral): - return lrange(skiprows) - elif isinstance(skiprows, collections.Container): + elif isinstance(skiprows, numbers.Integral) or com.is_list_like(skiprows): return skiprows - else: - raise TypeError('{0} is not a valid type for skipping' - ' rows'.format(type(skiprows))) + elif skiprows is None: + return 0 + raise TypeError('%r is not a valid type for skipping rows' % + type(skiprows).__name__) def _read(io): @@ -120,11 +117,10 @@ def _read(io): elif os.path.isfile(io): with open(io) as f: raw_text = f.read() - elif isinstance(io, compat.string_types): + elif isinstance(io, string_types): raw_text = io else: - raise TypeError("Cannot read object of type " - "'{0.__class__.__name__!r}'".format(io)) + raise TypeError("Cannot read object of type %r" % type(io).__name__) return raw_text @@ -194,12 +190,6 @@ def _parse_raw_data(self, rows): A callable that takes a row node as input and returns a list of the column node in that row. This must be defined by subclasses. - Raises - ------ - AssertionError - * If `text_getter` is not callable - * If `column_finder` is not callable - Returns ------- data : list of list of strings @@ -254,7 +244,7 @@ def _parse_tables(self, doc, match, attrs): Raises ------ - AssertionError + ValueError * If `match` does not match any text in the document. Returns @@ -406,25 +396,28 @@ def _parse_tfoot(self, table): def _parse_tables(self, doc, match, attrs): element_name = self._strainer.name tables = doc.find_all(element_name, attrs=attrs) + if not tables: - # known sporadically working release - raise AssertionError('No tables found') + raise ValueError('No tables found') - mts = [table.find(text=match) for table in tables] - matched_tables = [mt for mt in mts if mt is not None] - tables = list(set(mt.find_parent(element_name) - for mt in matched_tables)) + result = [] + unique_tables = set() - if not tables: - raise AssertionError("No tables found matching " - "'{0}'".format(match.pattern)) - return tables + for table in tables: + if (table not in unique_tables and + table.find(text=match) is not None): + result.append(table) + unique_tables.add(table) + + if not result: + raise ValueError("No tables found matching pattern %r" % + match.pattern) + return result def _setup_build_doc(self): raw_text = _read(self.io) if not raw_text: - raise AssertionError('No text parsed from document: ' - '{0}'.format(self.io)) + raise ValueError('No text parsed from document: %s' % self.io) return raw_text def _build_doc(self): @@ -432,7 +425,7 @@ def _build_doc(self): return BeautifulSoup(self._setup_build_doc(), features='html5lib') -def _build_node_xpath_expr(attrs): +def _build_xpath_expr(attrs): """Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. @@ -450,8 +443,8 @@ def _build_node_xpath_expr(attrs): if 'class_' in attrs: attrs['class'] = attrs.pop('class_') - s = (u("@{k}='{v}'").format(k=k, v=v) for k, v in compat.iteritems(attrs)) - return u('[{0}]').format(' and '.join(s)) + s = [u("@%s=%r") % (k, v) for k, v in iteritems(attrs)] + return u('[%s]') % ' and '.join(s) _re_namespace = {'re': 'http://exslt.org/regular-expressions'} @@ -491,23 +484,20 @@ def _parse_tr(self, table): def _parse_tables(self, doc, match, kwargs): pattern = match.pattern - # check all descendants for the given pattern - check_all_expr = u('//*') - if pattern: - check_all_expr += u("[re:test(text(), '{0}')]").format(pattern) - - # go up the tree until we find a table - check_table_expr = '/ancestor::table' - xpath_expr = check_all_expr + check_table_expr + # 1. check all descendants for the given pattern and only search tables + # 2. go up the tree until we find a table + query = '//table//*[re:test(text(), %r)]/ancestor::table' + xpath_expr = u(query) % pattern # if any table attributes were given build an xpath expression to # search for them if kwargs: - xpath_expr += _build_node_xpath_expr(kwargs) + xpath_expr += _build_xpath_expr(kwargs) + tables = doc.xpath(xpath_expr, namespaces=_re_namespace) + if not tables: - raise AssertionError("No tables found matching regex " - "'{0}'".format(pattern)) + raise ValueError("No tables found matching regex %r" % pattern) return tables def _build_doc(self): @@ -528,6 +518,7 @@ def _build_doc(self): """ from lxml.html import parse, fromstring, HTMLParser from lxml.etree import XMLSyntaxError + parser = HTMLParser(recover=False) try: @@ -552,8 +543,8 @@ def _build_doc(self): scheme = parse_url(self.io).scheme if scheme not in _valid_schemes: # lxml can't parse it - msg = ('{0} is not a valid url scheme, valid schemes are ' - '{1}').format(scheme, _valid_schemes) + msg = ('%r is not a valid url scheme, valid schemes are ' + '%s') % (scheme, _valid_schemes) raise ValueError(msg) else: # something else happened: maybe a faulty connection @@ -583,101 +574,38 @@ def _parse_raw_tfoot(self, table): table.xpath(expr)] -def _data_to_frame(data, header, index_col, infer_types, skiprows): - """Parse a BeautifulSoup table into a DataFrame. +def _expand_elements(body): + lens = Series(lmap(len, body)) + lens_max = lens.max() + not_max = lens[lens != lens_max] - Parameters - ---------- - data : tuple of lists - The raw data to be placed into a DataFrame. This is a list of lists of - strings or unicode. If it helps, it can be thought of as a matrix of - strings instead. - - header : int or None - An integer indicating the row to use for the column header or None - indicating no header will be used. + for ind, length in iteritems(not_max): + body[ind] += [np.nan] * (lens_max - length) - index_col : int or None - An integer indicating the column to use for the index or None - indicating no column will be used. - infer_types : bool - Whether to convert numbers and dates. +def _data_to_frame(data, header, index_col, skiprows, infer_types, + parse_dates, tupleize_cols, thousands): + head, body, _ = data # _ is footer which is rarely used: ignore for now - skiprows : collections.Container or int or slice - Iterable used to skip rows. + if head: + body = [head] + body - Returns - ------- - df : DataFrame - A DataFrame containing the data from `data` - - Raises - ------ - ValueError - * If `skiprows` is not found in the rows of the parsed DataFrame. + if header is None: # special case when a table has <th> elements + header = 0 - Raises - ------ - ValueError - * If `skiprows` is not found in the rows of the parsed DataFrame. - - See Also - -------- - read_html - - Notes - ----- - The `data` parameter is guaranteed not to be a list of empty lists. - """ - thead, tbody, tfoot = data - columns = thead or None - df = DataFrame(tbody, columns=columns) + # fill out elements of body that are "ragged" + _expand_elements(body) - if skiprows is not None: - it = _get_skiprows_iter(skiprows) + tp = TextParser(body, header=header, index_col=index_col, + skiprows=_get_skiprows(skiprows), + parse_dates=parse_dates, tupleize_cols=tupleize_cols, + thousands=thousands) + df = tp.read() - try: - df = df.drop(it) - except ValueError: - raise ValueError('Labels {0} not found when trying to skip' - ' rows'.format(it)) - - # convert to numbers/dates where possible - # must be sequential since dates trump numbers if both args are given - if infer_types: - df = df.convert_objects(convert_numeric=True) + if infer_types: # TODO: rm this code so infer_types has no effect in 0.14 df = df.convert_objects(convert_dates='coerce') - - if header is not None: - header_rows = df.iloc[header] - - if header_rows.ndim == 2: - names = header_rows.index - df.columns = MultiIndex.from_arrays(header_rows.values, - names=names) - else: - df.columns = header_rows - - df = df.drop(df.index[header]) - - if index_col is not None: - cols = df.columns[index_col] - - try: - cols = cols.tolist() - except AttributeError: - pass - - # drop by default - df.set_index(cols, inplace=True) - if df.index.nlevels == 1: - if isnull(df.index.name) or not df.index.name: - df.index.name = None - else: - names = [name or None for name in df.index.names] - df.index = MultiIndex.from_tuples(df.index.values, names=names) - + else: + df = df.applymap(text_type) return df @@ -701,15 +629,15 @@ def _parser_dispatch(flavor): Raises ------ - AssertionError + ValueError * If `flavor` is not a valid backend. ImportError * If you do not have the requested `flavor` """ valid_parsers = list(_valid_parsers.keys()) if flavor not in valid_parsers: - raise AssertionError('"{0!r}" is not a valid flavor, valid flavors are' - ' {1}'.format(flavor, valid_parsers)) + raise ValueError('%r is not a valid flavor, valid flavors are %s' % + (flavor, valid_parsers)) if flavor in ('bs4', 'html5lib'): if not _HAS_HTML5LIB: @@ -717,46 +645,54 @@ def _parser_dispatch(flavor): if not _HAS_BS4: raise ImportError("bs4 not found please install it") if bs4.__version__ == LooseVersion('4.2.0'): - raise AssertionError("You're using a version" - " of BeautifulSoup4 (4.2.0) that has been" - " known to cause problems on certain" - " operating systems such as Debian. " - "Please install a version of" - " BeautifulSoup4 != 4.2.0, both earlier" - " and later releases will work.") + raise ValueError("You're using a version" + " of BeautifulSoup4 (4.2.0) that has been" + " known to cause problems on certain" + " operating systems such as Debian. " + "Please install a version of" + " BeautifulSoup4 != 4.2.0, both earlier" + " and later releases will work.") else: if not _HAS_LXML: raise ImportError("lxml not found please install it") return _valid_parsers[flavor] -def _validate_parser_flavor(flavor): +def _print_as_set(s): + return '{%s}' % ', '.join([com.pprint_thing(el) for el in s]) + + +def _validate_flavor(flavor): if flavor is None: - flavor = ['lxml', 'bs4'] - elif isinstance(flavor, compat.string_types): - flavor = [flavor] + flavor = 'lxml', 'bs4' + elif isinstance(flavor, string_types): + flavor = flavor, elif isinstance(flavor, collections.Iterable): - if not all(isinstance(flav, compat.string_types) for flav in flavor): - raise TypeError('{0} is not an iterable of strings'.format(flavor)) + if not all(isinstance(flav, string_types) for flav in flavor): + raise TypeError('Object of type %r is not an iterable of strings' % + type(flavor).__name__) else: - raise TypeError('{0} is not a valid "flavor"'.format(flavor)) - - flavor = list(flavor) - valid_flavors = list(_valid_parsers.keys()) - - if not set(flavor) & set(valid_flavors): - raise ValueError('{0} is not a valid set of flavors, valid flavors are' - ' {1}'.format(flavor, valid_flavors)) + fmt = '{0!r}' if isinstance(flavor, string_types) else '{0}' + fmt += ' is not a valid flavor' + raise ValueError(fmt.format(flavor)) + + flavor = tuple(flavor) + valid_flavors = set(_valid_parsers) + flavor_set = set(flavor) + + if not flavor_set & valid_flavors: + raise ValueError('%s is not a valid set of flavors, valid flavors are ' + '%s' % (_print_as_set(flavor_set), + _print_as_set(valid_flavors))) return flavor -def _parse(flavor, io, match, header, index_col, skiprows, infer_types, attrs): - # bonus: re.compile is idempotent under function iteration so you can pass - # a compiled regex to it and it will return itself - flavor = _validate_parser_flavor(flavor) - compiled_match = re.compile(match) +def _parse(flavor, io, match, header, index_col, skiprows, infer_types, + parse_dates, tupleize_cols, thousands, attrs): + flavor = _validate_flavor(flavor) + compiled_match = re.compile(match) # you can pass a compiled regex here - # ugly hack because python 3 DELETES the exception variable! + # hack around python 3 deleting the exception variable retained = None for flav in flavor: parser = _parser_dispatch(flav) @@ -769,25 +705,26 @@ def _parse(flavor, io, match, header, index_col, skiprows, infer_types, attrs): else: break else: - raise retained + raise_with_traceback(retained) - return [_data_to_frame(table, header, index_col, infer_types, skiprows) + return [_data_to_frame(table, header, index_col, skiprows, infer_types, + parse_dates, tupleize_cols, thousands) for table in tables] def read_html(io, match='.+', flavor=None, header=None, index_col=None, - skiprows=None, infer_types=True, attrs=None): - r"""Read an HTML table into a DataFrame. + skiprows=None, infer_types=None, attrs=None, parse_dates=False, + tupleize_cols=False, thousands=','): + r"""Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str or file-like - A string or file like object that can be either a url, a file-like - object, or a raw string containing HTML. Note that lxml only accepts - the http, ftp and file url protocols. If you have a URI that starts - with ``'https'`` you might removing the ``'s'``. + A URL, a file-like object, or a raw string containing HTML. Note that + lxml only accepts the http, ftp and file url protocols. If you have a + URL that starts with ``'https'`` you might try removing the ``'s'``. - match : str or regex, optional, default '.+' + match : str or compiled regular expression, optional The set of tables containing text matching this regex or string will be returned. Unless the HTML is extremely simple you will probably need to pass a non-empty string here. Defaults to '.+' (match any non-empty @@ -795,44 +732,30 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, This value is converted to a regular expression so that there is consistent behavior between Beautiful Soup and lxml. - flavor : str, container of strings, default ``None`` - The parsing engine to use under the hood. 'bs4' and 'html5lib' are - synonymous with each other, they are both there for backwards - compatibility. The default of ``None`` tries to use ``lxml`` to parse - and if that fails it falls back on ``bs4`` + ``html5lib``. + flavor : str or None, container of strings + The parsing engine to use. 'bs4' and 'html5lib' are synonymous with + each other, they are both there for backwards compatibility. The + default of ``None`` tries to use ``lxml`` to parse and if that fails it + falls back on ``bs4`` + ``html5lib``. - header : int or array-like or None, optional, default ``None`` - The row (or rows for a MultiIndex) to use to make the columns headers. - Note that this row will be removed from the data. + header : int or list-like or None, optional + The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to + make the columns headers. - index_col : int or array-like or None, optional, default ``None`` - The column to use to make the index. Note that this column will be - removed from the data. + index_col : int or list-like or None, optional + The column (or list of columns) to use to create the index. - skiprows : int or collections.Container or slice or None, optional, default ``None`` - If an integer is given then skip this many rows after parsing the - column header. If a sequence of integers is given skip those specific - rows (0-based). Note that + skiprows : int or list-like or slice or None, optional + 0-based. Number of rows to skip after parsing the column integer. If a + sequence of integers or a slice is given, will skip the rows indexed by + that sequence. Note that a single element sequence means 'skip the nth + row' whereas an integer means 'skip n rows'. - .. code-block:: python - - skiprows == 0 - - yields the same result as - - .. code-block:: python + infer_types : bool, optional + This option is deprecated in 0.13, an will have no effect in 0.14. It + defaults to ``True``. - skiprows is None - - If `skiprows` is a positive integer, say :math:`n`, then - it is treated as "skip :math:`n` rows", *not* as "skip the - :math:`n^\textrm{th}` row". - - infer_types : bool, optional, default ``True`` - Whether to convert numeric types and date-appearing strings to numbers - and dates, respectively. - - attrs : dict or None, optional, default ``None`` + attrs : dict or None, optional This is a dictionary of attributes that you can pass to use to identify the table in the HTML. These are not checked for validity before being passed to lxml or Beautiful Soup. However, these attributes must be @@ -858,33 +781,38 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, <http://www.w3.org/TR/html-markup/table.html>`__. It contains the latest information on table attributes for the modern web. + parse_dates : bool, optional + See :func:`~pandas.read_csv` for details. + + tupleize_cols : bool, optional + If ``False`` try to parse multiple header rows into a + :class:`~pandas.MultiIndex`, otherwise return raw tuples. Defaults to + ``False``. + + thousands : str, optional + Separator to use to parse thousands. Defaults to ``','``. + Returns ------- dfs : list of DataFrames - A list of DataFrames, each of which is the parsed data from each of the - tables on the page. Notes ----- - Before using this function you should probably read the :ref:`gotchas about - the parser libraries that this function uses <html-gotchas>`. + Before using this function you should read the :ref:`gotchas about the + HTML parsing libraries <html-gotchas>`. - There's as little cleaning of the data as possible due to the heterogeneity - and general disorder of HTML on the web. + Expect to do some cleanup after you call this function. For example, you + might need to manually assign column names if the column names are + converted to NaN when you pass the `header=0` argument. We try to assume as + little as possible about the structure of the table and push the + idiosyncrasies of the HTML contained in the table to the user. - Expect some cleanup after you call this function. For example, - you might need to pass `infer_types=False` and perform manual conversion if - the column names are converted to NaN when you pass the `header=0` - argument. We try to assume as little as possible about the structure of the - table and push the idiosyncrasies of the HTML contained in the table to - you, the user. + This function searches for ``<table>`` elements and only for ``<tr>`` + and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>`` + element in the table. ``<td>`` stands for "table data". - This function only searches for <table> elements and only for <tr> and <th> - rows and <td> elements within those rows. This could be extended by - subclassing one of the parser classes contained in :mod:`pandas.io.html`. - - Similar to :func:`read_csv` the `header` argument is applied **after** - `skiprows` is applied. + Similar to :func:`~pandas.read_csv` the `header` argument is applied + **after** `skiprows` is applied. This function will *always* return a list of :class:`DataFrame` *or* it will fail, e.g., it will *not* return an empty list. @@ -892,12 +820,21 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None, Examples -------- See the :ref:`read_html documentation in the IO section of the docs - <io.read_html>` for many examples of reading HTML. + <io.read_html>` for some examples of reading in HTML tables. + + See Also + -------- + pandas.read_csv """ + if infer_types is not None: + warnings.warn("infer_types will have no effect in 0.14", FutureWarning) + else: + infer_types = True # TODO: remove in 0.14 + # Type check here. We don't want to parse only to fail because of an # invalid value of an integer skiprows. if isinstance(skiprows, numbers.Integral) and skiprows < 0: - raise AssertionError('cannot skip rows starting from the end of the ' - 'data (you passed a negative value)') + raise ValueError('cannot skip rows starting from the end of the ' + 'data (you passed a negative value)') return _parse(flavor, io, match, header, index_col, skiprows, infer_types, - attrs) + parse_dates, tupleize_cols, thousands, attrs) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 3ef3cbf856fef..8a2f249f6af06 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -606,16 +606,10 @@ def _failover_to_python(self): raise NotImplementedError def read(self, nrows=None): - suppressed_warnings = False if nrows is not None: if self.options.get('skip_footer'): raise ValueError('skip_footer not supported for iteration') - # # XXX hack - # if isinstance(self._engine, CParserWrapper): - # suppressed_warnings = True - # self._engine.set_error_bad_lines(False) - ret = self._engine.read(nrows) if self.options.get('as_recarray'): @@ -710,7 +704,6 @@ def _should_parse_dates(self, i): else: return (j in self.parse_dates) or (name in self.parse_dates) - def _extract_multi_indexer_columns(self, header, index_names, col_names, passed_names=False): """ extract and return the names, index_names, col_names header is a list-of-lists returned from the parsers """ @@ -728,12 +721,10 @@ def _extract_multi_indexer_columns(self, header, index_names, col_names, passed_ ic = [ ic ] sic = set(ic) - orig_header = list(header) - # clean the index_names index_names = header.pop(-1) - (index_names, names, - index_col) = _clean_index_names(index_names, self.index_col) + index_names, names, index_col = _clean_index_names(index_names, + self.index_col) # extract the columns field_count = len(header[0]) @@ -766,7 +757,7 @@ def _maybe_make_multi_index_columns(self, columns, col_names=None): return columns def _make_index(self, data, alldata, columns, indexnamerow=False): - if not _is_index_col(self.index_col) or len(self.index_col) == 0: + if not _is_index_col(self.index_col) or not self.index_col: index = None elif not self._has_complex_date_col: @@ -1430,7 +1421,7 @@ def read(self, rows=None): self._first_chunk = False columns = list(self.orig_names) - if len(content) == 0: # pragma: no cover + if not len(content): # pragma: no cover # DataFrame with the right metadata, even though it's length 0 return _get_empty_meta(self.orig_names, self.index_col, @@ -1468,8 +1459,8 @@ def _convert_data(self, data): col = self.orig_names[col] clean_conv[col] = f - return self._convert_to_ndarrays(data, self.na_values, self.na_fvalues, self.verbose, - clean_conv) + return self._convert_to_ndarrays(data, self.na_values, self.na_fvalues, + self.verbose, clean_conv) def _infer_columns(self): names = self.names @@ -1478,16 +1469,15 @@ def _infer_columns(self): header = self.header # we have a mi columns, so read and extra line - if isinstance(header,(list,tuple,np.ndarray)): + if isinstance(header, (list, tuple, np.ndarray)): have_mi_columns = True - header = list(header) + [header[-1]+1] + header = list(header) + [header[-1] + 1] else: have_mi_columns = False - header = [ header ] + header = [header] columns = [] for level, hr in enumerate(header): - if len(self.buf) > 0: line = self.buf[0] else: @@ -1521,10 +1511,11 @@ def _infer_columns(self): if names is not None: if len(names) != len(columns[0]): - raise Exception('Number of passed names did not match ' - 'number of header fields in the file') + raise ValueError('Number of passed names did not match ' + 'number of header fields in the file') if len(columns) > 1: - raise Exception('Cannot pass names with multi-index columns') + raise TypeError('Cannot pass names with multi-index ' + 'columns') columns = [ names ] else: diff --git a/pandas/io/tests/data/macau.html b/pandas/io/tests/data/macau.html new file mode 100644 index 0000000000000..be62b3221518d --- /dev/null +++ b/pandas/io/tests/data/macau.html @@ -0,0 +1,3691 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<!-- saved from url=(0037)http://www.camacau.com/statistic_list --> +<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + + +<link rel="stylesheet" type="text/css" href="./macau_files/style.css" media="screen"> +<script type="text/javascript" src="./macau_files/jquery.js"></script> + + + + + +<script type="text/javascript"> + +function slideSwitch() { + + var $active = $('#banner1 a.active'); + + var totalTmp=document.getElementById("bannerTotal").innerHTML; + + var randomTmp=Math.floor(Math.random()*totalTmp+1); + + var $next = $('#image'+randomTmp).length?$('#image'+randomTmp):$('#banner1 a:first'); + + if($next.attr("id")==$active.attr("id")){ + + $next = $active.next().length ? $active.next():$('#banner1 a:first'); + } + + $active.removeClass("active"); + + $next.addClass("active").show(); + + $active.hide(); + +} + +jQuery(function() { + + var totalTmp=document.getElementById("bannerTotal").innerHTML; + if(totalTmp>1){ + setInterval( "slideSwitch()", 5000 ); + } + +}); + +</script> +<script type="text/javascript"> +function close_notice(){ +jQuery("#tbNotice").hide(); +} +</script> + +<title>Traffic Statistics - Passengers</title> + +<!-- GOOGLE STATISTICS +<script type="text/javascript"> + + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-24989877-2']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); + +</script> +--> +<style type="text/css"></style><style type="text/css"></style><script id="fireplug-jssdk" src="./macau_files/all.js"></script><style type="text/css">.fireplug-credit-widget-overlay{z-index:9999999999999999999;background-color:rgba(91,91,91,0.6)}.fireplug-credit-widget-overlay div,.fireplug-credit-widget-overlay span,.fireplug-credit-widget-overlay applet,.fireplug-credit-widget-overlay object,.fireplug-credit-widget-overlay iframe,.fireplug-credit-widget-overlay h1,.fireplug-credit-widget-overlay h2,.fireplug-credit-widget-overlay h3,.fireplug-credit-widget-overlay h4,.fireplug-credit-widget-overlay h5,.fireplug-credit-widget-overlay h6,.fireplug-credit-widget-overlay p,.fireplug-credit-widget-overlay blockquote,.fireplug-credit-widget-overlay pre,.fireplug-credit-widget-overlay a,.fireplug-credit-widget-overlay abbr,.fireplug-credit-widget-overlay acronym,.fireplug-credit-widget-overlay address,.fireplug-credit-widget-overlay big,.fireplug-credit-widget-overlay cite,.fireplug-credit-widget-overlay code,.fireplug-credit-widget-overlay del,.fireplug-credit-widget-overlay dfn,.fireplug-credit-widget-overlay em,.fireplug-credit-widget-overlay img,.fireplug-credit-widget-overlay ins,.fireplug-credit-widget-overlay kbd,.fireplug-credit-widget-overlay q,.fireplug-credit-widget-overlay s,.fireplug-credit-widget-overlay samp,.fireplug-credit-widget-overlay small,.fireplug-credit-widget-overlay strike,.fireplug-credit-widget-overlay strong,.fireplug-credit-widget-overlay sub,.fireplug-credit-widget-overlay sup,.fireplug-credit-widget-overlay tt,.fireplug-credit-widget-overlay var,.fireplug-credit-widget-overlay b,.fireplug-credit-widget-overlay u,.fireplug-credit-widget-overlay i,.fireplug-credit-widget-overlay center,.fireplug-credit-widget-overlay dl,.fireplug-credit-widget-overlay dt,.fireplug-credit-widget-overlay dd,.fireplug-credit-widget-overlay ol,.fireplug-credit-widget-overlay ul,.fireplug-credit-widget-overlay li,.fireplug-credit-widget-overlay fieldset,.fireplug-credit-widget-overlay form,.fireplug-credit-widget-overlay label,.fireplug-credit-widget-overlay legend,.fireplug-credit-widget-overlay table,.fireplug-credit-widget-overlay caption,.fireplug-credit-widget-overlay tbody,.fireplug-credit-widget-overlay tfoot,.fireplug-credit-widget-overlay thead,.fireplug-credit-widget-overlay tr,.fireplug-credit-widget-overlay th,.fireplug-credit-widget-overlay td,.fireplug-credit-widget-overlay article,.fireplug-credit-widget-overlay aside,.fireplug-credit-widget-overlay canvas,.fireplug-credit-widget-overlay details,.fireplug-credit-widget-overlay embed,.fireplug-credit-widget-overlay figure,.fireplug-credit-widget-overlay figcaption,.fireplug-credit-widget-overlay footer,.fireplug-credit-widget-overlay header,.fireplug-credit-widget-overlay hgroup,.fireplug-credit-widget-overlay menu,.fireplug-credit-widget-overlay nav,.fireplug-credit-widget-overlay output,.fireplug-credit-widget-overlay ruby,.fireplug-credit-widget-overlay section,.fireplug-credit-widget-overlay summary,.fireplug-credit-widget-overlay time,.fireplug-credit-widget-overlay mark,.fireplug-credit-widget-overlay audio,.fireplug-credit-widget-overlay video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}.fireplug-credit-widget-overlay table{border-collapse:collapse;border-spacing:0}.fireplug-credit-widget-overlay caption,.fireplug-credit-widget-overlay th,.fireplug-credit-widget-overlay td{text-align:left;font-weight:normal;vertical-align:middle}.fireplug-credit-widget-overlay q,.fireplug-credit-widget-overlay blockquote{quotes:none}.fireplug-credit-widget-overlay q:before,.fireplug-credit-widget-overlay q:after,.fireplug-credit-widget-overlay blockquote:before,.fireplug-credit-widget-overlay blockquote:after{content:"";content:none}.fireplug-credit-widget-overlay a img{border:none}.fireplug-credit-widget-overlay .fireplug-credit-widget-overlay-item{z-index:9999999999999999999;-webkit-box-shadow:#333 0px 0px 10px;-moz-box-shadow:#333 0px 0px 10px;box-shadow:#333 0px 0px 10px}.fireplug-credit-widget-overlay-body{height:100% !important;overflow:hidden !important}.fp-getcredit iframe{border:none;overflow:hidden;height:20px;width:145px} +</style></head> +<body> +<div id="full"> +<div id="container"> + + +<div id="top"> + <div id="lang"> + + <a href="http://www.camacau.com/changeLang?lang=zh_TW&url=/statistic_list">繁體中文</a> | + <a href="http://www.camacau.com/changeLang?lang=zh_CN&url=/statistic_list">簡體中文</a> + <!--<a href="changeLang?lang=pt_PT&url=/statistic_list" >Portuguese</a> + --> + </div> +</div> + +<div id="header"> + <div id="sitelogo"><a href="http://www.camacau.com/index" style="color : #FFF;"><img src="./macau_files/cam h04.jpg"></a></div> + <div id="navcontainer"> + <div id="menu"> + <div id="search"> + <form id="searchForm" name="searchForm" action="http://www.camacau.com/search" method="POST"> + <input id="keyword" name="keyword" type="text"> + <a href="javascript:document.searchForm.submit();">Search</a> | + <a href="mailto:mkd@macau-airport.com">Contact Us</a> | + <a href="http://www.camacau.com/sitemap">SiteMap</a> | + + <a href="http://www.camacau.com/rssBuilder.action"><img src="./macau_files/rssIcon.png" alt="RSS">RSS</a> + </form></div> + </div> +</div> +</div> +<div id="menu2"> + <div> + + + <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID4" title="Main Page"> + <param name="movie" value="flash/button_index_EN.swf"> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 --> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 --> + <!--[if !IE]>--> + <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_index_EN.swf" width="92" height="20"> + <!--<![endif]--> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 --> + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p> + </div> + <!--[if !IE]>--> + </object> + <!--<![endif]--> + </object> + + <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID4" title="Our Business"> + <param name="movie" value="flash/button_our business_EN.swf"> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 --> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 --> + <!--[if !IE]>--> + <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_our%20business_EN.swf" width="92" height="20"> + <!--<![endif]--> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 --> + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p> + </div> + <!--[if !IE]>--> + </object> + <!--<![endif]--> + </object> + + <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" title="About Us"> + <param name="movie" value="flash/button_about us_EN.swf"> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 --> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 --> + <!--[if !IE]>--> + <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_about%20us_EN.swf" width="92" height="20"> + <!--<![endif]--> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 --> + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p> + </div> + <!--[if !IE]>--> + </object> + <!--<![endif]--> + </object> + + <object id="FlashID3" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" title="Media Centre"> + <param name="movie" value="flash/button_media centre_EN.swf"> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 --> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 --> + <!--[if !IE]>--> + <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_media%20centre_EN.swf" width="92" height="20"> + <!--<![endif]--> + <param name="quality" value="high"> + <param name="wmode" value="opaque"> + <param name="scale" value="exactfit"> + <param name="swfversion" value="6.0.65.0"> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 --> + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p> + </div> + <!--[if !IE]>--> + </object> + <!--<![endif]--> + </object> + + <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID5" title="Related Links"> + <param name="movie" value="flash/button_related links_EN.swf"> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 --> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 --> + <!--[if !IE]>--> + <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_related%20links_EN.swf" width="92" height="20"> + <!--<![endif]--> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 --> + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p> + </div> + <!--[if !IE]>--> + </object> + <!--<![endif]--> + </object> + + <object id="FlashID2" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" title="Interactive"> + <param name="movie" value="flash/button_interactive_EN.swf"> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <!-- 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 --> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 --> + <!--[if !IE]>--> + <object type="application/x-shockwave-flash" data="http://www.camacau.com/flash/button_interactive_EN.swf" width="92" height="20"> + <!--<![endif]--> + <param name="quality" value="high"> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque"> + <param name="swfversion" value="6.0.65.0"> + <param name="expressinstall" value="flash/expressInstall.swf"> + <!-- 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 --> + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="./macau_files/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33"></a></p> + </div> + <!--[if !IE]>--> + </object> + <!--<![endif]--> + </object> + + <!--<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="95" height="20" id="FlashID4" title="Group of Public"> + <param name="movie" value="flash/button_pressRelease_EN.swf" /> + <param name="quality" value="high" /> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque" /> + <param name="swfversion" value="6.0.65.0" /> + 此 param 標籤會提示使用 Flash Player 6.0 r65 和更新版本的使用者下載最新版本的 Flash Player。如果您不想讓使用者看到這項提示,請將其刪除。 + <param name="expressinstall" value="flash/expressInstall.swf" /> + 下一個物件標籤僅供非 IE 瀏覽器使用。因此,請使用 IECC 將其自 IE 隱藏。 + [if !IE]> + <object type="application/x-shockwave-flash" data="flash/button_pressRelease_EN.swf" width="92" height="20"> + <![endif] + <param name="quality" value="high" /> + <param name="scale" value="exactfit"> + <param name="wmode" value="opaque" /> + <param name="swfversion" value="6.0.65.0" /> + <param name="expressinstall" value="flash/expressInstall.swf" /> + 瀏覽器會為使用 Flash Player 6.0 和更早版本的使用者顯示下列替代內容。 + <div> + <h4>這個頁面上的內容需要較新版本的 Adobe Flash Player。</h4> + <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="取得 Adobe Flash Player" width="112" height="33" /></a></p> + </div> + [if !IE]> + </object> + <![endif] + </object> + + --></div> + </div> + + + + + + + +<style> +#slider ul li +{ +height: 90px; +list-style:none; +width:95%; +font-size:11pt; +text-indent:2em; +text-align:justify; +text-justify:inter-ideograph; +color:#663300; +} + + +#slider +{ +margin: auto; +overflow: hidden; +/* Non Core */ +background: #f6f7f8; +box-shadow: 4px 4px 15px #aaa; +-o-box-shadow: 4px 4px 15px #aaa; +-icab-box-shadow: 4px 4px 15px #aaa; +-khtml-box-shadow: 4px 4px 15px #aaa; +-moz-box-shadow: 4px 4px 15px #aaa; +-webkit-box-shadow: 4px 4px 15px #aaa; +border: 4px solid #bcc5cb; + +border-width: 1px 2px 2px 1px; + +-o-border-radius: 10px; +-icab-border-radius: 10px; +-khtml-border-radius: 10px; +-moz-border-radius: 10px; +-webkit-border-radius: 10px; +border-radius: 10px; + +} + +#close_tbNotice img +{ +width:20px; +height:20px; +align:right; +cursor:pointer; +} +</style> + +<div id="banner"> + <!--<div id="leftGradient"></div>--> + + <table id="tbNotice" style="display:none;width:800px;z-index:999;position:absolute;left:20%;" align="center"> + <tbody><tr height="40px"><td></td></tr> + <tr><td> + + <div id="slider"> + <div id="close_tbNotice"><img src="./macau_files/delete.png" onclick="close_notice()"></div> + <ul> + <li> + + + + + </li> + </ul> + + </div> + <div id="show_notice" style="display:none;"> + + </div> + + </td> + + </tr> + <tr><td align="right"></td></tr> + </tbody></table> + + + <div class="gradient"> + + </div> + <div class="banner1" id="banner1"> + + + + + <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image1" class=""> + <img src="./macau_files/41.jpeg" alt="Slideshow Image 1"> + </a> + + + + + + <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image2" class=""> + <img src="./macau_files/45.jpeg" alt="Slideshow Image 2"> + </a> + + + + + + <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image3" class=""> + <img src="./macau_files/46.jpeg" alt="Slideshow Image 3"> + </a> + + + + + + <a href="http://www.macau-airport.com/" target="_blank" style="display: inline;" id="image4" class="active"> + <img src="./macau_files/47.jpeg" alt="Slideshow Image 4"> + </a> + + + + + + <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image5" class=""> + <img src="./macau_files/48.jpeg" alt="Slideshow Image 5"> + </a> + + + + + + <a href="http://www.macau-airport.com/" target="_blank" style="display: none;" id="image6" class=""> + <img src="./macau_files/49.jpeg" alt="Slideshow Image 6"> + </a> + + + + + + <a href="http://www.4cpscac.com/" target="_blank" style="display: none;" id="image7" class=""> + <img src="./macau_files/50.jpg" alt="Slideshow Image 7"> + </a> + + + + + </div> + <div id="bannerTotal" style="display:none;">7</div> +</div> + +<div id="content"> + <div id="leftnav"> + + <div id="navmenu"> + + + + + +<link href="./macau_files/ddaccordion.css" rel="stylesheet" type="text/css"> +<script type="text/javascript" src="./macau_files/ddaccordion.js"></script> + + + +<script type="text/javascript"> + ddaccordion.init({ + headerclass: "leftmenu_silverheader", //Shared CSS class name of headers group + contentclass: "leftmenu_submenu", //Shared CSS class name of contents group + revealtype: "clickgo", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover" + mouseoverdelay: 100, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover + collapseprev: true, //Collapse previous content (so only one open at any time)? true/false + defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc] [] denotes no content + onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed) + animatedefault: true, //Should contents open by default be animated into view? + persiststate: true, //persist state of opened contents within browser session? + toggleclass: ["", "selected"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"] + togglehtml: ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively ["position", "html1", "html2"] (see docs) + animatespeed: "normal", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow" + oninit:function(headers, expandedindices){ //custom code to run when headers have initalized + //do nothing + }, + onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed + //do nothing + + } +}); +</script><style type="text/css"> +.leftmenu_submenu{display: none} +a.hiddenajaxlink{display: none} +</style> + + + <table> + <tbody><tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/geographic_information">MIA Geographical Information</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/airport_services">Scope of Service</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/services_agreement">Air Services Agreement</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/airport_charges" class="leftmenu_silverheader selected" headerindex="0h"><span>Airport Charges</span></a></td></tr> + <tr><td colspan="2" style="padding-top:0px;padding-bottom:0px;padding-right:0px;"> + <table class="leftmenu_submenu" contentindex="0c" style="display: block;"> + <tbody><tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges1">Passenger Service Fees</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges2">Aircraft Parking fees</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges3">Airport Security Fee</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges4">Utilization fees</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/airport_charges5">Refuelling Charge</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/calculation">Calculation of Landing fee Rate</a></td></tr></tbody></table></td></tr> + </tbody></table> + </td> + </tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/application_facilities">Application of Credit Facilities</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="javascript:void(0)" class="leftmenu_silverheader " headerindex="1h"><span>Passenger Flight Incentive Program</span></a></td></tr> + <tr><td colspan="2" style="padding-top:0px;padding-bottom:0px;padding-right:0px;"> + <table class="leftmenu_submenu" contentindex="1c" style="display: none;"> + <tbody><tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/incentive_program1">Incentive policy for new routes and additional flights</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/incentive_program1_1">Passenger flights</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/incentive_program1_2">Charter flights</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/docs/MIA_Route_Development_IncentiveApp_Form.pdf" target="_blank">Route Development Incentive Application Form</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/online_application">Online Application</a></td></tr></tbody></table></td></tr> + </tbody></table> + </td> + </tr> + + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/slot_application">Slot Application</a></td></tr> + + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/freighter_forwards">Macau Freight Forwarders</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/ctplatform">Cargo Tracking Platform</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/for_rent">For Rent</a></td></tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/capacity">Airport Capacity</a></td></tr> + + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td style="color: #606060;text-decoration: none;"><a href="javascript:void(0)" class="leftmenu_silverheader " headerindex="2h">Airport Characteristics &amp; Traffic Statistics</a></td></tr> + <tr><td colspan="2" style="padding-top:0px;padding-bottom:0px;padding-right:0px;"> + <table class="leftmenu_submenu" contentindex="2c" style="display: none;"> + <!--<tr><td>&nbsp;</td><td><table class="submenu"><tr><td><img width="20" height="15" src="images/sub_icon.gif"/></td><td><a href="airport_characteristics">Airport Characteristics</a></td></tr></table></td></tr> + --> + <tbody><tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="./macau_files/macau.html">Traffic Statistics - Passengers</a></td></tr></tbody></table></td></tr> + <tr><td>&nbsp;</td><td><table class="submenu"><tbody><tr><td><img width="20" height="15" src="./macau_files/sub_icon.gif"></td><td><a href="http://www.camacau.com/statistics_cargo">Traffic Statistics - Cargo</a></td></tr></tbody></table></td></tr> + </tbody></table> + </td> + </tr> + <tr><td><img width="20" height="15" src="./macau_files/double.gif"></td><td><a href="http://www.camacau.com/operational_routes">Operational Routes</a></td></tr> + + <!--<tr><td><img width="20" height="15" src="images/double.gif"/></td><td><a href="route_development">Member Registration</a></td></tr> + + --><!--<tr><td><img width="20" height="15" src="images/double.gif"/></td><td><a href="cargo_arrival">Cargo Flight Information</a></td></tr>--> + + <!--<tr><td><img width="20" height="15" src="images/double.gif"/></td><td><a href="/mvnforum/mvnforum/index">Forum</a></td></tr>--> + + </tbody></table> + + + </div> + </div> + +<div id="under"> + <div id="contextTitle"> + <h2 class="con">Traffic Statistics - Passengers</h2> + + </div> + <div class="contextTitleAfter"></div> + <div> + + + <div id="context"> + <!--/*begin context*/--> + <div class="Container"> + <div id="Scroller-1"> + <div class="Scroller-Container"> + <div id="statisticspassengers" style="width:550px;"> + + + <span id="title">Traffic Statistics</span> + + + + + + <br><br><br> + <span id="title">Passengers Figure(2008-2013) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">2013</th> + + <th align="center">2012</th> + + <th align="center">2011</th> + + <th align="center">2010</th> + + <th align="center">2009</th> + + <th align="center">2008</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + 374,917 + </td> + + <td align="center"> + + 362,379 + </td> + + <td align="center"> + + 301,503 + </td> + + <td align="center"> + + 358,902 + </td> + + <td align="center"> + + 342,323 + </td> + + <td align="center"> + + 420,574 + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + 393,152 + </td> + + <td align="center"> + + 312,405 + </td> + + <td align="center"> + + 301,259 + </td> + + <td align="center"> + + 351,654 + </td> + + <td align="center"> + + 297,755 + </td> + + <td align="center"> + + 442,809 + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + 408,755 + </td> + + <td align="center"> + + 334,000 + </td> + + <td align="center"> + + 318,908 + </td> + + <td align="center"> + + 360,365 + </td> + + <td align="center"> + + 387,879 + </td> + + <td align="center"> + + 468,540 + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + 408,860 + </td> + + <td align="center"> + + 358,198 + </td> + + <td align="center"> + + 339,060 + </td> + + <td align="center"> + + 352,976 + </td> + + <td align="center"> + + 400,553 + </td> + + <td align="center"> + + 492,930 + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + 374,397 + </td> + + <td align="center"> + + 329,218 + </td> + + <td align="center"> + + 321,060 + </td> + + <td align="center"> + + 330,407 + </td> + + <td align="center"> + + 335,967 + </td> + + <td align="center"> + + 465,045 + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + 401,995 + </td> + + <td align="center"> + + 356,679 + </td> + + <td align="center"> + + 343,006 + </td> + + <td align="center"> + + 326,724 + </td> + + <td align="center"> + + 296,748 + </td> + + <td align="center"> + + 426,764 + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 423,081 + </td> + + <td align="center"> + + 378,993 + </td> + + <td align="center"> + + 356,580 + </td> + + <td align="center"> + + 351,110 + </td> + + <td align="center"> + + 439,425 + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 453,391 + </td> + + <td align="center"> + + 395,883 + </td> + + <td align="center"> + + 364,011 + </td> + + <td align="center"> + + 404,076 + </td> + + <td align="center"> + + 425,814 + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 384,887 + </td> + + <td align="center"> + + 325,124 + </td> + + <td align="center"> + + 308,940 + </td> + + <td align="center"> + + 317,226 + </td> + + <td align="center"> + + 379,898 + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 383,889 + </td> + + <td align="center"> + + 333,102 + </td> + + <td align="center"> + + 317,040 + </td> + + <td align="center"> + + 355,935 + </td> + + <td align="center"> + + 415,339 + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 379,065 + </td> + + <td align="center"> + + 327,803 + </td> + + <td align="center"> + + 303,186 + </td> + + <td align="center"> + + 372,104 + </td> + + <td align="center"> + + 366,411 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 413,873 + </td> + + <td align="center"> + + 359,313 + </td> + + <td align="center"> + + 348,051 + </td> + + <td align="center"> + + 388,573 + </td> + + <td align="center"> + + 354,253 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 2,362,076 + </td> + + <td align="center"> + + 4,491,065 + </td> + + <td align="center"> + + 4,045,014 + </td> + + <td align="center"> + + 4,078,836 + </td> + + <td align="center"> + + 4,250,249 + </td> + + <td align="center"> + + 5,097,802 + </td> + + </tr> + </tbody> + </table> + + <br><br><br> + <span id="title">Passengers Figure(2002-2007) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">2007</th> + + <th align="center">2006</th> + + <th align="center">2005</th> + + <th align="center">2004</th> + + <th align="center">2003</th> + + <th align="center">2002</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + 381,887 + </td> + + <td align="center"> + + 323,282 + </td> + + <td align="center"> + + 289,701 + </td> + + <td align="center"> + + 288,507 + </td> + + <td align="center"> + + 290,140 + </td> + + <td align="center"> + + 268,783 + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + 426,014 + </td> + + <td align="center"> + + 360,820 + </td> + + <td align="center"> + + 348,723 + </td> + + <td align="center"> + + 207,710 + </td> + + <td align="center"> + + 323,264 + </td> + + <td align="center"> + + 323,654 + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + 443,805 + </td> + + <td align="center"> + + 389,125 + </td> + + <td align="center"> + + 321,953 + </td> + + <td align="center"> + + 273,910 + </td> + + <td align="center"> + + 295,052 + </td> + + <td align="center"> + + 360,668 + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + 500,917 + </td> + + <td align="center"> + + 431,550 + </td> + + <td align="center"> + + 367,976 + </td> + + <td align="center"> + + 324,931 + </td> + + <td align="center"> + + 144,082 + </td> + + <td align="center"> + + 380,648 + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + 468,637 + </td> + + <td align="center"> + + 399,743 + </td> + + <td align="center"> + + 359,298 + </td> + + <td align="center"> + + 250,601 + </td> + + <td align="center"> + + 47,333 + </td> + + <td align="center"> + + 359,547 + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + 463,676 + </td> + + <td align="center"> + + 393,713 + </td> + + <td align="center"> + + 360,147 + </td> + + <td align="center"> + + 296,000 + </td> + + <td align="center"> + + 94,294 + </td> + + <td align="center"> + + 326,508 + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + 490,404 + </td> + + <td align="center"> + + 465,497 + </td> + + <td align="center"> + + 413,131 + </td> + + <td align="center"> + + 365,454 + </td> + + <td align="center"> + + 272,784 + </td> + + <td align="center"> + + 388,061 + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + 490,830 + </td> + + <td align="center"> + + 478,474 + </td> + + <td align="center"> + + 409,281 + </td> + + <td align="center"> + + 372,802 + </td> + + <td align="center"> + + 333,840 + </td> + + <td align="center"> + + 384,719 + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + 446,594 + </td> + + <td align="center"> + + 412,444 + </td> + + <td align="center"> + + 354,751 + </td> + + <td align="center"> + + 321,456 + </td> + + <td align="center"> + + 295,447 + </td> + + <td align="center"> + + 334,029 + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + 465,757 + </td> + + <td align="center"> + + 461,215 + </td> + + <td align="center"> + + 390,435 + </td> + + <td align="center"> + + 358,362 + </td> + + <td align="center"> + + 291,193 + </td> + + <td align="center"> + + 372,706 + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + 455,132 + </td> + + <td align="center"> + + 425,116 + </td> + + <td align="center"> + + 323,347 + </td> + + <td align="center"> + + 327,593 + </td> + + <td align="center"> + + 268,282 + </td> + + <td align="center"> + + 350,324 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + 465,225 + </td> + + <td align="center"> + + 435,114 + </td> + + <td align="center"> + + 308,999 + </td> + + <td align="center"> + + 326,933 + </td> + + <td align="center"> + + 249,855 + </td> + + <td align="center"> + + 322,056 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 5,498,878 + </td> + + <td align="center"> + + 4,976,093 + </td> + + <td align="center"> + + 4,247,742 + </td> + + <td align="center"> + + 3,714,259 + </td> + + <td align="center"> + + 2,905,566 + </td> + + <td align="center"> + + 4,171,703 + </td> + + </tr> + </tbody> + </table> + + <br><br><br> + <span id="title">Passengers Figure(1996-2001) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">2001</th> + + <th align="center">2000</th> + + <th align="center">1999</th> + + <th align="center">1998</th> + + <th align="center">1997</th> + + <th align="center">1996</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + 265,603 + </td> + + <td align="center"> + + 184,381 + </td> + + <td align="center"> + + 161,264 + </td> + + <td align="center"> + + 161,432 + </td> + + <td align="center"> + + 117,984 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + 249,259 + </td> + + <td align="center"> + + 264,066 + </td> + + <td align="center"> + + 209,569 + </td> + + <td align="center"> + + 168,777 + </td> + + <td align="center"> + + 150,772 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + 312,319 + </td> + + <td align="center"> + + 226,483 + </td> + + <td align="center"> + + 186,965 + </td> + + <td align="center"> + + 172,060 + </td> + + <td align="center"> + + 149,795 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + 351,793 + </td> + + <td align="center"> + + 296,541 + </td> + + <td align="center"> + + 237,449 + </td> + + <td align="center"> + + 180,241 + </td> + + <td align="center"> + + 179,049 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + 338,692 + </td> + + <td align="center"> + + 288,949 + </td> + + <td align="center"> + + 230,691 + </td> + + <td align="center"> + + 172,391 + </td> + + <td align="center"> + + 189,925 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + 332,630 + </td> + + <td align="center"> + + 271,181 + </td> + + <td align="center"> + + 231,328 + </td> + + <td align="center"> + + 157,519 + </td> + + <td align="center"> + + 175,402 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + 344,658 + </td> + + <td align="center"> + + 304,276 + </td> + + <td align="center"> + + 243,534 + </td> + + <td align="center"> + + 205,595 + </td> + + <td align="center"> + + 173,103 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + 360,899 + </td> + + <td align="center"> + + 300,418 + </td> + + <td align="center"> + + 257,616 + </td> + + <td align="center"> + + 241,140 + </td> + + <td align="center"> + + 178,118 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + 291,817 + </td> + + <td align="center"> + + 280,803 + </td> + + <td align="center"> + + 210,885 + </td> + + <td align="center"> + + 183,954 + </td> + + <td align="center"> + + 163,385 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + 327,232 + </td> + + <td align="center"> + + 298,873 + </td> + + <td align="center"> + + 231,251 + </td> + + <td align="center"> + + 205,726 + </td> + + <td align="center"> + + 176,879 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + 315,538 + </td> + + <td align="center"> + + 265,528 + </td> + + <td align="center"> + + 228,637 + </td> + + <td align="center"> + + 181,677 + </td> + + <td align="center"> + + 146,804 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + 314,866 + </td> + + <td align="center"> + + 257,929 + </td> + + <td align="center"> + + 210,922 + </td> + + <td align="center"> + + 183,975 + </td> + + <td align="center"> + + 151,362 + </td> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 3,805,306 + </td> + + <td align="center"> + + 3,239,428 + </td> + + <td align="center"> + + 2,640,111 + </td> + + <td align="center"> + + 2,214,487 + </td> + + <td align="center"> + + 1,952,578 + </td> + + <td align="center"> + + 0 + </td> + + </tr> + </tbody> + </table> + + <br><br><br> + <span id="title">Passengers Figure(1995-1995) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">1995</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + 6,601 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + 37,041 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 43,642 + </td> + + </tr> + </tbody> + </table> + + + <br><br><br> + <div align="right"><img src="./macau_files/pass_stat.jpg" alt="passenger statistic picture" width="565" height="318"></div> + <br><br><br> + + + <!--statistics-movement --> + + <br><br><br> + <span id="title">Movement Statistics(2008-2013) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">2013</th> + + <th align="center">2012</th> + + <th align="center">2011</th> + + <th align="center">2010</th> + + <th align="center">2009</th> + + <th align="center">2008</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + 3,925 + </td> + + <td align="center"> + + 3,463 + </td> + + <td align="center"> + + 3,289 + </td> + + <td align="center"> + + 3,184 + </td> + + <td align="center"> + + 3,488 + </td> + + <td align="center"> + + 4,568 + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + 3,632 + </td> + + <td align="center"> + + 2,983 + </td> + + <td align="center"> + + 2,902 + </td> + + <td align="center"> + + 3,053 + </td> + + <td align="center"> + + 3,347 + </td> + + <td align="center"> + + 4,527 + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + 3,909 + </td> + + <td align="center"> + + 3,166 + </td> + + <td align="center"> + + 3,217 + </td> + + <td align="center"> + + 3,175 + </td> + + <td align="center"> + + 3,636 + </td> + + <td align="center"> + + 4,594 + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + 3,903 + </td> + + <td align="center"> + + 3,258 + </td> + + <td align="center"> + + 3,146 + </td> + + <td align="center"> + + 3,023 + </td> + + <td align="center"> + + 3,709 + </td> + + <td align="center"> + + 4,574 + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + 4,075 + </td> + + <td align="center"> + + 3,234 + </td> + + <td align="center"> + + 3,266 + </td> + + <td align="center"> + + 3,033 + </td> + + <td align="center"> + + 3,603 + </td> + + <td align="center"> + + 4,511 + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + 4,038 + </td> + + <td align="center"> + + 3,272 + </td> + + <td align="center"> + + 3,316 + </td> + + <td align="center"> + + 2,909 + </td> + + <td align="center"> + + 3,057 + </td> + + <td align="center"> + + 4,081 + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 3,661 + </td> + + <td align="center"> + + 3,359 + </td> + + <td align="center"> + + 3,062 + </td> + + <td align="center"> + + 3,354 + </td> + + <td align="center"> + + 4,215 + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 3,942 + </td> + + <td align="center"> + + 3,417 + </td> + + <td align="center"> + + 3,077 + </td> + + <td align="center"> + + 3,395 + </td> + + <td align="center"> + + 4,139 + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 3,703 + </td> + + <td align="center"> + + 3,169 + </td> + + <td align="center"> + + 3,095 + </td> + + <td align="center"> + + 3,100 + </td> + + <td align="center"> + + 3,752 + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 3,727 + </td> + + <td align="center"> + + 3,469 + </td> + + <td align="center"> + + 3,179 + </td> + + <td align="center"> + + 3,375 + </td> + + <td align="center"> + + 3,874 + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 3,722 + </td> + + <td align="center"> + + 3,145 + </td> + + <td align="center"> + + 3,159 + </td> + + <td align="center"> + + 3,213 + </td> + + <td align="center"> + + 3,567 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + + </td> + + <td align="center"> + + 3,866 + </td> + + <td align="center"> + + 3,251 + </td> + + <td align="center"> + + 3,199 + </td> + + <td align="center"> + + 3,324 + </td> + + <td align="center"> + + 3,362 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 23,482 + </td> + + <td align="center"> + + 41,997 + </td> + + <td align="center"> + + 38,946 + </td> + + <td align="center"> + + 37,148 + </td> + + <td align="center"> + + 40,601 + </td> + + <td align="center"> + + 49,764 + </td> + + </tr> + </tbody> + </table> + + <br><br><br> + <span id="title">Movement Statistics(2002-2007) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">2007</th> + + <th align="center">2006</th> + + <th align="center">2005</th> + + <th align="center">2004</th> + + <th align="center">2003</th> + + <th align="center">2002</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + 4,384 + </td> + + <td align="center"> + + 3,933 + </td> + + <td align="center"> + + 3,528 + </td> + + <td align="center"> + + 3,051 + </td> + + <td align="center"> + + 3,257 + </td> + + <td align="center"> + + 2,711 + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + 4,131 + </td> + + <td align="center"> + + 3,667 + </td> + + <td align="center"> + + 3,331 + </td> + + <td align="center"> + + 2,372 + </td> + + <td align="center"> + + 3,003 + </td> + + <td align="center"> + + 2,747 + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + 4,349 + </td> + + <td align="center"> + + 4,345 + </td> + + <td align="center"> + + 3,549 + </td> + + <td align="center"> + + 3,049 + </td> + + <td align="center"> + + 3,109 + </td> + + <td align="center"> + + 2,985 + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + 4,460 + </td> + + <td align="center"> + + 4,490 + </td> + + <td align="center"> + + 3,832 + </td> + + <td align="center"> + + 3,359 + </td> + + <td align="center"> + + 2,033 + </td> + + <td align="center"> + + 2,928 + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + 4,629 + </td> + + <td align="center"> + + 4,245 + </td> + + <td align="center"> + + 3,663 + </td> + + <td align="center"> + + 3,251 + </td> + + <td align="center"> + + 1,229 + </td> + + <td align="center"> + + 3,109 + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + 4,365 + </td> + + <td align="center"> + + 4,124 + </td> + + <td align="center"> + + 3,752 + </td> + + <td align="center"> + + 3,414 + </td> + + <td align="center"> + + 1,217 + </td> + + <td align="center"> + + 3,049 + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + 4,612 + </td> + + <td align="center"> + + 4,386 + </td> + + <td align="center"> + + 3,876 + </td> + + <td align="center"> + + 3,664 + </td> + + <td align="center"> + + 2,423 + </td> + + <td align="center"> + + 3,078 + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + 4,446 + </td> + + <td align="center"> + + 4,373 + </td> + + <td align="center"> + + 3,987 + </td> + + <td align="center"> + + 3,631 + </td> + + <td align="center"> + + 3,040 + </td> + + <td align="center"> + + 3,166 + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + 4,414 + </td> + + <td align="center"> + + 4,311 + </td> + + <td align="center"> + + 3,782 + </td> + + <td align="center"> + + 3,514 + </td> + + <td align="center"> + + 2,809 + </td> + + <td align="center"> + + 3,239 + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + 4,445 + </td> + + <td align="center"> + + 4,455 + </td> + + <td align="center"> + + 3,898 + </td> + + <td align="center"> + + 3,744 + </td> + + <td align="center"> + + 3,052 + </td> + + <td align="center"> + + 3,562 + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + 4,563 + </td> + + <td align="center"> + + 4,285 + </td> + + <td align="center"> + + 3,951 + </td> + + <td align="center"> + + 3,694 + </td> + + <td align="center"> + + 3,125 + </td> + + <td align="center"> + + 3,546 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + 4,588 + </td> + + <td align="center"> + + 4,435 + </td> + + <td align="center"> + + 3,855 + </td> + + <td align="center"> + + 3,763 + </td> + + <td align="center"> + + 2,996 + </td> + + <td align="center"> + + 3,444 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 53,386 + </td> + + <td align="center"> + + 51,049 + </td> + + <td align="center"> + + 45,004 + </td> + + <td align="center"> + + 40,506 + </td> + + <td align="center"> + + 31,293 + </td> + + <td align="center"> + + 37,564 + </td> + + </tr> + </tbody> + </table> + + <br><br><br> + <span id="title">Movement Statistics(1996-2001) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">2001</th> + + <th align="center">2000</th> + + <th align="center">1999</th> + + <th align="center">1998</th> + + <th align="center">1997</th> + + <th align="center">1996</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + 2,694 + </td> + + <td align="center"> + + 2,201 + </td> + + <td align="center"> + + 1,835 + </td> + + <td align="center"> + + 2,177 + </td> + + <td align="center"> + + 1,353 + </td> + + <td align="center"> + + 744 + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + 2,364 + </td> + + <td align="center"> + + 2,357 + </td> + + <td align="center"> + + 1,826 + </td> + + <td align="center"> + + 1,740 + </td> + + <td align="center"> + + 1,339 + </td> + + <td align="center"> + + 692 + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + 2,543 + </td> + + <td align="center"> + + 2,206 + </td> + + <td align="center"> + + 1,895 + </td> + + <td align="center"> + + 1,911 + </td> + + <td align="center"> + + 1,533 + </td> + + <td align="center"> + + 872 + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + 2,531 + </td> + + <td align="center"> + + 2,311 + </td> + + <td align="center"> + + 2,076 + </td> + + <td align="center"> + + 1,886 + </td> + + <td align="center"> + + 1,587 + </td> + + <td align="center"> + + 1,026 + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + 2,579 + </td> + + <td align="center"> + + 2,383 + </td> + + <td align="center"> + + 1,914 + </td> + + <td align="center"> + + 2,102 + </td> + + <td align="center"> + + 1,720 + </td> + + <td align="center"> + + 1,115 + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + 2,681 + </td> + + <td align="center"> + + 2,370 + </td> + + <td align="center"> + + 1,890 + </td> + + <td align="center"> + + 2,038 + </td> + + <td align="center"> + + 1,716 + </td> + + <td align="center"> + + 1,037 + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + 2,903 + </td> + + <td align="center"> + + 2,609 + </td> + + <td align="center"> + + 1,916 + </td> + + <td align="center"> + + 2,078 + </td> + + <td align="center"> + + 1,693 + </td> + + <td align="center"> + + 1,209 + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + 3,037 + </td> + + <td align="center"> + + 2,487 + </td> + + <td align="center"> + + 1,968 + </td> + + <td align="center"> + + 2,061 + </td> + + <td align="center"> + + 1,676 + </td> + + <td align="center"> + + 1,241 + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + 2,767 + </td> + + <td align="center"> + + 2,329 + </td> + + <td align="center"> + + 1,955 + </td> + + <td align="center"> + + 1,970 + </td> + + <td align="center"> + + 1,681 + </td> + + <td align="center"> + + 1,263 + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + 2,922 + </td> + + <td align="center"> + + 2,417 + </td> + + <td align="center"> + + 2,267 + </td> + + <td align="center"> + + 1,969 + </td> + + <td align="center"> + + 1,809 + </td> + + <td align="center"> + + 1,368 + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + 2,670 + </td> + + <td align="center"> + + 2,273 + </td> + + <td align="center"> + + 2,132 + </td> + + <td align="center"> + + 2,102 + </td> + + <td align="center"> + + 1,786 + </td> + + <td align="center"> + + 1,433 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + 2,815 + </td> + + <td align="center"> + + 2,749 + </td> + + <td align="center"> + + 2,187 + </td> + + <td align="center"> + + 1,981 + </td> + + <td align="center"> + + 1,944 + </td> + + <td align="center"> + + 1,386 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 32,506 + </td> + + <td align="center"> + + 28,692 + </td> + + <td align="center"> + + 23,861 + </td> + + <td align="center"> + + 24,015 + </td> + + <td align="center"> + + 19,837 + </td> + + <td align="center"> + + 13,386 + </td> + + </tr> + </tbody> + </table> + + <br><br><br> + <span id="title">Movement Statistics(1995-1995) </span><br><br> + <table class="style1"> + <tbody> + <tr height="17"> + <th align="right">&nbsp; </th> + + <th align="center">1995</th> + + </tr> + <tr height="17"> + <th align="right">January</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">February</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">March</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">April</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">May</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">June</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">July</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">August</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">September</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">October</th> + + <td align="center"> + + + </td> + + </tr> + <tr height="17"> + <th align="right">November</th> + + <td align="center"> + + 126 + </td> + + </tr> + <tr height="17"> + <th align="right">December</th> + + <td align="center"> + + 536 + </td> + + </tr> + <tr height="17"> + <th align="right">Total</th> + + <td align="center"> + + 662 + </td> + + </tr> + </tbody> + </table> + + + <br><br><br> + <div align="right"><img src="./macau_files/mov_stat.jpg" alt="passenger statistic picture" width="565" height="318"></div> + + + </div> + + </div> + </div> + </div> + + + <!--/*end context*/--> + </div> + </div> + + <div id="buttombar"><img height="100" src="./macau_files/buttombar.gif"></div> + <div id="logo"> + + + + <div> + + <a href="http://www.macau-airport.com/envirop/zh/default.php" style="display: inline;"><img height="80" src="./macau_files/38.jpg"></a> + + </div> + + + <div> + + <a href="http://www.macau-airport.com/envirop/en/default.php" style="display: inline;"><img height="80" src="./macau_files/36.jpg"></a> + + </div> + +</div> +</div> + + + +</div> + + +<div id="footer"> +<hr> + <div id="footer-left"> + <a href="http://www.camacau.com/index">Main Page</a> | + <a href="http://www.camacau.com/geographic_information">Our Business</a> | + <a href="http://www.camacau.com/about_us">About Us</a> | + <a href="http://www.camacau.com/pressReleases_list">Media Centre</a> | + <a href="http://www.camacau.com/rlinks2">Related Links</a> | + <a href="http://www.camacau.com/download_list">Interactive</a> + </div> + <div id="footer-right">Macau International Airport Co. Ltd. | Copyright 2013 | All rights reserved</div> +</div> +</div> +</div> + +<div id="___fireplug_chrome_extension___" style="display: none;"></div><iframe id="rdbIndicator" width="100%" height="270" border="0" src="./macau_files/indicator.html" style="display: none; border: 0; position: fixed; left: 0; top: 0; z-index: 2147483647"></iframe><link rel="stylesheet" type="text/css" media="screen" href="chrome-extension://fcdjadjbdihbaodagojiomdljhjhjfho/css/atd.css"></body></html> \ No newline at end of file diff --git a/pandas/io/tests/data/nyse_wsj.html b/pandas/io/tests/data/nyse_wsj.html new file mode 100644 index 0000000000000..aa3d470a5fbc6 --- /dev/null +++ b/pandas/io/tests/data/nyse_wsj.html @@ -0,0 +1,1207 @@ +<table border="0" cellpadding="0" cellspacing="0" class="autocompleteContainer"> + <tbody> + <tr> + <td> + <div class="symbolCompleteContainer"> + <div><input autocomplete="off" maxlength="80" name="KEYWORDS" type="text" value=""/></div> + </div> + <div class="hat_button"> + <span class="hat_button_text">SEARCH</span> + </div> + <div style="clear: both;"><div class="subSymbolCompleteResults"></div></div> + </td> + </tr> + </tbody> +</table> +<table bgcolor="" border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr> + <td height="0"><img alt="" border="0" height="0" src="null/img/b.gif" width="1"/></td> +</tr></tbody></table> +<table border="0" cellpadding="0" cellspacing="0" class="mdcTable" width="100%"> + <tbody><tr> + <td class="colhead" style="text-align:left"> </td> + <td class="colhead" style="text-align:left">Issue<span class="textb10gray" style="margin-left: 8px;">(Roll over for charts and headlines)</span> + </td> + <td class="colhead">Volume</td> + <td class="colhead">Price</td> + <td class="colhead" style="width:35px;">Chg</td> + <td class="colhead">% Chg</td> + </tr> + <tr> + <td class="num">1</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=JCP" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'JCP')">J.C. Penney (JCP) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">250,697,455</td> + <td class="nnum">$9.05</td> + <td class="nnum">-1.37</td> + <td class="nnum" style="border-right:0px">-13.15</td> + </tr> + <tr> + <td class="num">2</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=BAC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BAC')">Bank of America (BAC) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">77,162,103</td> + <td class="nnum">13.90</td> + <td class="nnum">-0.18</td> + <td class="nnum" style="border-right:0px">-1.28</td> + </tr> + <tr> + <td class="num">3</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=RAD" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RAD')">Rite Aid (RAD) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">52,140,382</td> + <td class="nnum">4.70</td> + <td class="nnum">-0.08</td> + <td class="nnum" style="border-right:0px">-1.67</td> + </tr> + <tr> + <td class="num">4</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=F" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'F')">Ford Motor (F) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">33,745,287</td> + <td class="nnum">17.05</td> + <td class="nnum">-0.22</td> + <td class="nnum" style="border-right:0px">-1.27</td> + </tr> + <tr> + <td class="num">5</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=PFE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PFE')">Pfizer (PFE) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">27,801,853</td> + <td class="pnum">28.88</td> + <td class="pnum">0.36</td> + <td class="pnum" style="border-right:0px">1.26</td> + </tr> + <tr> + <td class="num">6</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=HTZ" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HTZ')">Hertz Global Hldgs (HTZ) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">25,821,264</td> + <td class="pnum">22.32</td> + <td class="pnum">0.69</td> + <td class="pnum" style="border-right:0px">3.19</td> + </tr> + <tr> + <td class="num">7</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=GE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GE')">General Electric (GE) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">25,142,064</td> + <td class="nnum">24.05</td> + <td class="nnum">-0.20</td> + <td class="nnum" style="border-right:0px">-0.82</td> + </tr> + <tr> + <td class="num">8</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ELN" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ELN')">Elan ADS (ELN) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">24,725,209</td> + <td class="pnum">15.59</td> + <td class="pnum">0.08</td> + <td class="pnum" style="border-right:0px">0.52</td> + </tr> + <tr> + <td class="num">9</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=JPM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'JPM')">JPMorgan Chase (JPM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">22,402,756</td> + <td class="pnum">52.24</td> + <td class="pnum">0.35</td> + <td class="pnum" style="border-right:0px">0.67</td> + </tr> + <tr> + <td class="num">10</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=RF" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RF')">Regions Financial (RF) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">20,790,532</td> + <td class="pnum">9.30</td> + <td class="pnum">0.12</td> + <td class="pnum" style="border-right:0px">1.31</td> + </tr> + <tr> + <td class="num">11</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=VMEM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'VMEM')">Violin Memory (VMEM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">20,669,846</td> + <td class="nnum">7.02</td> + <td class="nnum">-1.98</td> + <td class="nnum" style="border-right:0px">-22.00</td> + </tr> + <tr> + <td class="num">12</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=C" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'C')">Citigroup (C) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">19,979,932</td> + <td class="nnum">48.89</td> + <td class="nnum">-0.04</td> + <td class="nnum" style="border-right:0px">-0.08</td> + </tr> + <tr> + <td class="num">13</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=NOK" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NOK')">Nokia ADS (NOK) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">19,585,075</td> + <td class="pnum">6.66</td> + <td class="pnum">0.02</td> + <td class="pnum" style="border-right:0px">0.30</td> + </tr> + <tr> + <td class="num">14</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=WFC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'WFC')">Wells Fargo (WFC) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">19,478,590</td> + <td class="nnum">41.59</td> + <td class="nnum">-0.02</td> + <td class="nnum" style="border-right:0px">-0.05</td> + </tr> + <tr> + <td class="num">15</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=VALE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'VALE')">Vale ADS (VALE) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">18,781,987</td> + <td class="nnum">15.60</td> + <td class="nnum">-0.52</td> + <td class="nnum" style="border-right:0px">-3.23</td> + </tr> + <tr> + <td class="num">16</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=DAL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'DAL')">Delta Air Lines (DAL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">16,013,956</td> + <td class="nnum">23.57</td> + <td class="nnum">-0.44</td> + <td class="nnum" style="border-right:0px">-1.83</td> + </tr> + <tr> + <td class="num">17</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=EMC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'EMC')">EMC (EMC) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">15,771,252</td> + <td class="nnum">26.07</td> + <td class="nnum">-0.11</td> + <td class="nnum" style="border-right:0px">-0.42</td> + </tr> + <tr> + <td class="num">18</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=NKE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NKE')">Nike Cl B (NKE) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">15,514,717</td> + <td class="pnum">73.64</td> + <td class="pnum">3.30</td> + <td class="pnum" style="border-right:0px">4.69</td> + </tr> + <tr> + <td class="num">19</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=AA" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AA')">Alcoa (AA) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">14,061,073</td> + <td class="nnum">8.20</td> + <td class="nnum">-0.07</td> + <td class="nnum" style="border-right:0px">-0.85</td> + </tr> + <tr> + <td class="num">20</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=GM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GM')">General Motors (GM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">13,984,004</td> + <td class="nnum">36.37</td> + <td class="nnum">-0.58</td> + <td class="nnum" style="border-right:0px">-1.57</td> + </tr> + <tr> + <td class="num">21</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ORCL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ORCL')">Oracle (ORCL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">13,856,671</td> + <td class="nnum">33.78</td> + <td class="nnum">-0.03</td> + <td class="nnum" style="border-right:0px">-0.09</td> + </tr> + <tr> + <td class="num">22</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=T" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'T')">AT&amp;T (T) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">13,736,948</td> + <td class="nnum">33.98</td> + <td class="nnum">-0.25</td> + <td class="nnum" style="border-right:0px">-0.73</td> + </tr> + <tr> + <td class="num">23</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=TSL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TSL')">Trina Solar ADS (TSL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">13,284,202</td> + <td class="pnum">14.83</td> + <td class="pnum">1.99</td> + <td class="pnum" style="border-right:0px">15.50</td> + </tr> + <tr> + <td class="num">24</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=YGE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'YGE')">Yingli Green Energy Holding ADS (YGE) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">12,978,378</td> + <td class="pnum">6.73</td> + <td class="pnum">0.63</td> + <td class="pnum" style="border-right:0px">10.33</td> + </tr> + <tr> + <td class="num">25</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=PBR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PBR')">Petroleo Brasileiro ADS (PBR) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">12,833,660</td> + <td class="nnum">15.40</td> + <td class="nnum">-0.21</td> + <td class="nnum" style="border-right:0px">-1.35</td> + </tr> + <tr> + <td class="num">26</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=UAL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'UAL')">United Continental Holdings (UAL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">12,603,225</td> + <td class="nnum">30.91</td> + <td class="nnum">-3.16</td> + <td class="nnum" style="border-right:0px">-9.28</td> + </tr> + <tr> + <td class="num">27</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=KO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KO')">Coca-Cola (KO) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">12,343,452</td> + <td class="nnum">38.40</td> + <td class="nnum">-0.34</td> + <td class="nnum" style="border-right:0px">-0.88</td> + </tr> + <tr> + <td class="num">28</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ACI" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ACI')">Arch Coal (ACI) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">12,261,138</td> + <td class="nnum">4.25</td> + <td class="nnum">-0.28</td> + <td class="nnum" style="border-right:0px">-6.18</td> + </tr> + <tr> + <td class="num">29</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MS')">Morgan Stanley (MS) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,956,345</td> + <td class="nnum">27.08</td> + <td class="nnum">-0.07</td> + <td class="nnum" style="border-right:0px">-0.26</td> + </tr> + <tr> + <td class="num">30</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=P" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'P')">Pandora Media (P) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,829,963</td> + <td class="pnum">25.52</td> + <td class="pnum">0.13</td> + <td class="pnum" style="border-right:0px">0.51</td> + </tr> + <tr> + <td class="num">31</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ABX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ABX')">Barrick Gold (ABX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,775,585</td> + <td class="num">18.53</td> + <td class="num">0.00</td> + <td class="num" style="border-right:0px">0.00</td> + </tr> + <tr> + <td class="num">32</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ABT" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ABT')">Abbott Laboratories (ABT) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,755,718</td> + <td class="nnum">33.14</td> + <td class="nnum">-0.52</td> + <td class="nnum" style="border-right:0px">-1.54</td> + </tr> + <tr> + <td class="num">33</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=BSBR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BSBR')">Banco Santander Brasil ADS (BSBR) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,587,310</td> + <td class="pnum">7.01</td> + <td class="pnum">0.46</td> + <td class="pnum" style="border-right:0px">7.02</td> + </tr> + <tr> + <td class="num">34</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=AMD" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AMD')">Advanced Micro Devices (AMD) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,337,609</td> + <td class="nnum">3.86</td> + <td class="nnum">-0.03</td> + <td class="nnum" style="border-right:0px">-0.77</td> + </tr> + <tr> + <td class="num">35</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=NLY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NLY')">Annaly Capital Management (NLY) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">11,004,440</td> + <td class="nnum">11.63</td> + <td class="nnum">-0.07</td> + <td class="nnum" style="border-right:0px">-0.60</td> + </tr> + <tr> + <td class="num">36</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ANR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ANR')">Alpha Natural Resources (ANR) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,941,074</td> + <td class="nnum">6.08</td> + <td class="nnum">-0.19</td> + <td class="nnum" style="border-right:0px">-3.03</td> + </tr> + <tr> + <td class="num">37</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=XOM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'XOM')">Exxon Mobil (XOM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,668,115</td> + <td class="nnum">86.90</td> + <td class="nnum">-0.17</td> + <td class="nnum" style="border-right:0px">-0.20</td> + </tr> + <tr> + <td class="num">38</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ITUB" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ITUB')">Itau Unibanco Holding ADS (ITUB) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,638,803</td> + <td class="pnum">14.30</td> + <td class="pnum">0.23</td> + <td class="pnum" style="border-right:0px">1.63</td> + </tr> + <tr> + <td class="num">39</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MRK" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MRK')">Merck&amp;Co (MRK) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,388,152</td> + <td class="pnum">47.79</td> + <td class="pnum">0.11</td> + <td class="pnum" style="border-right:0px">0.23</td> + </tr> + <tr> + <td class="num">40</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ALU" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ALU')">Alcatel-Lucent ADS (ALU) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,181,833</td> + <td class="pnum">3.65</td> + <td class="pnum">0.01</td> + <td class="pnum" style="border-right:0px">0.27</td> + </tr> + <tr> + <td class="num">41</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=VZ" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'VZ')">Verizon Communications (VZ) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,139,321</td> + <td class="nnum">47.00</td> + <td class="nnum">-0.67</td> + <td class="nnum" style="border-right:0px">-1.41</td> + </tr> + <tr> + <td class="num">42</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MHR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MHR')">Magnum Hunter Resources (MHR) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">10,004,303</td> + <td class="pnum">6.33</td> + <td class="pnum">0.46</td> + <td class="pnum" style="border-right:0px">7.84</td> + </tr> + <tr> + <td class="num">43</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=HPQ" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HPQ')">Hewlett-Packard (HPQ) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,948,935</td> + <td class="nnum">21.17</td> + <td class="nnum">-0.13</td> + <td class="nnum" style="border-right:0px">-0.61</td> + </tr> + <tr> + <td class="num">44</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=PHM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PHM')">PulteGroup (PHM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,899,141</td> + <td class="nnum">16.57</td> + <td class="nnum">-0.41</td> + <td class="nnum" style="border-right:0px">-2.41</td> + </tr> + <tr> + <td class="num">45</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=SOL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SOL')">ReneSola ADS (SOL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,667,438</td> + <td class="pnum">4.84</td> + <td class="pnum">0.39</td> + <td class="pnum" style="border-right:0px">8.76</td> + </tr> + <tr> + <td class="num">46</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=GLW" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GLW')">Corning (GLW) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,547,265</td> + <td class="nnum">14.73</td> + <td class="nnum">-0.21</td> + <td class="nnum" style="border-right:0px">-1.41</td> + </tr> + <tr> + <td class="num">47</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=COLE" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'COLE')">Cole Real Estate Investments (COLE) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,544,021</td> + <td class="pnum">12.21</td> + <td class="pnum">0.01</td> + <td class="pnum" style="border-right:0px">0.08</td> + </tr> + <tr> + <td class="num">48</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=DOW" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'DOW')">Dow Chemical (DOW) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,150,479</td> + <td class="nnum">39.02</td> + <td class="nnum">-0.97</td> + <td class="nnum" style="border-right:0px">-2.43</td> + </tr> + <tr> + <td class="num">49</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=IGT" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'IGT')">International Game Technology (IGT) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">9,129,123</td> + <td class="nnum">19.23</td> + <td class="nnum">-1.44</td> + <td class="nnum" style="border-right:0px">-6.97</td> + </tr> + <tr> + <td class="num">50</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ACN" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ACN')">Accenture Cl A (ACN) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,773,260</td> + <td class="nnum">74.09</td> + <td class="nnum">-1.78</td> + <td class="nnum" style="border-right:0px">-2.35</td> + </tr> + <tr> + <td class="num">51</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=KEY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KEY')">KeyCorp (KEY) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,599,333</td> + <td class="pnum">11.36</td> + <td class="pnum">0.02</td> + <td class="pnum" style="border-right:0px">0.18</td> + </tr> + <tr> + <td class="num">52</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=BMY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BMY')">Bristol-Myers Squibb (BMY) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,440,709</td> + <td class="nnum">46.20</td> + <td class="nnum">-0.73</td> + <td class="nnum" style="border-right:0px">-1.56</td> + </tr> + <tr> + <td class="num">53</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=SID" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SID')">Companhia Siderurgica Nacional ADS (SID) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,437,636</td> + <td class="nnum">4.36</td> + <td class="nnum">-0.05</td> + <td class="nnum" style="border-right:0px">-1.13</td> + </tr> + <tr> + <td class="num">54</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=HRB" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HRB')">H&amp;R Block (HRB) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,240,984</td> + <td class="pnum">26.36</td> + <td class="pnum">0.31</td> + <td class="pnum" style="border-right:0px">1.19</td> + </tr> + <tr> + <td class="num">55</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MTG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MTG')">MGIC Investment (MTG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,135,037</td> + <td class="nnum">7.26</td> + <td class="nnum">-0.10</td> + <td class="nnum" style="border-right:0px">-1.36</td> + </tr> + <tr> + <td class="num">56</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=RNG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RNG')">RingCentral Cl A (RNG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,117,469</td> + <td class="pnum">18.20</td> + <td class="pnum">5.20</td> + <td class="pnum" style="border-right:0px">40.00</td> + </tr> + <tr> + <td class="num">57</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=X" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'X')">United States Steel (X) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,107,899</td> + <td class="nnum">20.44</td> + <td class="nnum">-0.66</td> + <td class="nnum" style="border-right:0px">-3.13</td> + </tr> + <tr> + <td class="num">58</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=CLF" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CLF')">Cliffs Natural Resources (CLF) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,041,572</td> + <td class="nnum">21.00</td> + <td class="nnum">-0.83</td> + <td class="nnum" style="border-right:0px">-3.80</td> + </tr> + <tr> + <td class="num">59</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=NEM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NEM')">Newmont Mining (NEM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">8,014,250</td> + <td class="nnum">27.98</td> + <td class="nnum">-0.19</td> + <td class="nnum" style="border-right:0px">-0.67</td> + </tr> + <tr> + <td class="num">60</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MO')">Altria Group (MO) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,786,048</td> + <td class="nnum">34.71</td> + <td class="nnum">-0.29</td> + <td class="nnum" style="border-right:0px">-0.83</td> + </tr> + <tr> + <td class="num">61</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=SD" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SD')">SandRidge Energy (SD) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,782,745</td> + <td class="nnum">5.93</td> + <td class="nnum">-0.06</td> + <td class="nnum" style="border-right:0px">-1.00</td> + </tr> + <tr> + <td class="num">62</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MCP" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MCP')">Molycorp (MCP) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,735,831</td> + <td class="nnum">6.73</td> + <td class="nnum">-0.45</td> + <td class="nnum" style="border-right:0px">-6.27</td> + </tr> + <tr> + <td class="num">63</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=HAL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'HAL')">Halliburton (HAL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,728,735</td> + <td class="nnum">48.39</td> + <td class="nnum">-0.32</td> + <td class="nnum" style="border-right:0px">-0.66</td> + </tr> + <tr> + <td class="num">64</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=TSM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TSM')">Taiwan Semiconductor Manufacturing ADS (TSM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,661,397</td> + <td class="nnum">17.07</td> + <td class="nnum">-0.25</td> + <td class="nnum" style="border-right:0px">-1.44</td> + </tr> + <tr> + <td class="num">65</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=FCX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'FCX')">Freeport-McMoRan Copper&amp;Gold (FCX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,622,803</td> + <td class="nnum">33.42</td> + <td class="nnum">-0.45</td> + <td class="nnum" style="border-right:0px">-1.33</td> + </tr> + <tr> + <td class="num">66</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=KOG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KOG')">Kodiak Oil&amp;Gas (KOG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,543,806</td> + <td class="pnum">11.94</td> + <td class="pnum">0.16</td> + <td class="pnum" style="border-right:0px">1.36</td> + </tr> + <tr> + <td class="num">67</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=XRX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'XRX')">Xerox (XRX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,440,689</td> + <td class="nnum">10.37</td> + <td class="nnum">-0.01</td> + <td class="nnum" style="border-right:0px">-0.10</td> + </tr> + <tr> + <td class="num">68</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=S" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'S')">Sprint (S) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,291,351</td> + <td class="nnum">6.16</td> + <td class="nnum">-0.14</td> + <td class="nnum" style="border-right:0px">-2.22</td> + </tr> + <tr> + <td class="num">69</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=TWO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TWO')">Two Harbors Investment (TWO) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,153,803</td> + <td class="pnum">9.79</td> + <td class="pnum">0.05</td> + <td class="pnum" style="border-right:0px">0.51</td> + </tr> + <tr> + <td class="num">70</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=WLT" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'WLT')">Walter Energy (WLT) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,152,192</td> + <td class="nnum">14.19</td> + <td class="nnum">-0.36</td> + <td class="nnum" style="border-right:0px">-2.47</td> + </tr> + <tr> + <td class="num">71</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=IP" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'IP')">International Paper (IP) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,123,722</td> + <td class="nnum">45.44</td> + <td class="nnum">-1.85</td> + <td class="nnum" style="border-right:0px">-3.91</td> + </tr> + <tr> + <td class="num">72</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=PPL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PPL')">PPL (PPL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">7,026,292</td> + <td class="nnum">30.34</td> + <td class="nnum">-0.13</td> + <td class="nnum" style="border-right:0px">-0.43</td> + </tr> + <tr> + <td class="num">73</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=GG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'GG')">Goldcorp (GG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,857,447</td> + <td class="pnum">25.76</td> + <td class="pnum">0.08</td> + <td class="pnum" style="border-right:0px">0.31</td> + </tr> + <tr> + <td class="num">74</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=TWX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'TWX')">Time Warner (TWX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,807,237</td> + <td class="pnum">66.20</td> + <td class="pnum">1.33</td> + <td class="pnum" style="border-right:0px">2.05</td> + </tr> + <tr> + <td class="num">75</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=SNV" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SNV')">Synovus Financial (SNV) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,764,805</td> + <td class="pnum">3.29</td> + <td class="pnum">0.02</td> + <td class="pnum" style="border-right:0px">0.61</td> + </tr> + <tr> + <td class="num">76</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=AKS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AKS')">AK Steel Holding (AKS) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,662,599</td> + <td class="nnum">3.83</td> + <td class="nnum">-0.11</td> + <td class="nnum" style="border-right:0px">-2.79</td> + </tr> + <tr> + <td class="num">77</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=BSX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'BSX')">Boston Scientific (BSX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,629,084</td> + <td class="nnum">11.52</td> + <td class="nnum">-0.15</td> + <td class="nnum" style="border-right:0px">-1.29</td> + </tr> + <tr> + <td class="num">78</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=EGO" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'EGO')">Eldorado Gold (EGO) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,596,902</td> + <td class="nnum">6.65</td> + <td class="nnum">-0.03</td> + <td class="nnum" style="border-right:0px">-0.45</td> + </tr> + <tr> + <td class="num">79</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=NR" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'NR')">Newpark Resources (NR) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,552,453</td> + <td class="pnum">12.56</td> + <td class="pnum">0.09</td> + <td class="pnum" style="border-right:0px">0.72</td> + </tr> + <tr> + <td class="num">80</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=ABBV" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'ABBV')">AbbVie (ABBV) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,525,524</td> + <td class="nnum">44.33</td> + <td class="nnum">-0.67</td> + <td class="nnum" style="border-right:0px">-1.49</td> + </tr> + <tr> + <td class="num">81</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MBI" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MBI')">MBIA (MBI) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,416,587</td> + <td class="nnum">10.38</td> + <td class="nnum">-0.43</td> + <td class="nnum" style="border-right:0px">-3.98</td> + </tr> + <tr> + <td class="num">82</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=SAI" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SAI')">SAIC (SAI) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,404,587</td> + <td class="pnum">16.03</td> + <td class="pnum">0.13</td> + <td class="pnum" style="border-right:0px">0.82</td> + </tr> + <tr> + <td class="num">83</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=PG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'PG')">Procter&amp;Gamble (PG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,389,143</td> + <td class="nnum">77.21</td> + <td class="nnum">-0.84</td> + <td class="nnum" style="border-right:0px">-1.08</td> + </tr> + <tr> + <td class="num">84</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=IAG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'IAG')">IAMGOLD (IAG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,293,001</td> + <td class="nnum">4.77</td> + <td class="nnum">-0.06</td> + <td class="nnum" style="border-right:0px">-1.24</td> + </tr> + <tr> + <td class="num">85</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=SWY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'SWY')">Safeway (SWY) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,268,184</td> + <td class="nnum">32.25</td> + <td class="nnum">-0.29</td> + <td class="nnum" style="border-right:0px">-0.89</td> + </tr> + <tr> + <td class="num">86</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=KGC" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'KGC')">Kinross Gold (KGC) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">6,112,658</td> + <td class="nnum">4.99</td> + <td class="nnum">-0.03</td> + <td class="nnum" style="border-right:0px">-0.60</td> + </tr> + <tr> + <td class="num">87</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MGM" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MGM')">MGM Resorts International (MGM) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,986,143</td> + <td class="nnum">20.22</td> + <td class="nnum">-0.05</td> + <td class="nnum" style="border-right:0px">-0.25</td> + </tr> + <tr> + <td class="num">88</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=CX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CX')">Cemex ADS (CX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,907,040</td> + <td class="nnum">11.27</td> + <td class="nnum">-0.06</td> + <td class="nnum" style="border-right:0px">-0.53</td> + </tr> + <tr> + <td class="num">89</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=AIG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AIG')">American International Group (AIG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,900,133</td> + <td class="nnum">49.15</td> + <td class="nnum">-0.30</td> + <td class="nnum" style="border-right:0px">-0.61</td> + </tr> + <tr> + <td class="num">90</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=CHK" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CHK')">Chesapeake Energy (CHK) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,848,016</td> + <td class="nnum">26.21</td> + <td class="nnum">-0.20</td> + <td class="nnum" style="border-right:0px">-0.76</td> + </tr> + <tr> + <td class="num">91</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=RSH" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'RSH')">RadioShack (RSH) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,837,833</td> + <td class="nnum">3.44</td> + <td class="nnum">-0.43</td> + <td class="nnum" style="border-right:0px">-11.11</td> + </tr> + <tr> + <td class="num">92</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=USB" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'USB')">U.S. Bancorp (USB) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,814,373</td> + <td class="nnum">36.50</td> + <td class="nnum">-0.04</td> + <td class="nnum" style="border-right:0px">-0.11</td> + </tr> + <tr> + <td class="num">93</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=LLY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'LLY')">Eli Lilly (LLY) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,776,991</td> + <td class="nnum">50.50</td> + <td class="nnum">-0.54</td> + <td class="nnum" style="border-right:0px">-1.06</td> + </tr> + <tr> + <td class="num">94</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MET" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MET')">MetLife (MET) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,774,996</td> + <td class="nnum">47.21</td> + <td class="nnum">-0.37</td> + <td class="nnum" style="border-right:0px">-0.78</td> + </tr> + <tr> + <td class="num">95</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=AUY" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'AUY')">Yamana Gold (AUY) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,742,426</td> + <td class="pnum">10.37</td> + <td class="pnum">0.03</td> + <td class="pnum" style="border-right:0px">0.29</td> + </tr> + <tr> + <td class="num">96</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=CBS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CBS')">CBS Cl B (CBS) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,718,858</td> + <td class="nnum">55.50</td> + <td class="nnum">-0.06</td> + <td class="nnum" style="border-right:0px">-0.11</td> + </tr> + <tr> + <td class="num">97</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=CSX" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CSX')">CSX (CSX) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,710,066</td> + <td class="nnum">25.85</td> + <td class="nnum">-0.13</td> + <td class="nnum" style="border-right:0px">-0.50</td> + </tr> + <tr> + <td class="num">98</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=CCL" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'CCL')">Carnival (CCL) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,661,325</td> + <td class="nnum">32.88</td> + <td class="nnum">-0.05</td> + <td class="nnum" style="border-right:0px">-0.15</td> + </tr> + <tr> + <td class="num">99</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=MOS" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'MOS')">Mosaic (MOS) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,595,592</td> + <td class="nnum">43.43</td> + <td class="nnum">-0.76</td> + <td class="nnum" style="border-right:0px">-1.72</td> + </tr> + <tr> + <td class="num">100</td> + <td class="text" style="max-width:307px"> + <a class="linkb" href="/public/quotes/main.html?symbol=WAG" onmouseout="com.dowjones.rolloverQuotes.hidelater();" onmouseover="com.dowjones.rolloverQuotes.show(this,'WAG')">Walgreen (WAG) + </a> + </td> + <td align="right" class="num" style="font-weight:bold;">5,568,310</td> + <td class="nnum">54.51</td> + <td class="nnum">-0.22</td> + <td class="nnum" style="border-right:0px">-0.40</td> + </tr> +</tbody></table> +<table bgcolor="" border="0" cellpadding="0" cellspacing="0" width="100%"> + <tbody><tr><td height="20px"><img alt="" border="0" height="20px" src="/img/b.gif" width="1"/></td></tr> +</tbody></table> +<table align="center" bgcolor="#ffffff" border="0" cellpadding="0" cellspacing="0" style="border:1px solid #cfc7b7;margin-bottom:5px;" width="575px"> + <tbody><tr> + <td bgcolor="#e9e7e0" class="b12" colspan="3" style="padding:3px 0px 3px 0px;"><span class="p10" style="color:#000; float:right">An Advertising Feature  </span>  PARTNER CENTER</td> + </tr> + + <tr> + <td align="center" class="p10" style="padding:10px 0px 5px 0px;border-right:1px solid #cfc7b7;" valign="top"> + + + + <script type="text/javascript"> +<!-- + var tempHTML = ''; + var adURL = 'http://ad.doubleclick.net/adi/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=1;sz=170x67;ord=26093260932609326093;'; + if ( isSafari ) { + tempHTML += '<iframe id="mdc_tradingcenter1" src="'+adURL+'" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170">'; + } else { + tempHTML += '<iframe id="mdc_tradingcenter1" src="/static_html_files/blank.htm" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170px;">'; + ListOfIframes.mdc_tradingcenter1= adURL; + } + tempHTML += '<a href="http://ad.doubleclick.net/jump/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=1;sz=170x67;ord=26093260932609326093;" target="_new">'; + tempHTML += '<img src="http://ad.doubleclick.net/ad/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=1;sz=170x67;ord=26093260932609326093;" border="0" width="170" height="67" vspace="0" alt="Advertisement" /></a><br /></iframe>'; + document.write(tempHTML); + // --> + </script> + </td> + + <td align="center" class="p10" style="padding:10px 0px 5px 0px;border-right:1px solid #cfc7b7;" valign="top"> + + + + <script type="text/javascript"> +<!-- + var tempHTML = ''; + var adURL = 'http://ad.doubleclick.net/adi/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=2;sz=170x67;ord=26093260932609326093;'; + if ( isSafari ) { + tempHTML += '<iframe id="mdc_tradingcenter2" src="'+adURL+'" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170">'; + } else { + tempHTML += '<iframe id="mdc_tradingcenter2" src="/static_html_files/blank.htm" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170px;">'; + ListOfIframes.mdc_tradingcenter2= adURL; + } + tempHTML += '<a href="http://ad.doubleclick.net/jump/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=2;sz=170x67;ord=26093260932609326093;" target="_new">'; + tempHTML += '<img src="http://ad.doubleclick.net/ad/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=2;sz=170x67;ord=26093260932609326093;" border="0" width="170" height="67" vspace="0" alt="Advertisement" /></a><br /></iframe>'; + document.write(tempHTML); + // --> + </script> + </td> + + <td align="center" class="p10" style="padding:10px 0px 5px 0px;" valign="top"> + + + + <script type="text/javascript"> +<!-- + var tempHTML = ''; + var adURL = 'http://ad.doubleclick.net/adi/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=3;sz=170x67;ord=26093260932609326093;'; + if ( isSafari ) { + tempHTML += '<iframe id="mdc_tradingcenter3" src="'+adURL+'" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170">'; + } else { + tempHTML += '<iframe id="mdc_tradingcenter3" src="/static_html_files/blank.htm" width="170" height="67" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000" style="width:170px;">'; + ListOfIframes.mdc_tradingcenter3= adURL; + } + tempHTML += '<a href="http://ad.doubleclick.net/jump/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=3;sz=170x67;ord=26093260932609326093;" target="_new">'; + tempHTML += '<img src="http://ad.doubleclick.net/ad/'+((GetCookie('etsFlag'))?'ets.wsj.com':'brokerbuttons.wsj.com')+'/markets_front;!category=;msrc=' + msrc + ';' + segQS + ';' + mc + ';tile=3;sz=170x67;ord=26093260932609326093;" border="0" width="170" height="67" vspace="0" alt="Advertisement" /></a><br /></iframe>'; + document.write(tempHTML); + // --> + </script> + </td> + + </tr> + +</tbody></table> +<table bgcolor="" border="0" cellpadding="0" cellspacing="0" width="100%"> + <tbody><tr><td height="20px"><img alt="" border="0" height="20px" src="/img/b.gif" width="1"/></td></tr> +</tbody></table> diff --git a/pandas/io/tests/data/valid_markup.html b/pandas/io/tests/data/valid_markup.html index 5db90da3baec4..0130e9ed9d5f3 100644 --- a/pandas/io/tests/data/valid_markup.html +++ b/pandas/io/tests/data/valid_markup.html @@ -35,35 +35,26 @@ <td>7</td> <td>0</td> </tr> - <tr> - <th>4</th> - <td>4</td> - <td>3</td> - </tr> - <tr> - <th>5</th> - <td>5</td> - <td>4</td> - </tr> - <tr> - <th>6</th> - <td>4</td> - <td>5</td> - </tr> - <tr> - <th>7</th> - <td>1</td> - <td>4</td> + </tbody> + </table> + <table border="1" class="dataframe"> + <thead> + <tr style="text-align: right;"> + <th></th> + <th>a</th> + <th>b</th> </tr> + </thead> + <tbody> <tr> - <th>8</th> + <th>0</th> <td>6</td> <td>7</td> </tr> <tr> - <th>9</th> - <td>8</td> - <td>5</td> + <th>1</th> + <td>4</td> + <td>0</td> </tr> </tbody> </table> diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py index 44e4b5cfda7b6..9b0fb1cacfb65 100644 --- a/pandas/io/tests/test_html.py +++ b/pandas/io/tests/test_html.py @@ -1,33 +1,31 @@ from __future__ import print_function + import os import re -from unittest import TestCase import warnings +import unittest + +try: + from importlib import import_module +except ImportError: + import_module = __import__ + from distutils.version import LooseVersion -from pandas.io.common import URLError import nose -from nose.tools import assert_raises import numpy as np from numpy.random import rand from numpy.testing.decorators import slow -from pandas.compat import map, zip, StringIO -import pandas.compat as compat - -try: - from importlib import import_module -except ImportError: - import_module = __import__ +from pandas import (DataFrame, MultiIndex, read_csv, Timestamp, Index, + date_range, Series) +from pandas.compat import map, zip, StringIO, string_types +from pandas.io.common import URLError, urlopen from pandas.io.html import read_html -from pandas.io.common import urlopen - -from pandas import DataFrame, MultiIndex, read_csv, Timestamp -from pandas.util.testing import (assert_frame_equal, network, - get_data_path) -from pandas.util.testing import makeCustomDataframe as mkdf +import pandas.util.testing as tm +from pandas.util.testing import makeCustomDataframe as mkdf, network def _have_module(module_name): @@ -40,11 +38,11 @@ def _have_module(module_name): def _skip_if_no(module_name): if not _have_module(module_name): - raise nose.SkipTest("{0} not found".format(module_name)) + raise nose.SkipTest("{0!r} not found".format(module_name)) def _skip_if_none_of(module_names): - if isinstance(module_names, compat.string_types): + if isinstance(module_names, string_types): _skip_if_no(module_names) if module_names == 'bs4': import bs4 @@ -54,17 +52,14 @@ def _skip_if_none_of(module_names): not_found = [module_name for module_name in module_names if not _have_module(module_name)] if set(not_found) & set(module_names): - raise nose.SkipTest("{0} not found".format(not_found)) + raise nose.SkipTest("{0!r} not found".format(not_found)) if 'bs4' in module_names: import bs4 if bs4.__version__ == LooseVersion('4.2.0'): raise nose.SkipTest("Bad version of bs4: 4.2.0") -DATA_PATH = get_data_path() - -def isframe(x): - return isinstance(x, DataFrame) +DATA_PATH = tm.get_data_path() def assert_framelist_equal(list1, list2, *args, **kwargs): @@ -72,10 +67,12 @@ def assert_framelist_equal(list1, list2, *args, **kwargs): 'len(list1) == {0}, ' 'len(list2) == {1}'.format(len(list1), len(list2))) - assert all(map(lambda x, y: isframe(x) and isframe(y), list1, list2)), \ - 'not all list elements are DataFrames' + msg = 'not all list elements are DataFrames' + both_frames = all(map(lambda x, y: isinstance(x, DataFrame) and + isinstance(y, DataFrame), list1, list2)) + assert both_frames, msg for frame_i, frame_j in zip(list1, list2): - assert_frame_equal(frame_i, frame_j, *args, **kwargs) + tm.assert_frame_equal(frame_i, frame_j, *args, **kwargs) assert not frame_i.empty, 'frames are both empty' @@ -83,13 +80,13 @@ def test_bs4_version_fails(): _skip_if_none_of(('bs4', 'html5lib')) import bs4 if bs4.__version__ == LooseVersion('4.2.0'): - assert_raises(AssertionError, read_html, os.path.join(DATA_PATH, - "spam.html"), - flavor='bs4') + tm.assert_raises(AssertionError, read_html, os.path.join(DATA_PATH, + "spam.html"), + flavor='bs4') -class TestReadHtmlBase(TestCase): - def run_read_html(self, *args, **kwargs): +class TestReadHtml(unittest.TestCase): + def read_html(self, *args, **kwargs): kwargs['flavor'] = kwargs.get('flavor', self.flavor) return read_html(*args, **kwargs) @@ -112,18 +109,16 @@ def test_to_html_compat(self): df = mkdf(4, 3, data_gen_f=lambda *args: rand(), c_idx_names=False, r_idx_names=False).applymap('{0:.3f}'.format).astype(float) out = df.to_html() - res = self.run_read_html(out, attrs={'class': 'dataframe'}, + res = self.read_html(out, attrs={'class': 'dataframe'}, index_col=0)[0] - print(df.dtypes) - print(res.dtypes) - assert_frame_equal(res, df) + tm.assert_frame_equal(res, df) @network def test_banklist_url(self): url = 'http://www.fdic.gov/bank/individual/failed/banklist.html' - df1 = self.run_read_html(url, 'First Federal Bank of Florida', + df1 = self.read_html(url, 'First Federal Bank of Florida', attrs={"id": 'table'}) - df2 = self.run_read_html(url, 'Metcalf Bank', attrs={'id': 'table'}) + df2 = self.read_html(url, 'Metcalf Bank', attrs={'id': 'table'}) assert_framelist_equal(df1, df2) @@ -131,133 +126,148 @@ def test_banklist_url(self): def test_spam_url(self): url = ('http://ndb.nal.usda.gov/ndb/foods/show/1732?fg=&man=&' 'lfacet=&format=&count=&max=25&offset=&sort=&qlookup=spam') - df1 = self.run_read_html(url, '.*Water.*') - df2 = self.run_read_html(url, 'Unit') + df1 = self.read_html(url, '.*Water.*') + df2 = self.read_html(url, 'Unit') assert_framelist_equal(df1, df2) @slow def test_banklist(self): - df1 = self.run_read_html(self.banklist_data, '.*Florida.*', + df1 = self.read_html(self.banklist_data, '.*Florida.*', attrs={'id': 'table'}) - df2 = self.run_read_html(self.banklist_data, 'Metcalf Bank', + df2 = self.read_html(self.banklist_data, 'Metcalf Bank', attrs={'id': 'table'}) assert_framelist_equal(df1, df2) - def test_spam(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', - infer_types=False) - df2 = self.run_read_html(self.spam_data, 'Unit', infer_types=False) + def test_spam_no_types(self): + with tm.assert_produces_warning(FutureWarning): + df1 = self.read_html(self.spam_data, '.*Water.*', + infer_types=False) + with tm.assert_produces_warning(FutureWarning): + df2 = self.read_html(self.spam_data, 'Unit', infer_types=False) assert_framelist_equal(df1, df2) - print(df1[0]) + + self.assertEqual(df1[0].ix[0, 0], 'Proximates') + self.assertEqual(df1[0].columns[0], 'Nutrient') + + def test_spam_with_types(self): + df1 = self.read_html(self.spam_data, '.*Water.*') + df2 = self.read_html(self.spam_data, 'Unit') + assert_framelist_equal(df1, df2) self.assertEqual(df1[0].ix[0, 0], 'Proximates') self.assertEqual(df1[0].columns[0], 'Nutrient') def test_spam_no_match(self): - dfs = self.run_read_html(self.spam_data) + dfs = self.read_html(self.spam_data) for df in dfs: - self.assert_(isinstance(df, DataFrame)) + tm.assert_isinstance(df, DataFrame) def test_banklist_no_match(self): - dfs = self.run_read_html(self.banklist_data, attrs={'id': 'table'}) + dfs = self.read_html(self.banklist_data, attrs={'id': 'table'}) for df in dfs: - self.assert_(isinstance(df, DataFrame)) + tm.assert_isinstance(df, DataFrame) def test_spam_header(self): - df = self.run_read_html(self.spam_data, '.*Water.*', header=0) - df = self.run_read_html(self.spam_data, '.*Water.*', header=1)[0] - self.assertEqual(df.columns[0], 'Water') + df = self.read_html(self.spam_data, '.*Water.*', header=1)[0] + self.assertEqual(df.columns[0], 'Proximates') self.assertFalse(df.empty) def test_skiprows_int(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', skiprows=1) - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=1) + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=1) + df2 = self.read_html(self.spam_data, 'Unit', skiprows=1) assert_framelist_equal(df1, df2) def test_skiprows_xrange(self): - df1 = [self.run_read_html(self.spam_data, '.*Water.*').pop()[2:]] - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=range(2)) - - assert_framelist_equal(df1, df2) + df1 = self.read_html(self.spam_data, '.*Water.*', + skiprows=range(2))[0] + df2 = self.read_html(self.spam_data, 'Unit', skiprows=range(2))[0] + tm.assert_frame_equal(df1, df2) def test_skiprows_list(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', skiprows=[1, 2]) - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=[2, 1]) + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=[1, 2]) + df2 = self.read_html(self.spam_data, 'Unit', skiprows=[2, 1]) assert_framelist_equal(df1, df2) def test_skiprows_set(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=set([1, 2])) - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=set([2, 1])) + df2 = self.read_html(self.spam_data, 'Unit', skiprows=set([2, 1])) assert_framelist_equal(df1, df2) def test_skiprows_slice(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', skiprows=1) - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=1) + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=1) + df2 = self.read_html(self.spam_data, 'Unit', skiprows=1) assert_framelist_equal(df1, df2) def test_skiprows_slice_short(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=slice(2)) - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=slice(2)) + df2 = self.read_html(self.spam_data, 'Unit', skiprows=slice(2)) assert_framelist_equal(df1, df2) def test_skiprows_slice_long(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=slice(2, 5)) - df2 = self.run_read_html(self.spam_data, 'Unit', + df2 = self.read_html(self.spam_data, 'Unit', skiprows=slice(4, 1, -1)) assert_framelist_equal(df1, df2) def test_skiprows_ndarray(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', + df1 = self.read_html(self.spam_data, '.*Water.*', skiprows=np.arange(2)) - df2 = self.run_read_html(self.spam_data, 'Unit', skiprows=np.arange(2)) + df2 = self.read_html(self.spam_data, 'Unit', skiprows=np.arange(2)) assert_framelist_equal(df1, df2) def test_skiprows_invalid(self): - self.assertRaises(ValueError, self.run_read_html, self.spam_data, - '.*Water.*', skiprows='asdf') + with tm.assertRaisesRegexp(TypeError, + 'is not a valid type for skipping rows'): + self.read_html(self.spam_data, '.*Water.*', skiprows='asdf') def test_index(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', index_col=0) - df2 = self.run_read_html(self.spam_data, 'Unit', index_col=0) + df1 = self.read_html(self.spam_data, '.*Water.*', index_col=0) + df2 = self.read_html(self.spam_data, 'Unit', index_col=0) assert_framelist_equal(df1, df2) def test_header_and_index_no_types(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', header=1, - index_col=0, infer_types=False) - df2 = self.run_read_html(self.spam_data, 'Unit', header=1, index_col=0, - infer_types=False) + with tm.assert_produces_warning(FutureWarning): + df1 = self.read_html(self.spam_data, '.*Water.*', header=1, + index_col=0, infer_types=False) + with tm.assert_produces_warning(FutureWarning): + df2 = self.read_html(self.spam_data, 'Unit', header=1, + index_col=0, infer_types=False) assert_framelist_equal(df1, df2) def test_header_and_index_with_types(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', header=1, + df1 = self.read_html(self.spam_data, '.*Water.*', header=1, index_col=0) - df2 = self.run_read_html(self.spam_data, 'Unit', header=1, index_col=0) + df2 = self.read_html(self.spam_data, 'Unit', header=1, index_col=0) assert_framelist_equal(df1, df2) def test_infer_types(self): - df1 = self.run_read_html(self.spam_data, '.*Water.*', index_col=0, - infer_types=False) - df2 = self.run_read_html(self.spam_data, 'Unit', index_col=0, - infer_types=False) + with tm.assert_produces_warning(FutureWarning): + df1 = self.read_html(self.spam_data, '.*Water.*', index_col=0, + infer_types=False) + with tm.assert_produces_warning(FutureWarning): + df2 = self.read_html(self.spam_data, 'Unit', index_col=0, + infer_types=False) assert_framelist_equal(df1, df2) - df2 = self.run_read_html(self.spam_data, 'Unit', index_col=0, - infer_types=True) + with tm.assert_produces_warning(FutureWarning): + df2 = self.read_html(self.spam_data, 'Unit', index_col=0, + infer_types=True) - self.assertRaises(AssertionError, assert_framelist_equal, df1, df2) + with tm.assertRaises(AssertionError): + assert_framelist_equal(df1, df2) def test_string_io(self): with open(self.spam_data) as f: @@ -266,129 +276,197 @@ def test_string_io(self): with open(self.spam_data) as f: data2 = StringIO(f.read()) - df1 = self.run_read_html(data1, '.*Water.*', infer_types=False) - df2 = self.run_read_html(data2, 'Unit', infer_types=False) + df1 = self.read_html(data1, '.*Water.*') + df2 = self.read_html(data2, 'Unit') assert_framelist_equal(df1, df2) def test_string(self): with open(self.spam_data) as f: data = f.read() - df1 = self.run_read_html(data, '.*Water.*', infer_types=False) - df2 = self.run_read_html(data, 'Unit', infer_types=False) + df1 = self.read_html(data, '.*Water.*') + df2 = self.read_html(data, 'Unit') assert_framelist_equal(df1, df2) def test_file_like(self): with open(self.spam_data) as f: - df1 = self.run_read_html(f, '.*Water.*', infer_types=False) + df1 = self.read_html(f, '.*Water.*') with open(self.spam_data) as f: - df2 = self.run_read_html(f, 'Unit', infer_types=False) + df2 = self.read_html(f, 'Unit') assert_framelist_equal(df1, df2) @network def test_bad_url_protocol(self): - self.assertRaises(URLError, self.run_read_html, - 'git://github.com', '.*Water.*') + with tm.assertRaises(URLError): + self.read_html('git://github.com', match='.*Water.*') @network def test_invalid_url(self): - self.assertRaises(URLError, self.run_read_html, - 'http://www.a23950sdfa908sd.com') + with tm.assertRaises(URLError): + self.read_html('http://www.a23950sdfa908sd.com', match='.*Water.*') @slow def test_file_url(self): url = self.banklist_data - dfs = self.run_read_html('file://' + url, 'First', - attrs={'id': 'table'}) - self.assert_(isinstance(dfs, list)) + dfs = self.read_html('file://' + url, 'First', attrs={'id': 'table'}) + tm.assert_isinstance(dfs, list) for df in dfs: - self.assert_(isinstance(df, DataFrame)) + tm.assert_isinstance(df, DataFrame) @slow def test_invalid_table_attrs(self): url = self.banklist_data - self.assertRaises(AssertionError, self.run_read_html, url, - 'First Federal Bank of Florida', - attrs={'id': 'tasdfable'}) + with tm.assertRaisesRegexp(ValueError, 'No tables found'): + self.read_html(url, 'First Federal Bank of Florida', + attrs={'id': 'tasdfable'}) def _bank_data(self, *args, **kwargs): - return self.run_read_html(self.banklist_data, 'Metcalf', - attrs={'id': 'table'}, *args, **kwargs) + return self.read_html(self.banklist_data, 'Metcalf', + attrs={'id': 'table'}, *args, **kwargs) @slow def test_multiindex_header(self): df = self._bank_data(header=[0, 1])[0] - self.assert_(isinstance(df.columns, MultiIndex)) + tm.assert_isinstance(df.columns, MultiIndex) @slow def test_multiindex_index(self): df = self._bank_data(index_col=[0, 1])[0] - self.assert_(isinstance(df.index, MultiIndex)) + tm.assert_isinstance(df.index, MultiIndex) @slow def test_multiindex_header_index(self): df = self._bank_data(header=[0, 1], index_col=[0, 1])[0] - self.assert_(isinstance(df.columns, MultiIndex)) - self.assert_(isinstance(df.index, MultiIndex)) + tm.assert_isinstance(df.columns, MultiIndex) + tm.assert_isinstance(df.index, MultiIndex) + + @slow + def test_multiindex_header_skiprows_tuples(self): + df = self._bank_data(header=[0, 1], skiprows=1, tupleize_cols=True)[0] + tm.assert_isinstance(df.columns, Index) @slow def test_multiindex_header_skiprows(self): df = self._bank_data(header=[0, 1], skiprows=1)[0] - self.assert_(isinstance(df.columns, MultiIndex)) + tm.assert_isinstance(df.columns, MultiIndex) @slow def test_multiindex_header_index_skiprows(self): df = self._bank_data(header=[0, 1], index_col=[0, 1], skiprows=1)[0] - self.assert_(isinstance(df.index, MultiIndex)) + tm.assert_isinstance(df.index, MultiIndex) + tm.assert_isinstance(df.columns, MultiIndex) @slow def test_regex_idempotency(self): url = self.banklist_data - dfs = self.run_read_html('file://' + url, + dfs = self.read_html('file://' + url, match=re.compile(re.compile('Florida')), attrs={'id': 'table'}) - self.assert_(isinstance(dfs, list)) + tm.assert_isinstance(dfs, list) for df in dfs: - self.assert_(isinstance(df, DataFrame)) - - def test_negative_skiprows_spam(self): - url = self.spam_data - self.assertRaises(AssertionError, self.run_read_html, url, 'Water', - skiprows=-1) + tm.assert_isinstance(df, DataFrame) - def test_negative_skiprows_banklist(self): - url = self.banklist_data - self.assertRaises(AssertionError, self.run_read_html, url, 'Florida', - skiprows=-1) + def test_negative_skiprows(self): + with tm.assertRaisesRegexp(ValueError, + '\(you passed a negative value\)'): + self.read_html(self.spam_data, 'Water', skiprows=-1) @network def test_multiple_matches(self): url = 'http://code.google.com/p/pythonxy/wiki/StandardPlugins' - dfs = self.run_read_html(url, match='Python', + dfs = self.read_html(url, match='Python', attrs={'class': 'wikitable'}) self.assert_(len(dfs) > 1) @network def test_pythonxy_plugins_table(self): url = 'http://code.google.com/p/pythonxy/wiki/StandardPlugins' - dfs = self.run_read_html(url, match='Python', + dfs = self.read_html(url, match='Python', attrs={'class': 'wikitable'}) zz = [df.iloc[0, 0] for df in dfs] self.assertEqual(sorted(zz), sorted(['Python', 'SciTE'])) + @slow + def test_thousands_macau_stats(self): + all_non_nan_table_index = -2 + macau_data = os.path.join(DATA_PATH, 'macau.html') + dfs = self.read_html(macau_data, index_col=0, + attrs={'class': 'style1'}) + df = dfs[all_non_nan_table_index] + + self.assertFalse(any(s.isnull().any() for _, s in df.iteritems())) + + @slow + def test_thousands_macau_index_col(self): + all_non_nan_table_index = -2 + macau_data = os.path.join(DATA_PATH, 'macau.html') + dfs = self.read_html(macau_data, index_col=0, header=0) + df = dfs[all_non_nan_table_index] + + self.assertFalse(any(s.isnull().any() for _, s in df.iteritems())) + + def test_countries_municipalities(self): + # GH5048 + data1 = StringIO('''<table> + <thead> + <tr> + <th>Country</th> + <th>Municipality</th> + <th>Year</th> + </tr> + </thead> + <tbody> + <tr> + <td>Ukraine</td> + <th>Odessa</th> + <td>1944</td> + </tr> + </tbody> + </table>''') + data2 = StringIO(''' + <table> + <tbody> + <tr> + <th>Country</th> + <th>Municipality</th> + <th>Year</th> + </tr> + <tr> + <td>Ukraine</td> + <th>Odessa</th> + <td>1944</td> + </tr> + </tbody> + </table>''') + res1 = self.read_html(data1) + res2 = self.read_html(data2, header=0) + assert_framelist_equal(res1, res2) + + def test_nyse_wsj_commas_table(self): + data = os.path.join(DATA_PATH, 'nyse_wsj.html') + df = self.read_html(data, index_col=0, header=0, + attrs={'class': 'mdcTable'})[0] + + columns = Index(['Issue(Roll over for charts and headlines)', + 'Volume', 'Price', 'Chg', '% Chg']) + nrows = 100 + self.assertEqual(df.shape[0], nrows) + self.assertTrue(df.columns.equals(columns)) + @slow def test_banklist_header(self): from pandas.io.html import _remove_whitespace + def try_remove_ws(x): try: return _remove_whitespace(x) except AttributeError: return x - df = self.run_read_html(self.banklist_data, 'Metcalf', + df = self.read_html(self.banklist_data, 'Metcalf', attrs={'id': 'table'})[0] ground_truth = read_csv(os.path.join(DATA_PATH, 'banklist.csv'), converters={'Updated Date': Timestamp, @@ -412,8 +490,8 @@ def try_remove_ws(x): dfnew = df.applymap(try_remove_ws).replace(old, new) gtnew = ground_truth.applymap(try_remove_ws) converted = dfnew.convert_objects(convert_numeric=True) - assert_frame_equal(converted.convert_objects(convert_dates='coerce'), - gtnew) + tm.assert_frame_equal(converted.convert_objects(convert_dates='coerce'), + gtnew) @slow def test_gold_canyon(self): @@ -422,13 +500,93 @@ def test_gold_canyon(self): raw_text = f.read() self.assert_(gc in raw_text) - df = self.run_read_html(self.banklist_data, 'Gold Canyon', - attrs={'id': 'table'}, infer_types=False)[0] + df = self.read_html(self.banklist_data, 'Gold Canyon', + attrs={'id': 'table'})[0] self.assert_(gc in df.to_string()) + def test_different_number_of_rows(self): + expected = """<table border="1" class="dataframe"> + <thead> + <tr style="text-align: right;"> + <th></th> + <th>C_l0_g0</th> + <th>C_l0_g1</th> + <th>C_l0_g2</th> + <th>C_l0_g3</th> + <th>C_l0_g4</th> + </tr> + </thead> + <tbody> + <tr> + <th>R_l0_g0</th> + <td> 0.763</td> + <td> 0.233</td> + <td> nan</td> + <td> nan</td> + <td> nan</td> + </tr> + <tr> + <th>R_l0_g1</th> + <td> 0.244</td> + <td> 0.285</td> + <td> 0.392</td> + <td> 0.137</td> + <td> 0.222</td> + </tr> + </tbody> + </table>""" + out = """<table border="1" class="dataframe"> + <thead> + <tr style="text-align: right;"> + <th></th> + <th>C_l0_g0</th> + <th>C_l0_g1</th> + <th>C_l0_g2</th> + <th>C_l0_g3</th> + <th>C_l0_g4</th> + </tr> + </thead> + <tbody> + <tr> + <th>R_l0_g0</th> + <td> 0.763</td> + <td> 0.233</td> + </tr> + <tr> + <th>R_l0_g1</th> + <td> 0.244</td> + <td> 0.285</td> + <td> 0.392</td> + <td> 0.137</td> + <td> 0.222</td> + </tr> + </tbody> + </table>""" + expected = self.read_html(expected, index_col=0)[0] + res = self.read_html(out, index_col=0)[0] + tm.assert_frame_equal(expected, res) + + def test_parse_dates_list(self): + df = DataFrame({'date': date_range('1/1/2001', periods=10)}) + expected = df.to_html() + res = read_html(expected, parse_dates=[0], index_col=0) + tm.assert_frame_equal(df, res[0]) + + def test_parse_dates_combine(self): + raw_dates = Series(date_range('1/1/2001', periods=10)) + df = DataFrame({'date': raw_dates.map(lambda x: str(x.date())), + 'time': raw_dates.map(lambda x: str(x.time()))}) + res = read_html(df.to_html(), parse_dates={'datetime': [1, 2]}, + index_col=1) + newdf = DataFrame({'datetime': raw_dates}) + tm.assert_frame_equal(newdf, res[0]) + + +class TestReadHtmlLxml(unittest.TestCase): + def setUp(self): + self.try_skip() -class TestReadHtmlLxml(TestCase): - def run_read_html(self, *args, **kwargs): + def read_html(self, *args, **kwargs): self.flavor = ['lxml'] self.try_skip() kwargs['flavor'] = kwargs.get('flavor', self.flavor) @@ -437,31 +595,28 @@ def run_read_html(self, *args, **kwargs): def try_skip(self): _skip_if_no('lxml') - def test_spam_data_fail(self): + def test_data_fail(self): from lxml.etree import XMLSyntaxError spam_data = os.path.join(DATA_PATH, 'spam.html') - self.assertRaises(XMLSyntaxError, self.run_read_html, spam_data, - flavor=['lxml']) - - def test_banklist_data_fail(self): - from lxml.etree import XMLSyntaxError banklist_data = os.path.join(DATA_PATH, 'banklist.html') - self.assertRaises(XMLSyntaxError, self.run_read_html, banklist_data, flavor=['lxml']) + + with tm.assertRaises(XMLSyntaxError): + self.read_html(spam_data, flavor=['lxml']) + + with tm.assertRaises(XMLSyntaxError): + self.read_html(banklist_data, flavor=['lxml']) def test_works_on_valid_markup(self): filename = os.path.join(DATA_PATH, 'valid_markup.html') - dfs = self.run_read_html(filename, index_col=0, flavor=['lxml']) - self.assert_(isinstance(dfs, list)) - self.assert_(isinstance(dfs[0], DataFrame)) - - def setUp(self): - self.try_skip() + dfs = self.read_html(filename, index_col=0, flavor=['lxml']) + tm.assert_isinstance(dfs, list) + tm.assert_isinstance(dfs[0], DataFrame) @slow def test_fallback_success(self): _skip_if_none_of(('bs4', 'html5lib')) banklist_data = os.path.join(DATA_PATH, 'banklist.html') - self.run_read_html(banklist_data, '.*Water.*', flavor=['lxml', + self.read_html(banklist_data, '.*Water.*', flavor=['lxml', 'html5lib']) @@ -505,3 +660,11 @@ def test_lxml_finds_tables(): def test_lxml_finds_tbody(): filepath = os.path.join(DATA_PATH, "spam.html") assert get_lxml_elements(filepath, 'tbody') + + +def test_same_ordering(): + _skip_if_none_of(['bs4', 'lxml', 'html5lib']) + filename = os.path.join(DATA_PATH, 'valid_markup.html') + dfs_lxml = read_html(filename, index_col=0, flavor=['lxml']) + dfs_bs4 = read_html(filename, index_col=0, flavor=['bs4']) + assert_framelist_equal(dfs_lxml, dfs_bs4)
closes #4697 (refactor issue) (REF/ENH) closes #4700 (header inconsistency issue) (API) closes #5029 (comma issue, added this data set, ordering issue) (BUG) closes #5048 (header type conversion issue) (BUG) closes #5066 (index_col issue) (BUG) - [x] figure out `skiprows`, `header`, and `index_col` interaction (a somewhat longstanding `MultiIndex` sorting issue, I just took the long way to get there :)) - ~~spam url not working anymore~~ (US gov "shutdown" is responsible for this, it correctly skips) - ~~table ordering doc blurb/HTML gotchas~~ (was an actual "bug", now fixed in this PR) - ~~add tests for rows with a different length~~ (this is already done by the existing tests)
https://api.github.com/repos/pandas-dev/pandas/pulls/4770
2013-09-07T04:14:16Z
2013-10-03T02:26:05Z
2013-10-03T02:26:05Z
2015-08-23T12:59:28Z
TST: more robust testing for HDFStore dups
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index bcf2345913f1e..0a9e6855f094a 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -667,7 +667,7 @@ def func(_start, _stop): axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0] # concat and return - return concat(objs, axis=axis, verify_integrity=True) + return concat(objs, axis=axis, verify_integrity=True).consolidate() if iterator or chunksize is not None: return TableIterator(self, func, nrows=nrows, start=start, stop=stop, chunksize=chunksize, auto_close=auto_close) @@ -2910,9 +2910,7 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None, # reindex by our non_index_axes & compute data_columns for a in self.non_index_axes: - labels = _ensure_index(a[1]) - if not labels.equals(obj._get_axis(a[0])): - obj = obj.reindex_axis(labels, axis=a[0]) + obj = _reindex_axis(obj, a[0], a[1]) # figure out data_columns and get out blocks block_obj = self.get_object(obj).consolidate() @@ -3000,11 +2998,7 @@ def process_axes(self, obj, columns=None): # reorder by any non_index_axes & limit to the select columns for axis, labels in self.non_index_axes: - if columns is not None: - labels = Index(labels) & Index(columns) - labels = _ensure_index(labels) - if not labels.equals(obj._get_axis(axis)): - obj = obj.reindex_axis(labels, axis=axis) + obj = _reindex_axis(obj, axis, labels, columns) # apply the selection filters (but keep in the same order) if self.selection.filter: @@ -3219,7 +3213,7 @@ def read(self, where=None, columns=None, **kwargs): if len(objs) == 1: wp = objs[0] else: - wp = concat(objs, axis=0, verify_integrity=False) + wp = concat(objs, axis=0, verify_integrity=False).consolidate() # apply the selection filters & axis orderings wp = self.process_axes(wp, columns=columns) @@ -3510,7 +3504,7 @@ def read(self, where=None, columns=None, **kwargs): if len(frames) == 1: df = frames[0] else: - df = concat(frames, axis=1, verify_integrity=False) + df = concat(frames, axis=1, verify_integrity=False).consolidate() # apply the selection filters & axis orderings df = self.process_axes(df, columns=columns) @@ -3683,6 +3677,26 @@ class AppendableNDimTable(AppendablePanelTable): obj_type = Panel4D +def _reindex_axis(obj, axis, labels, other=None): + ax = obj._get_axis(axis) + labels = _ensure_index(labels) + + # try not to reindex even if other is provided + # if it equals our current index + if other is not None: + other = _ensure_index(other) + if (other is None or labels.equals(other)) and labels.equals(ax): + return obj + + labels = _ensure_index(labels.unique()) + if other is not None: + labels = labels & _ensure_index(other.unique()) + if not labels.equals(ax): + slicer = [ slice(None, None) ] * obj.ndim + slicer[axis] = labels + obj = obj.loc[tuple(slicer)] + return obj + def _get_info(info, name): """ get/create the info for this name """ try: diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 2ef4a9287a664..e9f4cf7d0f96f 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2298,15 +2298,24 @@ def test_wide_table(self): def test_select_with_dups(self): - # single dtypes df = DataFrame(np.random.randn(10,4),columns=['A','A','B','B']) df.index = date_range('20130101 9:30',periods=10,freq='T') with ensure_clean(self.path) as store: store.append('df',df) + result = store.select('df') - assert_frame_equal(result,df) + expected = df + assert_frame_equal(result,expected,by_blocks=True) + + result = store.select('df',columns=df.columns) + expected = df + assert_frame_equal(result,expected,by_blocks=True) + + result = store.select('df',columns=['A']) + expected = df.loc[:,['A']] + assert_frame_equal(result,expected) # dups accross dtypes df = concat([DataFrame(np.random.randn(10,4),columns=['A','A','B','B']), @@ -2316,8 +2325,22 @@ def test_select_with_dups(self): with ensure_clean(self.path) as store: store.append('df',df) + result = store.select('df') - assert_frame_equal(result,df) + expected = df + assert_frame_equal(result,expected,by_blocks=True) + + result = store.select('df',columns=df.columns) + expected = df + assert_frame_equal(result,expected,by_blocks=True) + + expected = df.loc[:,['A']] + result = store.select('df',columns=['A']) + assert_frame_equal(result,expected,by_blocks=True) + + expected = df.loc[:,['B','A']] + result = store.select('df',columns=['B','A']) + assert_frame_equal(result,expected,by_blocks=True) def test_wide_table_dups(self): wp = tm.makePanel() diff --git a/pandas/util/testing.py b/pandas/util/testing.py index c652c2da3214c..abc13fb2ad9ee 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -258,27 +258,41 @@ def assert_frame_equal(left, right, check_dtype=True, check_column_type=False, check_frame_type=False, check_less_precise=False, - check_names=True): + check_names=True, + by_blocks=False): if check_frame_type: assert_isinstance(left, type(right)) assert_isinstance(left, DataFrame) assert_isinstance(right, DataFrame) if check_less_precise: - assert_almost_equal(left.columns, right.columns) + if not by_blocks: + assert_almost_equal(left.columns, right.columns) assert_almost_equal(left.index, right.index) else: - assert_index_equal(left.columns, right.columns) + if not by_blocks: + assert_index_equal(left.columns, right.columns) assert_index_equal(left.index, right.index) - for i, col in enumerate(left.columns): - assert col in right - lcol = left.icol(i) - rcol = right.icol(i) - assert_series_equal(lcol, rcol, - check_dtype=check_dtype, - check_index_type=check_index_type, - check_less_precise=check_less_precise) + # compare by blocks + if by_blocks: + rblocks = right.blocks + lblocks = left.blocks + for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))): + assert dtype in lblocks + assert dtype in rblocks + assert_frame_equal(lblocks[dtype],rblocks[dtype],check_dtype=check_dtype) + + # compare by columns + else: + for i, col in enumerate(left.columns): + assert col in right + lcol = left.icol(i) + rcol = right.icol(i) + assert_series_equal(lcol, rcol, + check_dtype=check_dtype, + check_index_type=check_index_type, + check_less_precise=check_less_precise) if check_index_type: assert_isinstance(left.index, type(right.index))
https://api.github.com/repos/pandas-dev/pandas/pulls/4769
2013-09-07T02:25:23Z
2013-09-07T02:35:28Z
2013-09-07T02:35:28Z
2014-07-16T08:26:59Z
BUG: reading from a store with duplicate columns across dtypes would raise (GH4767)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 9a34cdbdfb5a8..01c2b39fbb97b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -237,6 +237,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - ``read_hdf`` was not respecting as passed ``mode`` (:issue:`4504`) - appending a 0-len table will work correctly (:issue:`4273`) - ``to_hdf`` was raising when passing both arguments ``append`` and ``table`` (:issue:`4584`) + - reading from a store with duplicate columns across dtypes would raise (:issue:`4767`) - Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while trying to access trans[pos + 1] (:issue:`4496`) - The ``by`` argument now works correctly with the ``layout`` argument diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 5ab63d016c3b8..bcf2345913f1e 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3219,7 +3219,7 @@ def read(self, where=None, columns=None, **kwargs): if len(objs) == 1: wp = objs[0] else: - wp = concat(objs, axis=0, verify_integrity=True) + wp = concat(objs, axis=0, verify_integrity=False) # apply the selection filters & axis orderings wp = self.process_axes(wp, columns=columns) @@ -3510,7 +3510,7 @@ def read(self, where=None, columns=None, **kwargs): if len(frames) == 1: df = frames[0] else: - df = concat(frames, axis=1, verify_integrity=True) + df = concat(frames, axis=1, verify_integrity=False) # apply the selection filters & axis orderings df = self.process_axes(df, columns=columns) diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 6941452075f4b..2ef4a9287a664 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2296,6 +2296,29 @@ def test_wide_table(self): wp = tm.makePanel() self._check_roundtrip_table(wp, assert_panel_equal) + def test_select_with_dups(self): + + + # single dtypes + df = DataFrame(np.random.randn(10,4),columns=['A','A','B','B']) + df.index = date_range('20130101 9:30',periods=10,freq='T') + + with ensure_clean(self.path) as store: + store.append('df',df) + result = store.select('df') + assert_frame_equal(result,df) + + # dups accross dtypes + df = concat([DataFrame(np.random.randn(10,4),columns=['A','A','B','B']), + DataFrame(np.random.randint(0,10,size=20).reshape(10,2),columns=['A','C'])], + axis=1) + df.index = date_range('20130101 9:30',periods=10,freq='T') + + with ensure_clean(self.path) as store: + store.append('df',df) + result = store.select('df') + assert_frame_equal(result,df) + def test_wide_table_dups(self): wp = tm.makePanel() with ensure_clean(self.path) as store:
closes #4767
https://api.github.com/repos/pandas-dev/pandas/pulls/4768
2013-09-07T00:10:23Z
2013-09-07T00:20:06Z
2013-09-07T00:20:06Z
2014-06-12T07:59:14Z
BUG: Bug in setting with loc/ix a single indexer on a multi-index axis and a listlike (related to GH3777)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 9a34cdbdfb5a8..1e0c980ca752d 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -327,6 +327,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Bug with Series indexing not raising an error when the right-hand-side has an incorrect length (:issue:`2702`) - Bug in multi-indexing with a partial string selection as one part of a MultIndex (:issue:`4758`) - Bug with reindexing on the index with a non-unique index will now raise ``ValueError`` (:issue:`4746`) + - Bug in setting with ``loc/ix`` a single indexer with a multi-index axis and a numpy array, related to (:issue:`3777`) pandas 0.12 =========== diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 19eeecfeb2bde..72196fcdad38d 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -163,6 +163,10 @@ def _setitem_with_indexer(self, indexer, value): labels = _safe_append_to_index(index, key) self.obj._data = self.obj.reindex_axis(labels,i)._data + if isinstance(labels,MultiIndex): + self.obj.sortlevel(inplace=True) + labels = self.obj._get_axis(i) + nindexer.append(labels.get_loc(key)) else: @@ -198,33 +202,77 @@ def _setitem_with_indexer(self, indexer, value): elif self.ndim >= 3: return self.obj.__setitem__(indexer,value) + # set + info_axis = self.obj._info_axis_number + item_labels = self.obj._get_axis(info_axis) + + # if we have a complicated setup, take the split path + if isinstance(indexer, tuple) and any([ isinstance(ax,MultiIndex) for ax in self.obj.axes ]): + take_split_path = True + # align and set the values if take_split_path: + if not isinstance(indexer, tuple): indexer = self._tuplify(indexer) if isinstance(value, ABCSeries): value = self._align_series(indexer, value) - info_axis = self.obj._info_axis_number info_idx = indexer[info_axis] - if com.is_integer(info_idx): info_idx = [info_idx] + labels = item_labels[info_idx] + + # if we have a partial multiindex, then need to adjust the plane indexer here + if len(labels) == 1 and isinstance(self.obj[labels[0]].index,MultiIndex): + index = self.obj[labels[0]].index + idx = indexer[:info_axis][0] + try: + if idx in index: + idx = index.get_loc(idx) + except: + pass + plane_indexer = tuple([idx]) + indexer[info_axis + 1:] + lplane_indexer = _length_of_indexer(plane_indexer[0],index) - plane_indexer = indexer[:info_axis] + indexer[info_axis + 1:] - item_labels = self.obj._get_axis(info_axis) + if is_list_like(value) and lplane_indexer != len(value): + raise ValueError("cannot set using a multi-index selection indexer with a different length than the value") + + # non-mi + else: + plane_indexer = indexer[:info_axis] + indexer[info_axis + 1:] + if info_axis > 0: + plane_axis = self.obj.axes[:info_axis][0] + lplane_indexer = _length_of_indexer(plane_indexer[0],plane_axis) + else: + lplane_indexer = 0 def setter(item, v): s = self.obj[item] - pi = plane_indexer[0] if len(plane_indexer) == 1 else plane_indexer + pi = plane_indexer[0] if lplane_indexer == 1 else plane_indexer # set the item, possibly having a dtype change s = s.copy() s._data = s._data.setitem(pi,v) self.obj[item] = s - labels = item_labels[info_idx] + def can_do_equal_len(): + """ return True if we have an equal len settable """ + if not len(labels) == 1: + return False + + l = len(value) + item = labels[0] + index = self.obj[item].index + + # equal len list/ndarray + if len(index) == l: + return True + elif lplane_indexer == l: + return True + + return False if _is_list_like(value): @@ -251,8 +299,7 @@ def setter(item, v): setter(item, value[:,i]) # we have an equal len list/ndarray - elif len(labels) == 1 and ( - len(self.obj[labels[0]]) == len(value) or len(plane_indexer[0]) == len(value)): + elif can_do_equal_len(): setter(labels[0], value) # per label values @@ -1104,6 +1151,31 @@ def _convert_key(self, key): # 32-bit floating point machine epsilon _eps = np.finfo('f4').eps +def _length_of_indexer(indexer,target=None): + """ return the length of a single non-tuple indexer which could be a slice """ + if target is not None and isinstance(indexer, slice): + l = len(target) + start = indexer.start + stop = indexer.stop + step = indexer.step + if start is None: + start = 0 + elif start < 0: + start += l + if stop is None or stop > l: + stop = l + elif stop < 0: + stop += l + if step is None: + step = 1 + elif step < 0: + step = abs(step) + return (stop-start) / step + elif isinstance(indexer, (ABCSeries, np.ndarray, list)): + return len(indexer) + elif not is_list_like(indexer): + return 1 + raise AssertionError("cannot find the length of the indexer") def _convert_to_index_sliceable(obj, key): """ if we are index sliceable, then return my slicer, otherwise return None """ diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 91fdc712fb9b8..57db36b252e3c 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -12,7 +12,8 @@ is_list_like, _infer_dtype_from_scalar) from pandas.core.index import (Index, MultiIndex, _ensure_index, _handle_legacy_indexes) -from pandas.core.indexing import _check_slice_bounds, _maybe_convert_indices +from pandas.core.indexing import (_check_slice_bounds, _maybe_convert_indices, + _length_of_indexer) import pandas.core.common as com from pandas.sparse.array import _maybe_to_sparse, SparseArray import pandas.lib as lib @@ -563,22 +564,7 @@ def setitem(self, indexer, value): elif isinstance(indexer, slice): if is_list_like(value) and l: - start = indexer.start - stop = indexer.stop - step = indexer.step - if start is None: - start = 0 - elif start < 0: - start += l - if stop is None or stop > l: - stop = len(values) - elif stop < 0: - stop += l - if step is None: - step = 1 - elif step < 0: - step = abs(step) - if (stop-start) / step != len(value): + if len(value) != _length_of_indexer(indexer, values): raise ValueError("cannot set using a slice indexer with a different length than the value") try: diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 66193248ffb7d..d6088c2d72525 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -917,6 +917,60 @@ def f(): #result = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] #tm.assert_panel_equal(result,expected) + def test_multiindex_assignment(self): + + # GH3777 part 2 + + # mixed dtype + df = DataFrame(np.random.randint(5,10,size=9).reshape(3, 3), + columns=list('abc'), + index=[[4,4,8],[8,10,12]]) + df['d'] = np.nan + arr = np.array([0.,1.]) + + df.ix[4,'d'] = arr + assert_series_equal(df.ix[4,'d'],Series(arr,index=[8,10],name='d')) + + # single dtype + df = DataFrame(np.random.randint(5,10,size=9).reshape(3, 3), + columns=list('abc'), + index=[[4,4,8],[8,10,12]]) + + df.ix[4,'c'] = arr + assert_series_equal(df.ix[4,'c'],Series(arr,index=[8,10],name='c',dtype='int64')) + + # scalar ok + df.ix[4,'c'] = 10 + assert_series_equal(df.ix[4,'c'],Series(10,index=[8,10],name='c',dtype='int64')) + + # invalid assignments + def f(): + df.ix[4,'c'] = [0,1,2,3] + self.assertRaises(ValueError, f) + + def f(): + df.ix[4,'c'] = [0] + self.assertRaises(ValueError, f) + + # groupby example + NUM_ROWS = 100 + NUM_COLS = 10 + col_names = ['A'+num for num in map(str,np.arange(NUM_COLS).tolist())] + index_cols = col_names[:5] + df = DataFrame(np.random.randint(5, size=(NUM_ROWS,NUM_COLS)), dtype=np.int64, columns=col_names) + df = df.set_index(index_cols).sort_index() + grp = df.groupby(level=index_cols[:4]) + df['new_col'] = np.nan + + f_index = np.arange(5) + def f(name,df2): + return Series(np.arange(df2.shape[0]),name=df2.index.values[0]).reindex(f_index) + new_df = pd.concat([ f(name,df2) for name, df2 in grp ],axis=1).T + + for name, df2 in grp: + new_vals = np.arange(df2.shape[0]) + df.ix[name, 'new_col'] = new_vals + def test_multi_assign(self): # GH 3626, an assignement of a sub-df to a df
related to #3777 This shows enlarging (and setting inplace) ``` In [8]: df = DataFrame(np.random.randint(5,10,size=9).reshape(3, 3), ...: ...: columns=list('abc'), ...: ...: index=[[4,4,8],[8,10,12]]) In [9]: In [9]: df Out[9]: a b c 4 8 8 8 8 10 9 7 6 8 12 8 7 9 In [10]: df.loc[4,'d'] = [0,1.] In [11]: df Out[11]: a b c d 4 8 8 8 8 0 10 9 7 6 1 8 12 8 7 9 NaN In [12]: df.loc[4,'d'] = [3,4] In [13]: df Out[13]: a b c d 4 8 8 8 8 3 10 9 7 6 4 8 12 8 7 9 NaN ``` Invalid assignments ``` In [10]: df.loc[4,'d'] = [3] ValueError: cannot set using a multi-index selection indexer with a different length than the value In [11]: df.loc[4,'d'] = [3,4,5] ValueError: cannot set using a multi-index selection indexer with a different length than the value ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4766
2013-09-06T23:00:49Z
2013-09-07T00:10:52Z
2013-09-07T00:10:52Z
2014-06-18T19:30:24Z
API: raise a TypeError when isin is passed a string
diff --git a/doc/source/api.rst b/doc/source/api.rst index e964ce569532a..9cf10d3f0780d 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -451,6 +451,7 @@ Indexing, iteration DataFrame.pop DataFrame.tail DataFrame.xs + DataFrame.isin Binary operator functions ~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/release.rst b/doc/source/release.rst index 00aba51eac37e..80cd935bc67e9 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -148,6 +148,9 @@ pandas 0.13 behavior. - ``DataFrame.update()`` no longer raises a ``DataConflictError``, it now will raise a ``ValueError`` instead (if necessary) (:issue:`4732`) + - ``Series.isin()`` and ``DataFrame.isin()`` now raise a ``TypeError`` when + passed a string (:issue:`4763`). Pass a ``list`` of one element (containing + the string) instead. **Internal Refactoring** diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0cd9f7f3f5330..8c6e7697f8ea1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4609,6 +4609,11 @@ def isin(self, values, iloc=False): else: + if not com.is_list_like(values): + raise TypeError("only list-like or dict-like objects are" + " allowed to be passed to DataFrame.isin(), " + "you passed a " + "{0!r}".format(type(values).__name__)) return DataFrame(lib.ismember(self.values.ravel(), set(values)).reshape(self.shape), self.index, diff --git a/pandas/core/series.py b/pandas/core/series.py index 1160f85751aee..5579e60ceb90e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2805,17 +2805,47 @@ def take(self, indices, axis=0, convert=True): def isin(self, values): """ - Return boolean vector showing whether each element in the Series is - exactly contained in the passed sequence of values + Return a boolean :ref:`~pandas.Series` showing whether each element in + the ref:`~pandas.Series` is exactly contained in the passed sequence of + ``values``. Parameters ---------- - values : sequence + values : list-like + The sequence of values to test. Passing in a single string will + raise a ``TypeError``: + + .. code-block:: python + + from pandas import Series + s = Series(list('abc')) + s.isin('a') + + Instead, turn a single string into a ``list`` of one element: + + .. code-block:: python + + from pandas import Series + s = Series(list('abc')) + s.isin(['a']) Returns ------- - isin : Series (boolean dtype) + isin : Series (bool dtype) + + Raises + ------ + TypeError + * If ``values`` is a string + + See Also + -------- + pandas.DataFrame.isin """ + if not com.is_list_like(values): + raise TypeError("only list-like objects are allowed to be passed" + " to Series.isin(), you passed a " + "{0!r}".format(type(values).__name__)) value_set = set(values) result = lib.ismember(_values_from_object(self), value_set) return self._constructor(result, self.index, name=self.name) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index c39634281ebb7..b4ec36ac5f29e 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -10915,6 +10915,16 @@ def test_isin_dict(self): expected.iloc[0, 0] = True assert_frame_equal(result, expected) + def test_isin_with_string_scalar(self): + #GH4763 + df = DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a', 'b', 'f', 'n'], + 'ids2': ['a', 'n', 'c', 'n']}, + index=['foo', 'bar', 'baz', 'qux']) + with tm.assertRaises(TypeError): + df.isin('a') + + with tm.assertRaises(TypeError): + df.isin('aaa') if __name__ == '__main__': # unittest.main() diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 514245e82ac28..556973acdcb95 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -4433,6 +4433,16 @@ def test_isin(self): expected = Series([True, False, True, False, False, False, True, True]) assert_series_equal(result, expected) + def test_isin_with_string_scalar(self): + #GH4763 + s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C']) + with tm.assertRaises(TypeError): + s.isin('a') + + with tm.assertRaises(TypeError): + s = Series(['aaa', 'b', 'c']) + s.isin('aaa') + def test_fillna_int(self): s = Series(np.random.randint(-100, 100, 50)) s.fillna(method='ffill', inplace=True)
closes #4763
https://api.github.com/repos/pandas-dev/pandas/pulls/4765
2013-09-06T19:08:12Z
2013-09-06T20:07:10Z
2013-09-06T20:07:10Z
2014-06-22T20:42:31Z
Gotachas -> Gotchas
diff --git a/doc/source/10min.rst b/doc/source/10min.rst index 96f9fd912b664..58c5b54968614 100644 --- a/doc/source/10min.rst +++ b/doc/source/10min.rst @@ -723,4 +723,4 @@ If you are trying an operation and you see an exception like: See :ref:`Comparisons<basics.compare>` for an explanation and what to do. -See :ref:`Gotachas<gotchas>` as well. +See :ref:`Gotchas<gotchas>` as well.
Just a quick typo fix.
https://api.github.com/repos/pandas-dev/pandas/pulls/4762
2013-09-06T04:46:59Z
2013-09-06T04:50:46Z
2013-09-06T04:50:46Z
2014-07-16T08:26:51Z
BUG: in multi-indexing with a partial string selection (GH4758)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 00aba51eac37e..adea4601b5a4c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -322,6 +322,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>` - Bug in using ``iloc/loc`` with a cross-sectional and duplicate indicies (:issue:`4726`) - Bug with using ``QUOTE_NONE`` with ``to_csv`` causing ``Exception``. (:issue:`4328`) - Bug with Series indexing not raising an error when the right-hand-side has an incorrect length (:issue:`2702`) + - Bug in multi-indexing with a partial string selection as one part of a MultIndex (:issue:`4758`) pandas 0.12 =========== diff --git a/pandas/core/index.py b/pandas/core/index.py index 57a913acf6355..2b5f761026924 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -2596,10 +2596,15 @@ def _maybe_drop_levels(indexer, levels, drop_level): if not drop_level: return self[indexer] # kludgearound - new_index = self[indexer] + orig_index = new_index = self[indexer] levels = [self._get_level_number(i) for i in levels] for i in sorted(levels, reverse=True): - new_index = new_index.droplevel(i) + try: + new_index = new_index.droplevel(i) + except: + + # no dropping here + return orig_index return new_index if isinstance(level, (tuple, list)): @@ -2635,20 +2640,37 @@ def _maybe_drop_levels(indexer, levels, drop_level): pass if not any(isinstance(k, slice) for k in key): - if len(key) == self.nlevels: - if self.is_unique: - return self._engine.get_loc(_values_from_object(key)), None - else: - indexer = slice(*self.slice_locs(key, key)) - return indexer, self[indexer] - else: - # partial selection + + # partial selection + def partial_selection(key): indexer = slice(*self.slice_locs(key, key)) if indexer.start == indexer.stop: raise KeyError(key) ilevels = [i for i in range(len(key)) if key[i] != slice(None, None)] return indexer, _maybe_drop_levels(indexer, ilevels, drop_level) + + if len(key) == self.nlevels: + + if self.is_unique: + + # here we have a completely specified key, but are using some partial string matching here + # GH4758 + can_index_exactly = any([ l.is_all_dates and not isinstance(k,compat.string_types) for k, l in zip(key, self.levels) ]) + if any([ l.is_all_dates for k, l in zip(key, self.levels) ]) and not can_index_exactly: + indexer = slice(*self.slice_locs(key, key)) + + # we have a multiple selection here + if not indexer.stop-indexer.start == 1: + return partial_selection(key) + + key = tuple(self[indexer].tolist()[0]) + + return self._engine.get_loc(_values_from_object(key)), None + else: + return partial_selection(key) + else: + return partial_selection(key) else: indexer = None for i, k in enumerate(key): diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 636a5e88817ee..9ecdf1930604f 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -952,9 +952,15 @@ def _has_valid_type(self, key, axis): if not len(ax): raise KeyError("The [%s] axis is empty" % self.obj._get_axis_name(axis)) - if not key in ax: + try: + if not key in ax: + raise KeyError("the label [%s] is not in the [%s]" % (key,self.obj._get_axis_name(axis))) + except (TypeError): + + # if we have a weird type of key/ax raise KeyError("the label [%s] is not in the [%s]" % (key,self.obj._get_axis_name(axis))) + return True def _getitem_axis(self, key, axis=0): diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 21462780e2ffd..d3d4368d8028e 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1842,9 +1842,9 @@ def test_duplicate_mi(self): columns=list('ABCD')) df = df.set_index(['A','B']) df = df.sortlevel(0) - result = df.loc[('foo','bar')] expected = DataFrame([['foo','bar',1.0,1],['foo','bar',2.0,2],['foo','bar',5.0,5]], columns=list('ABCD')).set_index(['A','B']) + result = df.loc[('foo','bar')] assert_frame_equal(result,expected) def test_multiindex_set_index(self): diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index 28b52d073c813..6c18b6582c4cc 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -175,6 +175,7 @@ def _check_output(res, col, rows=['A', 'B'], cols=['C']): exp = self.data.groupby(rows)[col].mean() tm.assert_series_equal(cmarg, exp) + res.sortlevel(inplace=True) rmarg = res.xs(('All', ''))[:-1] exp = self.data.groupby(cols)[col].mean() tm.assert_series_equal(rmarg, exp) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 5bed7777cf439..b5697a98de412 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -1970,495 +1970,6 @@ def test_join_self(self): joined = index.join(index, how=kind) self.assert_(index is joined) -# infortunately, too much has changed to handle these legacy pickles -# class TestLegacySupport(unittest.TestCase): -class LegacySupport(object): - - _multiprocess_can_split_ = True - - @classmethod - def setUpClass(cls): - if compat.PY3: - raise nose.SkipTest - - pth, _ = os.path.split(os.path.abspath(__file__)) - filepath = os.path.join(pth, 'data', 'frame.pickle') - - with open(filepath, 'rb') as f: - cls.frame = pickle.load(f) - - filepath = os.path.join(pth, 'data', 'series.pickle') - with open(filepath, 'rb') as f: - cls.series = pickle.load(f) - - def test_pass_offset_warn(self): - buf = StringIO() - - sys.stderr = buf - DatetimeIndex(start='1/1/2000', periods=10, offset='H') - sys.stderr = sys.__stderr__ - - def test_unpickle_legacy_frame(self): - dtindex = DatetimeIndex(start='1/3/2005', end='1/14/2005', - freq=BDay(1)) - - unpickled = self.frame - - self.assertEquals(type(unpickled.index), DatetimeIndex) - self.assertEquals(len(unpickled), 10) - self.assert_((unpickled.columns == Int64Index(np.arange(5))).all()) - self.assert_((unpickled.index == dtindex).all()) - self.assertEquals(unpickled.index.offset, BDay(1, normalize=True)) - - def test_unpickle_legacy_series(self): - from pandas.core.datetools import BDay - - unpickled = self.series - - dtindex = DatetimeIndex(start='1/3/2005', end='1/14/2005', - freq=BDay(1)) - - self.assertEquals(type(unpickled.index), DatetimeIndex) - self.assertEquals(len(unpickled), 10) - self.assert_((unpickled.index == dtindex).all()) - self.assertEquals(unpickled.index.offset, BDay(1, normalize=True)) - - def test_unpickle_legacy_len0_daterange(self): - pth, _ = os.path.split(os.path.abspath(__file__)) - filepath = os.path.join(pth, 'data', 'series_daterange0.pickle') - - result = pd.read_pickle(filepath) - - ex_index = DatetimeIndex([], freq='B') - - self.assert_(result.index.equals(ex_index)) - tm.assert_isinstance(result.index.freq, offsets.BDay) - self.assert_(len(result) == 0) - - def test_arithmetic_interaction(self): - index = self.frame.index - obj_index = index.asobject - - dseries = Series(rand(len(index)), index=index) - oseries = Series(dseries.values, index=obj_index) - - result = dseries + oseries - expected = dseries * 2 - tm.assert_isinstance(result.index, DatetimeIndex) - assert_series_equal(result, expected) - - result = dseries + oseries[:5] - expected = dseries + dseries[:5] - tm.assert_isinstance(result.index, DatetimeIndex) - assert_series_equal(result, expected) - - def test_join_interaction(self): - index = self.frame.index - obj_index = index.asobject - - def _check_join(left, right, how='inner'): - ra, rb, rc = left.join(right, how=how, return_indexers=True) - ea, eb, ec = left.join(DatetimeIndex(right), how=how, - return_indexers=True) - - tm.assert_isinstance(ra, DatetimeIndex) - self.assert_(ra.equals(ea)) - - assert_almost_equal(rb, eb) - assert_almost_equal(rc, ec) - - _check_join(index[:15], obj_index[5:], how='inner') - _check_join(index[:15], obj_index[5:], how='outer') - _check_join(index[:15], obj_index[5:], how='right') - _check_join(index[:15], obj_index[5:], how='left') - - def test_join_nonunique(self): - idx1 = to_datetime(['2012-11-06 16:00:11.477563', - '2012-11-06 16:00:11.477563']) - idx2 = to_datetime(['2012-11-06 15:11:09.006507', - '2012-11-06 15:11:09.006507']) - rs = idx1.join(idx2, how='outer') - self.assert_(rs.is_monotonic) - - def test_unpickle_daterange(self): - pth, _ = os.path.split(os.path.abspath(__file__)) - filepath = os.path.join(pth, 'data', 'daterange_073.pickle') - - rng = read_pickle(filepath) - tm.assert_isinstance(rng[0], datetime) - tm.assert_isinstance(rng.offset, offsets.BDay) - self.assert_(rng.values.dtype == object) - - def test_setops(self): - index = self.frame.index - obj_index = index.asobject - - result = index[:5].union(obj_index[5:]) - expected = index - tm.assert_isinstance(result, DatetimeIndex) - self.assert_(result.equals(expected)) - - result = index[:10].intersection(obj_index[5:]) - expected = index[5:10] - tm.assert_isinstance(result, DatetimeIndex) - self.assert_(result.equals(expected)) - - result = index[:10] - obj_index[5:] - expected = index[:5] - tm.assert_isinstance(result, DatetimeIndex) - self.assert_(result.equals(expected)) - - def test_index_conversion(self): - index = self.frame.index - obj_index = index.asobject - - conv = DatetimeIndex(obj_index) - self.assert_(conv.equals(index)) - - self.assertRaises(ValueError, DatetimeIndex, ['a', 'b', 'c', 'd']) - - def test_tolist(self): - rng = date_range('1/1/2000', periods=10) - - result = rng.tolist() - tm.assert_isinstance(result[0], Timestamp) - - def test_object_convert_fail(self): - idx = DatetimeIndex([NaT]) - self.assertRaises(ValueError, idx.astype, 'O') - - def test_setops_conversion_fail(self): - index = self.frame.index - - right = Index(['a', 'b', 'c', 'd']) - - result = index.union(right) - expected = Index(np.concatenate([index.asobject, right])) - self.assert_(result.equals(expected)) - - result = index.intersection(right) - expected = Index([]) - self.assert_(result.equals(expected)) - - def test_legacy_time_rules(self): - rules = [('WEEKDAY', 'B'), - ('EOM', 'BM'), - ('W@MON', 'W-MON'), ('W@TUE', 'W-TUE'), ('W@WED', 'W-WED'), - ('W@THU', 'W-THU'), ('W@FRI', 'W-FRI'), - ('Q@JAN', 'BQ-JAN'), ('Q@FEB', 'BQ-FEB'), ('Q@MAR', 'BQ-MAR'), - ('A@JAN', 'BA-JAN'), ('A@FEB', 'BA-FEB'), ('A@MAR', 'BA-MAR'), - ('A@APR', 'BA-APR'), ('A@MAY', 'BA-MAY'), ('A@JUN', 'BA-JUN'), - ('A@JUL', 'BA-JUL'), ('A@AUG', 'BA-AUG'), ('A@SEP', 'BA-SEP'), - ('A@OCT', 'BA-OCT'), ('A@NOV', 'BA-NOV'), ('A@DEC', 'BA-DEC'), - ('WOM@1FRI', 'WOM-1FRI'), ('WOM@2FRI', 'WOM-2FRI'), - ('WOM@3FRI', 'WOM-3FRI'), ('WOM@4FRI', 'WOM-4FRI')] - - start, end = '1/1/2000', '1/1/2010' - - for old_freq, new_freq in rules: - old_rng = date_range(start, end, freq=old_freq) - new_rng = date_range(start, end, freq=new_freq) - self.assert_(old_rng.equals(new_rng)) - - # test get_legacy_offset_name - offset = datetools.get_offset(new_freq) - old_name = datetools.get_legacy_offset_name(offset) - self.assertEquals(old_name, old_freq) - - def test_ms_vs_MS(self): - left = datetools.get_offset('ms') - right = datetools.get_offset('MS') - self.assert_(left == datetools.Milli()) - self.assert_(right == datetools.MonthBegin()) - - def test_rule_aliases(self): - rule = datetools.to_offset('10us') - self.assert_(rule == datetools.Micro(10)) - - def test_slice_year(self): - dti = DatetimeIndex(freq='B', start=datetime(2005, 1, 1), periods=500) - - s = Series(np.arange(len(dti)), index=dti) - result = s['2005'] - expected = s[s.index.year == 2005] - assert_series_equal(result, expected) - - df = DataFrame(np.random.rand(len(dti), 5), index=dti) - result = df.ix['2005'] - expected = df[df.index.year == 2005] - assert_frame_equal(result, expected) - - rng = date_range('1/1/2000', '1/1/2010') - - result = rng.get_loc('2009') - expected = slice(3288, 3653) - self.assert_(result == expected) - - def test_slice_quarter(self): - dti = DatetimeIndex(freq='D', start=datetime(2000, 6, 1), periods=500) - - s = Series(np.arange(len(dti)), index=dti) - self.assertEquals(len(s['2001Q1']), 90) - - df = DataFrame(np.random.rand(len(dti), 5), index=dti) - self.assertEquals(len(df.ix['1Q01']), 90) - - def test_slice_month(self): - dti = DatetimeIndex(freq='D', start=datetime(2005, 1, 1), periods=500) - s = Series(np.arange(len(dti)), index=dti) - self.assertEquals(len(s['2005-11']), 30) - - df = DataFrame(np.random.rand(len(dti), 5), index=dti) - self.assertEquals(len(df.ix['2005-11']), 30) - - assert_series_equal(s['2005-11'], s['11-2005']) - - def test_partial_slice(self): - rng = DatetimeIndex(freq='D', start=datetime(2005, 1, 1), periods=500) - s = Series(np.arange(len(rng)), index=rng) - - result = s['2005-05':'2006-02'] - expected = s['20050501':'20060228'] - assert_series_equal(result, expected) - - result = s['2005-05':] - expected = s['20050501':] - assert_series_equal(result, expected) - - result = s[:'2006-02'] - expected = s[:'20060228'] - assert_series_equal(result, expected) - - result = s['2005-1-1'] - self.assert_(result == s.irow(0)) - - self.assertRaises(Exception, s.__getitem__, '2004-12-31') - - def test_partial_slice_daily(self): - rng = DatetimeIndex(freq='H', start=datetime(2005, 1, 31), periods=500) - s = Series(np.arange(len(rng)), index=rng) - - result = s['2005-1-31'] - assert_series_equal(result, s.ix[:24]) - - self.assertRaises(Exception, s.__getitem__, '2004-12-31 00') - - def test_partial_slice_hourly(self): - rng = DatetimeIndex(freq='T', start=datetime(2005, 1, 1, 20, 0, 0), - periods=500) - s = Series(np.arange(len(rng)), index=rng) - - result = s['2005-1-1'] - assert_series_equal(result, s.ix[:60 * 4]) - - result = s['2005-1-1 20'] - assert_series_equal(result, s.ix[:60]) - - self.assert_(s['2005-1-1 20:00'] == s.ix[0]) - self.assertRaises(Exception, s.__getitem__, '2004-12-31 00:15') - - def test_partial_slice_minutely(self): - rng = DatetimeIndex(freq='S', start=datetime(2005, 1, 1, 23, 59, 0), - periods=500) - s = Series(np.arange(len(rng)), index=rng) - - result = s['2005-1-1 23:59'] - assert_series_equal(result, s.ix[:60]) - - result = s['2005-1-1'] - assert_series_equal(result, s.ix[:60]) - - self.assert_(s['2005-1-1 23:59:00'] == s.ix[0]) - self.assertRaises(Exception, s.__getitem__, '2004-12-31 00:00:00') - - def test_date_range_normalize(self): - snap = datetime.today() - n = 50 - - rng = date_range(snap, periods=n, normalize=False, freq='2D') - - offset = timedelta(2) - values = np.array([snap + i * offset for i in range(n)], - dtype='M8[ns]') - - self.assert_(np.array_equal(rng, values)) - - rng = date_range( - '1/1/2000 08:15', periods=n, normalize=False, freq='B') - the_time = time(8, 15) - for val in rng: - self.assert_(val.time() == the_time) - - def test_timedelta(self): - # this is valid too - index = date_range('1/1/2000', periods=50, freq='B') - shifted = index + timedelta(1) - back = shifted + timedelta(-1) - self.assert_(tm.equalContents(index, back)) - self.assertEqual(shifted.freq, index.freq) - self.assertEqual(shifted.freq, back.freq) - - result = index - timedelta(1) - expected = index + timedelta(-1) - self.assert_(result.equals(expected)) - - # GH4134, buggy with timedeltas - rng = date_range('2013', '2014') - s = Series(rng) - result1 = rng - pd.offsets.Hour(1) - result2 = DatetimeIndex(s - np.timedelta64(100000000)) - result3 = rng - np.timedelta64(100000000) - result4 = DatetimeIndex(s - pd.offsets.Hour(1)) - self.assert_(result1.equals(result4)) - self.assert_(result2.equals(result3)) - - def test_shift(self): - ts = Series(np.random.randn(5), - index=date_range('1/1/2000', periods=5, freq='H')) - - result = ts.shift(1, freq='5T') - exp_index = ts.index.shift(1, freq='5T') - self.assert_(result.index.equals(exp_index)) - - # GH #1063, multiple of same base - result = ts.shift(1, freq='4H') - exp_index = ts.index + datetools.Hour(4) - self.assert_(result.index.equals(exp_index)) - - idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04']) - self.assertRaises(ValueError, idx.shift, 1) - - def test_setops_preserve_freq(self): - rng = date_range('1/1/2000', '1/1/2002') - - result = rng[:50].union(rng[50:100]) - self.assert_(result.freq == rng.freq) - - result = rng[:50].union(rng[30:100]) - self.assert_(result.freq == rng.freq) - - result = rng[:50].union(rng[60:100]) - self.assert_(result.freq is None) - - result = rng[:50].intersection(rng[25:75]) - self.assert_(result.freqstr == 'D') - - nofreq = DatetimeIndex(list(rng[25:75])) - result = rng[:50].union(nofreq) - self.assert_(result.freq == rng.freq) - - result = rng[:50].intersection(nofreq) - self.assert_(result.freq == rng.freq) - - def test_min_max(self): - rng = date_range('1/1/2000', '12/31/2000') - rng2 = rng.take(np.random.permutation(len(rng))) - - the_min = rng2.min() - the_max = rng2.max() - tm.assert_isinstance(the_min, Timestamp) - tm.assert_isinstance(the_max, Timestamp) - self.assertEqual(the_min, rng[0]) - self.assertEqual(the_max, rng[-1]) - - self.assertEqual(rng.min(), rng[0]) - self.assertEqual(rng.max(), rng[-1]) - - def test_min_max_series(self): - rng = date_range('1/1/2000', periods=10, freq='4h') - lvls = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'] - df = DataFrame({'TS': rng, 'V': np.random.randn(len(rng)), - 'L': lvls}) - - result = df.TS.max() - exp = Timestamp(df.TS.iget(-1)) - self.assertTrue(isinstance(result, Timestamp)) - self.assertEqual(result, exp) - - result = df.TS.min() - exp = Timestamp(df.TS.iget(0)) - self.assertTrue(isinstance(result, Timestamp)) - self.assertEqual(result, exp) - - def test_from_M8_structured(self): - dates = [(datetime(2012, 9, 9, 0, 0), - datetime(2012, 9, 8, 15, 10))] - arr = np.array(dates, - dtype=[('Date', 'M8[us]'), ('Forecasting', 'M8[us]')]) - df = DataFrame(arr) - - self.assertEqual(df['Date'][0], dates[0][0]) - self.assertEqual(df['Forecasting'][0], dates[0][1]) - - s = Series(arr['Date']) - self.assertTrue(s[0], Timestamp) - self.assertEqual(s[0], dates[0][0]) - - s = Series.from_array(arr['Date'], Index([0])) - self.assertEqual(s[0], dates[0][0]) - - def test_get_level_values_box(self): - from pandas import MultiIndex - - dates = date_range('1/1/2000', periods=4) - levels = [dates, [0, 1]] - labels = [[0, 0, 1, 1, 2, 2, 3, 3], - [0, 1, 0, 1, 0, 1, 0, 1]] - - index = MultiIndex(levels=levels, labels=labels) - - self.assertTrue(isinstance(index.get_level_values(0)[0], Timestamp)) - - def test_frame_apply_dont_convert_datetime64(self): - from pandas.tseries.offsets import BDay - df = DataFrame({'x1': [datetime(1996, 1, 1)]}) - - df = df.applymap(lambda x: x + BDay()) - df = df.applymap(lambda x: x + BDay()) - - self.assertTrue(df.x1.dtype == 'M8[ns]') - - -class TestLegacyCompat(unittest.TestCase): - - def setUp(self): - # suppress deprecation warnings - sys.stderr = StringIO() - - def test_inferTimeRule(self): - from pandas.tseries.frequencies import inferTimeRule - - index1 = [datetime(2010, 1, 29, 0, 0), - datetime(2010, 2, 26, 0, 0), - datetime(2010, 3, 31, 0, 0)] - - index2 = [datetime(2010, 3, 26, 0, 0), - datetime(2010, 3, 29, 0, 0), - datetime(2010, 3, 30, 0, 0)] - - index3 = [datetime(2010, 3, 26, 0, 0), - datetime(2010, 3, 27, 0, 0), - datetime(2010, 3, 29, 0, 0)] - - # LEGACY - assert inferTimeRule(index1) == 'EOM' - assert inferTimeRule(index2) == 'WEEKDAY' - - self.assertRaises(Exception, inferTimeRule, index1[:2]) - self.assertRaises(Exception, inferTimeRule, index3) - - def test_time_rule(self): - result = DateRange('1/1/2000', '1/30/2000', time_rule='WEEKDAY') - result2 = DateRange('1/1/2000', '1/30/2000', timeRule='WEEKDAY') - expected = date_range('1/1/2000', '1/30/2000', freq='B') - - self.assert_(result.equals(expected)) - self.assert_(result2.equals(expected)) - - def tearDown(self): - sys.stderr = sys.__stderr__ - - class TestDatetime64(unittest.TestCase): """ Also test supoprt for datetime64[ns] in Series / DataFrame @@ -2956,6 +2467,273 @@ def test_hash_equivalent(self): stamp = Timestamp(datetime(2011, 1, 1)) self.assertEquals(d[stamp], 5) +class TestSlicing(unittest.TestCase): + + def test_slice_year(self): + dti = DatetimeIndex(freq='B', start=datetime(2005, 1, 1), periods=500) + + s = Series(np.arange(len(dti)), index=dti) + result = s['2005'] + expected = s[s.index.year == 2005] + assert_series_equal(result, expected) + + df = DataFrame(np.random.rand(len(dti), 5), index=dti) + result = df.ix['2005'] + expected = df[df.index.year == 2005] + assert_frame_equal(result, expected) + + rng = date_range('1/1/2000', '1/1/2010') + + result = rng.get_loc('2009') + expected = slice(3288, 3653) + self.assert_(result == expected) + + def test_slice_quarter(self): + dti = DatetimeIndex(freq='D', start=datetime(2000, 6, 1), periods=500) + + s = Series(np.arange(len(dti)), index=dti) + self.assertEquals(len(s['2001Q1']), 90) + + df = DataFrame(np.random.rand(len(dti), 5), index=dti) + self.assertEquals(len(df.ix['1Q01']), 90) + + def test_slice_month(self): + dti = DatetimeIndex(freq='D', start=datetime(2005, 1, 1), periods=500) + s = Series(np.arange(len(dti)), index=dti) + self.assertEquals(len(s['2005-11']), 30) + + df = DataFrame(np.random.rand(len(dti), 5), index=dti) + self.assertEquals(len(df.ix['2005-11']), 30) + + assert_series_equal(s['2005-11'], s['11-2005']) + + def test_partial_slice(self): + rng = DatetimeIndex(freq='D', start=datetime(2005, 1, 1), periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s['2005-05':'2006-02'] + expected = s['20050501':'20060228'] + assert_series_equal(result, expected) + + result = s['2005-05':] + expected = s['20050501':] + assert_series_equal(result, expected) + + result = s[:'2006-02'] + expected = s[:'20060228'] + assert_series_equal(result, expected) + + result = s['2005-1-1'] + self.assert_(result == s.irow(0)) + + self.assertRaises(Exception, s.__getitem__, '2004-12-31') + + def test_partial_slice_daily(self): + rng = DatetimeIndex(freq='H', start=datetime(2005, 1, 31), periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s['2005-1-31'] + assert_series_equal(result, s.ix[:24]) + + self.assertRaises(Exception, s.__getitem__, '2004-12-31 00') + + def test_partial_slice_hourly(self): + rng = DatetimeIndex(freq='T', start=datetime(2005, 1, 1, 20, 0, 0), + periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s['2005-1-1'] + assert_series_equal(result, s.ix[:60 * 4]) + + result = s['2005-1-1 20'] + assert_series_equal(result, s.ix[:60]) + + self.assert_(s['2005-1-1 20:00'] == s.ix[0]) + self.assertRaises(Exception, s.__getitem__, '2004-12-31 00:15') + + def test_partial_slice_minutely(self): + rng = DatetimeIndex(freq='S', start=datetime(2005, 1, 1, 23, 59, 0), + periods=500) + s = Series(np.arange(len(rng)), index=rng) + + result = s['2005-1-1 23:59'] + assert_series_equal(result, s.ix[:60]) + + result = s['2005-1-1'] + assert_series_equal(result, s.ix[:60]) + + self.assert_(s[Timestamp('2005-1-1 23:59:00')] == s.ix[0]) + self.assertRaises(Exception, s.__getitem__, '2004-12-31 00:00:00') + + def test_partial_slicing_with_multiindex(self): + + # GH 4758 + # partial string indexing with a multi-index buggy + df = DataFrame({'ACCOUNT':["ACCT1", "ACCT1", "ACCT1", "ACCT2"], + 'TICKER':["ABC", "MNP", "XYZ", "XYZ"], + 'val':[1,2,3,4]}, + index=date_range("2013-06-19 09:30:00", periods=4, freq='5T')) + df_multi = df.set_index(['ACCOUNT', 'TICKER'], append=True) + + expected = DataFrame([[1]],index=Index(['ABC'],name='TICKER'),columns=['val']) + result = df_multi.loc[('2013-06-19 09:30:00', 'ACCT1')] + assert_frame_equal(result, expected) + + expected = df_multi.loc[(pd.Timestamp('2013-06-19 09:30:00', tz=None), 'ACCT1', 'ABC')] + result = df_multi.loc[('2013-06-19 09:30:00', 'ACCT1', 'ABC')] + assert_series_equal(result, expected) + + # this is a KeyError as we don't do partial string selection on multi-levels + def f(): + df_multi.loc[('2013-06-19', 'ACCT1', 'ABC')] + self.assertRaises(KeyError, f) + + def test_date_range_normalize(self): + snap = datetime.today() + n = 50 + + rng = date_range(snap, periods=n, normalize=False, freq='2D') + + offset = timedelta(2) + values = np.array([snap + i * offset for i in range(n)], + dtype='M8[ns]') + + self.assert_(np.array_equal(rng, values)) + + rng = date_range( + '1/1/2000 08:15', periods=n, normalize=False, freq='B') + the_time = time(8, 15) + for val in rng: + self.assert_(val.time() == the_time) + + def test_timedelta(self): + # this is valid too + index = date_range('1/1/2000', periods=50, freq='B') + shifted = index + timedelta(1) + back = shifted + timedelta(-1) + self.assert_(tm.equalContents(index, back)) + self.assertEqual(shifted.freq, index.freq) + self.assertEqual(shifted.freq, back.freq) + + result = index - timedelta(1) + expected = index + timedelta(-1) + self.assert_(result.equals(expected)) + + # GH4134, buggy with timedeltas + rng = date_range('2013', '2014') + s = Series(rng) + result1 = rng - pd.offsets.Hour(1) + result2 = DatetimeIndex(s - np.timedelta64(100000000)) + result3 = rng - np.timedelta64(100000000) + result4 = DatetimeIndex(s - pd.offsets.Hour(1)) + self.assert_(result1.equals(result4)) + self.assert_(result2.equals(result3)) + + def test_shift(self): + ts = Series(np.random.randn(5), + index=date_range('1/1/2000', periods=5, freq='H')) + + result = ts.shift(1, freq='5T') + exp_index = ts.index.shift(1, freq='5T') + self.assert_(result.index.equals(exp_index)) + + # GH #1063, multiple of same base + result = ts.shift(1, freq='4H') + exp_index = ts.index + datetools.Hour(4) + self.assert_(result.index.equals(exp_index)) + + idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04']) + self.assertRaises(ValueError, idx.shift, 1) + + def test_setops_preserve_freq(self): + rng = date_range('1/1/2000', '1/1/2002') + + result = rng[:50].union(rng[50:100]) + self.assert_(result.freq == rng.freq) + + result = rng[:50].union(rng[30:100]) + self.assert_(result.freq == rng.freq) + + result = rng[:50].union(rng[60:100]) + self.assert_(result.freq is None) + + result = rng[:50].intersection(rng[25:75]) + self.assert_(result.freqstr == 'D') + + nofreq = DatetimeIndex(list(rng[25:75])) + result = rng[:50].union(nofreq) + self.assert_(result.freq == rng.freq) + + result = rng[:50].intersection(nofreq) + self.assert_(result.freq == rng.freq) + + def test_min_max(self): + rng = date_range('1/1/2000', '12/31/2000') + rng2 = rng.take(np.random.permutation(len(rng))) + + the_min = rng2.min() + the_max = rng2.max() + tm.assert_isinstance(the_min, Timestamp) + tm.assert_isinstance(the_max, Timestamp) + self.assertEqual(the_min, rng[0]) + self.assertEqual(the_max, rng[-1]) + + self.assertEqual(rng.min(), rng[0]) + self.assertEqual(rng.max(), rng[-1]) + + def test_min_max_series(self): + rng = date_range('1/1/2000', periods=10, freq='4h') + lvls = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'] + df = DataFrame({'TS': rng, 'V': np.random.randn(len(rng)), + 'L': lvls}) + + result = df.TS.max() + exp = Timestamp(df.TS.iget(-1)) + self.assertTrue(isinstance(result, Timestamp)) + self.assertEqual(result, exp) + + result = df.TS.min() + exp = Timestamp(df.TS.iget(0)) + self.assertTrue(isinstance(result, Timestamp)) + self.assertEqual(result, exp) + + def test_from_M8_structured(self): + dates = [(datetime(2012, 9, 9, 0, 0), + datetime(2012, 9, 8, 15, 10))] + arr = np.array(dates, + dtype=[('Date', 'M8[us]'), ('Forecasting', 'M8[us]')]) + df = DataFrame(arr) + + self.assertEqual(df['Date'][0], dates[0][0]) + self.assertEqual(df['Forecasting'][0], dates[0][1]) + + s = Series(arr['Date']) + self.assertTrue(s[0], Timestamp) + self.assertEqual(s[0], dates[0][0]) + + s = Series.from_array(arr['Date'], Index([0])) + self.assertEqual(s[0], dates[0][0]) + + def test_get_level_values_box(self): + from pandas import MultiIndex + + dates = date_range('1/1/2000', periods=4) + levels = [dates, [0, 1]] + labels = [[0, 0, 1, 1, 2, 2, 3, 3], + [0, 1, 0, 1, 0, 1, 0, 1]] + + index = MultiIndex(levels=levels, labels=labels) + + self.assertTrue(isinstance(index.get_level_values(0)[0], Timestamp)) + + def test_frame_apply_dont_convert_datetime64(self): + from pandas.tseries.offsets import BDay + df = DataFrame({'x1': [datetime(1996, 1, 1)]}) + + df = df.applymap(lambda x: x + BDay()) + df = df.applymap(lambda x: x + BDay()) + + self.assertTrue(df.x1.dtype == 'M8[ns]') if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], diff --git a/pandas/tseries/tests/test_timeseries_legacy.py b/pandas/tseries/tests/test_timeseries_legacy.py new file mode 100644 index 0000000000000..babf60758f751 --- /dev/null +++ b/pandas/tseries/tests/test_timeseries_legacy.py @@ -0,0 +1,300 @@ +# pylint: disable-msg=E1101,W0612 +from datetime import datetime, time, timedelta +import sys +import os +import unittest + +import nose + +import numpy as np +randn = np.random.randn + +from pandas import (Index, Series, TimeSeries, DataFrame, + isnull, date_range, Timestamp, DatetimeIndex, + Int64Index, to_datetime, bdate_range) + +from pandas.core.daterange import DateRange +import pandas.core.datetools as datetools +import pandas.tseries.offsets as offsets +import pandas.tseries.frequencies as fmod +import pandas as pd + +from pandas.util.testing import assert_series_equal, assert_almost_equal +import pandas.util.testing as tm + +from pandas.tslib import NaT, iNaT +import pandas.lib as lib +import pandas.tslib as tslib + +import pandas.index as _index + +from pandas.compat import( + range, long, StringIO, lrange, lmap, map, zip, cPickle as pickle, product +) +from pandas import read_pickle +import pandas.core.datetools as dt +from numpy.random import rand +from numpy.testing import assert_array_equal +from pandas.util.testing import assert_frame_equal +import pandas.compat as compat +from pandas.core.datetools import BDay +import pandas.core.common as com +from pandas import concat + +from numpy.testing.decorators import slow + + +def _skip_if_no_pytz(): + try: + import pytz + except ImportError: + raise nose.SkipTest + +# infortunately, too much has changed to handle these legacy pickles +# class TestLegacySupport(unittest.TestCase): +class LegacySupport(object): + + _multiprocess_can_split_ = True + + @classmethod + def setUpClass(cls): + if compat.PY3: + raise nose.SkipTest + + pth, _ = os.path.split(os.path.abspath(__file__)) + filepath = os.path.join(pth, 'data', 'frame.pickle') + + with open(filepath, 'rb') as f: + cls.frame = pickle.load(f) + + filepath = os.path.join(pth, 'data', 'series.pickle') + with open(filepath, 'rb') as f: + cls.series = pickle.load(f) + + def test_pass_offset_warn(self): + buf = StringIO() + + sys.stderr = buf + DatetimeIndex(start='1/1/2000', periods=10, offset='H') + sys.stderr = sys.__stderr__ + + def test_unpickle_legacy_frame(self): + dtindex = DatetimeIndex(start='1/3/2005', end='1/14/2005', + freq=BDay(1)) + + unpickled = self.frame + + self.assertEquals(type(unpickled.index), DatetimeIndex) + self.assertEquals(len(unpickled), 10) + self.assert_((unpickled.columns == Int64Index(np.arange(5))).all()) + self.assert_((unpickled.index == dtindex).all()) + self.assertEquals(unpickled.index.offset, BDay(1, normalize=True)) + + def test_unpickle_legacy_series(self): + from pandas.core.datetools import BDay + + unpickled = self.series + + dtindex = DatetimeIndex(start='1/3/2005', end='1/14/2005', + freq=BDay(1)) + + self.assertEquals(type(unpickled.index), DatetimeIndex) + self.assertEquals(len(unpickled), 10) + self.assert_((unpickled.index == dtindex).all()) + self.assertEquals(unpickled.index.offset, BDay(1, normalize=True)) + + def test_unpickle_legacy_len0_daterange(self): + pth, _ = os.path.split(os.path.abspath(__file__)) + filepath = os.path.join(pth, 'data', 'series_daterange0.pickle') + + result = pd.read_pickle(filepath) + + ex_index = DatetimeIndex([], freq='B') + + self.assert_(result.index.equals(ex_index)) + tm.assert_isinstance(result.index.freq, offsets.BDay) + self.assert_(len(result) == 0) + + def test_arithmetic_interaction(self): + index = self.frame.index + obj_index = index.asobject + + dseries = Series(rand(len(index)), index=index) + oseries = Series(dseries.values, index=obj_index) + + result = dseries + oseries + expected = dseries * 2 + tm.assert_isinstance(result.index, DatetimeIndex) + assert_series_equal(result, expected) + + result = dseries + oseries[:5] + expected = dseries + dseries[:5] + tm.assert_isinstance(result.index, DatetimeIndex) + assert_series_equal(result, expected) + + def test_join_interaction(self): + index = self.frame.index + obj_index = index.asobject + + def _check_join(left, right, how='inner'): + ra, rb, rc = left.join(right, how=how, return_indexers=True) + ea, eb, ec = left.join(DatetimeIndex(right), how=how, + return_indexers=True) + + tm.assert_isinstance(ra, DatetimeIndex) + self.assert_(ra.equals(ea)) + + assert_almost_equal(rb, eb) + assert_almost_equal(rc, ec) + + _check_join(index[:15], obj_index[5:], how='inner') + _check_join(index[:15], obj_index[5:], how='outer') + _check_join(index[:15], obj_index[5:], how='right') + _check_join(index[:15], obj_index[5:], how='left') + + def test_join_nonunique(self): + idx1 = to_datetime(['2012-11-06 16:00:11.477563', + '2012-11-06 16:00:11.477563']) + idx2 = to_datetime(['2012-11-06 15:11:09.006507', + '2012-11-06 15:11:09.006507']) + rs = idx1.join(idx2, how='outer') + self.assert_(rs.is_monotonic) + + def test_unpickle_daterange(self): + pth, _ = os.path.split(os.path.abspath(__file__)) + filepath = os.path.join(pth, 'data', 'daterange_073.pickle') + + rng = read_pickle(filepath) + tm.assert_isinstance(rng[0], datetime) + tm.assert_isinstance(rng.offset, offsets.BDay) + self.assert_(rng.values.dtype == object) + + def test_setops(self): + index = self.frame.index + obj_index = index.asobject + + result = index[:5].union(obj_index[5:]) + expected = index + tm.assert_isinstance(result, DatetimeIndex) + self.assert_(result.equals(expected)) + + result = index[:10].intersection(obj_index[5:]) + expected = index[5:10] + tm.assert_isinstance(result, DatetimeIndex) + self.assert_(result.equals(expected)) + + result = index[:10] - obj_index[5:] + expected = index[:5] + tm.assert_isinstance(result, DatetimeIndex) + self.assert_(result.equals(expected)) + + def test_index_conversion(self): + index = self.frame.index + obj_index = index.asobject + + conv = DatetimeIndex(obj_index) + self.assert_(conv.equals(index)) + + self.assertRaises(ValueError, DatetimeIndex, ['a', 'b', 'c', 'd']) + + def test_tolist(self): + rng = date_range('1/1/2000', periods=10) + + result = rng.tolist() + tm.assert_isinstance(result[0], Timestamp) + + def test_object_convert_fail(self): + idx = DatetimeIndex([NaT]) + self.assertRaises(ValueError, idx.astype, 'O') + + def test_setops_conversion_fail(self): + index = self.frame.index + + right = Index(['a', 'b', 'c', 'd']) + + result = index.union(right) + expected = Index(np.concatenate([index.asobject, right])) + self.assert_(result.equals(expected)) + + result = index.intersection(right) + expected = Index([]) + self.assert_(result.equals(expected)) + + def test_legacy_time_rules(self): + rules = [('WEEKDAY', 'B'), + ('EOM', 'BM'), + ('W@MON', 'W-MON'), ('W@TUE', 'W-TUE'), ('W@WED', 'W-WED'), + ('W@THU', 'W-THU'), ('W@FRI', 'W-FRI'), + ('Q@JAN', 'BQ-JAN'), ('Q@FEB', 'BQ-FEB'), ('Q@MAR', 'BQ-MAR'), + ('A@JAN', 'BA-JAN'), ('A@FEB', 'BA-FEB'), ('A@MAR', 'BA-MAR'), + ('A@APR', 'BA-APR'), ('A@MAY', 'BA-MAY'), ('A@JUN', 'BA-JUN'), + ('A@JUL', 'BA-JUL'), ('A@AUG', 'BA-AUG'), ('A@SEP', 'BA-SEP'), + ('A@OCT', 'BA-OCT'), ('A@NOV', 'BA-NOV'), ('A@DEC', 'BA-DEC'), + ('WOM@1FRI', 'WOM-1FRI'), ('WOM@2FRI', 'WOM-2FRI'), + ('WOM@3FRI', 'WOM-3FRI'), ('WOM@4FRI', 'WOM-4FRI')] + + start, end = '1/1/2000', '1/1/2010' + + for old_freq, new_freq in rules: + old_rng = date_range(start, end, freq=old_freq) + new_rng = date_range(start, end, freq=new_freq) + self.assert_(old_rng.equals(new_rng)) + + # test get_legacy_offset_name + offset = datetools.get_offset(new_freq) + old_name = datetools.get_legacy_offset_name(offset) + self.assertEquals(old_name, old_freq) + + def test_ms_vs_MS(self): + left = datetools.get_offset('ms') + right = datetools.get_offset('MS') + self.assert_(left == datetools.Milli()) + self.assert_(right == datetools.MonthBegin()) + + def test_rule_aliases(self): + rule = datetools.to_offset('10us') + self.assert_(rule == datetools.Micro(10)) + +class TestLegacyCompat(unittest.TestCase): + + def setUp(self): + # suppress deprecation warnings + sys.stderr = StringIO() + + def test_inferTimeRule(self): + from pandas.tseries.frequencies import inferTimeRule + + index1 = [datetime(2010, 1, 29, 0, 0), + datetime(2010, 2, 26, 0, 0), + datetime(2010, 3, 31, 0, 0)] + + index2 = [datetime(2010, 3, 26, 0, 0), + datetime(2010, 3, 29, 0, 0), + datetime(2010, 3, 30, 0, 0)] + + index3 = [datetime(2010, 3, 26, 0, 0), + datetime(2010, 3, 27, 0, 0), + datetime(2010, 3, 29, 0, 0)] + + # LEGACY + assert inferTimeRule(index1) == 'EOM' + assert inferTimeRule(index2) == 'WEEKDAY' + + self.assertRaises(Exception, inferTimeRule, index1[:2]) + self.assertRaises(Exception, inferTimeRule, index3) + + def test_time_rule(self): + result = DateRange('1/1/2000', '1/30/2000', time_rule='WEEKDAY') + result2 = DateRange('1/1/2000', '1/30/2000', timeRule='WEEKDAY') + expected = date_range('1/1/2000', '1/30/2000', freq='B') + + self.assert_(result.equals(expected)) + self.assert_(result2.equals(expected)) + + def tearDown(self): + sys.stderr = sys.__stderr__ + + +if __name__ == '__main__': + nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], + exit=False)
closes #4758 ``` In [2]: df = DataFrame({'ACCOUNT':["ACCT1", "ACCT1", "ACCT1", "ACCT2"], ...: 'TICKER':["ABC", "MNP", "XYZ", "XYZ"], ...: 'val':[1,2,3,4]}, ...: index=date_range("2013-06-19 09:30:00", periods=4, freq='5T')) In [3]: df_multi = df.set_index(['ACCOUNT', 'TICKER'], append=True) In [4]: df_multi.loc[(pd.Timestamp('2013-06-19 09:30:00', tz=None), 'ACCT1', 'ABC')] Out[4]: val 1 Name: (2013-06-19 09:30:00, ACCT1, ABC), dtype: int64 In [5]: df_multi.loc[('2013-06-19 09:30:00', 'ACCT1', 'ABC')] Out[5]: val 1 Name: (2013-06-19 09:30:00, ACCT1, ABC), dtype: int64 ``` This is quite difficult to do, a partial selection on a single indexer, so KeyError for now ``` In [6]: df_multi.loc[('2013-06-19', 'ACCT1', 'ABC')] KeyError: 'the label [ACCT1] is not in the [columns]' ```
https://api.github.com/repos/pandas-dev/pandas/pulls/4761
2013-09-06T03:08:12Z
2013-09-06T08:16:56Z
2013-09-06T08:16:56Z
2014-07-02T05:01:36Z