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
API: allow the iloc indexer to run off the end and not raise IndexError (GH6296)
diff --git a/doc/source/10min.rst b/doc/source/10min.rst index 90198fa48bcb4..7fc6f6d197dff 100644 --- a/doc/source/10min.rst +++ b/doc/source/10min.rst @@ -273,25 +273,6 @@ For getting fast access to a scalar (equiv to the prior method) df.iat[1,1] -There is one signficant departure from standard python/numpy slicing semantics. -python/numpy allow slicing past the end of an array without an associated -error. - -.. ipython:: python - - # these are allowed in python/numpy. - x = list('abcdef') - x[4:10] - x[8:10] - -Pandas will detect this and raise ``IndexError``, rather than return an empty -structure. - -:: - - >>> df.iloc[:,8:10] - IndexError: out-of-bounds on slice (end) - Boolean Indexing ~~~~~~~~~~~~~~~~ diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 0c4b57358d3d1..d65c1519fe869 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -77,8 +77,9 @@ of multi-axis indexing. See more at :ref:`Selection by Label <indexing.label>` - ``.iloc`` is strictly integer position based (from ``0`` to ``length-1`` of - the axis), will raise ``IndexError`` when the requested indicies are out of - bounds. Allowed inputs are: + the axis), will raise ``IndexError`` if a single index is requested and it + is out-of-bounds, otherwise it will conform the bounds to size of the object. + Allowed inputs are: - An integer e.g. ``5`` - A list or array of integers ``[4, 3, 0]`` @@ -420,12 +421,19 @@ python/numpy allow slicing past the end of an array without an associated error. x[4:10] x[8:10] -Pandas will detect this and raise ``IndexError``, rather than return an empty structure. +- as of v0.14.0, ``iloc`` will now accept out-of-bounds indexers, e.g. a value that exceeds the length of the object being + indexed. These will be excluded. This will make pandas conform more with pandas/numpy indexing of out-of-bounds + values. A single indexer that is out-of-bounds and drops the dimensions of the object will still raise + ``IndexError`` (:issue:`6296`). This could result in an empty axis (e.g. an empty DataFrame being returned) -:: + .. ipython:: python - >>> df.iloc[:,3:6] - IndexError: out-of-bounds on slice (end) + df = DataFrame(np.random.randn(5,2),columns=list('AB')) + df + df.iloc[[4,5,6]] + df.iloc[4:6] + df.iloc[:,2:3] + df.iloc[:,1:3] .. _indexing.basics.partial_setting: diff --git a/doc/source/release.rst b/doc/source/release.rst index 4d2130979392d..d3814ab324e92 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -56,6 +56,10 @@ New features API Changes ~~~~~~~~~~~ +- ``iloc`` will now accept out-of-bounds indexers, e.g. a value that exceeds the length of the object being + indexed. These will be excluded. This will make pandas conform more with pandas/numpy indexing of out-of-bounds + values. A single indexer that is out-of-bounds and drops the dimensions of the object will still raise + ``IndexError`` (:issue:`6296`) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt index d044c254f9482..ee38fed810af0 100644 --- a/doc/source/v0.14.0.txt +++ b/doc/source/v0.14.0.txt @@ -15,6 +15,20 @@ Highlights include: API changes ~~~~~~~~~~~ +- ``iloc`` will now accept out-of-bounds indexers, e.g. a value that exceeds the length of the object being + indexed. These will be excluded. This will make pandas conform more with pandas/numpy indexing of out-of-bounds + values. A single indexer that is out-of-bounds and drops the dimensions of the object will still raise + ``IndexError`` (:issue:`6296`). This could result in an empty axis (e.g. an empty DataFrame being returned) + + .. ipython:: python + + df = DataFrame(np.random.randn(5,2),columns=list('AB')) + df + df.iloc[[4,5,6]] + df.iloc[4:6] + df.iloc[:,2:3] + df.iloc[:,1:3] + Prior Version Deprecations/Changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 68b35db3827c8..03e16f243836a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1756,10 +1756,6 @@ def head(self, n=5): l = len(self) if l == 0 or n==0: return self - if n > l: - n = l - elif n < -l: - n = -l return self.iloc[:n] def tail(self, n=5): @@ -1769,10 +1765,6 @@ def tail(self, n=5): l = len(self) if l == 0 or n == 0: return self - if n > l: - n = l - elif n < -l: - n = -l return self.iloc[-n:] #---------------------------------------------------------------------- diff --git a/pandas/core/index.py b/pandas/core/index.py index 3b58b27c7569f..5a02c0445c006 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -621,9 +621,15 @@ def __getitem__(self, key): if com._is_bool_indexer(key): key = np.asarray(key) - result = arr_idx[key] - if result.ndim > 1: - return result + try: + result = arr_idx[key] + if result.ndim > 1: + return result + except (IndexError): + if not len(key): + result = [] + else: + raise return Index(result, name=self.name) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index d2f538decd576..029055d80b1af 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -73,6 +73,29 @@ def _get_loc(self, key, axis=0): return self.obj._ixs(key, axis=axis) def _slice(self, obj, axis=0, raise_on_error=False, typ=None): + + # make out-of-bounds into bounds of the object + if typ == 'iloc': + ax = self.obj._get_axis(axis) + l = len(ax) + start = obj.start + stop = obj.stop + step = obj.step + if start is not None: + # degenerate to return nothing + if start >= l: + return self._getitem_axis(tuple(),axis=axis) + + # equiv to a null slice + elif start <= -l: + start = None + if stop is not None: + if stop > l: + stop = None + elif stop <= -l: + stop = None + obj = slice(start,stop,step) + return self.obj._slice(obj, axis=axis, raise_on_error=raise_on_error, typ=typ) @@ -1188,14 +1211,23 @@ def _getitem_tuple(self, tup): pass retval = self.obj + axis=0 for i, key in enumerate(tup): if i >= self.obj.ndim: raise IndexingError('Too many indexers') if _is_null_slice(key): + axis += 1 continue - retval = getattr(retval, self.name)._getitem_axis(key, axis=i) + retval = getattr(retval, self.name)._getitem_axis(key, axis=axis) + + # if the dim was reduced, then pass a lower-dim the next time + if retval.ndim<self.ndim: + axis -= 1 + + # try to get for the next axis + axis += 1 return retval @@ -1224,10 +1256,18 @@ def _getitem_axis(self, key, axis=0): # a single integer or a list of integers else: + ax = self.obj._get_axis(axis) if _is_list_like(key): + # coerce the key to not exceed the maximum size of the index + arr = np.array(key) + l = len(ax) + if len(arr) and (arr.max() >= l or arr.min() <= -l): + key = arr[(arr>-l) & (arr<l)] + # force an actual list key = list(key) + else: key = self._convert_scalar_indexer(key, axis) @@ -1235,6 +1275,9 @@ def _getitem_axis(self, key, axis=0): raise TypeError("Cannot index by location index with a " "non-integer key") + if key > len(ax): + raise IndexError("single indexer is out-of-bounds") + return self._get_loc(key, axis=axis) def _convert_to_indexer(self, obj, axis=0, is_setter=False): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index d0a8e1c06fd28..a7e1548b41bbb 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3246,7 +3246,7 @@ def reindex_indexer(self, new_axis, indexer, axis=1, fill_value=None, pandas-indexer with -1's only. """ # trying to reindex on an axis with duplicates - if not allow_dups and not self.axes[axis].is_unique: + if not allow_dups and not self.axes[axis].is_unique and len(indexer): raise ValueError("cannot reindex from a duplicate axis") if not self.is_consolidated(): diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index 958ca81b0a2ee..6c7e455bb1c03 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -873,7 +873,7 @@ def test_equals(self): s2[0] = 9.9 self.assert_(not s1.equals(s2)) - + idx = MultiIndex.from_tuples([(0, 'a'), (1, 'b'), (2, 'c')]) s1 = Series([1, 2, np.nan], index=idx) s2 = s1.copy() @@ -900,17 +900,17 @@ def test_equals(self): # different dtype different = df1.copy() different['floats'] = different['floats'].astype('float32') - self.assert_(not df1.equals(different)) + self.assert_(not df1.equals(different)) # different index different_index = -index different = df2.set_index(different_index) - self.assert_(not df1.equals(different)) + self.assert_(not df1.equals(different)) # different columns different = df2.copy() different.columns = df2.columns[::-1] - self.assert_(not df1.equals(different)) + self.assert_(not df1.equals(different)) # DatetimeIndex index = pd.date_range('2000-1-1', periods=10, freq='T') diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 97cdc5ff349a1..52de461f0281b 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -339,6 +339,72 @@ def test_repeated_getitem_dups(self): result = df.loc[:,0].loc['A'] assert_series_equal(result,expected) + def test_iloc_exceeds_bounds(self): + + # GH6296 + # iloc should allow indexers that exceed the bounds + df = DataFrame(np.random.random_sample((20,5)), columns=list('ABCDE')) + expected = df + result = df.iloc[:,[0,1,2,3,4,5]] + assert_frame_equal(result,expected) + + result = df.iloc[[1,30]] + expected = df.iloc[[1]] + assert_frame_equal(result,expected) + + result = df.iloc[[1,-30]] + expected = df.iloc[[1]] + assert_frame_equal(result,expected) + + result = df.iloc[:,4:10] + expected = df.iloc[:,4:] + assert_frame_equal(result,expected) + + result = df.iloc[:,-4:-10] + expected = df.iloc[:,-4:] + assert_frame_equal(result,expected) + + result = df.iloc[[100]] + expected = DataFrame(columns=df.columns) + assert_frame_equal(result,expected) + + # still raise on a single indexer + def f(): + df.iloc[30] + self.assertRaises(IndexError, f) + + s = df['A'] + result = s.iloc[[100]] + expected = Series() + assert_series_equal(result,expected) + + result = s.iloc[[-100]] + expected = Series() + assert_series_equal(result,expected) + + # slice + result = s.iloc[18:30] + expected = s.iloc[18:] + assert_series_equal(result,expected) + + # doc example + df = DataFrame(np.random.randn(5,2),columns=list('AB')) + result = df.iloc[[4,5,6]] + expected = df.iloc[[4]] + assert_frame_equal(result,expected) + + result = df.iloc[4:6] + expected = df.iloc[[4]] + assert_frame_equal(result,expected) + + result = df.iloc[:,2:3] + expected = DataFrame(index=df.index) + assert_frame_equal(result,expected) + + result = df.iloc[:,1:3] + expected = df.iloc[:,[1]] + assert_frame_equal(result,expected) + def test_iloc_getitem_int(self): # integer @@ -442,14 +508,6 @@ def test_iloc_getitem_multiindex(self): xp = df.xs('b',drop_level=False) assert_frame_equal(rs,xp) - def test_iloc_getitem_out_of_bounds(self): - - # out-of-bounds slice - self.assertRaises(IndexError, self.frame_ints.iloc.__getitem__, tuple([slice(None),slice(1,5,None)])) - self.assertRaises(IndexError, self.frame_ints.iloc.__getitem__, tuple([slice(None),slice(-5,3,None)])) - self.assertRaises(IndexError, self.frame_ints.iloc.__getitem__, tuple([slice(1,5,None)])) - self.assertRaises(IndexError, self.frame_ints.iloc.__getitem__, tuple([slice(-5,3,None)])) - def test_iloc_setitem(self): df = self.frame_ints @@ -738,12 +796,6 @@ def test_iloc_getitem_frame(self): expected = df.ix[[2,4,6,8]] assert_frame_equal(result, expected) - # out-of-bounds slice - self.assertRaises(IndexError, df.iloc.__getitem__, tuple([slice(None),slice(1,5,None)])) - self.assertRaises(IndexError, df.iloc.__getitem__, tuple([slice(None),slice(-5,3,None)])) - self.assertRaises(IndexError, df.iloc.__getitem__, tuple([slice(1,11,None)])) - self.assertRaises(IndexError, df.iloc.__getitem__, tuple([slice(-11,3,None)])) - # try with labelled frame df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD'))
closes #6296 Here's the behavior I left it raising an `IndexError` if a single indexer is given that is out-of-bounds (consistent with the way `ix/loc` would work) ``` In [1]: df = DataFrame(np.random.randn(5,2),columns=list('AB')) In [2]: df Out[2]: A B 0 1.105982 0.309531 1 -0.619102 -0.002967 2 -0.817371 0.270714 3 1.569206 1.595204 4 0.276390 -1.316232 [5 rows x 2 columns] In [3]: df.iloc[[4,5,6]] Out[3]: A B 4 0.27639 -1.316232 [1 rows x 2 columns] In [4]: df.iloc[4:6] Out[4]: A B 4 0.27639 -1.316232 [1 rows x 2 columns] In [5]: df.iloc[:,2:3] Out[5]: Empty DataFrame Columns: [] Index: [0, 1, 2, 3, 4] [5 rows x 0 columns] In [6]: df.iloc[:,1:3] Out[6]: B 0 0.309531 1 -0.002967 2 0.270714 3 1.595204 4 -1.316232 [5 rows x 1 columns] In [7]: df.iloc[10] IndexError: ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6299
2014-02-07T22:02:01Z
2014-02-08T15:53:33Z
2014-02-08T15:53:33Z
2014-06-16T19:22:59Z
DOC: clean-up docstrings of sql + fix doc build
diff --git a/doc/source/io.rst b/doc/source/io.rst index f8986ce997999..e4af9534efc7e 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3133,12 +3133,14 @@ the database using :func:`~pandas.io.sql.to_sql`. .. ipython:: python :suppress: + import datetime c = ['id', 'Date', 'Col_1', 'Col_2', 'Col_3'] d = [(26, datetime.datetime(2010,10,18), 'X', 27.5, True), (42, datetime.datetime(2010,10,19), 'Y', -12.5, False), (63, datetime.datetime(2010,10,20), 'Z', 5.73, True)] data = DataFrame(d, columns=c) + sql.to_sql(data, 'data', engine) Reading Tables ~~~~~~~~~~~~~~ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index e705a3b20585a..989f6983b28d3 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -80,14 +80,14 @@ def execute(sql, con, cur=None, params=None, flavor='sqlite'): Parameters ---------- - sql: string + sql : string Query to be executed - con: SQLAlchemy engine or DBAPI2 connection (legacy mode) + con : SQLAlchemy engine or DBAPI2 connection (legacy mode) Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, a supported SQL flavor must also be provided - cur: depreciated, cursor is obtained from connection - params: list or tuple, optional + cur : depreciated, cursor is obtained from connection + params : list or tuple, optional List of parameters to pass to execute method. flavor : string "sqlite", "mysql" Specifies the flavor of SQL to use. @@ -178,42 +178,46 @@ def read_sql(sql, con, index_col=None, flavor='sqlite', coerce_float=True, Returns a DataFrame corresponding to the result set of the query string. - Optionally provide an index_col parameter to use one of the - columns as the index, otherwise default integer index will be used + Optionally provide an `index_col` parameter to use one of the + columns as the index, otherwise default integer index will be used. Parameters ---------- - sql: string + sql : string SQL query to be executed - con: SQLAlchemy engine or DBAPI2 connection (legacy mode) + con : SQLAlchemy engine or DBAPI2 connection (legacy mode) Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object is given, a supported SQL flavor must also be provided - index_col: string, optional + index_col : string, optional column name to use for the returned DataFrame object. - flavor : string specifying the flavor of SQL to use. Ignored when using + flavor : string, {'sqlite', 'mysql'} + The flavor of SQL to use. Ignored when using SQLAlchemy engine. Required when using DBAPI2 connection. coerce_float : boolean, default True Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets - cur: depreciated, cursor is obtained from connection - params: list or tuple, optional + cur : depreciated, cursor is obtained from connection + params : list or tuple, optional List of parameters to pass to execute method. - parse_dates: list or dict - List of column names to parse as dates - Or - Dict of {column_name: format string} where format string is - strftime compatible in case of parsing string times or is one of - (D, s, ns, ms, us) in case of parsing integer timestamps - Or - Dict of {column_name: arg dict}, where the arg dict corresponds - to the keyword arguments of :func:`pandas.tseries.tools.to_datetime` - Especially useful with databases without native Datetime support, - such as SQLite + parse_dates : list or dict + - List of column names to parse as dates + - Dict of ``{column_name: format string}`` where format string is + strftime compatible in case of parsing string times or is one of + (D, s, ns, ms, us) in case of parsing integer timestamps + - Dict of ``{column_name: arg dict}``, where the arg dict corresponds + to the keyword arguments of :func:`pandas.to_datetime` + Especially useful with databases without native Datetime support, + such as SQLite Returns ------- DataFrame + + See also + -------- + read_table + """ pandas_sql = pandasSQL_builder(con, flavor=flavor) return pandas_sql.read_sql(sql, @@ -229,20 +233,22 @@ def to_sql(frame, name, con, flavor='sqlite', if_exists='fail', index=True): Parameters ---------- - frame: DataFrame - name: name of SQL table - con: SQLAlchemy engine or DBAPI2 connection (legacy mode) + frame : DataFrame + name : string + Name of SQL table + con : SQLAlchemy engine or DBAPI2 connection (legacy mode) Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object is given, a supported SQL flavor must also be provided - flavor: {'sqlite', 'mysql', 'postgres'}, default 'sqlite' - ignored when SQLAlchemy engine. Required when using DBAPI2 connection. - 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. + flavor : {'sqlite', 'mysql'}, default 'sqlite' + The flavor of SQL to use. Ignored when using SQLAlchemy engine. + Required when using DBAPI2 connection. + 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. index : boolean, default True - Write DataFrame index as an column + Write DataFrame index as a column """ pandas_sql = pandasSQL_builder(con, flavor=flavor) pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index) @@ -250,17 +256,20 @@ def to_sql(frame, name, con, flavor='sqlite', if_exists='fail', index=True): def has_table(table_name, con, meta=None, flavor='sqlite'): """ - Check if DB has named table + Check if DataBase has named table. Parameters ---------- - frame: DataFrame - name: name of SQL table + table_name: string + Name of SQL table con: SQLAlchemy engine or DBAPI2 connection (legacy mode) Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object is given, a supported SQL flavor name must also be provided - flavor: {'sqlite', 'mysql'}, default 'sqlite', ignored when using engine + flavor: {'sqlite', 'mysql'}, default 'sqlite' + The flavor of SQL to use. Ignored when using SQLAlchemy engine. + Required when using DBAPI2 connection. + Returns ------- boolean @@ -272,33 +281,42 @@ def has_table(table_name, con, meta=None, flavor='sqlite'): def read_table(table_name, con, meta=None, index_col=None, coerce_float=True, parse_dates=None, columns=None): """Given a table name and SQLAlchemy engine, return a DataFrame. - Type convertions will be done automatically + + Type convertions will be done automatically. Parameters ---------- - table_name: name of SQL table in database - con: SQLAlchemy engine. Legacy mode not supported - meta: SQLAlchemy meta, optional. If omitted MetaData is reflected from engine - index_col: column to set as index, optional + table_name : string + Name of SQL table in database + con : SQLAlchemy engine + Legacy mode not supported + meta : SQLAlchemy meta, optional + If omitted MetaData is reflected from engine + index_col : string, optional + Column to set as index coerce_float : boolean, default True Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point. Can result in loss of Precision. - parse_dates: list or dict - List of column names to parse as dates - Or - Dict of {column_name: format string} where format string is - strftime compatible in case of parsing string times or is one of - (D, s, ns, ms, us) in case of parsing integer timestamps - Or - Dict of {column_name: arg dict}, where the arg dict corresponds - to the keyword arguments of :func:`pandas.tseries.tools.to_datetime` - Especially useful with databases without native Datetime support, - such as SQLite - columns: list + parse_dates : list or dict + - List of column names to parse as dates + - Dict of ``{column_name: format string}`` where format string is + strftime compatible in case of parsing string times or is one of + (D, s, ns, ms, us) in case of parsing integer timestamps + - Dict of ``{column_name: arg dict}``, where the arg dict corresponds + to the keyword arguments of :func:`pandas.to_datetime` + Especially useful with databases without native Datetime support, + such as SQLite + columns : list List of column names to select from sql table + Returns ------- DataFrame + + See also + -------- + read_sql + """ pandas_sql = PandasSQLAlchemy(con, meta=meta) table = pandas_sql.read_table(table_name, @@ -342,11 +360,12 @@ def pandasSQL_builder(con, flavor=None, meta=None): class PandasSQLTable(PandasObject): - """ For mapping Pandas tables to SQL tables. - Uses fact that table is reflected by SQLAlchemy to - do better type convertions. - Also holds various flags needed to avoid having to - pass them between functions all the time. + """ + For mapping Pandas tables to SQL tables. + Uses fact that table is reflected by SQLAlchemy to + do better type convertions. + Also holds various flags needed to avoid having to + pass them between functions all the time. """ # TODO: support for multiIndex def __init__(self, name, pandas_sql_engine, frame=None, index=True, @@ -556,7 +575,6 @@ def _numpy_type(self, sqltype): class PandasSQL(PandasObject): - """ Subclasses Should define read_sql and to_sql """ @@ -571,7 +589,6 @@ def to_sql(self, *args, **kwargs): class PandasSQLAlchemy(PandasSQL): - """ This class enables convertion between DataFrame and SQL databases using SQLAlchemy to handle DataBase abstraction
@mangecoeur I don't think I changed some real content, just some adjustments for the numpy docstring standards. Only for has_table I corrected the parameters. And the second commit should fix the doc builds (see http://pandas-docs.github.io/pandas-docs-travis/io.html#io-sql)
https://api.github.com/repos/pandas-dev/pandas/pulls/6298
2014-02-07T21:35:24Z
2014-02-09T22:40:32Z
2014-02-09T22:40:32Z
2014-06-26T12:27:21Z
BUG: preserve dtypes in interpolate
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f8dbe079610c0..b9ffeb636615b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2435,7 +2435,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, return self._constructor(new_data).__finalize__(self) def interpolate(self, method='linear', axis=0, limit=None, inplace=False, - downcast='infer', **kwargs): + downcast=None, **kwargs): """ Interpolate values according to different methods. @@ -2468,7 +2468,7 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, Maximum number of consecutive NaNs to fill. inplace : bool, default False Update the NDFrame in place if possible. - downcast : optional, 'infer' or None, defaults to 'infer' + downcast : optional, 'infer' or None, defaults to None Downcast dtypes if possible. Returns @@ -2492,7 +2492,6 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, dtype: float64 """ - if self.ndim > 2: raise NotImplementedError("Interpolate has not been implemented " "on Panel and Panel 4D objects.") @@ -2534,7 +2533,6 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, inplace=inplace, downcast=downcast, **kwargs) - if inplace: if axis == 1: self._update_inplace(new_data) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index c89aac0fa7923..6a1bd1000adce 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -826,6 +826,12 @@ def interpolate(self, method='pad', axis=0, index=None, m = None if m is not None: + # Skip interpolating this block if no NaNs. + if (~isnull(self.values)).all(): + if inplace: + return self + else: + return self.copy() return self._interpolate(method=m, index=index, values=values, diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index d694efff9b351..7e4b23b633477 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -459,7 +459,10 @@ def test_interpolate(self): self.assert_numpy_array_equal(time_interp, ord_ts) # try time interpolation on a non-TimeSeries - self.assertRaises(ValueError, self.series.interpolate, method='time') + # Only raises ValueError if there are NaNs. + non_ts = self.series.copy() + non_ts[0] = np.NaN + self.assertRaises(ValueError, non_ts.interpolate, method='time') def test_interp_regression(self): _skip_if_no_scipy() @@ -512,7 +515,7 @@ def test_interpolate_non_ts(self): def test_nan_interpolate(self): s = Series([0, 1, np.nan, 3]) result = s.interpolate() - expected = Series([0, 1, 2, 3]) + expected = Series([0., 1., 2., 3.]) assert_series_equal(result, expected) _skip_if_no_scipy() @@ -522,20 +525,20 @@ def test_nan_interpolate(self): 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]) + 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')) + 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]) + expected = Series([1., 4., 9., 16.], index=[1, 2, 3, 4]) assert_series_equal(result, expected) def test_interp_scipy_basic(self): @@ -545,18 +548,30 @@ def test_interp_scipy_basic(self): expected = Series([1., 3., 7.5, 12., 18.5, 25.]) result = s.interpolate(method='slinear') assert_series_equal(result, expected) + + result = s.interpolate(method='slinear', donwcast='infer') + assert_series_equal(result, expected) # nearest expected = Series([1, 3, 3, 12, 12, 25]) result = s.interpolate(method='nearest') + assert_series_equal(result, expected.astype('float')) + + result = s.interpolate(method='nearest', downcast='infer') assert_series_equal(result, expected) # zero expected = Series([1, 3, 3, 12, 12, 25]) result = s.interpolate(method='zero') + assert_series_equal(result, expected.astype('float')) + + result = s.interpolate(method='zero', downcast='infer') 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) + + result = s.interpolate(method='quadratic', downcast='infer') + assert_series_equal(result, expected) # cubic expected = Series([1., 3., 6.8, 12., 18.2, 25.]) result = s.interpolate(method='cubic') @@ -585,7 +600,6 @@ def test_interp_multiIndex(self): expected = s.copy() expected.loc[2] = 2 - expected = expected.astype(np.int64) result = s.interpolate() assert_series_equal(result, expected) @@ -595,7 +609,7 @@ def test_interp_multiIndex(self): def test_interp_nonmono_raise(self): _skip_if_no_scipy() - s = pd.Series([1, 2, 3], index=[0, 2, 1]) + s = Series([1, np.nan, 3], index=[0, 2, 1]) with tm.assertRaises(ValueError): s.interpolate(method='krogh') @@ -603,7 +617,7 @@ def test_interp_datetime64(self): _skip_if_no_scipy() df = Series([1, np.nan, 3], index=date_range('1/1/2000', periods=3)) result = df.interpolate(method='nearest') - expected = Series([1, 1, 3], index=date_range('1/1/2000', periods=3)) + expected = Series([1., 1., 3.], index=date_range('1/1/2000', periods=3)) assert_series_equal(result, expected) class TestDataFrame(tm.TestCase, Generic): @@ -639,7 +653,7 @@ def test_get_numeric_data_preserve_dtype(self): 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], + 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) @@ -648,8 +662,6 @@ def test_interp_basic(self): 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): @@ -663,9 +675,14 @@ def test_interp_combo(self): 'C': [1, 2, 3, 5], 'D': list('abcd')}) result = df['A'].interpolate() + expected = Series([1., 2., 3., 4.]) + assert_series_equal(result, expected) + + result = df['A'].interpolate(downcast='infer') 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') @@ -722,13 +739,16 @@ def test_interp_alt_scipy(self): expected = df.copy() expected['A'].iloc[2] = 3 expected['A'].iloc[5] = 6 + assert_frame_equal(result, expected) + + result = df.interpolate(method='barycentric', downcast='infer') assert_frame_equal(result, expected.astype(np.int64)) 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) + # expectedk['A'].iloc[2] = 3 + # expectedk['A'].iloc[5] = 6 + expectedk['A'] = expected['A'] assert_frame_equal(result, expectedk) _skip_if_no_pchip() @@ -786,9 +806,32 @@ def test_interp_raise_on_only_mixed(self): def test_interp_inplace(self): df = DataFrame({'a': [1., 2., np.nan, 4.]}) - expected = DataFrame({'a': [1, 2, 3, 4]}) - df['a'].interpolate(inplace=True) - assert_frame_equal(df, expected) + expected = DataFrame({'a': [1., 2., 3., 4.]}) + result = df.copy() + result['a'].interpolate(inplace=True) + assert_frame_equal(result, expected) + + result = df.copy() + result['a'].interpolate(inplace=True, downcast='infer') + assert_frame_equal(result, expected.astype('int')) + + def test_interp_ignore_all_good(self): + # GH + df = DataFrame({'A': [1, 2, np.nan, 4], + 'B': [1, 2, 3, 4], + 'C': [1., 2., np.nan, 4.], + 'D': [1., 2., 3., 4.]}) + expected = DataFrame({'A': np.array([1, 2, 3, 4], dtype='float'), + 'B': np.array([1, 2, 3, 4], dtype='int'), + 'C': np.array([1., 2., 3, 4.], dtype='float'), + 'D': np.array([1., 2., 3., 4.], dtype='float')}) + + result = df.interpolate(downcast=None) + assert_frame_equal(result, expected) + + # all good + result = df[['B', 'D']].interpolate(downcast=None) + assert_frame_equal(result, df[['B', 'D']]) def test_no_order(self): _skip_if_no_scipy() @@ -802,7 +845,7 @@ 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]) + expected = Series([1., 2., 3., 4., 5., 6., 7.]) assert_series_equal(result, expected) def test_metadata_propagation_indiv(self): diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py index e658ce75247b4..a70d756c82b0a 100644 --- a/vb_suite/frame_methods.py +++ b/vb_suite/frame_methods.py @@ -403,3 +403,29 @@ def test_unequal(name): frame_object_unequal = Benchmark('test_unequal("object_df")', setup) frame_nonunique_unequal = Benchmark('test_unequal("nonunique_cols")', setup) +#----------------------------------------------------------------------------- +# interpolate +# this is the worst case, where every column has NaNs. +setup = common_setup + """ +df = DataFrame(randn(10000, 100)) +df.values[::2] = np.nan +""" + +frame_interpolate = Benchmark('df.interpolate()', setup, + start_date=datetime(2014, 2, 7)) + +setup = common_setup + """ +df = DataFrame({'A': np.arange(0, 10000), + 'B': np.random.randint(0, 100, 10000), + 'C': randn(10000), + 'D': randn(10000)}) +df.loc[1::5, 'A'] = np.nan +df.loc[1::5, 'C'] = np.nan +""" + +frame_interpolate_some_good = Benchmark('df.interpolate()', setup, + start_date=datetime(2014, 2, 7)) +frame_interpolate_some_good_infer = Benchmark('df.interpolate(downcast="infer")', + setup, + start_date=datetime(2014, 2, 7)) +
Closes https://github.com/pydata/pandas/issues/6290 @jreback is there a good way to update **part** of a BlockManager inplace? I have a new BlockManager from `interpolate` and the original BlockManager (or DataFrame) which contains some "all good" columns that didn't get interpolate on, and some bad columns that did get interpolated on. For the non inplace version I'm calling `self._constructor` on the BlockManager returned from interpolating and concating that to the all good columns.
https://api.github.com/repos/pandas-dev/pandas/pulls/6291
2014-02-06T21:45:18Z
2014-02-17T17:06:56Z
null
2016-11-03T12:37:51Z
ENH: All args and kwargs to generic expanding/rolling apply.
diff --git a/doc/source/release.rst b/doc/source/release.rst index ae95c882fe356..a56f13a17d1ab 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -65,6 +65,7 @@ Improvements to existing features - pd.read_clipboard will, if 'sep' is unspecified, try to detect data copied from a spreadsheet and parse accordingly. (:issue:`6223`) +- pd.expanding_apply and pd.rolling_apply now take args and kwargs that are passed on to the func. .. _release.bug_fixes-0.14.0: diff --git a/pandas/algos.pyx b/pandas/algos.pyx index 64df9df0205ff..0be238117fe4e 100644 --- a/pandas/algos.pyx +++ b/pandas/algos.pyx @@ -1627,7 +1627,7 @@ def roll_quantile(ndarray[float64_t, cast=True] input, int win, return output def roll_generic(ndarray[float64_t, cast=True] input, int win, - int minp, object func): + int minp, object func, object args, object kwargs): cdef ndarray[double_t] output, counts, bufarr cdef Py_ssize_t i, n cdef float64_t *buf @@ -1652,7 +1652,8 @@ def roll_generic(ndarray[float64_t, cast=True] input, int win, n = len(input) for i from 0 <= i < int_min(win, n): if counts[i] >= minp: - output[i] = func(input[int_max(i - win + 1, 0) : i + 1]) + output[i] = func(input[int_max(i - win + 1, 0) : i + 1], *args, + **kwargs) else: output[i] = NaN @@ -1660,7 +1661,7 @@ def roll_generic(ndarray[float64_t, cast=True] input, int win, buf = buf + 1 bufarr.data = <char*> buf if counts[i] >= minp: - output[i] = func(bufarr) + output[i] = func(bufarr, *args, **kwargs) else: output[i] = NaN diff --git a/pandas/stats/moments.py b/pandas/stats/moments.py index 904e6018dba1f..ca4bbc3c8868a 100644 --- a/pandas/stats/moments.py +++ b/pandas/stats/moments.py @@ -141,7 +141,7 @@ def rolling_count(arg, window, freq=None, center=False, time_rule=None): center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + Returns ------- rolling_count : type of caller @@ -255,8 +255,8 @@ def rolling_corr_pairwise(df, window, min_periods=None): return Panel.from_dict(all_results).swapaxes('items', 'major') -def _rolling_moment(arg, window, func, minp, axis=0, freq=None, - center=False, time_rule=None, **kwargs): +def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center=False, + time_rule=None, args=(), kwargs={}, **kwds): """ Rolling statistical measure using supplied function. Designed to be used with passed-in Cython array-based functions. @@ -274,13 +274,18 @@ def _rolling_moment(arg, window, func, minp, axis=0, freq=None, center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + args : tuple + Passed on to func + kwargs : dict + Passed on to func + Returns ------- y : type of input """ arg = _conv_timerule(arg, freq, time_rule) - calc = lambda x: func(x, window, minp=minp, **kwargs) + calc = lambda x: func(x, window, minp=minp, args=args, kwargs=kwargs, + **kwds) return_hook, values = _process_data_structure(arg) # actually calculate the moment. Faster way to do this? if values.ndim > 1: @@ -509,7 +514,7 @@ def _rolling_func(func, desc, check_minp=_use_window): @wraps(func) def f(arg, window, min_periods=None, freq=None, center=False, time_rule=None, **kwargs): - def call_cython(arg, window, minp, **kwds): + def call_cython(arg, window, minp, args=(), kwargs={}, **kwds): minp = check_minp(minp, window) return func(arg, window, minp, **kwds) return _rolling_moment(arg, window, call_cython, min_periods, @@ -551,13 +556,13 @@ def rolling_quantile(arg, window, quantile, min_periods=None, freq=None, center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + Returns ------- y : type of input argument """ - def call_cython(arg, window, minp): + def call_cython(arg, window, minp, args=(), kwargs={}): minp = _use_window(minp, window) return algos.roll_quantile(arg, window, minp, quantile) return _rolling_moment(arg, window, call_cython, min_periods, @@ -565,7 +570,7 @@ def call_cython(arg, window, minp): def rolling_apply(arg, window, func, min_periods=None, freq=None, - center=False, time_rule=None): + center=False, time_rule=None, args=(), kwargs={}): """Generic moving function application Parameters @@ -581,16 +586,21 @@ def rolling_apply(arg, window, func, min_periods=None, freq=None, center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + args : tuple + Passed on to func + kwargs : dict + Passed on to func + Returns ------- y : type of input argument """ - def call_cython(arg, window, minp): + def call_cython(arg, window, minp, args, kwargs): minp = _use_window(minp, window) - return algos.roll_generic(arg, window, minp, func) + return algos.roll_generic(arg, window, minp, func, args, kwargs) return _rolling_moment(arg, window, call_cython, min_periods, - freq=freq, center=center, time_rule=time_rule) + freq=freq, center=center, time_rule=time_rule, + args=args, kwargs=kwargs) def rolling_window(arg, window=None, win_type=None, min_periods=None, @@ -618,7 +628,7 @@ def rolling_window(arg, window=None, win_type=None, min_periods=None, If True computes weighted mean, else weighted sum time_rule : Legacy alias for freq axis : {0, 1}, default 0 - + Returns ------- y : type of input argument @@ -703,7 +713,7 @@ def f(arg, min_periods=1, freq=None, center=False, time_rule=None, **kwargs): window = len(arg) - def call_cython(arg, window, minp, **kwds): + def call_cython(arg, window, minp, args=(), kwargs={}, **kwds): minp = check_minp(minp, window) return func(arg, window, minp, **kwds) return _rolling_moment(arg, window, call_cython, min_periods, @@ -744,7 +754,7 @@ def expanding_count(arg, freq=None, center=False, time_rule=None): center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + Returns ------- expanding_count : type of caller @@ -768,7 +778,7 @@ def expanding_quantile(arg, quantile, min_periods=1, freq=None, center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + Returns ------- y : type of input argument @@ -818,7 +828,7 @@ def expanding_corr_pairwise(df, min_periods=1): def expanding_apply(arg, func, min_periods=1, freq=None, center=False, - time_rule=None): + time_rule=None, args=(), kwargs={}): """Generic expanding function application Parameters @@ -833,11 +843,16 @@ def expanding_apply(arg, func, min_periods=1, freq=None, center=False, center : boolean, default False Whether the label should correspond with center of window time_rule : Legacy alias for freq - + args : tuple + Passed on to func + kwargs : dict + Passed on to func + Returns ------- y : type of input argument """ window = len(arg) return rolling_apply(arg, window, func, min_periods=min_periods, freq=freq, - center=center, time_rule=time_rule) + center=center, time_rule=time_rule, args=args, + kwargs=kwargs) diff --git a/pandas/stats/tests/test_moments.py b/pandas/stats/tests/test_moments.py index 970adeace1e0f..50b1854f0e24b 100644 --- a/pandas/stats/tests/test_moments.py +++ b/pandas/stats/tests/test_moments.py @@ -694,6 +694,21 @@ def expanding_mean(x, min_periods=1, freq=None): freq=freq) self._check_expanding(expanding_mean, np.mean) + def test_expanding_apply_args_kwargs(self): + def mean_w_arg(x, const): + return np.mean(x) + const + + df = DataFrame(np.random.rand(20, 3)) + + expected = mom.expanding_apply(df, np.mean) + 20. + + assert_frame_equal(mom.expanding_apply(df, mean_w_arg, args=(20,)), + expected) + assert_frame_equal(mom.expanding_apply(df, mean_w_arg, + kwargs={'const' : 20}), + expected) + + def test_expanding_corr(self): A = self.series.dropna() B = (A + randn(len(A)))[:-5]
Been bugging me lately. Simple enough fix I think. Example usage ``` def mean(x, const): return np.mean(x) + const df = pd.DataFrame(np.random.rand(20, 3)) pd.expanding_apply(df, mean, args=(20,) pd.expanding_apply(df, mean, kwargs=dict(const=20)) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6289
2014-02-06T19:40:15Z
2014-02-07T01:16:39Z
null
2014-06-21T08:12:07Z
BLD: re cythonize files only if we have changed then
diff --git a/ci/prep_ccache.sh b/ci/prep_ccache.sh index 9c7267ee21623..775aec555a824 100755 --- a/ci/prep_ccache.sh +++ b/ci/prep_ccache.sh @@ -6,6 +6,7 @@ if [ "$IRON_TOKEN" ]; then pip install -I --allow-external --allow-insecure git+https://github.com/iron-io/iron_cache_python.git@8a451c7d7e4d16e0c3bedffd0f280d5d9bd4fe59#egg=iron_cache + curdir=$(pwd) python ci/ironcache/get.py ccache -C @@ -22,14 +23,23 @@ if [ "$IRON_TOKEN" ]; then fi # did the last commit change cython files? - git diff HEAD~5 | grep diff | grep -P "pyx|pxd" + cd $curdir - if [ "$?" != "0" ]; then + echo "diff from HEAD~5" + git diff HEAD~5 --numstat + + retval=$(git diff HEAD~5 --numstat | grep -P "pyx|pxd"|wc -l) + echo "number of cython files changed: $retval" + + if [ $retval -eq 0 ] + then # nope, reuse cython files echo "Will reuse cached cython file" touch "$TRAVIS_BUILD_DIR"/pandas/*.c touch "$TRAVIS_BUILD_DIR"/pandas/src/*.c touch "$TRAVIS_BUILD_DIR"/pandas/*.cpp + else + echo "Rebuilding cythonized files" fi fi
https://api.github.com/repos/pandas-dev/pandas/pulls/6285
2014-02-06T15:03:40Z
2014-02-06T15:03:51Z
2014-02-06T15:03:51Z
2014-07-16T08:52:34Z
BUG: Fix interpolate with inplace=True
diff --git a/doc/source/release.rst b/doc/source/release.rst index ae95c882fe356..1568a2c3af439 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -77,6 +77,7 @@ Bug Fixes - Bug in ``.xs`` with a Series multiindex (:issue:`6258`, :issue:`5684`) - Bug in conversion of a string types to a DatetimeIndex with a specified frequency (:issue:`6273`, :issue:`6274`) - Bug in ``eval`` where type-promotion failed for large expressions (:issue:`6205`) +- Bug in interpolate with inplace=True (:issue:`6281`) pandas 0.13.1 ------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0a0cfe94409f9..68b35db3827c8 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2541,9 +2541,9 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, self._update_inplace(new_data) else: res = self._constructor(new_data).__finalize__(self) - if axis == 1: - res = res.T - return res + if axis == 1: + res = res.T + return res #---------------------------------------------------------------------- # Action Methods diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index eb7f178df39d8..958ca81b0a2ee 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -784,6 +784,12 @@ def test_interp_raise_on_only_mixed(self): with tm.assertRaises(TypeError): df.interpolate(axis=1) + def test_interp_inplace(self): + df = DataFrame({'a': [1., 2., np.nan, 4.]}) + expected = DataFrame({'a': [1, 2, 3, 4]}) + df['a'].interpolate(inplace=True) + assert_frame_equal(df, expected) + def test_no_order(self): _skip_if_no_scipy() s = Series([0, 1, np.nan, 3])
Closes https://github.com/pydata/pandas/issues/6281 I didn't have the non inplace return in an else block. And I clearly didn't test this :/
https://api.github.com/repos/pandas-dev/pandas/pulls/6284
2014-02-06T13:32:22Z
2014-02-06T21:41:11Z
2014-02-06T21:41:11Z
2014-07-16T08:52:32Z
DOC: fix link to str.get_dummies
diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst index 8f0686dedb9d6..9aab5543aff92 100644 --- a/doc/source/reshaping.rst +++ b/doc/source/reshaping.rst @@ -418,7 +418,7 @@ This function is often used along with discretization functions like ``cut``: get_dummies(cut(values, bins)) -See also :func:`~pandas.Series.str.get_dummies`. +See also :func:`Series.str.get_dummies <pandas.core.strings.StringMethods.get_dummies>`. Factorizing values ------------------
Links directly to `Series.str.get_dummies` don't work, as the object actually lives in `StringMethods`.
https://api.github.com/repos/pandas-dev/pandas/pulls/6278
2014-02-05T21:17:22Z
2014-02-05T21:17:34Z
2014-02-05T21:17:34Z
2014-06-15T07:03:45Z
BUG: Bug in conversion of a string types to a DatetimeIndex with a specifed frequency (GH6273)
diff --git a/doc/source/release.rst b/doc/source/release.rst index c6a901252903f..5f7d87ea03f67 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -75,6 +75,7 @@ Bug Fixes - Inconsistent tz parsing Timestamp/to_datetime for current year (:issue:`5958`) - Indexing bugs with reordered indexes (:issue:`6252`, :issue:`6254`) - Bug in ``.xs`` with a Series multiindex (:issue:`6258`, :issue:`5684`) +- Bug in conversion of a string types to a DatetimeIndex with a specified frequency (:issue:`6273`, :issue:`6274`) pandas 0.13.1 ------------- diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index b3dbfe910680a..30e9a68a88122 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -146,6 +146,31 @@ def test_constructor_corner(self): # corner case self.assertRaises(TypeError, Index, 0) + def test_constructor_from_series(self): + + expected = DatetimeIndex([Timestamp('20110101'),Timestamp('20120101'),Timestamp('20130101')]) + s = Series([Timestamp('20110101'),Timestamp('20120101'),Timestamp('20130101')]) + result = Index(s) + self.assertTrue(result.equals(expected)) + result = DatetimeIndex(s) + self.assertTrue(result.equals(expected)) + + # GH 6273 + # create from a series, passing a freq + s = Series(pd.to_datetime(['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'])) + result = DatetimeIndex(s, freq='MS') + expected = DatetimeIndex(['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'],freq='MS') + self.assertTrue(result.equals(expected)) + + df = pd.DataFrame(np.random.rand(5,3)) + df['date'] = ['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'] + result = DatetimeIndex(df['date'], freq='MS') + + # GH 6274 + # infer freq of same + result = pd.infer_freq(df['date']) + self.assertEqual(result,'MS') + def test_index_ctor_infer_periodindex(self): from pandas import period_range, PeriodIndex xp = period_range('2012-1-1', freq='M', periods=3) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 5cd3b8a87c974..2762f5fca9a97 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -254,6 +254,11 @@ def __new__(cls, data=None, else: try: subarr = tools.to_datetime(data, box=False) + + # make sure that we have a index/ndarray like (and not a Series) + if isinstance(subarr, ABCSeries): + subarr = subarr.values + except ValueError: # tz aware subarr = tools.to_datetime(data, box=False, utc=True)
closes #6273 closes #6274
https://api.github.com/repos/pandas-dev/pandas/pulls/6275
2014-02-05T18:03:20Z
2014-02-05T18:31:59Z
2014-02-05T18:31:59Z
2014-06-14T23:51:41Z
PERF: micro optimizations
diff --git a/pandas/core/common.py b/pandas/core/common.py index 134e43bcd006a..e895c8ed0cf2d 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -134,7 +134,7 @@ def _isnull_new(obj): elif isinstance(obj, (ABCSeries, np.ndarray)): return _isnull_ndarraylike(obj) elif isinstance(obj, ABCGeneric): - return obj._constructor(obj._data.apply(lambda x: isnull(x.values))) + return obj._constructor(obj._data.isnull(func=isnull)) elif isinstance(obj, list) or hasattr(obj, '__array__'): return _isnull_ndarraylike(np.asarray(obj)) else: @@ -160,8 +160,7 @@ def _isnull_old(obj): elif isinstance(obj, (ABCSeries, np.ndarray)): return _isnull_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): - return obj._constructor(obj._data.apply( - lambda x: _isnull_old(x.values))) + return obj._constructor(obj._data.isnull(func=_isnull_old)) elif isinstance(obj, list) or hasattr(obj, '__array__'): return _isnull_ndarraylike_old(np.asarray(obj)) else: @@ -1540,14 +1539,7 @@ def _maybe_box(indexer, values, obj, key): # return the value return values - -def _values_from_object(o): - """ return my values or the object if we are say an ndarray """ - f = getattr(o, 'get_values', None) - if f is not None: - o = f() - return o - +_values_from_object = lib.values_from_object def _possibly_convert_objects(values, convert_dates=True, convert_numeric=True, @@ -2036,20 +2028,16 @@ def _maybe_make_list(obj): return obj -def is_bool(obj): - return isinstance(obj, (bool, np.bool_)) +is_bool = lib.is_bool -def is_integer(obj): - return isinstance(obj, (numbers.Integral, np.integer)) +is_integer = lib.is_integer -def is_float(obj): - return isinstance(obj, (float, np.floating)) +is_float = lib.is_float -def is_complex(obj): - return isinstance(obj, (numbers.Complex, np.complexfloating)) +is_complex = lib.is_complex def is_iterator(obj): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4c19831c6cbe3..de8bac05f211f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2825,14 +2825,14 @@ def _combine_match_columns(self, other, func, fill_value=None): fill_value) new_data = left._data.eval( - func, right, axes=[left.columns, self.index]) + func=func, other=right, axes=[left.columns, self.index]) return self._constructor(new_data) def _combine_const(self, other, func, raise_on_error=True): if self.empty: return self - new_data = self._data.eval(func, other, raise_on_error=raise_on_error) + new_data = self._data.eval(func=func, other=other, raise_on_error=raise_on_error) return self._constructor(new_data) def _compare_frame_evaluate(self, other, func, str_rep): @@ -3228,7 +3228,7 @@ def diff(self, periods=1): ------- diffed : DataFrame """ - new_data = self._data.diff(periods) + new_data = self._data.diff(n=periods) return self._constructor(new_data) #---------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2ee96d660eb87..0a0cfe94409f9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -128,7 +128,7 @@ def _init_mgr(self, mgr, axes=None, dtype=None, copy=False): elif dtype is not None: # avoid copy if we can if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype: - mgr = mgr.astype(dtype) + mgr = mgr.astype(dtype=dtype) return mgr #---------------------------------------------------------------------- @@ -2011,7 +2011,7 @@ def astype(self, dtype, copy=True, raise_on_error=True): """ mgr = self._data.astype( - dtype, copy=copy, raise_on_error=raise_on_error) + dtype=dtype, copy=copy, raise_on_error=raise_on_error) return self._constructor(mgr).__finalize__(self) def copy(self, deep=True): @@ -2153,7 +2153,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, from pandas import Series value = Series(value) - new_data = self._data.fillna(value, inplace=inplace, + new_data = self._data.fillna(value=value, inplace=inplace, downcast=downcast) elif isinstance(value, (dict, com.ABCSeries)): @@ -2170,7 +2170,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, obj.fillna(v, inplace=True) return result else: - new_data = self._data.fillna(value, inplace=inplace, + new_data = self._data.fillna(value=value, inplace=inplace, downcast=downcast) if inplace: @@ -2355,7 +2355,8 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, new_data = self._data for c, src in compat.iteritems(to_replace): if c in value and c in self: - new_data = new_data.replace(src, value[c], + new_data = new_data.replace(to_replace=src, + value=value[c], filter=[c], inplace=inplace, regex=regex) @@ -2365,7 +2366,8 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, new_data = self._data for k, src in compat.iteritems(to_replace): if k in self: - new_data = new_data.replace(src, value, + new_data = new_data.replace(to_replace=src, + value=value, filter=[k], inplace=inplace, regex=regex) @@ -2380,13 +2382,16 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, 'in length. Expecting %d got %d ' % (len(to_replace), len(value))) - new_data = self._data.replace_list(to_replace, value, + new_data = self._data.replace_list(src_list=to_replace, + dest_list=value, inplace=inplace, regex=regex) else: # [NA, ''] -> 0 - new_data = self._data.replace(to_replace, value, - inplace=inplace, regex=regex) + new_data = self._data.replace(to_replace=to_replace, + value=value, + inplace=inplace, + regex=regex) elif to_replace is None: if not (com.is_re_compilable(regex) or com.is_list_like(regex) or @@ -2406,13 +2411,14 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, for k, v in compat.iteritems(value): if k in self: - new_data = new_data.replace(to_replace, v, + new_data = new_data.replace(to_replace=to_replace, + value=v, filter=[k], inplace=inplace, regex=regex) elif not com.is_list_like(value): # NA -> 0 - new_data = self._data.replace(to_replace, value, + new_data = self._data.replace(to_replace=to_replace, value=value, inplace=inplace, regex=regex) else: msg = ('Invalid "to_replace" type: ' @@ -3116,12 +3122,12 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, if inplace: # we may have different type blocks come out of putmask, so # reconstruct the block manager - new_data = self._data.putmask(cond, other, align=axis is None, + new_data = self._data.putmask(mask=cond, new=other, align=axis is None, inplace=True) self._update_inplace(new_data) else: - new_data = self._data.where(other, cond, align=axis is None, + new_data = self._data.where(other=other, cond=cond, align=axis is None, raise_on_error=raise_on_error, try_cast=try_cast) @@ -3168,7 +3174,7 @@ def shift(self, periods=1, freq=None, axis=0, **kwds): 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) + new_data = self._data.shift(indexer=indexer, periods=periods, axis=block_axis) else: return self.tshift(periods, freq, **kwds) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 780ad57ed8f13..d2f538decd576 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -321,7 +321,7 @@ def _setitem_with_indexer(self, indexer, value): # 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) + obj._data = obj._data.setitem(indexer=tuple([idx]), value=value) self.obj[item] = obj return @@ -341,7 +341,7 @@ def setter(item, v): # set the item, possibly having a dtype change s = s.copy() - s._data = s._data.setitem(pi, v) + s._data = s._data.setitem(indexer=pi, value=v) s._maybe_update_cacher(clear=True) self.obj[item] = s @@ -419,7 +419,7 @@ def can_do_equal_len(): value = self._align_panel(indexer, value) # actually do the set - self.obj._data = self.obj._data.setitem(indexer, value) + self.obj._data = self.obj._data.setitem(indexer=indexer, value=value) self.obj._maybe_update_cacher(clear=True) def _align_series(self, indexer, ser): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e88f1972b5f7d..d0a8e1c06fd28 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -215,6 +215,14 @@ def dtype(self): def ftype(self): return "%s:%s" % (self.dtype, self._ftype) + def as_block(self, result): + """ if we are not a block, then wrap as a block, must have compatible shape """ + if not isinstance(result, Block): + result = make_block(result, + self.items, + self.ref_items) + return result + def merge(self, other): if not self.ref_items.equals(other.ref_items): raise AssertionError('Merge operands must have same ref_items') @@ -346,6 +354,10 @@ def split_block_at(self, item): klass=self.__class__, fastpath=True) + def apply(self, func, **kwargs): + """ apply the function to my values; return a block if we are not one """ + return self.as_block(func(self.values)) + def fillna(self, value, inplace=False, downcast=None): if not self._can_hold_na: if inplace: @@ -2342,38 +2354,32 @@ def _verify_integrity(self): 'tot_items: {1}'.format(len(self.items), tot_items)) - def apply(self, f, *args, **kwargs): - """ iterate over the blocks, collect and create a new block manager + def apply(self, f, axes=None, filter=None, do_integrity_check=False, **kwargs): + """ + iterate over the blocks, collect and create a new block manager Parameters ---------- f : the callable or function name to operate on at the block level axes : optional (if not supplied, use self.axes) filter : list, if supplied, only call the block if the filter is in - the block + the block + do_integrity_check : boolean, default False. Do the block manager integrity check + + Returns + ------- + Block Manager (new object) + """ - axes = kwargs.pop('axes', None) - filter = kwargs.get('filter') - do_integrity_check = kwargs.pop('do_integrity_check', False) result_blocks = [] for blk in self.blocks: if filter is not None: - kwargs['filter'] = set(kwargs['filter']) + kwargs['filter'] = set(filter) if not blk.items.isin(filter).any(): result_blocks.append(blk) continue - if callable(f): - applied = f(blk, *args, **kwargs) - - # if we are no a block, try to coerce - if not isinstance(applied, Block): - applied = make_block(applied, - blk.items, - blk.ref_items) - - else: - applied = getattr(blk, f)(*args, **kwargs) + applied = getattr(blk, f)(**kwargs) if isinstance(applied, list): result_blocks.extend(applied) @@ -2386,43 +2392,46 @@ def apply(self, f, *args, **kwargs): bm._consolidate_inplace() return bm - def where(self, *args, **kwargs): - return self.apply('where', *args, **kwargs) + def isnull(self, **kwargs): + return self.apply('apply', **kwargs) + + def where(self, **kwargs): + return self.apply('where', **kwargs) - def eval(self, *args, **kwargs): - return self.apply('eval', *args, **kwargs) + def eval(self, **kwargs): + return self.apply('eval', **kwargs) - def setitem(self, *args, **kwargs): - return self.apply('setitem', *args, **kwargs) + def setitem(self, **kwargs): + return self.apply('setitem', **kwargs) - def putmask(self, *args, **kwargs): - return self.apply('putmask', *args, **kwargs) + def putmask(self, **kwargs): + return self.apply('putmask', **kwargs) - def diff(self, *args, **kwargs): - return self.apply('diff', *args, **kwargs) + def diff(self, **kwargs): + return self.apply('diff', **kwargs) - def interpolate(self, *args, **kwargs): - return self.apply('interpolate', *args, **kwargs) + def interpolate(self, **kwargs): + return self.apply('interpolate', **kwargs) - def shift(self, *args, **kwargs): - return self.apply('shift', *args, **kwargs) + def shift(self, **kwargs): + return self.apply('shift', **kwargs) - def fillna(self, *args, **kwargs): - return self.apply('fillna', *args, **kwargs) + def fillna(self, **kwargs): + return self.apply('fillna', **kwargs) - def downcast(self, *args, **kwargs): - return self.apply('downcast', *args, **kwargs) + def downcast(self, **kwargs): + return self.apply('downcast', **kwargs) - def astype(self, *args, **kwargs): - return self.apply('astype', *args, **kwargs) + def astype(self, dtype, **kwargs): + return self.apply('astype', dtype=dtype, **kwargs) - def convert(self, *args, **kwargs): - return self.apply('convert', *args, **kwargs) + def convert(self, **kwargs): + return self.apply('convert', **kwargs) - def replace(self, *args, **kwargs): - return self.apply('replace', *args, **kwargs) + def replace(self, **kwargs): + return self.apply('replace', **kwargs) - def replace_list(self, src_lst, dest_lst, inplace=False, regex=False): + def replace_list(self, src_list, dest_list, inplace=False, regex=False): """ do a list replace """ # figure out our mask a-priori to avoid repeated replacements @@ -2432,7 +2441,7 @@ def comp(s): if isnull(s): return isnull(values) return values == getattr(s, 'asm8', s) - masks = [comp(s) for i, s in enumerate(src_lst)] + masks = [comp(s) for i, s in enumerate(src_list)] result_blocks = [] for blk in self.blocks: @@ -2440,7 +2449,7 @@ def comp(s): # its possible to get multiple result blocks here # replace ALWAYS will return a list rb = [blk if inplace else blk.copy()] - for i, (s, d) in enumerate(zip(src_lst, dest_lst)): + for i, (s, d) in enumerate(zip(src_list, dest_list)): new_rb = [] for b in rb: if b.dtype == np.object_: @@ -2465,13 +2474,13 @@ def comp(s): bm._consolidate_inplace() return bm - def prepare_for_merge(self, *args, **kwargs): + def prepare_for_merge(self, **kwargs): """ prepare for merging, return a new block manager with Sparse -> Dense """ self._consolidate_inplace() if self._has_sparse: - return self.apply('prepare_for_merge', *args, **kwargs) + return self.apply('prepare_for_merge', **kwargs) return self def post_merge(self, objs, **kwargs): @@ -3631,6 +3640,18 @@ def shape(self): self._shape = tuple([len(self.axes[0])]) return self._shape + def apply(self, f, axes=None, do_integrity_check=False, **kwargs): + """ + fast path for SingleBlock Manager + + ssee also BlockManager.apply + """ + applied = getattr(self._block, f)(**kwargs) + bm = self.__class__(applied, axes or self.axes, + do_integrity_check=do_integrity_check) + bm._consolidate_inplace() + return bm + def reindex(self, new_axis, indexer=None, method=None, fill_value=None, limit=None, copy=True): # if we are the same and don't copy, just return @@ -3687,14 +3708,14 @@ def set_ref_items(self, ref_items, maybe_rename=True): def index(self): return self.axes[0] - def convert(self, *args, **kwargs): + def convert(self, **kwargs): """ convert the whole block as one """ kwargs['by_item'] = False - return self.apply('convert', *args, **kwargs) + return self.apply('convert', **kwargs) @property def dtype(self): - return self._block.dtype + return self._values.dtype @property def ftype(self): @@ -3706,7 +3727,7 @@ def values(self): @property def itemsize(self): - return self._block.itemsize + return self._values.itemsize @property def _can_hold_na(self): diff --git a/pandas/core/series.py b/pandas/core/series.py index 8873af08cc5f3..300da3dc6834d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -212,7 +212,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None, # create/copy the manager if isinstance(data, SingleBlockManager): if dtype is not None: - data = data.astype(dtype, raise_on_error=False) + data = data.astype(dtype=dtype, raise_on_error=False) elif copy: data = data.copy() else: @@ -281,23 +281,23 @@ def _set_subtyp(self, is_all_dates): # ndarray compatibility def item(self): - return self.values.item() + return self._data.values.item() @property def data(self): - return self.values.data + return self._data.values.data @property def strides(self): - return self.values.strides + return self._data.values.strides @property def size(self): - return self.values.size + return self._data.values.size @property def flags(self): - return self.values.flags + return self._data.values.flags @property def dtype(self): @@ -694,7 +694,7 @@ def _set_labels(self, key, value): def _set_values(self, key, value): if isinstance(key, Series): key = key.values - self._data = self._data.setitem(key, value) + self._data = self._data.setitem(indexer=key, value=value) # help out SparseSeries _get_val_at = ndarray.__getitem__ @@ -1643,7 +1643,7 @@ def update(self, other): other = other.reindex_like(self) mask = notnull(other) - self._data = self._data.putmask(mask, other, inplace=True) + self._data = self._data.putmask(mask=mask, new=other, inplace=True) self._maybe_update_cacher() #---------------------------------------------------------------------- diff --git a/pandas/lib.pyx b/pandas/lib.pyx index ea5071eab976c..dccc68ab59ad3 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -59,6 +59,16 @@ PyDateTime_IMPORT import_array() import_ufunc() +def values_from_object(object o): + """ return my values or the object if we are say an ndarray """ + cdef f + + f = getattr(o, 'get_values', None) + if f is not None: + o = f() + + return o + cpdef map_indices_list(list index): ''' Produce a dict mapping the values of the input array to their respective diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index c048b2786bd91..046fa3887a32d 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -3,6 +3,19 @@ from tslib import NaT from datetime import datetime, timedelta iNaT = util.get_nat() +# core.common import for fast inference checks +def is_float(object obj): + return util.is_float_object(obj) + +def is_integer(object obj): + return util.is_integer_object(obj) + +def is_bool(object obj): + return util.is_bool_object(obj) + +def is_complex(object obj): + return util.is_complex_object(obj) + _TYPE_MAP = { np.int8: 'integer', np.int16: 'integer', diff --git a/pandas/src/reduce.pyx b/pandas/src/reduce.pyx index 50fff7f9eb460..a22e7e636d7e4 100644 --- a/pandas/src/reduce.pyx +++ b/pandas/src/reduce.pyx @@ -55,12 +55,6 @@ cdef class Reducer: # in cython, so increment first Py_INCREF(dummy) else: - if dummy.dtype != self.arr.dtype: - raise ValueError('Dummy array must be same dtype') - if len(dummy) != self.chunksize: - raise ValueError('Dummy array must be length %d' % - self.chunksize) - # we passed a series-like if hasattr(dummy,'values'): @@ -68,6 +62,12 @@ cdef class Reducer: index = getattr(dummy,'index',None) dummy = dummy.values + if dummy.dtype != self.arr.dtype: + raise ValueError('Dummy array must be same dtype') + if len(dummy) != self.chunksize: + raise ValueError('Dummy array must be length %d' % + self.chunksize) + return dummy, index def get_result(self): @@ -193,9 +193,9 @@ cdef class SeriesBinGrouper: values = np.empty(0, dtype=self.arr.dtype) index = None else: - if dummy.dtype != self.arr.dtype: - raise ValueError('Dummy array must be same dtype') values = dummy.values + if values.dtype != self.arr.dtype: + raise ValueError('Dummy array must be same dtype') if not values.flags.contiguous: values = values.copy() index = dummy.index @@ -318,9 +318,9 @@ cdef class SeriesGrouper: values = np.empty(0, dtype=self.arr.dtype) index = None else: + values = dummy.values if dummy.dtype != self.arr.dtype: raise ValueError('Dummy array must be same dtype') - values = dummy.values if not values.flags.contiguous: values = values.copy() index = dummy.index diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index e28aca3e5ef3a..2c32b5d0310db 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -198,7 +198,7 @@ def test_nan_to_nat_conversions(): assert(result == iNaT) s = df['B'].copy() - s._data = s._data.setitem(tuple([slice(8,9)]),np.nan) + s._data = s._data.setitem(indexer=tuple([slice(8,9)]),value=np.nan) assert(isnull(s[8])) # numpy < 1.7.0 is wrong diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index f86dec1a99850..eca1eae540920 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -604,7 +604,7 @@ def test_equals(self): bm1 = BlockManager([block1, block2], [index, np.arange(block1.shape[1])]) bm2 = BlockManager([block2, block1], [index, np.arange(block1.shape[1])]) self.assert_(bm1.equals(bm2)) - + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 2762f5fca9a97..23181485d3bbb 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -1205,16 +1205,14 @@ def get_value(self, series, key): Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ - timestamp = None - #if isinstance(key, Timestamp): - # timestamp = key - #el + if isinstance(key, datetime): + # needed to localize naive datetimes - timestamp = Timestamp(key, tz=self.tz) + if self.tz is not None: + key = Timestamp(key, tz=self.tz) - if timestamp: - return self.get_value_maybe_box(series, timestamp) + return self.get_value_maybe_box(series, key) try: return _maybe_box(self, Index.get_value(self, series, key), series, key)
PERF: enhance tseries getitem indexing PERF: micro optimzations in inference API/CLN: core.internals.apply now only takes kwargs; makes code a bit simpler CLN: wrap core/common/isnull into more direct Block.isnull PERF: fast path series block operations closes #6264 original timings ``` In [11]: %timeit com.is_integer(13) 100000 loops, best of 3: 1.29 µs per loop In [12]: %timeit com.is_integer(np.int32(2)) 100000 loops, best of 3: 3.32 µs per loop In [13]: %timeit com.is_integer(np.int64(2)) 100000 loops, best of 3: 1.86 µs per loop In [14]: %timeit com.is_integer(14L) 100000 loops, best of 3: 1.29 µs per loop In [15]: %timeit com.is_integer("1") 100000 loops, best of 3: 2.2 µs per loop ``` with this PR ``` In [2]: %timeit com.is_integer(13) 10000000 loops, best of 3: 72.5 ns per loop In [3]: %timeit com.is_integer(np.int32(2)) 1000000 loops, best of 3: 620 ns per loop In [4]: %timeit com.is_integer(np.int64(2)) 1000000 loops, best of 3: 315 ns per loop In [5]: %timeit com.is_integer(14L) 10000000 loops, best of 3: 72.4 ns per loop In [6]: %timeit com.is_integer("1") 10000000 loops, best of 3: 78.8 ns per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6269
2014-02-05T13:45:03Z
2014-02-06T15:49:01Z
2014-02-06T15:49:00Z
2014-07-16T08:52:22Z
BLD: add support for pytables 3.1
diff --git a/ci/requirements-3.3.txt b/ci/requirements-3.3.txt index 73009b572c4c2..8bc7f0bb44fac 100644 --- a/ci/requirements-3.3.txt +++ b/ci/requirements-3.3.txt @@ -6,8 +6,8 @@ xlrd==0.9.2 html5lib==1.0b2 numpy==1.8.0 cython==0.19.1 -numexpr==2.1 -tables==3.0.0 +numexpr==2.3 +tables==3.1.0 matplotlib==1.2.1 patsy==0.1.0 lxml==3.2.1 diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 568a4aaf29486..5609dfcc6eee0 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -1449,7 +1449,7 @@ def col(t,column): tables.__version__ = v self.assertRaises(Exception, store.create_table_index, 'f') - for v in ['2.3.1', '2.3.1b', '2.4dev', '2.4', original]: + for v in ['2.3.1', '2.3.1b', '2.4dev', '2.4', '3.0.0', '3.1.0', original]: pytables._table_mod = None pytables._table_supports_index = False tables.__version__ = v @@ -3732,6 +3732,26 @@ def test_select_as_multiple(self): self.assertRaises(ValueError, store.select_as_multiple, ['df1','df3'], where=['A>0', 'B>0'], selector='df1') + + def test_nan_selection_bug_4858(self): + + # GH 4858; nan selection bug, only works for pytables >= 3.1 + if LooseVersion(tables.__version__) < '3.1.0': + raise nose.SkipTest('tables version does not support fix for nan selection bug: GH 4858') + + with ensure_clean_store(self.path) as store: + + df = DataFrame(dict(cols = range(6), values = range(6)), dtype='float64') + df['cols'] = (df['cols']+10).apply(str) + df.iloc[0] = np.nan + + expected = DataFrame(dict(cols = ['13.0','14.0','15.0'], values = [3.,4.,5.]), index=[3,4,5]) + + # write w/o the index on that particular column + store.append('df',df, data_columns=True,index=['cols']) + result = store.select('df',where='values>2.0') + assert_frame_equal(result,expected) + def test_start_stop(self): with ensure_clean_store(self.path) as store:
BLD: update 3.3 build for numexpr 2.3 closes #5861
https://api.github.com/repos/pandas-dev/pandas/pulls/6268
2014-02-05T13:29:20Z
2014-02-13T22:47:36Z
2014-02-13T22:47:35Z
2014-06-18T17:18:27Z
CLN: Converting assert_'s to specialized forms, in pandas/*/tests
diff --git a/pandas/io/tests/test_cparser.py b/pandas/io/tests/test_cparser.py index 0b104ffba4242..9100673f99579 100644 --- a/pandas/io/tests/test_cparser.py +++ b/pandas/io/tests/test_cparser.py @@ -70,7 +70,7 @@ def test_string_factorize(self): data = 'a\nb\na\nb\na' reader = TextReader(StringIO(data), header=None) result = reader.read() - self.assert_(len(set(map(id, result[0]))) == 2) + self.assertEqual(len(set(map(id, result[0]))), 2) def test_skipinitialspace(self): data = ('a, b\n' @@ -91,7 +91,7 @@ def test_parse_booleans(self): reader = TextReader(StringIO(data), header=None) result = reader.read() - self.assert_(result[0].dtype == np.bool_) + self.assertEqual(result[0].dtype, np.bool_) def test_delimit_whitespace(self): data = 'a b\na\t\t "b"\n"a"\t \t b' @@ -233,25 +233,25 @@ def _make_reader(**kwds): reader = _make_reader(dtype='S5,i4') result = reader.read() - self.assert_(result[0].dtype == 'S5') + self.assertEqual(result[0].dtype, 'S5') ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaaa'], dtype='S5') self.assert_((result[0] == ex_values).all()) - self.assert_(result[1].dtype == 'i4') + self.assertEqual(result[1].dtype, 'i4') reader = _make_reader(dtype='S4') result = reader.read() - self.assert_(result[0].dtype == 'S4') + self.assertEqual(result[0].dtype, 'S4') ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaa'], dtype='S4') self.assert_((result[0] == ex_values).all()) - self.assert_(result[1].dtype == 'S4') + self.assertEqual(result[1].dtype, 'S4') reader = _make_reader(dtype='S4', as_recarray=True) result = reader.read() - self.assert_(result['0'].dtype == 'S4') + self.assertEqual(result['0'].dtype, 'S4') ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaa'], dtype='S4') self.assert_((result['0'] == ex_values).all()) - self.assert_(result['1'].dtype == 'S4') + self.assertEqual(result['1'].dtype, 'S4') def test_pass_dtype(self): data = """\ @@ -266,19 +266,19 @@ def _make_reader(**kwds): reader = _make_reader(dtype={'one': 'u1', 1: 'S1'}) result = reader.read() - self.assert_(result[0].dtype == 'u1') - self.assert_(result[1].dtype == 'S1') + self.assertEqual(result[0].dtype, 'u1') + self.assertEqual(result[1].dtype, 'S1') reader = _make_reader(dtype={'one': np.uint8, 1: object}) result = reader.read() - self.assert_(result[0].dtype == 'u1') - self.assert_(result[1].dtype == 'O') + self.assertEqual(result[0].dtype, 'u1') + self.assertEqual(result[1].dtype, 'O') reader = _make_reader(dtype={'one': np.dtype('u1'), 1: np.dtype('O')}) result = reader.read() - self.assert_(result[0].dtype == 'u1') - self.assert_(result[1].dtype == 'O') + self.assertEqual(result[0].dtype, 'u1') + self.assertEqual(result[1].dtype, 'O') def test_usecols(self): data = """\ diff --git a/pandas/io/tests/test_date_converters.py b/pandas/io/tests/test_date_converters.py index 74dad8537bb88..6aa1f7e1786a1 100644 --- a/pandas/io/tests/test_date_converters.py +++ b/pandas/io/tests/test_date_converters.py @@ -50,7 +50,7 @@ def test_parse_date_time(self): df = read_table(StringIO(data), sep=',', header=0, parse_dates=datecols, date_parser=conv.parse_date_time) self.assert_('date_time' in df) - self.assert_(df.date_time.ix[0] == datetime(2001, 1, 5, 10, 0, 0)) + self.assertEqual(df.date_time.ix[0], datetime(2001, 1, 5, 10, 0, 0)) data = ("KORD,19990127, 19:00:00, 18:56:00, 0.8100\n" "KORD,19990127, 20:00:00, 19:56:00, 0.0100\n" @@ -74,7 +74,7 @@ def test_parse_date_fields(self): parse_dates=datecols, date_parser=conv.parse_date_fields) self.assert_('ymd' in df) - self.assert_(df.ymd.ix[0] == datetime(2001, 1, 10)) + self.assertEqual(df.ymd.ix[0], datetime(2001, 1, 10)) def test_datetime_six_col(self): result = conv.parse_all_fields(self.years, self.months, self.days, @@ -91,7 +91,7 @@ def test_datetime_six_col(self): parse_dates=datecols, date_parser=conv.parse_all_fields) self.assert_('ymdHMS' in df) - self.assert_(df.ymdHMS.ix[0] == datetime(2001, 1, 5, 10, 0, 0)) + self.assertEqual(df.ymdHMS.ix[0], datetime(2001, 1, 5, 10, 0, 0)) def test_datetime_fractional_seconds(self): data = """\ @@ -104,10 +104,10 @@ def test_datetime_fractional_seconds(self): parse_dates=datecols, date_parser=conv.parse_all_fields) self.assert_('ymdHMS' in df) - self.assert_(df.ymdHMS.ix[0] == datetime(2001, 1, 5, 10, 0, 0, - microsecond=123456)) - self.assert_(df.ymdHMS.ix[1] == datetime(2001, 1, 5, 10, 0, 0, - microsecond=500000)) + self.assertEqual(df.ymdHMS.ix[0], datetime(2001, 1, 5, 10, 0, 0, + microsecond=123456)) + self.assertEqual(df.ymdHMS.ix[1], datetime(2001, 1, 5, 10, 0, 0, + microsecond=500000)) def test_generic(self): data = "year, month, day, a\n 2001, 01, 10, 10.\n 2001, 02, 1, 11." @@ -117,7 +117,7 @@ def test_generic(self): parse_dates=datecols, date_parser=dateconverter) self.assert_('ym' in df) - self.assert_(df.ym.ix[0] == date(2001, 1, 1)) + self.assertEqual(df.ym.ix[0], date(2001, 1, 1)) if __name__ == '__main__': diff --git a/pandas/io/tests/test_packers.py b/pandas/io/tests/test_packers.py index 8cab9a65995bf..0bbf81384672e 100644 --- a/pandas/io/tests/test_packers.py +++ b/pandas/io/tests/test_packers.py @@ -194,7 +194,7 @@ def test_timestamp(self): '20130101'), Timestamp('20130101', tz='US/Eastern'), Timestamp('201301010501')]: i_rec = self.encode_decode(i) - self.assert_(i == i_rec) + self.assertEqual(i, i_rec) def test_datetimes(self): @@ -207,7 +207,7 @@ def test_datetimes(self): 2013, 1, 1), datetime.datetime(2013, 1, 1, 5, 1), datetime.date(2013, 1, 1), np.datetime64(datetime.datetime(2013, 1, 5, 2, 15))]: i_rec = self.encode_decode(i) - self.assert_(i == i_rec) + self.assertEqual(i, i_rec) def test_timedeltas(self): @@ -215,7 +215,7 @@ def test_timedeltas(self): datetime.timedelta(days=1, seconds=10), np.timedelta64(1000000)]: i_rec = self.encode_decode(i) - self.assert_(i == i_rec) + self.assertEqual(i, i_rec) class TestIndex(TestPackers): diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 76006507be524..344f5a3f215b2 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -309,7 +309,7 @@ def func(*date_cols): self.assert_('X3' not in df) d = datetime(1999, 1, 27, 19, 0) - self.assert_(df.ix[0, 'nominal'] == d) + self.assertEqual(df.ix[0, 'nominal'], d) df = self.read_csv(StringIO(data), header=None, date_parser=func, @@ -342,7 +342,7 @@ def func(*date_cols): self.assert_('X3' not in df) d = datetime(1999, 1, 27, 19, 0) - self.assert_(df.ix[0, 'X1_X2'] == d) + self.assertEqual(df.ix[0, 'X1_X2'], d) df = read_csv(StringIO(data), header=None, parse_dates=[[1, 2], [1, 3]], keep_date_col=True) @@ -363,7 +363,7 @@ def func(*date_cols): df = self.read_csv(StringIO(data), sep=',', header=None, parse_dates=[1], index_col=1) d = datetime(1999, 1, 27, 19, 0) - self.assert_(df.index[0] == d) + self.assertEqual(df.index[0], d) def test_multiple_date_cols_int_cast(self): data = ("KORD,19990127, 19:00:00, 18:56:00, 0.8100\n" @@ -473,11 +473,11 @@ def test_index_col_named(self): index=Index(['hello', 'world', 'foo'], name='message')) rs = self.read_csv(StringIO(data), names=names, index_col=['message']) tm.assert_frame_equal(xp, rs) - self.assert_(xp.index.name == rs.index.name) + self.assertEqual(xp.index.name, rs.index.name) rs = self.read_csv(StringIO(data), names=names, index_col='message') tm.assert_frame_equal(xp, rs) - self.assert_(xp.index.name == rs.index.name) + self.assertEqual(xp.index.name, rs.index.name) def test_converter_index_col_bug(self): # 1835 @@ -488,7 +488,7 @@ def test_converter_index_col_bug(self): xp = DataFrame({'B': [2, 4]}, index=Index([1, 3], name='A')) tm.assert_frame_equal(rs, xp) - self.assert_(rs.index.name == xp.index.name) + self.assertEqual(rs.index.name, xp.index.name) def test_date_parser_int_bug(self): # #3071 @@ -640,7 +640,7 @@ def test_quoting(self): good_line_small = bad_line_small + '"' df = self.read_table(StringIO(good_line_small), sep='\t') - self.assert_(len(df) == 3) + self.assertEqual(len(df), 3) def test_non_string_na_values(self): # GH3611, na_values that are not a string are an issue @@ -1005,10 +1005,10 @@ def test_read_csv_dataframe(self): df2 = self.read_table(self.csv1, sep=',', index_col=0, parse_dates=True) self.assert_(np.array_equal(df.columns, ['A', 'B', 'C', 'D'])) - self.assert_(df.index.name == 'index') + self.assertEqual(df.index.name, 'index') self.assert_(isinstance(df.index[0], (datetime, np.datetime64, Timestamp))) - self.assert_(df.values.dtype == np.float64) + self.assertEqual(df.values.dtype, np.float64) tm.assert_frame_equal(df, df2) def test_read_csv_no_index_name(self): @@ -1018,7 +1018,7 @@ def test_read_csv_no_index_name(self): self.assert_(np.array_equal(df.columns, ['A', 'B', 'C', 'D', 'E'])) self.assert_(isinstance(df.index[0], (datetime, np.datetime64, Timestamp))) - self.assert_(df.ix[:, ['A', 'B', 'C', 'D']].values.dtype == np.float64) + self.assertEqual(df.ix[:, ['A', 'B', 'C', 'D']].values.dtype, np.float64) tm.assert_frame_equal(df, df2) def test_read_table_unicode(self): @@ -1070,7 +1070,7 @@ def test_parse_bools(self): True,3 """ data = self.read_csv(StringIO(data)) - self.assert_(data['A'].dtype == np.bool_) + self.assertEqual(data['A'].dtype, np.bool_) data = """A,B YES,1 @@ -1082,7 +1082,7 @@ def test_parse_bools(self): data = self.read_csv(StringIO(data), true_values=['yes', 'Yes', 'YES'], false_values=['no', 'NO', 'No']) - self.assert_(data['A'].dtype == np.bool_) + self.assertEqual(data['A'].dtype, np.bool_) data = """A,B TRUE,1 @@ -1090,7 +1090,7 @@ def test_parse_bools(self): TRUE,3 """ data = self.read_csv(StringIO(data)) - self.assert_(data['A'].dtype == np.bool_) + self.assertEqual(data['A'].dtype, np.bool_) data = """A,B foo,bar @@ -1107,8 +1107,8 @@ def test_int_conversion(self): 3.0,3 """ data = self.read_csv(StringIO(data)) - self.assert_(data['A'].dtype == np.float64) - self.assert_(data['B'].dtype == np.int64) + self.assertEqual(data['A'].dtype, np.float64) + self.assertEqual(data['B'].dtype, np.int64) def test_infer_index_col(self): data = """A,B,C @@ -1218,7 +1218,7 @@ def test_iterator(self): reader = self.read_csv(StringIO(data), chunksize=1) result = list(reader) expected = DataFrame(dict(A = [1,4,7], B = [2,5,8], C = [3,6,9]), index=['foo','bar','baz']) - self.assert_(len(result) == 3) + self.assertEqual(len(result), 3) tm.assert_frame_equal(pd.concat(result), expected) def test_header_not_first_line(self): @@ -1513,7 +1513,7 @@ def test_converters_no_implicit_conv(self): f = lambda x: x.strip() converter = {0: f} df = self.read_csv(StringIO(data), header=None, converters=converter) - self.assert_(df[0].dtype == object) + self.assertEqual(df[0].dtype, object) def test_converters_euro_decimal_format(self): data = """Id;Number1;Number2;Text1;Text2;Number3 @@ -1523,9 +1523,9 @@ def test_converters_euro_decimal_format(self): f = lambda x: float(x.replace(",", ".")) converter = {'Number1': f, 'Number2': f, 'Number3': f} df2 = self.read_csv(StringIO(data), sep=';', converters=converter) - self.assert_(df2['Number1'].dtype == float) - self.assert_(df2['Number2'].dtype == float) - self.assert_(df2['Number3'].dtype == float) + self.assertEqual(df2['Number1'].dtype, float) + self.assertEqual(df2['Number2'].dtype, float) + self.assertEqual(df2['Number3'].dtype, float) def test_converter_return_string_bug(self): # GH #583 @@ -1536,7 +1536,7 @@ def test_converter_return_string_bug(self): f = lambda x: float(x.replace(",", ".")) converter = {'Number1': f, 'Number2': f, 'Number3': f} df2 = self.read_csv(StringIO(data), sep=';', converters=converter) - self.assert_(df2['Number1'].dtype == float) + self.assertEqual(df2['Number1'].dtype, float) def test_read_table_buglet_4x_multiindex(self): text = """ A B C D E @@ -1659,15 +1659,15 @@ def test_parse_tz_aware(self): # it works result = read_csv(data, index_col=0, parse_dates=True) stamp = result.index[0] - self.assert_(stamp.minute == 39) + self.assertEqual(stamp.minute, 39) try: self.assert_(result.index.tz is pytz.utc) except AssertionError: # hello Yaroslav arr = result.index.to_pydatetime() result = tools.to_datetime(arr, utc=True)[0] - self.assert_(stamp.minute == result.minute) - self.assert_(stamp.hour == result.hour) - self.assert_(stamp.day == result.day) + self.assertEqual(stamp.minute, result.minute) + self.assertEqual(stamp.hour, result.hour) + self.assertEqual(stamp.day, result.day) def test_multiple_date_cols_index(self): data = """\ @@ -2364,7 +2364,7 @@ def test_verbose_import(self): try: # it works! df = self.read_csv(StringIO(text), verbose=True) - self.assert_(buf.getvalue() == 'Filled 3 NA values in column a\n') + self.assertEqual(buf.getvalue(), 'Filled 3 NA values in column a\n') finally: sys.stdout = sys.__stdout__ @@ -2384,7 +2384,7 @@ def test_verbose_import(self): try: # it works! df = self.read_csv(StringIO(text), verbose=True, index_col=0) - self.assert_(buf.getvalue() == 'Filled 1 NA values in column a\n') + self.assertEqual(buf.getvalue(), 'Filled 1 NA values in column a\n') finally: sys.stdout = sys.__stdout__ @@ -2597,8 +2597,8 @@ def test_pass_dtype(self): result = self.read_csv(StringIO(data), dtype={'one': 'u1', 1: 'S1'}, as_recarray=True) - self.assert_(result['one'].dtype == 'u1') - self.assert_(result['two'].dtype == 'S1') + self.assertEqual(result['one'].dtype, 'u1') + self.assertEqual(result['two'].dtype, 'S1') def test_usecols_dtypes(self): data = """\ @@ -2765,9 +2765,9 @@ def test_euro_decimal_format(self): 3;878,158;108013,434;GHI;rez;2,735694704""" df2 = self.read_csv(StringIO(data), sep=';', decimal=',') - self.assert_(df2['Number1'].dtype == float) - self.assert_(df2['Number2'].dtype == float) - self.assert_(df2['Number3'].dtype == float) + self.assertEqual(df2['Number1'].dtype, float) + self.assertEqual(df2['Number2'].dtype, float) + self.assertEqual(df2['Number3'].dtype, float) def test_custom_lineterminator(self): data = 'a,b,c~1,2,3~4,5,6' diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index dc218b530db64..3c8e40fb1566a 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -385,9 +385,9 @@ def test_versioning(self): _maybe_remove(store, 'df1') store.append('df1', df[:10]) store.append('df1', df[10:]) - self.assert_(store.root.a._v_attrs.pandas_version == '0.10.1') - self.assert_(store.root.b._v_attrs.pandas_version == '0.10.1') - self.assert_(store.root.df1._v_attrs.pandas_version == '0.10.1') + self.assertEqual(store.root.a._v_attrs.pandas_version, '0.10.1') + self.assertEqual(store.root.b._v_attrs.pandas_version, '0.10.1') + self.assertEqual(store.root.df1._v_attrs.pandas_version, '0.10.1') # write a file and wipe its versioning _maybe_remove(store, 'df2') @@ -412,7 +412,7 @@ def check(mode): else: store = HDFStore(path,mode=mode) - self.assert_(store._handle.mode == mode) + self.assertEqual(store._handle.mode, mode) store.close() with ensure_clean_path(self.path) as path: @@ -425,7 +425,7 @@ def f(): self.assertRaises(IOError, f) else: with get_store(path,mode=mode) as store: - self.assert_(store._handle.mode == mode) + self.assertEqual(store._handle.mode, mode) with ensure_clean_path(self.path) as path: @@ -474,7 +474,7 @@ def test_reopen_handle(self): store.open('r') self.assert_(store.is_open) self.assertEquals(len(store), 1) - self.assert_(store._mode == 'r') + self.assertEqual(store._mode, 'r') store.close() self.assert_(not store.is_open) @@ -482,7 +482,7 @@ def test_reopen_handle(self): store.open('a') self.assert_(store.is_open) self.assertEquals(len(store), 1) - self.assert_(store._mode == 'a') + self.assertEqual(store._mode, 'a') store.close() self.assert_(not store.is_open) @@ -490,7 +490,7 @@ def test_reopen_handle(self): store.open('a') self.assert_(store.is_open) self.assertEquals(len(store), 1) - self.assert_(store._mode == 'a') + self.assertEqual(store._mode, 'a') store.close() self.assert_(not store.is_open) @@ -788,7 +788,7 @@ def test_append_series(self): store.append('ns', ns) result = store['ns'] tm.assert_series_equal(result, ns) - self.assert_(result.name == ns.name) + self.assertEqual(result.name, ns.name) # select on the values expected = ns[ns>60] @@ -1113,7 +1113,7 @@ def test_append_with_strings(self): dict([(x, "%s_extra" % x) for x in wp.minor_axis]), axis=2) def check_col(key,name,size): - self.assert_(getattr(store.get_storer(key).table.description,name).itemsize == size) + self.assertEqual(getattr(store.get_storer(key).table.description,name).itemsize, size) store.append('s1', wp, min_itemsize=20) store.append('s1', wp2) @@ -1179,7 +1179,7 @@ def check_col(key,name,size): with ensure_clean_store(self.path) as store: def check_col(key,name,size): - self.assert_(getattr(store.get_storer(key).table.description,name).itemsize == size) + self.assertEqual(getattr(store.get_storer(key).table.description,name).itemsize, size) df = DataFrame(dict(A = 'foo', B = 'bar'),index=range(10)) @@ -1187,20 +1187,20 @@ def check_col(key,name,size): _maybe_remove(store, 'df') store.append('df', df, min_itemsize={'A' : 200 }) check_col('df', 'A', 200) - self.assert_(store.get_storer('df').data_columns == ['A']) + self.assertEqual(store.get_storer('df').data_columns, ['A']) # a min_itemsize that creates a data_column2 _maybe_remove(store, 'df') store.append('df', df, data_columns = ['B'], min_itemsize={'A' : 200 }) check_col('df', 'A', 200) - self.assert_(store.get_storer('df').data_columns == ['B','A']) + self.assertEqual(store.get_storer('df').data_columns, ['B','A']) # a min_itemsize that creates a data_column2 _maybe_remove(store, 'df') store.append('df', df, data_columns = ['B'], min_itemsize={'values' : 200 }) check_col('df', 'B', 200) check_col('df', 'values_block_0', 200) - self.assert_(store.get_storer('df').data_columns == ['B']) + self.assertEqual(store.get_storer('df').data_columns, ['B']) # infer the .typ on subsequent appends _maybe_remove(store, 'df') @@ -1252,7 +1252,7 @@ def test_append_with_data_columns(self): # using min_itemsize and a data column def check_col(key,name,size): - self.assert_(getattr(store.get_storer(key).table.description,name).itemsize == size) + self.assertEqual(getattr(store.get_storer(key).table.description,name).itemsize, size) with ensure_clean_store(self.path) as store: _maybe_remove(store, 'df') @@ -1803,7 +1803,7 @@ def test_append_raise(self): # list in column df = tm.makeDataFrame() df['invalid'] = [['a']] * len(df) - self.assert_(df.dtypes['invalid'] == np.object_) + self.assertEqual(df.dtypes['invalid'], np.object_) self.assertRaises(TypeError, store.append,'df',df) # multiple invalid columns @@ -1817,7 +1817,7 @@ def test_append_raise(self): s = s.astype(object) s[0:5] = np.nan df['invalid'] = s - self.assert_(df.dtypes['invalid'] == np.object_) + self.assertEqual(df.dtypes['invalid'], np.object_) self.assertRaises(TypeError, store.append,'df', df) # directy ndarray @@ -3034,14 +3034,14 @@ def test_select_with_many_inputs(self): result = store.select('df', [Term('B=selector')]) expected = df[ df.B.isin(selector) ] tm.assert_frame_equal(expected, result) - self.assert_(len(result) == 100) + self.assertEqual(len(result), 100) # big selector along the index selector = Index(df.ts[0:100].values) result = store.select('df', [Term('ts=selector')]) expected = df[ df.ts.isin(selector.values) ] tm.assert_frame_equal(expected, result) - self.assert_(len(result) == 100) + self.assertEqual(len(result), 100) def test_select_iterator(self): @@ -3062,7 +3062,7 @@ def test_select_iterator(self): results = [] for s in store.select('df',chunksize=100): results.append(s) - self.assert_(len(results) == 5) + self.assertEqual(len(results), 5) result = concat(results) tm.assert_frame_equal(expected, result) @@ -3088,7 +3088,7 @@ def test_select_iterator(self): for x in read_hdf(path,'df',chunksize=100): results.append(x) - self.assert_(len(results) == 5) + self.assertEqual(len(results), 5) result = concat(results) tm.assert_frame_equal(result, df) tm.assert_frame_equal(result, read_hdf(path,'df')) @@ -3175,7 +3175,7 @@ def test_retain_index_attributes2(self): df = DataFrame(dict(A = Series(lrange(3), index=idx))) df.to_hdf(path,'data',mode='w',append=True) - self.assert_(read_hdf(path,'data').index.name == 'foo') + self.assertEqual(read_hdf(path,'data').index.name, 'foo') with tm.assert_produces_warning(expected_warning=AttributeConflictWarning): @@ -3906,7 +3906,7 @@ def do_copy(f = None, new_f = None, keys = None, propindexes = True, **kwargs): # check keys if keys is None: keys = store.keys() - self.assert_(set(keys) == set(tstore.keys())) + self.assertEqual(set(keys), set(tstore.keys())) # check indicies & nrows for k in tstore.keys(): @@ -3914,13 +3914,13 @@ def do_copy(f = None, new_f = None, keys = None, propindexes = True, **kwargs): new_t = tstore.get_storer(k) orig_t = store.get_storer(k) - self.assert_(orig_t.nrows == new_t.nrows) + self.assertEqual(orig_t.nrows, new_t.nrows) # check propindixes if propindexes: for a in orig_t.axes: if a.is_indexed: - self.assert_(new_t[a.name].is_indexed == True) + self.assertTrue(new_t[a.name].is_indexed) finally: safe_close(store) diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index 649d391820147..1640bee7a9929 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -230,11 +230,11 @@ def test_encoding(self): if compat.PY3: expected = raw.kreis1849[0] - self.assert_(result == expected) + self.assertEqual(result, expected) self.assert_(isinstance(result, compat.string_types)) else: expected = raw.kreis1849.str.decode("latin-1")[0] - self.assert_(result == expected) + self.assertEqual(result, expected) self.assert_(isinstance(result, unicode)) def test_read_write_dta11(self): diff --git a/pandas/sparse/tests/test_list.py b/pandas/sparse/tests/test_list.py index 21241050e39dc..c18654c7360a4 100644 --- a/pandas/sparse/tests/test_list.py +++ b/pandas/sparse/tests/test_list.py @@ -68,12 +68,12 @@ def test_consolidate(self): splist.append(arr[6:]) consol = splist.consolidate(inplace=False) - self.assert_(consol.nchunks == 1) - self.assert_(splist.nchunks == 3) + self.assertEqual(consol.nchunks, 1) + self.assertEqual(splist.nchunks, 3) assert_sp_array_equal(consol.to_array(), exp_sparr) splist.consolidate() - self.assert_(splist.nchunks == 1) + self.assertEqual(splist.nchunks, 1) assert_sp_array_equal(splist.to_array(), exp_sparr) def test_copy(self): diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index 70f1e50f475bb..7523b2d912f6f 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -252,13 +252,13 @@ def test_constructor(self): values = np.ones(self.bseries.npoints) sp = SparseSeries(values, sparse_index=self.bseries.sp_index) sp.sp_values[:5] = 97 - self.assert_(values[0] == 97) + self.assertEqual(values[0], 97) # but can make it copy! sp = SparseSeries(values, sparse_index=self.bseries.sp_index, copy=True) sp.sp_values[:5] = 100 - self.assert_(values[0] == 97) + self.assertEqual(values[0], 97) def test_constructor_scalar(self): data = 5 @@ -282,7 +282,7 @@ def test_copy_astype(self): cop = self.bseries.astype(np.float64) self.assert_(cop is not self.bseries) self.assert_(cop.sp_index is self.bseries.sp_index) - self.assert_(cop.dtype == np.float64) + self.assertEqual(cop.dtype, np.float64) cop2 = self.iseries.copy() @@ -291,8 +291,8 @@ def test_copy_astype(self): # test that data is copied cop[:5] = 97 - self.assert_(cop.sp_values[0] == 97) - self.assert_(self.bseries.sp_values[0] != 97) + self.assertEqual(cop.sp_values[0], 97) + self.assertNotEqual(self.bseries.sp_values[0], 97) # correct fill value zbcop = self.zbseries.copy() @@ -376,7 +376,7 @@ def test_set_value(self): self.assertEqual(self.btseries[idx], 0) self.iseries.set_value('foobar', 0) - self.assert_(self.iseries.index[-1] == 'foobar') + self.assertEqual(self.iseries.index[-1], 'foobar') self.assertEqual(self.iseries['foobar'], 0) def test_getitem_slice(self): @@ -423,7 +423,7 @@ def _compare(idx): def test_setitem(self): self.bseries[5] = 7. - self.assert_(self.bseries[5] == 7.) + self.assertEqual(self.bseries[5], 7.) def test_setslice(self): self.bseries[5:10] = 7. @@ -779,15 +779,15 @@ def setUp(self): def test_as_matrix(self): empty = self.empty.as_matrix() - self.assert_(empty.shape == (0, 0)) + self.assertEqual(empty.shape, (0, 0)) no_cols = SparseDataFrame(index=np.arange(10)) mat = no_cols.as_matrix() - self.assert_(mat.shape == (10, 0)) + self.assertEqual(mat.shape, (10, 0)) no_index = SparseDataFrame(columns=np.arange(10)) mat = no_index.as_matrix() - self.assert_(mat.shape == (0, 10)) + self.assertEqual(mat.shape, (0, 10)) def test_copy(self): cp = self.frame.copy() @@ -859,8 +859,8 @@ def test_constructor_ndarray(self): def test_constructor_empty(self): sp = SparseDataFrame() - self.assert_(len(sp.index) == 0) - self.assert_(len(sp.columns) == 0) + self.assertEqual(len(sp.index), 0) + self.assertEqual(len(sp.columns), 0) def test_constructor_dataframe(self): dense = self.frame.to_dense() @@ -1087,14 +1087,14 @@ def test_set_value(self): # ok as the index gets conver to object frame = self.frame.copy() res = frame.set_value('foobar', 'B', 1.5) - self.assert_(res.index.dtype == 'object') + self.assertEqual(res.index.dtype, 'object') 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') + self.assertEqual(res.index[-1], 'foobar') self.assertEqual(res.get_value('foobar', 'B'), 1.5) res2 = res.set_value('foobar', 'qux', 1.5) @@ -1239,7 +1239,7 @@ def test_apply(self): assert_almost_equal(applied.values, np.sqrt(self.frame.values)) applied = self.fill_frame.apply(np.sqrt) - self.assert_(applied['A'].fill_value == np.sqrt(2)) + self.assertEqual(applied['A'].fill_value, np.sqrt(2)) # agg / broadcast broadcasted = self.frame.apply(np.sum, broadcast=True) diff --git a/pandas/stats/tests/test_moments.py b/pandas/stats/tests/test_moments.py index 50b1854f0e24b..a8359c102a902 100644 --- a/pandas/stats/tests/test_moments.py +++ b/pandas/stats/tests/test_moments.py @@ -119,13 +119,13 @@ def test_cmov_window_corner(self): # empty vals = np.array([]) rs = mom.rolling_window(vals, 5, 'boxcar', center=True) - self.assert_(len(rs) == 0) + self.assertEqual(len(rs), 0) # shorter than window vals = np.random.randn(5) rs = mom.rolling_window(vals, 10, 'boxcar') self.assert_(np.isnan(rs).all()) - self.assert_(len(rs) == 5) + self.assertEqual(len(rs), 5) def test_cmov_window_frame(self): _skip_if_no_scipy() @@ -570,7 +570,7 @@ def _check_ew_ndarray(self, func, preserve_nan=False): # pass in ints result2 = func(np.arange(50), span=10) - self.assert_(result2.dtype == np.float_) + self.assertEqual(result2.dtype, np.float_) def _check_ew_structures(self, func): series_result = func(self.series, com=10) diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 64a5d981f6cf6..cddf8669950aa 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -2392,7 +2392,7 @@ def test_multifunc_sum_bug(self): grouped = x.groupby('test') result = grouped.agg({'fl': 'sum', 2: 'size'}) - self.assert_(result['fl'].dtype == np.float64) + self.assertEqual(result['fl'].dtype, np.float64) def test_handle_dict_return_value(self): def f(group): diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index 78d6002bcea47..bfa6fd77ba733 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -317,8 +317,8 @@ def test_join_index_mixed(self): df1 = DataFrame({'A': 1., 'B': 2, 'C': 'foo', 'D': True}, index=np.arange(10), columns=['A', 'B', 'C', 'D']) - self.assert_(df1['B'].dtype == np.int64) - self.assert_(df1['D'].dtype == np.bool_) + self.assertEqual(df1['B'].dtype, np.int64) + self.assertEqual(df1['D'].dtype, np.bool_) df2 = DataFrame({'A': 1., 'B': 2, 'C': 'foo', 'D': True}, index=np.arange(0, 10, 2), @@ -459,9 +459,9 @@ def test_join_float64_float32(self): a = DataFrame(randn(10, 2), columns=['a', 'b'], dtype = np.float64) b = DataFrame(randn(10, 1), columns=['c'], dtype = np.float32) joined = a.join(b) - self.assert_(joined.dtypes['a'] == 'float64') - self.assert_(joined.dtypes['b'] == 'float64') - self.assert_(joined.dtypes['c'] == 'float32') + self.assertEqual(joined.dtypes['a'], 'float64') + self.assertEqual(joined.dtypes['b'], 'float64') + self.assertEqual(joined.dtypes['c'], 'float32') a = np.random.randint(0, 5, 100).astype('int64') b = np.random.random(100).astype('float64') @@ -470,10 +470,10 @@ def test_join_float64_float32(self): xpdf = DataFrame({'a': a, 'b': b, 'c': c }) s = DataFrame(np.random.random(5).astype('float32'), columns=['md']) rs = df.merge(s, left_on='a', right_index=True) - self.assert_(rs.dtypes['a'] == 'int64') - self.assert_(rs.dtypes['b'] == 'float64') - self.assert_(rs.dtypes['c'] == 'float32') - self.assert_(rs.dtypes['md'] == 'float32') + self.assertEqual(rs.dtypes['a'], 'int64') + self.assertEqual(rs.dtypes['b'], 'float64') + self.assertEqual(rs.dtypes['c'], 'float32') + self.assertEqual(rs.dtypes['md'], 'float32') xp = xpdf.merge(s, left_on='a', right_index=True) assert_frame_equal(rs, xp) @@ -1230,7 +1230,7 @@ def test_append_preserve_index_name(self): df2 = df2.set_index(['A']) result = df1.append(df2) - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') def test_join_many(self): df = DataFrame(np.random.randn(10, 6), columns=list('abcdef')) @@ -1275,8 +1275,8 @@ def test_append_missing_column_proper_upcast(self): dtype=bool)}) appended = df1.append(df2, ignore_index=True) - self.assert_(appended['A'].dtype == 'f8') - self.assert_(appended['B'].dtype == 'O') + self.assertEqual(appended['A'].dtype, 'f8') + self.assertEqual(appended['B'].dtype, 'O') def test_concat_with_group_keys(self): df = DataFrame(np.random.randn(4, 3)) diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index 1571cf3bf6a7d..2843433fc61e3 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -114,7 +114,7 @@ def test_pivot_dtypes(self): # can convert dtypes f = DataFrame({'a' : ['cat', 'bat', 'cat', 'bat'], 'v' : [1,2,3,4], 'i' : ['a','b','a','b']}) - self.assert_(f.dtypes['v'] == 'int64') + self.assertEqual(f.dtypes['v'], 'int64') z = pivot_table(f, values='v', rows=['a'], cols=['i'], fill_value=0, aggfunc=np.sum) result = z.get_dtype_counts() @@ -123,7 +123,7 @@ def test_pivot_dtypes(self): # cannot convert dtypes f = DataFrame({'a' : ['cat', 'bat', 'cat', 'bat'], 'v' : [1.5,2.5,3.5,4.5], 'i' : ['a','b','a','b']}) - self.assert_(f.dtypes['v'] == 'float64') + self.assertEqual(f.dtypes['v'], 'float64') z = pivot_table(f, values='v', rows=['a'], cols=['i'], fill_value=0, aggfunc=np.mean) result = z.get_dtype_counts() diff --git a/pandas/tools/tests/test_tile.py b/pandas/tools/tests/test_tile.py index ba51946173d5f..efb28ccb4c9e2 100644 --- a/pandas/tools/tests/test_tile.py +++ b/pandas/tools/tests/test_tile.py @@ -143,7 +143,7 @@ def test_qcut_bounds(self): arr = np.random.randn(1000) factor = qcut(arr, 10, labels=False) - self.assert_(len(np.unique(factor)) == 10) + self.assertEqual(len(np.unique(factor)), 10) def test_qcut_specify_quantiles(self): arr = np.random.randn(100) diff --git a/pandas/tools/tests/test_tools.py b/pandas/tools/tests/test_tools.py index 2c70427f79559..4fd70e28497a8 100644 --- a/pandas/tools/tests/test_tools.py +++ b/pandas/tools/tests/test_tools.py @@ -14,10 +14,10 @@ def test_value_range(self): res = value_range(df) - self.assert_(res['Minimum'] == -5) - self.assert_(res['Maximum'] == 5) + self.assertEqual(res['Minimum'], -5) + self.assertEqual(res['Maximum'], 5) df.ix[0, 1] = np.NaN - self.assert_(res['Minimum'] == -5) - self.assert_(res['Maximum'] == 5) + self.assertEqual(res['Minimum'], -5) + self.assertEqual(res['Maximum'], 5) diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py index d1efa12953caa..479fb599f9e3a 100644 --- a/pandas/tseries/tests/test_daterange.py +++ b/pandas/tseries/tests/test_daterange.py @@ -265,7 +265,7 @@ def test_intersection(self): expected = rng[10:25] self.assert_(the_int.equals(expected)) tm.assert_isinstance(the_int, DatetimeIndex) - self.assert_(the_int.offset == rng.offset) + self.assertEqual(the_int.offset, rng.offset) the_int = rng1.intersection(rng2.view(DatetimeIndex)) self.assert_(the_int.equals(expected)) @@ -363,7 +363,7 @@ def test_range_tz(self): end = datetime(2011, 1, 3, tzinfo=tz('US/Eastern')) dr = date_range(start=start, periods=3) - self.assert_(dr.tz == tz('US/Eastern')) + self.assertEqual(dr.tz, tz('US/Eastern')) self.assertEqual(dr[0], start) self.assertEqual(dr[2], end) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 214b7fb928dec..5d846229ed515 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -1613,7 +1613,7 @@ def test_append_concat_tz(self): def test_set_dataframe_column_ns_dtype(self): x = DataFrame([datetime.now(), datetime.now()]) - self.assert_(x[0].dtype == np.dtype('M8[ns]')) + self.assertEqual(x[0].dtype, np.dtype('M8[ns]')) def test_groupby_count_dateparseerror(self): dr = date_range(start='1/1/2012', freq='5min', periods=10) diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py index b7582619b577d..48fd68b71cfc1 100644 --- a/pandas/tseries/tests/test_timezones.py +++ b/pandas/tseries/tests/test_timezones.py @@ -77,7 +77,7 @@ def test_utc_to_local_no_modify(self): # Values are unmodified self.assert_(np.array_equal(rng.asi8, rng_eastern.asi8)) - self.assert_(rng_eastern.tz == pytz.timezone('US/Eastern')) + self.assertEqual(rng_eastern.tz, pytz.timezone('US/Eastern')) def test_localize_utc_conversion(self): @@ -253,7 +253,7 @@ def test_date_range_localize(self): rng = date_range('3/11/2012 00:00', periods=10, freq='H', tz='US/Eastern') - self.assert_(rng[2].hour == 3) + self.assertEqual(rng[2].hour, 3) def test_utc_box_timestamp_and_localize(self): rng = date_range('3/11/2012', '3/12/2012', freq='H', tz='utc') @@ -288,7 +288,7 @@ def test_pass_dates_localize_to_utc(self): fromdates = DatetimeIndex(strdates, tz='US/Eastern') - self.assert_(conv.tz == fromdates.tz) + self.assertEqual(conv.tz, fromdates.tz) self.assert_(np.array_equal(conv.values, fromdates.values)) def test_field_access_localize(self): @@ -417,8 +417,8 @@ def test_take_dont_lose_meta(self): rng = date_range('1/1/2000', periods=20, tz='US/Eastern') result = rng.take(lrange(5)) - self.assert_(result.tz == rng.tz) - self.assert_(result.freq == rng.freq) + self.assertEqual(result.tz, rng.tz) + self.assertEqual(result.freq, rng.freq) def test_index_with_timezone_repr(self): rng = date_range('4/13/2010', '5/6/2010') @@ -457,13 +457,13 @@ def test_localized_at_time_between_time(self): result = ts_local.at_time(time(10, 0)) expected = ts.at_time(time(10, 0)).tz_localize('US/Eastern') assert_series_equal(result, expected) - self.assert_(result.index.tz.zone == 'US/Eastern') + self.assertEqual(result.index.tz.zone, 'US/Eastern') t1, t2 = time(10, 0), time(11, 0) result = ts_local.between_time(t1, t2) expected = ts.between_time(t1, t2).tz_localize('US/Eastern') assert_series_equal(result, expected) - self.assert_(result.index.tz.zone == 'US/Eastern') + self.assertEqual(result.index.tz.zone, 'US/Eastern') def test_string_index_alias_tz_aware(self): rng = date_range('1/1/2000', periods=10, tz='US/Eastern') @@ -477,7 +477,7 @@ def test_fixed_offset(self): datetime(2000, 1, 2, tzinfo=fixed_off), datetime(2000, 1, 3, tzinfo=fixed_off)] result = to_datetime(dates) - self.assert_(result.tz == fixed_off) + self.assertEqual(result.tz, fixed_off) def test_fixedtz_topydatetime(self): dates = np.array([datetime(2000, 1, 1, tzinfo=fixed_off), @@ -498,7 +498,7 @@ def test_convert_tz_aware_datetime_datetime(self): dates_aware = [tz.localize(x) for x in dates] result = to_datetime(dates_aware) - self.assert_(result.tz.zone == 'US/Eastern') + self.assertEqual(result.tz.zone, 'US/Eastern') converted = to_datetime(dates_aware, utc=True) ex_vals = [Timestamp(x).value for x in dates_aware] @@ -533,7 +533,7 @@ def test_frame_no_datetime64_dtype(self): dr = date_range('2011/1/1', '2012/1/1', freq='W-FRI') dr_tz = dr.tz_localize('US/Eastern') e = DataFrame({'A': 'foo', 'B': dr_tz}, index=dr) - self.assert_(e['B'].dtype == 'M8[ns]') + self.assertEqual(e['B'].dtype, 'M8[ns]') # GH 2810 (with timezones) datetimes_naive = [ ts.to_pydatetime() for ts in dr ] @@ -566,7 +566,7 @@ def test_shift_localized(self): dr_tz = dr.tz_localize('US/Eastern') result = dr_tz.shift(1, '10T') - self.assert_(result.tz == dr_tz.tz) + self.assertEqual(result.tz, dr_tz.tz) def test_tz_aware_asfreq(self): dr = date_range( @@ -587,7 +587,7 @@ def test_tzaware_datetime_to_index(self): d = [datetime(2012, 8, 19, tzinfo=pytz.timezone('US/Eastern'))] index = DatetimeIndex(d) - self.assert_(index.tz.zone == 'US/Eastern') + self.assertEqual(index.tz.zone, 'US/Eastern') def test_date_range_span_dst_transition(self): # #1778 @@ -606,8 +606,8 @@ def test_convert_datetime_list(self): dr2 = DatetimeIndex(list(dr), name='foo') self.assert_(dr.equals(dr2)) - self.assert_(dr.tz == dr2.tz) - self.assert_(dr2.name == 'foo') + self.assertEqual(dr.tz, dr2.tz) + self.assertEqual(dr2.name, 'foo') def test_frame_from_records_utc(self): rec = {'datum': 1.5, @@ -703,17 +703,17 @@ def test_series_frame_tz_localize(self): ts = Series(1, index=rng) result = ts.tz_localize('utc') - self.assert_(result.index.tz.zone == 'UTC') + self.assertEqual(result.index.tz.zone, 'UTC') df = DataFrame({'a': 1}, index=rng) result = df.tz_localize('utc') expected = DataFrame({'a': 1}, rng.tz_localize('UTC')) - self.assert_(result.index.tz.zone == 'UTC') + self.assertEqual(result.index.tz.zone, 'UTC') assert_frame_equal(result, expected) df = df.T result = df.tz_localize('utc', axis=1) - self.assert_(result.columns.tz.zone == 'UTC') + self.assertEqual(result.columns.tz.zone, 'UTC') assert_frame_equal(result, expected.T) # Can't localize if already tz-aware @@ -727,17 +727,17 @@ def test_series_frame_tz_convert(self): ts = Series(1, index=rng) result = ts.tz_convert('Europe/Berlin') - self.assert_(result.index.tz.zone == 'Europe/Berlin') + self.assertEqual(result.index.tz.zone, 'Europe/Berlin') df = DataFrame({'a': 1}, index=rng) result = df.tz_convert('Europe/Berlin') expected = DataFrame({'a': 1}, rng.tz_convert('Europe/Berlin')) - self.assert_(result.index.tz.zone == 'Europe/Berlin') + self.assertEqual(result.index.tz.zone, 'Europe/Berlin') assert_frame_equal(result, expected) df = df.T result = df.tz_convert('Europe/Berlin', axis=1) - self.assert_(result.columns.tz.zone == 'Europe/Berlin') + self.assertEqual(result.columns.tz.zone, 'Europe/Berlin') assert_frame_equal(result, expected.T) # can't convert tz-naive @@ -754,11 +754,11 @@ def test_join_utc_convert(self): for how in ['inner', 'outer', 'left', 'right']: result = left.join(left[:-5], how=how) tm.assert_isinstance(result, DatetimeIndex) - self.assert_(result.tz == left.tz) + self.assertEqual(result.tz, left.tz) result = left.join(right[:-5], how=how) tm.assert_isinstance(result, DatetimeIndex) - self.assert_(result.tz.zone == 'UTC') + self.assertEqual(result.tz.zone, 'UTC') def test_join_aware(self): rng = date_range('1/1/2011', periods=10, freq='H') @@ -888,7 +888,7 @@ def test_arith_utc_convert(self): uts2 = ts2.tz_convert('utc') expected = uts1 + uts2 - self.assert_(result.index.tz == pytz.UTC) + self.assertEqual(result.index.tz, pytz.UTC) assert_series_equal(result, expected) def test_intersection(self): @@ -897,9 +897,9 @@ def test_intersection(self): left = rng[10:90][::-1] right = rng[20:80][::-1] - self.assert_(left.tz == rng.tz) + self.assertEqual(left.tz, rng.tz) result = left.intersection(right) - self.assert_(result.tz == left.tz) + self.assertEqual(result.tz, left.tz) def test_timestamp_equality_different_timezones(self): utc_range = date_range('1/1/2000', periods=20, tz='UTC')
Work on #6175, in pandas/*/tests. Tests still pass locally. Finishes most (all?) of the remaining vanilla assert_(x == y) conversions
https://api.github.com/repos/pandas-dev/pandas/pulls/6267
2014-02-05T13:22:33Z
2014-02-07T13:46:21Z
2014-02-07T13:46:21Z
2014-06-19T15:12:16Z
PERF: various performance optimizations
diff --git a/pandas/core/common.py b/pandas/core/common.py index 134e43bcd006a..e895c8ed0cf2d 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -134,7 +134,7 @@ def _isnull_new(obj): elif isinstance(obj, (ABCSeries, np.ndarray)): return _isnull_ndarraylike(obj) elif isinstance(obj, ABCGeneric): - return obj._constructor(obj._data.apply(lambda x: isnull(x.values))) + return obj._constructor(obj._data.isnull(func=isnull)) elif isinstance(obj, list) or hasattr(obj, '__array__'): return _isnull_ndarraylike(np.asarray(obj)) else: @@ -160,8 +160,7 @@ def _isnull_old(obj): elif isinstance(obj, (ABCSeries, np.ndarray)): return _isnull_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): - return obj._constructor(obj._data.apply( - lambda x: _isnull_old(x.values))) + return obj._constructor(obj._data.isnull(func=_isnull_old)) elif isinstance(obj, list) or hasattr(obj, '__array__'): return _isnull_ndarraylike_old(np.asarray(obj)) else: @@ -1540,14 +1539,7 @@ def _maybe_box(indexer, values, obj, key): # return the value return values - -def _values_from_object(o): - """ return my values or the object if we are say an ndarray """ - f = getattr(o, 'get_values', None) - if f is not None: - o = f() - return o - +_values_from_object = lib.values_from_object def _possibly_convert_objects(values, convert_dates=True, convert_numeric=True, @@ -2036,20 +2028,16 @@ def _maybe_make_list(obj): return obj -def is_bool(obj): - return isinstance(obj, (bool, np.bool_)) +is_bool = lib.is_bool -def is_integer(obj): - return isinstance(obj, (numbers.Integral, np.integer)) +is_integer = lib.is_integer -def is_float(obj): - return isinstance(obj, (float, np.floating)) +is_float = lib.is_float -def is_complex(obj): - return isinstance(obj, (numbers.Complex, np.complexfloating)) +is_complex = lib.is_complex def is_iterator(obj): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4c19831c6cbe3..de8bac05f211f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2825,14 +2825,14 @@ def _combine_match_columns(self, other, func, fill_value=None): fill_value) new_data = left._data.eval( - func, right, axes=[left.columns, self.index]) + func=func, other=right, axes=[left.columns, self.index]) return self._constructor(new_data) def _combine_const(self, other, func, raise_on_error=True): if self.empty: return self - new_data = self._data.eval(func, other, raise_on_error=raise_on_error) + new_data = self._data.eval(func=func, other=other, raise_on_error=raise_on_error) return self._constructor(new_data) def _compare_frame_evaluate(self, other, func, str_rep): @@ -3228,7 +3228,7 @@ def diff(self, periods=1): ------- diffed : DataFrame """ - new_data = self._data.diff(periods) + new_data = self._data.diff(n=periods) return self._constructor(new_data) #---------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2ee96d660eb87..0a0cfe94409f9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -128,7 +128,7 @@ def _init_mgr(self, mgr, axes=None, dtype=None, copy=False): elif dtype is not None: # avoid copy if we can if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype: - mgr = mgr.astype(dtype) + mgr = mgr.astype(dtype=dtype) return mgr #---------------------------------------------------------------------- @@ -2011,7 +2011,7 @@ def astype(self, dtype, copy=True, raise_on_error=True): """ mgr = self._data.astype( - dtype, copy=copy, raise_on_error=raise_on_error) + dtype=dtype, copy=copy, raise_on_error=raise_on_error) return self._constructor(mgr).__finalize__(self) def copy(self, deep=True): @@ -2153,7 +2153,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, from pandas import Series value = Series(value) - new_data = self._data.fillna(value, inplace=inplace, + new_data = self._data.fillna(value=value, inplace=inplace, downcast=downcast) elif isinstance(value, (dict, com.ABCSeries)): @@ -2170,7 +2170,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, obj.fillna(v, inplace=True) return result else: - new_data = self._data.fillna(value, inplace=inplace, + new_data = self._data.fillna(value=value, inplace=inplace, downcast=downcast) if inplace: @@ -2355,7 +2355,8 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, new_data = self._data for c, src in compat.iteritems(to_replace): if c in value and c in self: - new_data = new_data.replace(src, value[c], + new_data = new_data.replace(to_replace=src, + value=value[c], filter=[c], inplace=inplace, regex=regex) @@ -2365,7 +2366,8 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, new_data = self._data for k, src in compat.iteritems(to_replace): if k in self: - new_data = new_data.replace(src, value, + new_data = new_data.replace(to_replace=src, + value=value, filter=[k], inplace=inplace, regex=regex) @@ -2380,13 +2382,16 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, 'in length. Expecting %d got %d ' % (len(to_replace), len(value))) - new_data = self._data.replace_list(to_replace, value, + new_data = self._data.replace_list(src_list=to_replace, + dest_list=value, inplace=inplace, regex=regex) else: # [NA, ''] -> 0 - new_data = self._data.replace(to_replace, value, - inplace=inplace, regex=regex) + new_data = self._data.replace(to_replace=to_replace, + value=value, + inplace=inplace, + regex=regex) elif to_replace is None: if not (com.is_re_compilable(regex) or com.is_list_like(regex) or @@ -2406,13 +2411,14 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, for k, v in compat.iteritems(value): if k in self: - new_data = new_data.replace(to_replace, v, + new_data = new_data.replace(to_replace=to_replace, + value=v, filter=[k], inplace=inplace, regex=regex) elif not com.is_list_like(value): # NA -> 0 - new_data = self._data.replace(to_replace, value, + new_data = self._data.replace(to_replace=to_replace, value=value, inplace=inplace, regex=regex) else: msg = ('Invalid "to_replace" type: ' @@ -3116,12 +3122,12 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None, if inplace: # we may have different type blocks come out of putmask, so # reconstruct the block manager - new_data = self._data.putmask(cond, other, align=axis is None, + new_data = self._data.putmask(mask=cond, new=other, align=axis is None, inplace=True) self._update_inplace(new_data) else: - new_data = self._data.where(other, cond, align=axis is None, + new_data = self._data.where(other=other, cond=cond, align=axis is None, raise_on_error=raise_on_error, try_cast=try_cast) @@ -3168,7 +3174,7 @@ def shift(self, periods=1, freq=None, axis=0, **kwds): 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) + new_data = self._data.shift(indexer=indexer, periods=periods, axis=block_axis) else: return self.tshift(periods, freq, **kwds) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 780ad57ed8f13..d2f538decd576 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -321,7 +321,7 @@ def _setitem_with_indexer(self, indexer, value): # 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) + obj._data = obj._data.setitem(indexer=tuple([idx]), value=value) self.obj[item] = obj return @@ -341,7 +341,7 @@ def setter(item, v): # set the item, possibly having a dtype change s = s.copy() - s._data = s._data.setitem(pi, v) + s._data = s._data.setitem(indexer=pi, value=v) s._maybe_update_cacher(clear=True) self.obj[item] = s @@ -419,7 +419,7 @@ def can_do_equal_len(): value = self._align_panel(indexer, value) # actually do the set - self.obj._data = self.obj._data.setitem(indexer, value) + self.obj._data = self.obj._data.setitem(indexer=indexer, value=value) self.obj._maybe_update_cacher(clear=True) def _align_series(self, indexer, ser): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e88f1972b5f7d..d0a8e1c06fd28 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -215,6 +215,14 @@ def dtype(self): def ftype(self): return "%s:%s" % (self.dtype, self._ftype) + def as_block(self, result): + """ if we are not a block, then wrap as a block, must have compatible shape """ + if not isinstance(result, Block): + result = make_block(result, + self.items, + self.ref_items) + return result + def merge(self, other): if not self.ref_items.equals(other.ref_items): raise AssertionError('Merge operands must have same ref_items') @@ -346,6 +354,10 @@ def split_block_at(self, item): klass=self.__class__, fastpath=True) + def apply(self, func, **kwargs): + """ apply the function to my values; return a block if we are not one """ + return self.as_block(func(self.values)) + def fillna(self, value, inplace=False, downcast=None): if not self._can_hold_na: if inplace: @@ -2342,38 +2354,32 @@ def _verify_integrity(self): 'tot_items: {1}'.format(len(self.items), tot_items)) - def apply(self, f, *args, **kwargs): - """ iterate over the blocks, collect and create a new block manager + def apply(self, f, axes=None, filter=None, do_integrity_check=False, **kwargs): + """ + iterate over the blocks, collect and create a new block manager Parameters ---------- f : the callable or function name to operate on at the block level axes : optional (if not supplied, use self.axes) filter : list, if supplied, only call the block if the filter is in - the block + the block + do_integrity_check : boolean, default False. Do the block manager integrity check + + Returns + ------- + Block Manager (new object) + """ - axes = kwargs.pop('axes', None) - filter = kwargs.get('filter') - do_integrity_check = kwargs.pop('do_integrity_check', False) result_blocks = [] for blk in self.blocks: if filter is not None: - kwargs['filter'] = set(kwargs['filter']) + kwargs['filter'] = set(filter) if not blk.items.isin(filter).any(): result_blocks.append(blk) continue - if callable(f): - applied = f(blk, *args, **kwargs) - - # if we are no a block, try to coerce - if not isinstance(applied, Block): - applied = make_block(applied, - blk.items, - blk.ref_items) - - else: - applied = getattr(blk, f)(*args, **kwargs) + applied = getattr(blk, f)(**kwargs) if isinstance(applied, list): result_blocks.extend(applied) @@ -2386,43 +2392,46 @@ def apply(self, f, *args, **kwargs): bm._consolidate_inplace() return bm - def where(self, *args, **kwargs): - return self.apply('where', *args, **kwargs) + def isnull(self, **kwargs): + return self.apply('apply', **kwargs) + + def where(self, **kwargs): + return self.apply('where', **kwargs) - def eval(self, *args, **kwargs): - return self.apply('eval', *args, **kwargs) + def eval(self, **kwargs): + return self.apply('eval', **kwargs) - def setitem(self, *args, **kwargs): - return self.apply('setitem', *args, **kwargs) + def setitem(self, **kwargs): + return self.apply('setitem', **kwargs) - def putmask(self, *args, **kwargs): - return self.apply('putmask', *args, **kwargs) + def putmask(self, **kwargs): + return self.apply('putmask', **kwargs) - def diff(self, *args, **kwargs): - return self.apply('diff', *args, **kwargs) + def diff(self, **kwargs): + return self.apply('diff', **kwargs) - def interpolate(self, *args, **kwargs): - return self.apply('interpolate', *args, **kwargs) + def interpolate(self, **kwargs): + return self.apply('interpolate', **kwargs) - def shift(self, *args, **kwargs): - return self.apply('shift', *args, **kwargs) + def shift(self, **kwargs): + return self.apply('shift', **kwargs) - def fillna(self, *args, **kwargs): - return self.apply('fillna', *args, **kwargs) + def fillna(self, **kwargs): + return self.apply('fillna', **kwargs) - def downcast(self, *args, **kwargs): - return self.apply('downcast', *args, **kwargs) + def downcast(self, **kwargs): + return self.apply('downcast', **kwargs) - def astype(self, *args, **kwargs): - return self.apply('astype', *args, **kwargs) + def astype(self, dtype, **kwargs): + return self.apply('astype', dtype=dtype, **kwargs) - def convert(self, *args, **kwargs): - return self.apply('convert', *args, **kwargs) + def convert(self, **kwargs): + return self.apply('convert', **kwargs) - def replace(self, *args, **kwargs): - return self.apply('replace', *args, **kwargs) + def replace(self, **kwargs): + return self.apply('replace', **kwargs) - def replace_list(self, src_lst, dest_lst, inplace=False, regex=False): + def replace_list(self, src_list, dest_list, inplace=False, regex=False): """ do a list replace """ # figure out our mask a-priori to avoid repeated replacements @@ -2432,7 +2441,7 @@ def comp(s): if isnull(s): return isnull(values) return values == getattr(s, 'asm8', s) - masks = [comp(s) for i, s in enumerate(src_lst)] + masks = [comp(s) for i, s in enumerate(src_list)] result_blocks = [] for blk in self.blocks: @@ -2440,7 +2449,7 @@ def comp(s): # its possible to get multiple result blocks here # replace ALWAYS will return a list rb = [blk if inplace else blk.copy()] - for i, (s, d) in enumerate(zip(src_lst, dest_lst)): + for i, (s, d) in enumerate(zip(src_list, dest_list)): new_rb = [] for b in rb: if b.dtype == np.object_: @@ -2465,13 +2474,13 @@ def comp(s): bm._consolidate_inplace() return bm - def prepare_for_merge(self, *args, **kwargs): + def prepare_for_merge(self, **kwargs): """ prepare for merging, return a new block manager with Sparse -> Dense """ self._consolidate_inplace() if self._has_sparse: - return self.apply('prepare_for_merge', *args, **kwargs) + return self.apply('prepare_for_merge', **kwargs) return self def post_merge(self, objs, **kwargs): @@ -3631,6 +3640,18 @@ def shape(self): self._shape = tuple([len(self.axes[0])]) return self._shape + def apply(self, f, axes=None, do_integrity_check=False, **kwargs): + """ + fast path for SingleBlock Manager + + ssee also BlockManager.apply + """ + applied = getattr(self._block, f)(**kwargs) + bm = self.__class__(applied, axes or self.axes, + do_integrity_check=do_integrity_check) + bm._consolidate_inplace() + return bm + def reindex(self, new_axis, indexer=None, method=None, fill_value=None, limit=None, copy=True): # if we are the same and don't copy, just return @@ -3687,14 +3708,14 @@ def set_ref_items(self, ref_items, maybe_rename=True): def index(self): return self.axes[0] - def convert(self, *args, **kwargs): + def convert(self, **kwargs): """ convert the whole block as one """ kwargs['by_item'] = False - return self.apply('convert', *args, **kwargs) + return self.apply('convert', **kwargs) @property def dtype(self): - return self._block.dtype + return self._values.dtype @property def ftype(self): @@ -3706,7 +3727,7 @@ def values(self): @property def itemsize(self): - return self._block.itemsize + return self._values.itemsize @property def _can_hold_na(self): diff --git a/pandas/core/series.py b/pandas/core/series.py index 8873af08cc5f3..300da3dc6834d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -212,7 +212,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None, # create/copy the manager if isinstance(data, SingleBlockManager): if dtype is not None: - data = data.astype(dtype, raise_on_error=False) + data = data.astype(dtype=dtype, raise_on_error=False) elif copy: data = data.copy() else: @@ -281,23 +281,23 @@ def _set_subtyp(self, is_all_dates): # ndarray compatibility def item(self): - return self.values.item() + return self._data.values.item() @property def data(self): - return self.values.data + return self._data.values.data @property def strides(self): - return self.values.strides + return self._data.values.strides @property def size(self): - return self.values.size + return self._data.values.size @property def flags(self): - return self.values.flags + return self._data.values.flags @property def dtype(self): @@ -694,7 +694,7 @@ def _set_labels(self, key, value): def _set_values(self, key, value): if isinstance(key, Series): key = key.values - self._data = self._data.setitem(key, value) + self._data = self._data.setitem(indexer=key, value=value) # help out SparseSeries _get_val_at = ndarray.__getitem__ @@ -1643,7 +1643,7 @@ def update(self, other): other = other.reindex_like(self) mask = notnull(other) - self._data = self._data.putmask(mask, other, inplace=True) + self._data = self._data.putmask(mask=mask, new=other, inplace=True) self._maybe_update_cacher() #---------------------------------------------------------------------- diff --git a/pandas/lib.pyx b/pandas/lib.pyx index ea5071eab976c..510ab5f74a0eb 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -59,6 +59,15 @@ PyDateTime_IMPORT import_array() import_ufunc() +def values_from_object(object o): + """ return my values or the object if we are say an ndarray """ + cdef f + + f = getattr(o, 'get_values', None) + if f is not None: + o = f() + return o + cpdef map_indices_list(list index): ''' Produce a dict mapping the values of the input array to their respective diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index c048b2786bd91..8b8715509301e 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -3,6 +3,23 @@ from tslib import NaT from datetime import datetime, timedelta iNaT = util.get_nat() +# core.common import for fast inference checks +def is_float(object obj): + return util.is_float_object(obj) + + +def is_integer(object obj): + return util.is_integer_object(obj) + + +def is_bool(object obj): + return util.is_bool_object(obj) + + +def is_complex(object obj): + return util.is_complex_object(obj) + + _TYPE_MAP = { np.int8: 'integer', np.int16: 'integer', diff --git a/pandas/src/reduce.pyx b/pandas/src/reduce.pyx index 50fff7f9eb460..a22e7e636d7e4 100644 --- a/pandas/src/reduce.pyx +++ b/pandas/src/reduce.pyx @@ -55,12 +55,6 @@ cdef class Reducer: # in cython, so increment first Py_INCREF(dummy) else: - if dummy.dtype != self.arr.dtype: - raise ValueError('Dummy array must be same dtype') - if len(dummy) != self.chunksize: - raise ValueError('Dummy array must be length %d' % - self.chunksize) - # we passed a series-like if hasattr(dummy,'values'): @@ -68,6 +62,12 @@ cdef class Reducer: index = getattr(dummy,'index',None) dummy = dummy.values + if dummy.dtype != self.arr.dtype: + raise ValueError('Dummy array must be same dtype') + if len(dummy) != self.chunksize: + raise ValueError('Dummy array must be length %d' % + self.chunksize) + return dummy, index def get_result(self): @@ -193,9 +193,9 @@ cdef class SeriesBinGrouper: values = np.empty(0, dtype=self.arr.dtype) index = None else: - if dummy.dtype != self.arr.dtype: - raise ValueError('Dummy array must be same dtype') values = dummy.values + if values.dtype != self.arr.dtype: + raise ValueError('Dummy array must be same dtype') if not values.flags.contiguous: values = values.copy() index = dummy.index @@ -318,9 +318,9 @@ cdef class SeriesGrouper: values = np.empty(0, dtype=self.arr.dtype) index = None else: + values = dummy.values if dummy.dtype != self.arr.dtype: raise ValueError('Dummy array must be same dtype') - values = dummy.values if not values.flags.contiguous: values = values.copy() index = dummy.index diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index e28aca3e5ef3a..2c32b5d0310db 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -198,7 +198,7 @@ def test_nan_to_nat_conversions(): assert(result == iNaT) s = df['B'].copy() - s._data = s._data.setitem(tuple([slice(8,9)]),np.nan) + s._data = s._data.setitem(indexer=tuple([slice(8,9)]),value=np.nan) assert(isnull(s[8])) # numpy < 1.7.0 is wrong diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index f86dec1a99850..eca1eae540920 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -604,7 +604,7 @@ def test_equals(self): bm1 = BlockManager([block1, block2], [index, np.arange(block1.shape[1])]) bm2 = BlockManager([block2, block1], [index, np.arange(block1.shape[1])]) self.assert_(bm1.equals(bm2)) - + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 5cd3b8a87c974..c598f1061f54e 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -1200,16 +1200,14 @@ def get_value(self, series, key): Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ - timestamp = None - #if isinstance(key, Timestamp): - # timestamp = key - #el + if isinstance(key, datetime): + # needed to localize naive datetimes - timestamp = Timestamp(key, tz=self.tz) + if self.tz is not None: + key = Timestamp(key, tz=self.tz) - if timestamp: - return self.get_value_maybe_box(series, timestamp) + return self.get_value_maybe_box(series, key) try: return _maybe_box(self, Index.get_value(self, series, key), series, key)
PERF: enhance tseries getitem indexing PERF: micro optimzations in inference API/CLN: core.internals.apply now only takes kwargs; makes code a bit simpler CLN: wrap core/common/isnull into more direct Block.isnull PERF: fast path series block operations closes #6264 original timings ``` In [11]: %timeit com.is_integer(13) 100000 loops, best of 3: 1.29 µs per loop In [12]: %timeit com.is_integer(np.int32(2)) 100000 loops, best of 3: 3.32 µs per loop In [13]: %timeit com.is_integer(np.int64(2)) 100000 loops, best of 3: 1.86 µs per loop In [14]: %timeit com.is_integer(14L) 100000 loops, best of 3: 1.29 µs per loop In [15]: %timeit com.is_integer("1") 100000 loops, best of 3: 2.2 µs per loop ``` withi this PR ``` In [2]: %timeit com.is_integer(13) 10000000 loops, best of 3: 72.5 ns per loop In [3]: %timeit com.is_integer(np.int32(2)) 1000000 loops, best of 3: 620 ns per loop In [4]: %timeit com.is_integer(np.int64(2)) 1000000 loops, best of 3: 315 ns per loop In [5]: %timeit com.is_integer(14L) 10000000 loops, best of 3: 72.4 ns per loop In [6]: %timeit com.is_integer("1") 10000000 loops, best of 3: 78.8 ns per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6266
2014-02-05T12:30:20Z
2014-02-05T13:46:13Z
null
2014-06-26T12:41:13Z
CLN: Work on converting assert_'s to specialized forms, in pandas/tests
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index fc94a9da00dae..b3dbfe910680a 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -92,7 +92,7 @@ def test_hash_error(self): def test_new_axis(self): new_index = self.dateIndex[None, :] - self.assert_(new_index.ndim == 2) + self.assertEqual(new_index.ndim, 2) tm.assert_isinstance(new_index, np.ndarray) def test_copy_and_deepcopy(self): @@ -133,7 +133,7 @@ def test_constructor(self): arr = np.array(self.strIndex) index = Index(arr, copy=True, name='name') tm.assert_isinstance(index, Index) - self.assert_(index.name == 'name') + self.assertEqual(index.name, 'name') assert_array_equal(arr, index) arr[0] = "SOMEBIGLONGSTRING" self.assertNotEqual(index[0], "SOMEBIGLONGSTRING") @@ -156,12 +156,12 @@ def test_index_ctor_infer_periodindex(self): def test_copy(self): i = Index([], name='Foo') i_copy = i.copy() - self.assert_(i_copy.name == 'Foo') + self.assertEqual(i_copy.name, 'Foo') def test_view(self): i = Index([], name='Foo') i_view = i.view() - self.assert_(i_view.name == 'Foo') + self.assertEqual(i_view.name, 'Foo') def test_astype(self): casted = self.intIndex.astype('i8') @@ -234,7 +234,7 @@ def test_asof(self): self.assert_(np.isnan(self.dateIndex.asof(d - timedelta(1)))) d = self.dateIndex[-1] - self.assert_(self.dateIndex.asof(d + timedelta(1)) == d) + self.assertEqual(self.dateIndex.asof(d + timedelta(1)), d) d = self.dateIndex[0].to_datetime() tm.assert_isinstance(self.dateIndex.asof(d), Timestamp) @@ -356,7 +356,7 @@ def test_union(self): first.name = 'A' second.name = 'A' union = first.union(second) - self.assert_(union.name == 'A') + self.assertEqual(union.name, 'A') second.name = 'B' union = first.union(second) @@ -393,7 +393,7 @@ def test_append_empty_preserve_name(self): right = Index([1, 2, 3], name='foo') result = left.append(right) - self.assert_(result.name == 'foo') + self.assertEqual(result.name, 'foo') left = Index([], name='foo') right = Index([1, 2, 3], name='bar') @@ -440,7 +440,7 @@ def test_diff(self): # with everythin result = first.diff(first) - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) self.assertEqual(result.name, first.name) # non-iterable input @@ -511,14 +511,14 @@ def test_format_with_name_time_info(self): dates = Index([dt + inc for dt in self.dateIndex], name='something') formatted = dates.format(name=True) - self.assert_(formatted[0] == 'something') + self.assertEqual(formatted[0], 'something') def test_format_datetime_with_time(self): t = Index([datetime(2012, 2, 7), datetime(2012, 2, 7, 23)]) result = t.format() expected = ['2012-02-07 00:00:00', '2012-02-07 23:00:00'] - self.assert_(len(result) == 2) + self.assertEqual(len(result), 2) self.assertEquals(result, expected) def test_format_none(self): @@ -579,16 +579,16 @@ def test_slice_locs(self): def test_slice_locs_dup(self): idx = Index(['a', 'a', 'b', 'c', 'd', 'd']) rs = idx.slice_locs('a', 'd') - self.assert_(rs == (0, 6)) + self.assertEqual(rs, (0, 6)) rs = idx.slice_locs(end='d') - self.assert_(rs == (0, 6)) + self.assertEqual(rs, (0, 6)) rs = idx.slice_locs('a', 'c') - self.assert_(rs == (0, 4)) + self.assertEqual(rs, (0, 4)) rs = idx.slice_locs('b', 'd') - self.assert_(rs == (2, 6)) + self.assertEqual(rs, (2, 6)) def test_drop(self): n = len(self.strIndex) @@ -624,13 +624,13 @@ def test_tuple_union_bug(self): int_idx = idx1.intersection(idx2) # needs to be 1d like idx1 and idx2 expected = idx1[:4] # pandas.Index(sorted(set(idx1) & set(idx2))) - self.assert_(int_idx.ndim == 1) + self.assertEqual(int_idx.ndim, 1) self.assert_(int_idx.equals(expected)) # union broken union_idx = idx1.union(idx2) expected = pandas.Index(sorted(set(idx1) | set(idx2))) - self.assert_(union_idx.ndim == 1) + self.assertEqual(union_idx.ndim, 1) self.assert_(union_idx.equals(expected)) def test_is_monotonic_incomparable(self): @@ -658,8 +658,8 @@ def test_isin(self): # empty, return dtype bool idx = Index([]) result = idx.isin(values) - self.assert_(len(result) == 0) - self.assert_(result.dtype == np.bool_) + self.assertEqual(len(result), 0) + self.assertEqual(result.dtype, np.bool_) def test_boolean_cmp(self): values = [1, 2, 3, 4] @@ -668,7 +668,7 @@ def test_boolean_cmp(self): res = (idx == values) self.assert_(res.all()) - self.assert_(res.dtype == 'bool') + self.assertEqual(res.dtype, 'bool') self.assert_(not isinstance(res, Index)) def test_get_level_values(self): @@ -728,15 +728,15 @@ def test_constructor(self): self.assert_(isinstance(index, Float64Index)) index = Float64Index(np.array([1.,2,3,4,5])) self.assert_(isinstance(index, Float64Index)) - self.assert_(index.dtype == object) + self.assertEqual(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) + self.assertEqual(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) + self.assertEqual(index.dtype, object) # nan handling result = Float64Index([np.nan, np.nan]) @@ -818,7 +818,7 @@ def test_constructor(self): def test_constructor_corner(self): arr = np.array([1, 2, 3, 4], dtype=object) index = Int64Index(arr) - self.assert_(index.values.dtype == np.int64) + self.assertEqual(index.values.dtype, np.int64) self.assert_(index.equals(arr)) # preventing casting @@ -839,12 +839,12 @@ def test_hash_error(self): def test_copy(self): i = Int64Index([], name='Foo') i_copy = i.copy() - self.assert_(i_copy.name == 'Foo') + self.assertEqual(i_copy.name, 'Foo') def test_view(self): i = Int64Index([], name='Foo') i_view = i.view() - self.assert_(i_view.name == 'Foo') + self.assertEqual(i_view.name, 'Foo') def test_coerce_list(self): # coerce things @@ -856,7 +856,7 @@ def test_coerce_list(self): tm.assert_isinstance(arr, Index) def test_dtype(self): - self.assert_(self.index.dtype == np.int64) + self.assertEqual(self.index.dtype, np.int64) def test_is_monotonic(self): self.assert_(self.index.is_monotonic) @@ -1123,7 +1123,7 @@ def test_intersect_str_dates(self): i2 = Index(['aa'], dtype=object) res = i2.intersection(i1) - self.assert_(len(res) == 0) + self.assertEqual(len(res), 0) def test_union_noncomparable(self): from datetime import datetime, timedelta @@ -1152,7 +1152,7 @@ def test_view_Index(self): def test_prevent_casting(self): result = self.index.astype('O') - self.assert_(result.dtype == np.object_) + self.assertEqual(result.dtype, np.object_) def test_take_preserve_name(self): index = Int64Index([1, 2, 3, 4], name='foo') @@ -1223,7 +1223,7 @@ def test_hash_error(self): def test_set_names_and_rename(self): # so long as these are synonyms, we don't need to test set_names - self.assert_(self.index.rename == self.index.set_names) + self.assertEqual(self.index.rename, self.index.set_names) new_names = [name + "SUFFIX" for name in self.index_names] ind = self.index.set_names(new_names) self.assertEqual(self.index.names, self.index_names) @@ -1433,7 +1433,7 @@ def test_constructor_single_level(self): names=['first']) tm.assert_isinstance(single_level, Index) self.assert_(not isinstance(single_level, MultiIndex)) - self.assert_(single_level.name == 'first') + self.assertEqual(single_level.name, 'first') single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']], labels=[[0, 1, 2, 3]]) @@ -1644,7 +1644,7 @@ def test_iter(self): result = list(self.index) expected = [('foo', 'one'), ('foo', 'two'), ('bar', 'one'), ('baz', 'two'), ('qux', 'one'), ('qux', 'two')] - self.assert_(result == expected) + self.assertEqual(result, expected) def test_pickle(self): pickled = pickle.dumps(self.index) @@ -1735,8 +1735,8 @@ def test_getitem_group_select(self): self.assertEquals(sorted_idx.get_loc('foo'), slice(0, 2)) def test_get_loc(self): - self.assert_(self.index.get_loc(('foo', 'two')) == 1) - self.assert_(self.index.get_loc(('baz', 'two')) == 3) + self.assertEqual(self.index.get_loc(('foo', 'two')), 1) + self.assertEqual(self.index.get_loc(('baz', 'two')), 3) self.assertRaises(KeyError, self.index.get_loc, ('bar', 'two')) self.assertRaises(KeyError, self.index.get_loc, 'quux') @@ -1748,13 +1748,13 @@ def test_get_loc(self): np.array([0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) self.assertRaises(KeyError, index.get_loc, (1, 1)) - self.assert_(index.get_loc((2, 0)) == slice(3, 5)) + self.assertEqual(index.get_loc((2, 0)), slice(3, 5)) def test_get_loc_duplicates(self): index = Index([2, 2, 2, 2]) result = index.get_loc(2) expected = slice(0, 4) - assert(result == expected) + self.assertEqual(result, expected) # self.assertRaises(Exception, index.get_loc, 2) index = Index(['c', 'a', 'a', 'b', 'b']) @@ -2213,7 +2213,7 @@ def test_diff(self): # empty, but non-equal result = self.index - self.index.sortlevel(1)[0] - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) # raise Exception called with non-MultiIndex result = first.diff(first._tuple_index) @@ -2352,7 +2352,7 @@ def test_insert(self): # key contained in all levels new_index = self.index.insert(0, ('bar', 'two')) self.assert_(new_index.equal_levels(self.index)) - self.assert_(new_index[0] == ('bar', 'two')) + self.assertEqual(new_index[0], ('bar', 'two')) # key not contained in all levels new_index = self.index.insert(0, ('abc', 'three')) @@ -2360,7 +2360,7 @@ def test_insert(self): list(self.index.levels[0]) + ['abc'])) self.assert_(np.array_equal(new_index.levels[1], list(self.index.levels[1]) + ['three'])) - self.assert_(new_index[0] == ('abc', 'three')) + self.assertEqual(new_index[0], ('abc', 'three')) # key wrong length assertRaisesRegexp(ValueError, "Item must have length equal to number" diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 435b0ca5d722f..a567e7ce0294d 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -180,7 +180,7 @@ def _print(result, error = None): try: if np.isscalar(rs) and np.isscalar(xp): - self.assert_(rs == xp) + self.assertEqual(rs, xp) elif xp.ndim == 1: assert_series_equal(rs,xp) elif xp.ndim == 2: @@ -326,7 +326,7 @@ def test_at_timestamp(self): result = s.at[dates[5]] xp = s.values[5] - self.assert_(result == xp) + self.assertEqual(result, xp) def test_iat_invalid_args(self): pass @@ -427,7 +427,7 @@ def test_iloc_getitem_multiindex(self): rs = df.iloc[2,2] xp = df.values[2,2] - self.assert_(rs == xp) + self.assertEqual(rs, xp) # for multiple items # GH 5528 @@ -455,7 +455,7 @@ def test_iloc_setitem(self): df.iloc[1,1] = 1 result = df.iloc[1,1] - self.assert_(result == 1) + self.assertEqual(result, 1) df.iloc[:,2:3] = 0 expected = df.iloc[:,2:3] @@ -627,7 +627,7 @@ def test_loc_general(self): result = DataFrame({ 'a' : [Timestamp('20130101')], 'b' : [1] }).iloc[0] expected = Series([ Timestamp('20130101'), 1],index=['a','b']) assert_series_equal(result,expected) - self.assert_(result.dtype == object) + self.assertEqual(result.dtype, object) def test_loc_setitem_frame(self): df = self.frame_labels @@ -636,10 +636,10 @@ def test_loc_setitem_frame(self): df.loc['a','A'] = 1 result = df.loc['a','A'] - self.assert_(result == 1) + self.assertEqual(result, 1) result = df.iloc[0,0] - self.assert_(result == 1) + self.assertEqual(result, 1) df.loc[:,'B':'D'] = 0 expected = df.loc[:,'B':'D'] @@ -676,7 +676,7 @@ def test_iloc_getitem_frame(self): result = df.iloc[2,2] exp = df.ix[4,4] - self.assert_(result == exp) + self.assertEqual(result, exp) # slice result = df.iloc[4:8] @@ -723,7 +723,7 @@ def test_iloc_getitem_frame(self): result = df.iloc[1,1] exp = df.ix['b','B'] - self.assert_(result == exp) + self.assertEqual(result, exp) result = df.iloc[:,2:3] expected = df.ix[:,['C']] @@ -732,7 +732,7 @@ def test_iloc_getitem_frame(self): # negative indexing result = df.iloc[-1,-1] exp = df.ix['j','D'] - self.assert_(result == exp) + self.assertEqual(result, exp) # out-of-bounds exception self.assertRaises(IndexError, df.iloc.__getitem__, tuple([10,5])) @@ -817,7 +817,7 @@ def test_iloc_setitem_series(self): df.iloc[1,1] = 1 result = df.iloc[1,1] - self.assert_(result == 1) + self.assertEqual(result, 1) df.iloc[:,2:3] = 0 expected = df.iloc[:,2:3] @@ -829,7 +829,7 @@ def test_iloc_setitem_series(self): s.iloc[1] = 1 result = s.iloc[1] - self.assert_(result == 1) + self.assertEqual(result, 1) s.iloc[:4] = 0 expected = s.iloc[:4] @@ -859,12 +859,12 @@ def test_iloc_getitem_multiindex(self): # corner column rs = mi_int.iloc[2,2] xp = mi_int.ix[:,2].ix[2] - self.assert_(rs == xp) + self.assertEqual(rs, xp) # this is basically regular indexing rs = mi_labels.iloc[2,2] xp = mi_labels.ix['j'].ix[:,'j'].ix[0,0] - self.assert_(rs == xp) + self.assertEqual(rs, xp) def test_loc_multiindex(self): @@ -1006,7 +1006,7 @@ def test_setitem_dtype_upcast(self): # GH3216 df = DataFrame([{"a": 1}, {"a": 3, "b": 2}]) df['c'] = np.nan - self.assert_(df['c'].dtype == np.float64) + self.assertEqual(df['c'].dtype, np.float64) df.ix[0,'c'] = 'foo' expected = DataFrame([{"a": 1, "c" : 'foo'}, {"a": 3, "b": 2, "c" : np.nan}]) @@ -1114,7 +1114,7 @@ def test_indexing_mixed_frame_bug(self): idx=df['test']=='_' temp=df.ix[idx,'a'].apply(lambda x: '-----' if x=='aaa' else x) df.ix[idx,'test']=temp - self.assert_(df.iloc[0,2] == '-----') + self.assertEqual(df.iloc[0,2], '-----') #if I look at df, then element [0,2] equals '_'. If instead I type df.ix[idx,'test'], I get '-----', finally by typing df.iloc[0,2] I get '_'. @@ -1151,13 +1151,13 @@ def test_iloc_panel_issue(self): # GH 3617 p = Panel(randn(4, 4, 4)) - self.assert_(p.iloc[:3, :3, :3].shape == (3,3,3)) - self.assert_(p.iloc[1, :3, :3].shape == (3,3)) - self.assert_(p.iloc[:3, 1, :3].shape == (3,3)) - self.assert_(p.iloc[:3, :3, 1].shape == (3,3)) - self.assert_(p.iloc[1, 1, :3].shape == (3,)) - self.assert_(p.iloc[1, :3, 1].shape == (3,)) - self.assert_(p.iloc[:3, 1, 1].shape == (3,)) + self.assertEqual(p.iloc[:3, :3, :3].shape, (3,3,3)) + self.assertEqual(p.iloc[1, :3, :3].shape, (3,3)) + self.assertEqual(p.iloc[:3, 1, :3].shape, (3,3)) + self.assertEqual(p.iloc[:3, :3, 1].shape, (3,3)) + self.assertEqual(p.iloc[1, 1, :3].shape, (3,)) + self.assertEqual(p.iloc[1, :3, 1].shape, (3,)) + self.assertEqual(p.iloc[:3, 1, 1].shape, (3,)) def test_panel_getitem(self): # GH4016, date selection returns a frame when a partial string selection @@ -1305,7 +1305,7 @@ def test_ix_assign_column_mixed(self): indexer = i*2 v = 1000 + i*200 expected.ix[indexer, 'y'] = v - self.assert_(expected.ix[indexer, 'y'] == v) + self.assertEqual(expected.ix[indexer, 'y'], v) df.ix[df.x % 2 == 0, 'y'] = df.ix[df.x % 2 == 0, 'y'] * 100 assert_frame_equal(df,expected) @@ -1337,16 +1337,16 @@ def test_ix_get_set_consistency(self): columns=['a', 'b', 8, 'c'], index=['e', 7, 'f', 'g']) - self.assert_(df.ix['e', 8] == 2) - self.assert_(df.loc['e', 8] == 2) + self.assertEqual(df.ix['e', 8], 2) + self.assertEqual(df.loc['e', 8], 2) df.ix['e', 8] = 42 - self.assert_(df.ix['e', 8] == 42) - self.assert_(df.loc['e', 8] == 42) + self.assertEqual(df.ix['e', 8], 42) + self.assertEqual(df.loc['e', 8], 42) df.loc['e', 8] = 45 - self.assert_(df.ix['e', 8] == 45) - self.assert_(df.loc['e', 8] == 45) + self.assertEqual(df.ix['e', 8], 45) + self.assertEqual(df.loc['e', 8], 45) def test_setitem_list(self): @@ -1490,13 +1490,13 @@ def test_loc_name(self): df = DataFrame([[1, 1], [1, 1]]) df.index.name = 'index_name' result = df.iloc[[0, 1]].index.name - self.assert_(result == 'index_name') + self.assertEqual(result, 'index_name') result = df.ix[[0, 1]].index.name - self.assert_(result == 'index_name') + self.assertEqual(result, 'index_name') result = df.loc[[0, 1]].index.name - self.assert_(result == 'index_name') + self.assertEqual(result, 'index_name') def test_iloc_non_unique_indexing(self): @@ -2035,7 +2035,7 @@ def f(): # correct setting df.loc[(0,0),'z'] = 2 result = df.loc[(0,0),'z'] - self.assert_(result == 2) + self.assertEqual(result, 2) def test_slice_consolidate_invalidate_item_cache(self): # #3970 @@ -2069,8 +2069,8 @@ def test_setitem_cache_updating(self): # set it df.ix[7,'c'] = 1 - self.assert_(df.ix[0,'c'] == 0.0) - self.assert_(df.ix[7,'c'] == 1.0) + self.assertEqual(df.ix[0,'c'], 0.0) + self.assertEqual(df.ix[7,'c'], 1.0) def test_setitem_chained_setfault(self): @@ -2289,10 +2289,10 @@ 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) + self.assertEqual(s[3], 2) + self.assertEqual(s.ix[3], 2) + self.assertEqual(s.loc[3], 2) + self.assertEqual(s.iloc[3], 3) def test_floating_index(self): @@ -2311,16 +2311,16 @@ def test_floating_index(self): result1 = s[5.0] result2 = s.loc[5.0] result3 = s.ix[5.0] - self.assert_(result1 == result2) - self.assert_(result1 == result3) + self.assertEqual(result1, result2) + self.assertEqual(result1, result3) result1 = s[5] result2 = s.loc[5] result3 = s.ix[5] - self.assert_(result1 == result2) - self.assert_(result1 == result3) + self.assertEqual(result1, result2) + self.assertEqual(result1, result3) - self.assert_(s[5.0] == s[5]) + self.assertEqual(s[5.0], s[5]) # value not found (and no fallbacking at all) @@ -2450,11 +2450,11 @@ def check_getitem(index): # 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) + self.assertEqual(result1, result2) + self.assertEqual(result1, result3) + self.assertEqual(result1, result4) + self.assertEqual(result1, result5) + self.assertEqual(result1, result6) # all index types except float/int for index in [ tm.makeStringIndex, tm.makeUnicodeIndex, @@ -2470,11 +2470,11 @@ def check_getitem(index): 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) + self.assertEqual(result1, result2) + self.assertEqual(result1, result3) + self.assertEqual(result1, result4) + self.assertEqual(result1, result5) + self.assertEqual(result1, result6) def test_slice_indexer(self): diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 27860b738d161..f86dec1a99850 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -100,7 +100,7 @@ def setUp(self): def test_constructor(self): int32block = get_int_ex(['a'],dtype = np.int32) - self.assert_(int32block.dtype == np.int32) + self.assertEqual(int32block.dtype, np.int32) def test_pickle(self): import pickle @@ -119,9 +119,9 @@ def test_ref_locs(self): assert_almost_equal(self.fblock.ref_locs, [0, 2, 4]) def test_attrs(self): - self.assert_(self.fblock.shape == self.fblock.values.shape) - self.assert_(self.fblock.dtype == self.fblock.values.dtype) - self.assert_(len(self.fblock) == len(self.fblock.values)) + self.assertEqual(self.fblock.shape, self.fblock.values.shape) + self.assertEqual(self.fblock.dtype, self.fblock.values.dtype) + self.assertEqual(len(self.fblock), len(self.fblock.values)) def test_merge(self): avals = randn(2, 10) @@ -346,17 +346,17 @@ def test_set_change_dtype(self): self.mgr.set('baz', np.zeros(N, dtype=bool)) self.mgr.set('baz', np.repeat('foo', N)) - self.assert_(self.mgr.get('baz').dtype == np.object_) + self.assertEqual(self.mgr.get('baz').dtype, np.object_) mgr2 = self.mgr.consolidate() mgr2.set('baz', np.repeat('foo', N)) - self.assert_(mgr2.get('baz').dtype == np.object_) + self.assertEqual(mgr2.get('baz').dtype, np.object_) mgr2.set('quux', randn(N).astype(int)) - self.assert_(mgr2.get('quux').dtype == np.int_) + self.assertEqual(mgr2.get('quux').dtype, np.int_) mgr2.set('quux', randn(N)) - self.assert_(mgr2.get('quux').dtype == np.float_) + self.assertEqual(mgr2.get('quux').dtype, np.float_) def test_copy(self): shallow = self.mgr.copy(deep=False) @@ -368,17 +368,17 @@ def test_copy(self): if cp_blk.values is blk.values: found = True break - self.assert_(found == True) + self.assertTrue(found) def test_sparse(self): mgr = create_blockmanager([get_sparse_ex1(),get_sparse_ex2()]) # what to test here? - self.assert_(mgr.as_matrix().dtype == np.float64) + self.assertEqual(mgr.as_matrix().dtype, np.float64) def test_sparse_mixed(self): mgr = create_blockmanager([get_sparse_ex1(),get_sparse_ex2(),get_float_ex()]) - self.assert_(len(mgr.blocks) == 3) + self.assertEqual(len(mgr.blocks), 3) self.assert_(isinstance(mgr,BlockManager)) # what to test here? @@ -386,25 +386,25 @@ def test_sparse_mixed(self): def test_as_matrix_float(self): mgr = create_blockmanager([get_float_ex(['c'],np.float32), get_float_ex(['d'],np.float16), get_float_ex(['e'],np.float64)]) - self.assert_(mgr.as_matrix().dtype == np.float64) + self.assertEqual(mgr.as_matrix().dtype, np.float64) mgr = create_blockmanager([get_float_ex(['c'],np.float32), get_float_ex(['d'],np.float16)]) - self.assert_(mgr.as_matrix().dtype == np.float32) + self.assertEqual(mgr.as_matrix().dtype, np.float32) def test_as_matrix_int_bool(self): mgr = create_blockmanager([get_bool_ex(['a']), get_bool_ex(['b'])]) - self.assert_(mgr.as_matrix().dtype == np.bool_) + self.assertEqual(mgr.as_matrix().dtype, np.bool_) mgr = create_blockmanager([get_int_ex(['a'],np.int64), get_int_ex(['b'],np.int64), get_int_ex(['c'],np.int32), get_int_ex(['d'],np.int16), get_int_ex(['e'],np.uint8) ]) - self.assert_(mgr.as_matrix().dtype == np.int64) + self.assertEqual(mgr.as_matrix().dtype, np.int64) mgr = create_blockmanager([get_int_ex(['c'],np.int32), get_int_ex(['d'],np.int16), get_int_ex(['e'],np.uint8) ]) - self.assert_(mgr.as_matrix().dtype == np.int32) + self.assertEqual(mgr.as_matrix().dtype, np.int32) def test_as_matrix_datetime(self): mgr = create_blockmanager([get_dt_ex(['h']), get_dt_ex(['g'])]) - self.assert_(mgr.as_matrix().dtype == 'M8[ns]') + self.assertEqual(mgr.as_matrix().dtype, 'M8[ns]') def test_astype(self): @@ -413,13 +413,13 @@ def test_astype(self): for t in ['float16','float32','float64','int32','int64']: tmgr = mgr.astype(t) - self.assert_(tmgr.as_matrix().dtype == np.dtype(t)) + self.assertEqual(tmgr.as_matrix().dtype, np.dtype(t)) # mixed mgr = create_blockmanager([get_obj_ex(['a','b']),get_bool_ex(['c']),get_dt_ex(['d']),get_float_ex(['e'],np.float32), get_float_ex(['f'],np.float16), get_float_ex(['g'],np.float64)]) for t in ['float16','float32','float64','int32','int64']: tmgr = mgr.astype(t, raise_on_error = False).get_numeric_data() - self.assert_(tmgr.as_matrix().dtype == np.dtype(t)) + self.assertEqual(tmgr.as_matrix().dtype, np.dtype(t)) def test_convert(self): @@ -427,7 +427,7 @@ def _compare(old_mgr, new_mgr): """ compare the blocks, numeric compare ==, object don't """ old_blocks = set(old_mgr.blocks) new_blocks = set(new_mgr.blocks) - self.assert_(len(old_blocks) == len(new_blocks)) + self.assertEqual(len(old_blocks), len(new_blocks)) # compare non-numeric for b in old_blocks: @@ -436,7 +436,7 @@ def _compare(old_mgr, new_mgr): if (b.values == nb.values).all(): found = True break - self.assert_(found == True) + self.assertTrue(found) for b in new_blocks: found = False @@ -444,7 +444,7 @@ def _compare(old_mgr, new_mgr): if (b.values == ob.values).all(): found = True break - self.assert_(found == True) + self.assertTrue(found) # noops mgr = create_blockmanager([get_int_ex(['f']), get_float_ex(['g'])]) @@ -462,7 +462,7 @@ def _check(new_mgr,block_type, citems): if isinstance(b,block_type): for i in list(b.items): items.add(i) - self.assert_(items == set(citems)) + self.assertEqual(items, set(citems)) # convert mat = np.empty((N, 3), dtype=object) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 7dd9dbd51d730..b997d1fff9e9b 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -867,7 +867,7 @@ def test_stack_mixed_dtype(self): stacked = df.stack() assert_series_equal(stacked['foo'], df['foo'].stack()) - self.assert_(stacked['bar'].dtype == np.float_) + self.assertEqual(stacked['bar'].dtype, np.float_) def test_unstack_bug(self): df = DataFrame({'state': ['naive', 'naive', 'naive', @@ -1138,7 +1138,7 @@ def test_is_lexsorted(self): labels=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]]) self.assert_(not index.is_lexsorted()) - self.assert_(index.lexsort_depth == 0) + self.assertEqual(index.lexsort_depth, 0) def test_frame_getitem_view(self): df = self.frame.T.copy() @@ -1381,9 +1381,9 @@ def test_unstack_preserve_types(self): self.ymd['F'] = 2 unstacked = self.ymd.unstack('month') - self.assert_(unstacked['A', 1].dtype == np.float64) - self.assert_(unstacked['E', 1].dtype == np.object_) - self.assert_(unstacked['F', 1].dtype == np.float64) + self.assertEqual(unstacked['A', 1].dtype, np.float64) + self.assertEqual(unstacked['E', 1].dtype, np.object_) + self.assertEqual(unstacked['F', 1].dtype, np.float64) def test_unstack_group_index_overflow(self): labels = np.tile(np.arange(500), 2) @@ -1425,7 +1425,7 @@ def test_getitem_lowerdim_corner(self): # in theory should be inserting in a sorted space???? self.frame.ix[('bar','three'),'B'] = 0 - self.assert_(self.frame.sortlevel().ix[('bar','three'),'B'] == 0) + self.assertEqual(self.frame.sortlevel().ix[('bar','three'),'B'], 0) #---------------------------------------------------------------------- # AMBIGUOUS CASES! @@ -1694,7 +1694,7 @@ def test_drop_preserve_names(self): df = DataFrame(np.random.randn(6, 3), index=index) result = df.drop([(0, 2)]) - self.assert_(result.index.names == ('one', 'two')) + self.assertEqual(result.index.names, ('one', 'two')) def test_unicode_repr_issues(self): levels = [Index([u('a/\u03c3'), u('b/\u03c3'), u('c/\u03c3')]), diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 170eedd3754b3..581f4df58757e 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -458,16 +458,16 @@ def test_setitem(self): # scalar self.panel['ItemG'] = 1 self.panel['ItemE'] = True - self.assert_(self.panel['ItemG'].values.dtype == np.int64) - self.assert_(self.panel['ItemE'].values.dtype == np.bool_) + self.assertEqual(self.panel['ItemG'].values.dtype, np.int64) + self.assertEqual(self.panel['ItemE'].values.dtype, np.bool_) # object dtype self.panel['ItemQ'] = 'foo' - self.assert_(self.panel['ItemQ'].values.dtype == np.object_) + self.assertEqual(self.panel['ItemQ'].values.dtype, np.object_) # boolean dtype self.panel['ItemP'] = self.panel['ItemA'] > 0 - self.assert_(self.panel['ItemP'].values.dtype == np.bool_) + self.assertEqual(self.panel['ItemP'].values.dtype, np.bool_) self.assertRaises(TypeError, self.panel.__setitem__, 'foo', self.panel.ix[['ItemP']]) @@ -510,8 +510,8 @@ def test_major_xs(self): def test_major_xs_mixed(self): self.panel['ItemD'] = 'foo' xs = self.panel.major_xs(self.panel.major_axis[0]) - self.assert_(xs['ItemA'].dtype == np.float64) - self.assert_(xs['ItemD'].dtype == np.object_) + self.assertEqual(xs['ItemA'].dtype, np.float64) + self.assertEqual(xs['ItemD'].dtype, np.object_) def test_minor_xs(self): ref = self.panel['ItemA'] @@ -528,8 +528,8 @@ def test_minor_xs_mixed(self): self.panel['ItemD'] = 'foo' xs = self.panel.minor_xs('D') - self.assert_(xs['ItemA'].dtype == np.float64) - self.assert_(xs['ItemD'].dtype == np.object_) + self.assertEqual(xs['ItemA'].dtype, np.float64) + self.assertEqual(xs['ItemD'].dtype, np.object_) def test_xs(self): itemA = self.panel.xs('ItemA', axis=0) @@ -840,7 +840,7 @@ def test_constructor(self): # strings handled prop wp = Panel([[['foo', 'foo', 'foo', ], ['foo', 'foo', 'foo']]]) - self.assert_(wp.values.dtype == np.object_) + self.assertEqual(wp.values.dtype, np.object_) vals = self.panel.values @@ -875,22 +875,22 @@ def test_constructor_cast(self): def test_constructor_empty_panel(self): empty = Panel() - self.assert_(len(empty.items) == 0) - self.assert_(len(empty.major_axis) == 0) - self.assert_(len(empty.minor_axis) == 0) + self.assertEqual(len(empty.items), 0) + self.assertEqual(len(empty.major_axis), 0) + self.assertEqual(len(empty.minor_axis), 0) def test_constructor_observe_dtype(self): # GH #411 panel = Panel(items=lrange(3), major_axis=lrange(3), minor_axis=lrange(3), dtype='O') - self.assert_(panel.values.dtype == np.object_) + self.assertEqual(panel.values.dtype, np.object_) def test_constructor_dtypes(self): # GH #797 def _check_dtype(panel, dtype): for i in panel.items: - self.assert_(panel[i].values.dtype.name == dtype) + self.assertEqual(panel[i].values.dtype.name, dtype) # only nan holding types allowed here for dtype in ['float64','float32','object']: @@ -1029,8 +1029,8 @@ def test_from_dict_mixed_orient(self): panel = Panel.from_dict(data, orient='minor') - self.assert_(panel['foo'].values.dtype == np.object_) - self.assert_(panel['A'].values.dtype == np.float64) + self.assertEqual(panel['foo'].values.dtype, np.object_) + self.assertEqual(panel['A'].values.dtype, np.float64) def test_constructor_error_msgs(self): @@ -1186,7 +1186,7 @@ def test_reindex(self): # this ok result = self.panel.reindex() assert_panel_equal(result,self.panel) - self.assert_((result is self.panel) == False) + self.assertFalse(result is self.panel) # with filling smaller_major = self.panel.major_axis[::5] @@ -1201,7 +1201,7 @@ def test_reindex(self): # don't necessarily copy result = self.panel.reindex(major=self.panel.major_axis, copy=False) assert_panel_equal(result,self.panel) - self.assert_((result is self.panel) == True) + self.assertTrue(result is self.panel) def test_reindex_multi(self): diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index fb5030ac66831..773079556e3e2 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -355,16 +355,16 @@ def test_setitem(self): # scalar self.panel4d['lG'] = 1 self.panel4d['lE'] = True - self.assert_(self.panel4d['lG'].values.dtype == np.int64) - self.assert_(self.panel4d['lE'].values.dtype == np.bool_) + self.assertEqual(self.panel4d['lG'].values.dtype, np.int64) + self.assertEqual(self.panel4d['lE'].values.dtype, np.bool_) # object dtype self.panel4d['lQ'] = 'foo' - self.assert_(self.panel4d['lQ'].values.dtype == np.object_) + self.assertEqual(self.panel4d['lQ'].values.dtype, np.object_) # boolean dtype self.panel4d['lP'] = self.panel4d['l1'] > 0 - self.assert_(self.panel4d['lP'].values.dtype == np.bool_) + self.assertEqual(self.panel4d['lP'].values.dtype, np.bool_) def test_comparisons(self): p1 = tm.makePanel4D() @@ -426,8 +426,8 @@ def test_major_xs(self): def test_major_xs_mixed(self): self.panel4d['l4'] = 'foo' xs = self.panel4d.major_xs(self.panel4d.major_axis[0]) - self.assert_(xs['l1']['A'].dtype == np.float64) - self.assert_(xs['l4']['A'].dtype == np.object_) + self.assertEqual(xs['l1']['A'].dtype, np.float64) + self.assertEqual(xs['l4']['A'].dtype, np.object_) def test_minor_xs(self): ref = self.panel4d['l1']['ItemA'] @@ -444,8 +444,8 @@ def test_minor_xs_mixed(self): self.panel4d['l4'] = 'foo' xs = self.panel4d.minor_xs('D') - self.assert_(xs['l1'].T['ItemA'].dtype == np.float64) - self.assert_(xs['l4'].T['ItemA'].dtype == np.object_) + self.assertEqual(xs['l1'].T['ItemA'].dtype, np.float64) + self.assertEqual(xs['l4'].T['ItemA'].dtype, np.object_) def test_xs(self): l1 = self.panel4d.xs('l1', axis=0) @@ -567,7 +567,7 @@ def test_constructor(self): # strings handled prop # panel4d = Panel4D([[['foo', 'foo', 'foo',], # ['foo', 'foo', 'foo']]]) - # self.assert_(wp.values.dtype == np.object_) + # self.assertEqual(wp.values.dtype, np.object_) vals = self.panel4d.values @@ -602,15 +602,15 @@ def test_constructor_cast(self): def test_constructor_empty_panel(self): empty = Panel() - self.assert_(len(empty.items) == 0) - self.assert_(len(empty.major_axis) == 0) - self.assert_(len(empty.minor_axis) == 0) + self.assertEqual(len(empty.items), 0) + self.assertEqual(len(empty.major_axis), 0) + self.assertEqual(len(empty.minor_axis), 0) def test_constructor_observe_dtype(self): # GH #411 panel = Panel(items=lrange(3), major_axis=lrange(3), minor_axis=lrange(3), dtype='O') - self.assert_(panel.values.dtype == np.object_) + self.assertEqual(panel.values.dtype, np.object_) def test_consolidate(self): self.assert_(self.panel4d._data.is_consolidated()) @@ -714,8 +714,8 @@ def test_from_dict_mixed_orient(self): # panel = Panel.from_dict(data, orient='minor') - # self.assert_(panel['foo'].values.dtype == np.object_) - # self.assert_(panel['A'].values.dtype == np.float64) + # self.assertEqual(panel['foo'].values.dtype, np.object_) + # self.assertEqual(panel['A'].values.dtype, np.float64) def test_values(self): self.assertRaises(Exception, Panel, np.random.randn(5, 5, 5), @@ -764,7 +764,7 @@ def test_reindex(self): # don't necessarily copy result = self.panel4d.reindex() assert_panel4d_equal(result,self.panel4d) - self.assert_((result is self.panel4d) == False) + self.assertFalse(result is self.panel4d) # with filling smaller_major = self.panel4d.major_axis[::5] @@ -780,7 +780,7 @@ def test_reindex(self): result = self.panel4d.reindex( major=self.panel4d.major_axis, copy=False) assert_panel4d_equal(result,self.panel4d) - self.assert_((result is self.panel4d) == True) + self.assertTrue(result is self.panel4d) def test_not_hashable(self): p4D_empty = Panel4D() diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 00f1b826303c9..c43b7b3eee533 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -275,14 +275,14 @@ def test_none_comparison(self): def test_sum_zero(self): arr = np.array([]) - self.assert_(nanops.nansum(arr) == 0) + self.assertEqual(nanops.nansum(arr), 0) arr = np.empty((10, 0)) self.assert_((nanops.nansum(arr, axis=1) == 0).all()) # GH #844 s = Series([], index=[]) - self.assert_(s.sum() == 0) + self.assertEqual(s.sum(), 0) df = DataFrame(np.empty((10, 0))) self.assert_((df.sum(1) == 0).all()) @@ -324,25 +324,25 @@ def test_scalar_conversion(self): self.assert_(not isinstance(scalar, float)) # coercion - self.assert_(float(Series([1.])) == 1.0) - self.assert_(int(Series([1.])) == 1) - self.assert_(long(Series([1.])) == 1) + self.assertEqual(float(Series([1.])), 1.0) + self.assertEqual(int(Series([1.])), 1) + self.assertEqual(long(Series([1.])), 1) def test_astype(self): s = Series(np.random.randn(5),name='foo') for dtype in ['float32','float64','int64','int32']: astyped = s.astype(dtype) - self.assert_(astyped.dtype == dtype) - self.assert_(astyped.name == s.name) + self.assertEqual(astyped.dtype, dtype) + self.assertEqual(astyped.name, s.name) def test_constructor(self): # Recognize TimeSeries - self.assert_(self.ts.is_time_series == True) + self.assertTrue(self.ts.is_time_series) # Pass in Series derived = Series(self.ts) - self.assert_(derived.is_time_series == True) + self.assertTrue(derived.is_time_series) self.assert_(tm.equalContents(derived.index, self.ts.index)) # Ensure new index is not created @@ -350,7 +350,7 @@ def test_constructor(self): # Mixed type Series mixed = Series(['hello', np.NaN], index=[0, 1]) - self.assert_(mixed.dtype == np.object_) + self.assertEqual(mixed.dtype, np.object_) self.assert_(mixed[1] is np.NaN) self.assert_(not self.empty.is_time_series) @@ -504,10 +504,10 @@ def test_constructor_sanitize(self): def test_constructor_pass_none(self): s = Series(None, index=lrange(5)) - self.assert_(s.dtype == np.float64) + self.assertEqual(s.dtype, np.float64) s = Series(None, index=lrange(5), dtype=object) - self.assert_(s.dtype == np.object_) + self.assertEqual(s.dtype, np.object_) def test_constructor_cast(self): self.assertRaises(ValueError, Series, ['a', 'b', 'c'], dtype=float) @@ -525,23 +525,23 @@ def test_constructor_dtype_datetime64(self): import pandas.tslib as tslib s = Series(tslib.iNaT, dtype='M8[ns]', index=lrange(5)) - self.assert_(isnull(s).all() == True) + self.assertTrue(isnull(s).all()) # in theory this should be all nulls, but since # we are not specifying a dtype is ambiguous s = Series(tslib.iNaT, index=lrange(5)) - self.assert_(isnull(s).all() == False) + self.assertFalse(isnull(s).all()) s = Series(nan, dtype='M8[ns]', index=lrange(5)) - self.assert_(isnull(s).all() == True) + self.assertTrue(isnull(s).all()) s = Series([datetime(2001, 1, 2, 0, 0), tslib.iNaT], dtype='M8[ns]') - self.assert_(isnull(s[1]) == True) - self.assert_(s.dtype == 'M8[ns]') + self.assertTrue(isnull(s[1])) + self.assertEqual(s.dtype, 'M8[ns]') s = Series([datetime(2001, 1, 2, 0, 0), nan], dtype='M8[ns]') - self.assert_(isnull(s[1]) == True) - self.assert_(s.dtype == 'M8[ns]') + self.assertTrue(isnull(s[1])) + self.assertEqual(s.dtype, 'M8[ns]') # GH3416 dates = [ @@ -551,10 +551,10 @@ def test_constructor_dtype_datetime64(self): ] s = Series(dates) - self.assert_(s.dtype == 'M8[ns]') + self.assertEqual(s.dtype, 'M8[ns]') s.ix[0] = np.nan - self.assert_(s.dtype == 'M8[ns]') + self.assertEqual(s.dtype, 'M8[ns]') # invalid astypes for t in ['s', 'D', 'us', 'ms']: @@ -568,15 +568,15 @@ def test_constructor_dtype_datetime64(self): # invalid dates can be help as object result = Series([datetime(2,1,1)]) - self.assert_(result[0] == datetime(2,1,1,0,0)) + self.assertEqual(result[0], datetime(2,1,1,0,0)) result = Series([datetime(3000,1,1)]) - self.assert_(result[0] == datetime(3000,1,1,0,0)) + self.assertEqual(result[0], datetime(3000,1,1,0,0)) # don't mix types result = Series([ Timestamp('20130101'), 1],index=['a','b']) - self.assert_(result['a'] == Timestamp('20130101')) - self.assert_(result['b'] == 1) + self.assertEqual(result['a'], Timestamp('20130101')) + self.assertEqual(result['b'], 1) def test_constructor_dict(self): d = {'a': 0., 'b': 1., 'c': 2.} @@ -641,15 +641,15 @@ def test_fromDict(self): data = {'a': 0, 'b': '1', 'c': '2', 'd': datetime.now()} series = Series(data) - self.assert_(series.dtype == np.object_) + self.assertEqual(series.dtype, np.object_) data = {'a': 0, 'b': '1', 'c': '2', 'd': '3'} series = Series(data) - self.assert_(series.dtype == np.object_) + self.assertEqual(series.dtype, np.object_) data = {'a': '0', 'b': '1'} series = Series(data, dtype=float) - self.assert_(series.dtype == np.float64) + self.assertEqual(series.dtype, np.float64) def test_setindex(self): # wrong type @@ -678,16 +678,16 @@ def test_not_hashable(self): def test_fromValue(self): nans = Series(np.NaN, index=self.ts.index) - self.assert_(nans.dtype == np.float_) + self.assertEqual(nans.dtype, np.float_) self.assertEqual(len(nans), len(self.ts)) strings = Series('foo', index=self.ts.index) - self.assert_(strings.dtype == np.object_) + self.assertEqual(strings.dtype, np.object_) self.assertEqual(len(strings), len(self.ts)) d = datetime.now() dates = Series(d, index=self.ts.index) - self.assert_(dates.dtype == 'M8[ns]') + self.assertEqual(dates.dtype, 'M8[ns]') self.assertEqual(len(dates), len(self.ts)) def test_contains(self): @@ -916,7 +916,7 @@ def test_getitem_ambiguous_keyerror(self): def test_getitem_unordered_dup(self): obj = Series(lrange(5), index=['c', 'a', 'a', 'b', 'b']) self.assert_(np.isscalar(obj['c'])) - self.assert_(obj['c'] == 0) + self.assertEqual(obj['c'], 0) def test_getitem_dups_with_missing(self): @@ -990,14 +990,14 @@ def f(): def test_slice_floats2(self): s = Series(np.random.rand(10), index=np.arange(10, 20, dtype=float)) - self.assert_(len(s.ix[12.0:]) == 8) - self.assert_(len(s.ix[12.5:]) == 7) + self.assertEqual(len(s.ix[12.0:]), 8) + self.assertEqual(len(s.ix[12.5:]), 7) i = np.arange(10, 20, dtype=float) i[2] = 12.2 s.index = i - self.assert_(len(s.ix[12.0:]) == 8) - self.assert_(len(s.ix[12.5:]) == 7) + self.assertEqual(len(s.ix[12.0:]), 8) + self.assertEqual(len(s.ix[12.5:]), 7) def test_slice_float64(self): @@ -1082,12 +1082,12 @@ def test_set_value(self): s = self.series.copy() res = s.set_value('foobar', 0) self.assert_(res is s) - self.assert_(res.index[-1] == 'foobar') + self.assertEqual(res.index[-1], 'foobar') self.assertEqual(res['foobar'], 0) s = self.series.copy() s.loc['foobar'] = 0 - self.assert_(s.index[-1] == 'foobar') + self.assertEqual(s.index[-1], 'foobar') self.assertEqual(s['foobar'], 0) def test_setslice(self): @@ -1868,10 +1868,10 @@ def test_argsort(self): # GH 2967 (introduced bug in 0.11-dev I think) s = Series([Timestamp('201301%02d' % (i + 1)) for i in range(5)]) - self.assert_(s.dtype == 'datetime64[ns]') + self.assertEqual(s.dtype, 'datetime64[ns]') shifted = s.shift(-1) - self.assert_(shifted.dtype == 'datetime64[ns]') - self.assert_(isnull(shifted[4]) == True) + self.assertEqual(shifted.dtype, 'datetime64[ns]') + self.assertTrue(isnull(shifted[4])) result = s.argsort() expected = Series(lrange(5), dtype='int64') @@ -2090,13 +2090,13 @@ def test_describe_objects(self): def test_describe_empty(self): result = self.empty.describe() - self.assert_(result['count'] == 0) + self.assertEqual(result['count'], 0) self.assert_(result.drop('count').isnull().all()) nanSeries = Series([np.nan]) nanSeries.name = 'NaN' result = nanSeries.describe() - self.assert_(result['count'] == 0) + self.assertEqual(result['count'], 0) self.assert_(result.drop('count').isnull().all()) def test_describe_none(self): @@ -2265,43 +2265,43 @@ def test_constructor_dtype_timedelta64(self): # basic td = Series([timedelta(days=i) for i in range(3)]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') td = Series([timedelta(days=1)]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') if not _np_version_under1p7: td = Series([timedelta(days=1),timedelta(days=2),np.timedelta64(1,'s')]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') # mixed with NaT from pandas import tslib td = Series([timedelta(days=1),tslib.NaT ], dtype='m8[ns]' ) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') td = Series([timedelta(days=1),np.nan ], dtype='m8[ns]' ) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') td = Series([np.timedelta64(300000000), pd.NaT],dtype='m8[ns]') - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') # improved inference # GH5689 td = Series([np.timedelta64(300000000), pd.NaT]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') td = Series([np.timedelta64(300000000), tslib.iNaT]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') td = Series([np.timedelta64(300000000), np.nan]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') td = Series([pd.NaT, np.timedelta64(300000000)]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') if not _np_version_under1p7: td = Series([np.timedelta64(1,'s')]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') # these are frequency conversion astypes #for t in ['s', 'D', 'us', 'ms']: @@ -2320,7 +2320,7 @@ def f(): # leave as object here td = Series([timedelta(days=i) for i in range(3)] + ['foo']) - self.assert_(td.dtype == 'object') + self.assertEqual(td.dtype, 'object') def test_operators_timedelta64(self): @@ -2339,25 +2339,25 @@ def test_operators_timedelta64(self): xp = Series(1e9 * 3600 * 24, rs.index).astype( 'int64').astype('timedelta64[ns]') assert_series_equal(rs, xp) - self.assert_(rs.dtype == 'timedelta64[ns]') + self.assertEqual(rs.dtype, 'timedelta64[ns]') df = DataFrame(dict(A=v1)) td = Series([timedelta(days=i) for i in range(3)]) - self.assert_(td.dtype == 'timedelta64[ns]') + self.assertEqual(td.dtype, 'timedelta64[ns]') # series on the rhs result = df['A'] - df['A'].shift() - self.assert_(result.dtype == 'timedelta64[ns]') + self.assertEqual(result.dtype, 'timedelta64[ns]') result = df['A'] + td - self.assert_(result.dtype == 'M8[ns]') + self.assertEqual(result.dtype, 'M8[ns]') # scalar Timestamp on rhs maxa = df['A'].max() tm.assert_isinstance(maxa, Timestamp) resultb = df['A'] - df['A'].max() - self.assert_(resultb.dtype == 'timedelta64[ns]') + self.assertEqual(resultb.dtype, 'timedelta64[ns]') # timestamp on lhs result = resultb + df['A'] @@ -2369,11 +2369,11 @@ def test_operators_timedelta64(self): result = df['A'] - datetime(2001, 1, 1) expected = Series([timedelta(days=4017 + i) for i in range(3)]) assert_series_equal(result, expected) - self.assert_(result.dtype == 'm8[ns]') + self.assertEqual(result.dtype, 'm8[ns]') d = datetime(2001, 1, 1, 3, 4) resulta = df['A'] - d - self.assert_(resulta.dtype == 'm8[ns]') + self.assertEqual(resulta.dtype, 'm8[ns]') # roundtrip resultb = resulta + d @@ -2384,19 +2384,19 @@ def test_operators_timedelta64(self): resulta = df['A'] + td resultb = resulta - td assert_series_equal(resultb, df['A']) - self.assert_(resultb.dtype == 'M8[ns]') + self.assertEqual(resultb.dtype, 'M8[ns]') # roundtrip td = timedelta(minutes=5, seconds=3) resulta = df['A'] + td resultb = resulta - td assert_series_equal(df['A'], resultb) - self.assert_(resultb.dtype == 'M8[ns]') + self.assertEqual(resultb.dtype, 'M8[ns]') # inplace value = rs[2] + np.timedelta64(timedelta(minutes=5,seconds=1)) rs[2] += np.timedelta64(timedelta(minutes=5,seconds=1)) - self.assert_(rs[2] == value) + self.assertEqual(rs[2], value) def test_timedeltas_with_DateOffset(self): @@ -2464,7 +2464,7 @@ def test_timedelta64_operations_with_timedeltas(self): result = td1 - td2 expected = Series([timedelta(seconds=0)] * 3) -Series( [timedelta(seconds=1)] * 3) - self.assert_(result.dtype == 'm8[ns]') + self.assertEqual(result.dtype, 'm8[ns]') assert_series_equal(result, expected) result2 = td2 - td1 @@ -2483,7 +2483,7 @@ def test_timedelta64_operations_with_timedeltas(self): result = td1 - td2 expected = Series([timedelta(seconds=0)] * 3) -Series( [timedelta(seconds=1)] * 3) - self.assert_(result.dtype == 'm8[ns]') + self.assertEqual(result.dtype, 'm8[ns]') assert_series_equal(result, expected) result2 = td2 - td1 @@ -2680,20 +2680,20 @@ def test_timedelta64_functions(self): Timestamp('20120101') result = td.idxmin() - self.assert_(result == 0) + self.assertEqual(result, 0) result = td.idxmax() - self.assert_(result == 2) + self.assertEqual(result, 2) # GH 2982 # with NaT td[0] = np.nan result = td.idxmin() - self.assert_(result == 1) + self.assertEqual(result, 1) result = td.idxmax() - self.assert_(result == 2) + self.assertEqual(result, 2) # abs s1 = Series(date_range('20120101', periods=3)) @@ -2906,10 +2906,10 @@ def test_sub_of_datetime_from_TimeSeries(self): b = datetime(1993, 6, 22, 13, 30) a = Series([a]) result = _possibly_cast_to_timedelta(np.abs(a - b)) - self.assert_(result.dtype == 'timedelta64[ns]') + self.assertEqual(result.dtype, 'timedelta64[ns]') result = _possibly_cast_to_timedelta(np.abs(b - a)) - self.assert_(result.dtype == 'timedelta64[ns]') + self.assertEqual(result.dtype, 'timedelta64[ns]') def test_datetime64_with_index(self): @@ -2943,27 +2943,27 @@ def test_timedelta64_nan(self): # nan ops on timedeltas td1 = td.copy() td1[0] = np.nan - self.assert_(isnull(td1[0]) == True) - self.assert_(td1[0].view('i8') == tslib.iNaT) + self.assertTrue(isnull(td1[0])) + self.assertEqual(td1[0].view('i8'), tslib.iNaT) td1[0] = td[0] - self.assert_(isnull(td1[0]) == False) + self.assertFalse(isnull(td1[0])) td1[1] = tslib.iNaT - self.assert_(isnull(td1[1]) == True) - self.assert_(td1[1].view('i8') == tslib.iNaT) + self.assertTrue(isnull(td1[1])) + self.assertEqual(td1[1].view('i8'), tslib.iNaT) td1[1] = td[1] - self.assert_(isnull(td1[1]) == False) + self.assertFalse(isnull(td1[1])) td1[2] = tslib.NaT - self.assert_(isnull(td1[2]) == True) - self.assert_(td1[2].view('i8') == tslib.iNaT) + self.assertTrue(isnull(td1[2])) + self.assertEqual(td1[2].view('i8'), tslib.iNaT) td1[2] = td[2] - self.assert_(isnull(td1[2]) == False) + self.assertFalse(isnull(td1[2])) # boolean setting # this doesn't work, not sure numpy even supports it #result = td[(td>np.timedelta64(timedelta(days=3))) & (td<np.timedelta64(timedelta(days=7)))] = np.nan - #self.assert_(isnull(result).sum() == 7) + #self.assertEqual(isnull(result).sum(), 7) # NumPy limitiation =( @@ -3268,11 +3268,11 @@ def test_idxmin(self): from pandas import date_range s = Series(date_range('20130102', periods=6)) result = s.idxmin() - self.assert_(result == 0) + self.assertEqual(result, 0) s[0] = np.nan result = s.idxmin() - self.assert_(result == 1) + self.assertEqual(result, 1) def test_idxmax(self): # test idxmax @@ -3298,25 +3298,25 @@ def test_idxmax(self): from pandas import date_range s = Series(date_range('20130102', periods=6)) result = s.idxmax() - self.assert_(result == 5) + self.assertEqual(result, 5) s[5] = np.nan result = s.idxmax() - self.assert_(result == 4) + self.assertEqual(result, 4) # Float64Index # GH 5914 s = pd.Series([1,2,3],[1.1,2.1,3.1]) result = s.idxmax() - self.assert_(result == 3.1) + self.assertEqual(result, 3.1) result = s.idxmin() - self.assert_(result == 1.1) + self.assertEqual(result, 1.1) s = pd.Series(s.index, s.index) result = s.idxmax() - self.assert_(result == 3.1) + self.assertEqual(result, 3.1) result = s.idxmin() - self.assert_(result == 1.1) + self.assertEqual(result, 1.1) def test_ndarray_compat(self): @@ -3333,8 +3333,8 @@ def f(x): # .item() s = Series([1]) result = s.item() - self.assert_(result == 1) - self.assert_(s.item() == s.iloc[0]) + self.assertEqual(result, 1) + self.assertEqual(s.item(), s.iloc[0]) # using an ndarray like function s = Series(np.random.randn(10)) @@ -3380,7 +3380,7 @@ def test_underlying_data_conversion(self): df["bb"].iloc[0] = .13 df_tmp = df.iloc[ck] df["bb"].iloc[0] = .15 - self.assert_(df['bb'].iloc[0] == 0.15) + self.assertEqual(df['bb'].iloc[0], 0.15) # GH 3217 df = DataFrame(dict(a = [1,3], b = [np.nan, 2])) @@ -3399,7 +3399,7 @@ def test_operators_corner(self): self.assert_(np.isnan(result).all()) result = empty + Series([], index=Index([])) - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) # TODO: this returned NotImplemented earlier, what to do? # deltas = Series([timedelta(1)] * 5, index=np.arange(5)) @@ -3668,10 +3668,10 @@ def test_count(self): def test_dtype(self): - self.assert_(self.ts.dtype == np.dtype('float64')) - self.assert_(self.ts.dtypes == np.dtype('float64')) - self.assert_(self.ts.ftype == 'float64:dense') - self.assert_(self.ts.ftypes == 'float64:dense') + self.assertEqual(self.ts.dtype, np.dtype('float64')) + self.assertEqual(self.ts.dtypes, np.dtype('float64')) + self.assertEqual(self.ts.ftype, 'float64:dense') + self.assertEqual(self.ts.ftypes, 'float64:dense') assert_series_equal(self.ts.get_dtype_counts(),Series(1,['float64'])) assert_series_equal(self.ts.get_ftype_counts(),Series(1,['float64:dense'])) @@ -3764,12 +3764,12 @@ def test_value_counts_nunique(self): "person_id", "dt", "food"], parse_dates=["dt"]) s = df.dt.copy() result = s.value_counts() - self.assert_(result.index.dtype == 'datetime64[ns]') + self.assertEqual(result.index.dtype, 'datetime64[ns]') # with NaT s = s.append(Series({4: pd.NaT})) result = s.value_counts() - self.assert_(result.index.dtype == 'datetime64[ns]') + self.assertEqual(result.index.dtype, 'datetime64[ns]') # timedelta64[ns] from datetime import timedelta @@ -3777,16 +3777,16 @@ def test_value_counts_nunique(self): td2 = timedelta(1) + (df.dt - df.dt) result = td.value_counts() result2 = td2.value_counts() - #self.assert_(result.index.dtype == 'timedelta64[ns]') - self.assert_(result.index.dtype == 'int64') - self.assert_(result2.index.dtype == 'int64') + #self.assertEqual(result.index.dtype, 'timedelta64[ns]') + self.assertEqual(result.index.dtype, 'int64') + self.assertEqual(result2.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) + self.assertEqual(result, 11) def test_unique(self): @@ -3794,18 +3794,18 @@ def test_unique(self): s = Series([1.2345] * 100) s[::2] = np.nan result = s.unique() - self.assert_(len(result) == 2) + self.assertEqual(len(result), 2) s = Series([1.2345] * 100, dtype='f4') s[::2] = np.nan result = s.unique() - self.assert_(len(result) == 2) + self.assertEqual(len(result), 2) # NAs in object arrays #714 s = Series(['foo'] * 100, dtype='O') s[::2] = np.nan result = s.unique() - self.assert_(len(result) == 2) + self.assertEqual(len(result), 2) # integers s = Series(np.random.randint(0, 100, size=100)) @@ -3833,9 +3833,9 @@ def test_unique(self): def test_dropna_empty(self): s = Series([]) - self.assert_(len(s.dropna()) == 0) + self.assertEqual(len(s.dropna()), 0) s.dropna(inplace=True) - self.assert_(len(s) == 0) + self.assertEqual(len(s), 0) # invalid axis self.assertRaises(ValueError, s.dropna, axis=1) @@ -4291,7 +4291,7 @@ def test_getitem_setitem_datetimeindex(self): result = ts["1990-01-01 04:00:00"] expected = ts[4] - self.assert_(result == expected) + self.assertEqual(result, expected) result = ts.copy() result["1990-01-01 04:00:00"] = 0 @@ -4316,7 +4316,7 @@ def test_getitem_setitem_datetimeindex(self): # repeat all the above with naive datetimes result = ts[datetime(1990, 1, 1, 4)] expected = ts[4] - self.assert_(result == expected) + self.assertEqual(result, expected) result = ts.copy() result[datetime(1990, 1, 1, 4)] = 0 @@ -4340,7 +4340,7 @@ def test_getitem_setitem_datetimeindex(self): result = ts[ts.index[4]] expected = ts[4] - self.assert_(result == expected) + self.assertEqual(result, expected) result = ts[ts.index[4:8]] expected = ts[4:8] @@ -4401,7 +4401,7 @@ def test_getitem_setitem_periodindex(self): result = ts["1990-01-01 04"] expected = ts[4] - self.assert_(result == expected) + self.assertEqual(result, expected) result = ts.copy() result["1990-01-01 04"] = 0 @@ -4426,7 +4426,7 @@ def test_getitem_setitem_periodindex(self): # GH 2782 result = ts[ts.index[4]] expected = ts[4] - self.assert_(result == expected) + self.assertEqual(result, expected) result = ts[ts.index[4:8]] expected = ts[4:8] @@ -4529,17 +4529,17 @@ def test_astype_datetimes(self): s = Series(tslib.iNaT, dtype='M8[ns]', index=lrange(5)) s = s.astype('O') - self.assert_(s.dtype == np.object_) + self.assertEqual(s.dtype, np.object_) s = Series([datetime(2001, 1, 2, 0, 0)]) s = s.astype('O') - self.assert_(s.dtype == np.object_) + self.assertEqual(s.dtype, np.object_) s = Series([datetime(2001, 1, 2, 0, 0) for i in range(3)]) s[1] = np.nan - self.assert_(s.dtype == 'M8[ns]') + self.assertEqual(s.dtype, 'M8[ns]') s = s.astype('O') - self.assert_(s.dtype == np.object_) + self.assertEqual(s.dtype, np.object_) def test_astype_str(self): # GH4405 @@ -4579,11 +4579,11 @@ def test_map_int(self): left = Series({'a': 1., 'b': 2., 'c': 3., 'd': 4}) right = Series({1: 11, 2: 22, 3: 33}) - self.assert_(left.dtype == np.float_) + self.assertEqual(left.dtype, np.float_) self.assert_(issubclass(right.dtype.type, np.integer)) merged = left.map(right) - self.assert_(merged.dtype == np.float_) + self.assertEqual(merged.dtype, np.float_) self.assert_(isnull(merged['d'])) self.assert_(not isnull(merged['c'])) @@ -4596,7 +4596,7 @@ def test_map_decimal(self): from decimal import Decimal result = self.series.map(lambda x: Decimal(str(x))) - self.assert_(result.dtype == np.object_) + self.assertEqual(result.dtype, np.object_) tm.assert_isinstance(result[0], Decimal) def test_map_na_exclusion(self): @@ -4647,7 +4647,7 @@ def test_apply_dont_convert_dtype(self): f = lambda x: x if x > 0 else np.nan result = s.apply(f, convert_dtype=False) - self.assert_(result.dtype == object) + self.assertEqual(result.dtype, object) def test_convert_objects(self): @@ -4727,7 +4727,7 @@ def test_convert_objects(self): #r = s.copy() #r[0] = np.nan #result = r.convert_objects(convert_dates=True,convert_numeric=False) - #self.assert_(result.dtype == 'M8[ns]') + #self.assertEqual(result.dtype, 'M8[ns]') # dateutil parses some single letters into today's value as a date for x in 'abcdefghijklmnopqrstuvwxyz': @@ -4742,7 +4742,7 @@ def test_apply_args(self): s = Series(['foo,bar']) result = s.apply(str.split, args=(',',)) - self.assert_(result[0] == ['foo', 'bar']) + self.assertEqual(result[0], ['foo', 'bar']) def test_align(self): def _check_align(a, b, how='left', fill=None): @@ -4881,7 +4881,7 @@ def test_reindex(self): # return a copy the same index here result = self.ts.reindex() - self.assert_((result is self.ts) == False) + self.assertFalse((result is self.ts)) def test_reindex_corner(self): # (don't forget to fix this) I think it's fixed @@ -4950,11 +4950,11 @@ def test_reindex_int(self): reindexed_int = int_ts.reindex(self.ts.index) # if NaNs introduced - self.assert_(reindexed_int.dtype == np.float_) + self.assertEqual(reindexed_int.dtype, np.float_) # NO NaNs introduced reindexed_int = int_ts.reindex(int_ts.index[::2]) - self.assert_(reindexed_int.dtype == np.int_) + self.assertEqual(reindexed_int.dtype, np.int_) def test_reindex_bool(self): @@ -4966,11 +4966,11 @@ def test_reindex_bool(self): reindexed_bool = bool_ts.reindex(self.ts.index) # if NaNs introduced - self.assert_(reindexed_bool.dtype == np.object_) + self.assertEqual(reindexed_bool.dtype, np.object_) # NO NaNs introduced reindexed_bool = bool_ts.reindex(bool_ts.index[::2]) - self.assert_(reindexed_bool.dtype == np.bool_) + self.assertEqual(reindexed_bool.dtype, np.bool_) def test_reindex_bool_pad(self): # fail @@ -5367,7 +5367,7 @@ def test_asfreq(self): self.assert_(np.array_equal(monthly_ts, ts)) result = ts[:0].asfreq('M') - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) self.assert_(result is not ts) def test_weekday(self): @@ -5543,7 +5543,7 @@ def test_datetime_indexing(self): self.assertRaises(KeyError, s.__getitem__, stamp) s[stamp] = 0 - self.assert_(s[stamp] == 0) + self.assertEqual(s[stamp], 0) # not monotonic s = Series(len(index), index=index) @@ -5551,7 +5551,7 @@ def test_datetime_indexing(self): self.assertRaises(KeyError, s.__getitem__, stamp) s[stamp] = 0 - self.assert_(s[stamp] == 0) + self.assertEqual(s[stamp], 0) def test_reset_index(self): df = tm.makeDataFrame()[:5] @@ -5578,7 +5578,7 @@ def test_reset_index(self): [0, 1, 0, 1, 0, 1]]) s = Series(np.random.randn(6), index=index) rs = s.reset_index(level=1) - self.assert_(len(rs.columns) == 2) + self.assertEqual(len(rs.columns), 2) rs = s.reset_index(level=[0, 2], drop=True) self.assert_(rs.index.equals(Index(index.get_level_values(1)))) @@ -5595,7 +5595,7 @@ def test_set_index_makes_timeseries(self): def test_timeseries_coercion(self): idx = tm.makeDateIndex(10000) ser = Series(np.random.randn(len(idx)), idx.astype(object)) - self.assert_(ser.is_time_series == True) + self.assertTrue(ser.is_time_series) self.assert_(isinstance(ser.index, DatetimeIndex)) def test_replace(self): diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 6c9832ebc5c2b..d6a1f4f0341b7 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -186,7 +186,7 @@ def test_contains(self): values = ['foo', 'xyz', 'fooommm__foo', 'mmm_'] result = strings.str_contains(values, pat) expected = [False, False, True, True] - self.assert_(result.dtype == np.bool_) + self.assertEqual(result.dtype, np.bool_) tm.assert_almost_equal(result, expected) # mixed @@ -214,7 +214,7 @@ def test_contains(self): values = ['foo', 'xyz', 'fooommm__foo', 'mmm_'] result = strings.str_contains(values, pat) expected = [False, False, True, True] - self.assert_(result.dtype == np.bool_) + self.assertEqual(result.dtype, np.bool_) tm.assert_almost_equal(result, expected) # na diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index 5de5eee0ec011..e1afd0b0e4d10 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -627,13 +627,13 @@ def test_datetime(self): import datetime dates = [datetime.datetime(2012, 1, x) for x in range(1, 20)] index = Index(dates) - self.assert_(index.inferred_type == 'datetime64') + self.assertEqual(index.inferred_type, 'datetime64') def test_date(self): import datetime dates = [datetime.date(2012, 1, x) for x in range(1, 20)] index = Index(dates) - self.assert_(index.inferred_type == 'date') + self.assertEqual(index.inferred_type, 'date') def test_to_object_array_tuples(self): r = (5, 6)
Work on #6175, in pandas/tests. Tests still pass locally. A work-in-progress, but--with #6261--removes many/most cases of assert_(x == y) in this directory Replacements: - assert_(x == y) ==> assertEqual(x, y) - assert_(x == True) ==> assertTrue(x) - assert_(x == False) ==> assertFalse(x)
https://api.github.com/repos/pandas-dev/pandas/pulls/6262
2014-02-05T03:55:11Z
2014-02-05T12:18:04Z
2014-02-05T12:18:03Z
2014-06-19T04:48:27Z
CLN: More work on converting assert_'s to specialized forms
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 1ea3b32713ca4..e28aca3e5ef3a 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -803,7 +803,7 @@ def test_1d_bool(self): self.assert_(np.array_equal(result, expected)) result = com.take_1d(arr, [0, 2, -1]) - self.assert_(result.dtype == np.object_) + self.assertEqual(result.dtype, np.object_) def test_2d_bool(self): arr = np.array([[0, 1, 0], @@ -819,7 +819,7 @@ def test_2d_bool(self): self.assert_(np.array_equal(result, expected)) result = com.take_nd(arr, [0, 2, -1]) - self.assert_(result.dtype == np.object_) + self.assertEqual(result.dtype, np.object_) def test_2d_float32(self): arr = np.random.randn(4, 3).astype(np.float32) diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 7d392586c159b..2b539b3386226 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -238,19 +238,19 @@ def test_invalid(self): # no op result = expr._can_use_numexpr(operator.add, None, self.frame, self.frame, 'evaluate') - self.assert_(result == False) + self.assertFalse(result) # mixed result = expr._can_use_numexpr(operator.add, '+', self.mixed, self.frame, 'evaluate') - self.assert_(result == False) + self.assertFalse(result) # min elements result = expr._can_use_numexpr(operator.add, '+', self.frame2, self.frame2, 'evaluate') - self.assert_(result == False) + self.assertFalse(result) # ok, we only check on first part of expression result = expr._can_use_numexpr(operator.add, '+', self.frame, self.frame2, 'evaluate') - self.assert_(result == True) + self.assertTrue(result) def test_binary_ops(self): @@ -265,14 +265,14 @@ def testit(): op = getattr(operator, op, None) if op is not None: result = expr._can_use_numexpr(op, op_str, f, f, 'evaluate') - self.assert_(result == (not f._is_mixed_type)) + self.assertNotEqual(result, f._is_mixed_type) result = expr.evaluate(op, op_str, f, f, use_numexpr=True) expected = expr.evaluate(op, op_str, f, f, use_numexpr=False) assert_array_equal(result,expected.values) result = expr._can_use_numexpr(op, op_str, f2, f2, 'evaluate') - self.assert_(result == False) + self.assertFalse(result) expr.set_use_numexpr(False) @@ -300,14 +300,14 @@ def testit(): op = getattr(operator,op) result = expr._can_use_numexpr(op, op_str, f11, f12, 'evaluate') - self.assert_(result == (not f11._is_mixed_type)) + self.assertNotEqual(result, f11._is_mixed_type) result = expr.evaluate(op, op_str, f11, f12, use_numexpr=True) expected = expr.evaluate(op, op_str, f11, f12, use_numexpr=False) assert_array_equal(result,expected.values) result = expr._can_use_numexpr(op, op_str, f21, f22, 'evaluate') - self.assert_(result == False) + self.assertFalse(result) expr.set_use_numexpr(False) testit() diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index bf71f2e3b1431..cca2083339398 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -290,7 +290,7 @@ def test_to_string_repr_unicode(self): except: pass if not line.startswith('dtype:'): - self.assert_(len(line) == line_len) + self.assertEqual(len(line), line_len) # it works even if sys.stdin in None _stdin= sys.stdin @@ -731,7 +731,7 @@ def test_nonunicode_nonascii_alignment(self): df = DataFrame([["aa\xc3\xa4\xc3\xa4", 1], ["bbbb", 2]]) rep_str = df.to_string() lines = rep_str.split('\n') - self.assert_(len(lines[1]) == len(lines[2])) + self.assertEqual(len(lines[1]), len(lines[2])) def test_unicode_problem_decoding_as_ascii(self): dm = DataFrame({u('c/\u03c3'): Series({'test': np.NaN})}) @@ -915,7 +915,7 @@ def test_long_series(self): import re str_rep = str(s) nmatches = len(re.findall('dtype',str_rep)) - self.assert_(nmatches == 1) + self.assertEqual(nmatches, 1) def test_index_with_nan(self): # GH 2850 diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 210e56e453b8f..3fae4ee683e86 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -285,7 +285,7 @@ def test_getitem_boolean(self): assert_frame_equal(bif, bifw, check_dtype=False) for c in df.columns: if bif[c].dtype != bifw[c].dtype: - self.assert_(bif[c].dtype == df[c].dtype) + self.assertEqual(bif[c].dtype, df[c].dtype) def test_getitem_boolean_casting(self): @@ -436,7 +436,7 @@ def test_setitem(self): # with a dtype for dtype in ['int32','int64','float32','float64']: self.frame[dtype] = np.array(arr,dtype=dtype) - self.assert_(self.frame[dtype].dtype.name == dtype) + self.assertEqual(self.frame[dtype].dtype.name, dtype) # dtype changing GH4204 df = DataFrame([[0,0]]) @@ -511,13 +511,13 @@ def test_setitem_boolean(self): def test_setitem_cast(self): self.frame['D'] = self.frame['D'].astype('i8') - self.assert_(self.frame['D'].dtype == np.int64) + self.assertEqual(self.frame['D'].dtype, np.int64) # #669, should not cast? # this is now set to int64, which means a replacement of the column to # the value dtype (and nothing to do with the existing dtype) self.frame['B'] = 0 - self.assert_(self.frame['B'].dtype == np.int64) + self.assertEqual(self.frame['B'].dtype, np.int64) # cast if pass array of course self.frame['B'] = np.arange(len(self.frame)) @@ -525,18 +525,18 @@ def test_setitem_cast(self): self.frame['foo'] = 'bar' self.frame['foo'] = 0 - self.assert_(self.frame['foo'].dtype == np.int64) + self.assertEqual(self.frame['foo'].dtype, np.int64) self.frame['foo'] = 'bar' self.frame['foo'] = 2.5 - self.assert_(self.frame['foo'].dtype == np.float64) + self.assertEqual(self.frame['foo'].dtype, np.float64) self.frame['something'] = 0 - self.assert_(self.frame['something'].dtype == np.int64) + self.assertEqual(self.frame['something'].dtype, np.int64) self.frame['something'] = 2 - self.assert_(self.frame['something'].dtype == np.int64) + self.assertEqual(self.frame['something'].dtype, np.int64) self.frame['something'] = 2.5 - self.assert_(self.frame['something'].dtype == np.float64) + self.assertEqual(self.frame['something'].dtype, np.float64) def test_setitem_boolean_column(self): expected = self.frame.copy() @@ -626,7 +626,7 @@ def test_setitem_ambig(self): dm[2] = uncoercable_series self.assertEqual(len(dm.columns), 3) # self.assert_(dm.objects is not None) - self.assert_(dm[2].dtype == np.object_) + self.assertEqual(dm[2].dtype, np.object_) def test_setitem_clear_caches(self): # GH #304 @@ -837,7 +837,7 @@ def test_setitem_fancy_2d(self): def test_fancy_getitem_slice_mixed(self): sliced = self.mixed_frame.ix[:, -3:] - self.assert_(sliced['D'].dtype == np.float64) + self.assertEqual(sliced['D'].dtype, np.float64) # get view with single block sliced = self.frame.ix[:, -3:] @@ -1474,7 +1474,7 @@ def test_getitem_list_duplicates(self): df.columns.name = 'foo' result = df[['B', 'C']] - self.assert_(result.columns.name == 'foo') + self.assertEqual(result.columns.name, 'foo') expected = df.ix[:, 2:] assert_frame_equal(result, expected) @@ -1515,7 +1515,7 @@ def testit(df): df['mask'] = df.lookup(df.index, 'mask_' + df['label']) exp_mask = alt(df, df.index, 'mask_' + df['label']) assert_almost_equal(df['mask'], exp_mask) - self.assert_(df['mask'].dtype == np.bool_) + self.assertEqual(df['mask'].dtype, np.bool_) with tm.assertRaises(KeyError): self.frame.lookup(['xyz'], ['A']) @@ -1536,7 +1536,7 @@ def test_set_value_resize(self): res = self.frame.set_value('foobar', 'B', 0) self.assert_(res is self.frame) - self.assert_(res.index[-1] == 'foobar') + self.assertEqual(res.index[-1], 'foobar') self.assertEqual(res.get_value('foobar', 'B'), 0) self.frame.loc['foobar','qux'] = 0 @@ -1544,11 +1544,11 @@ def test_set_value_resize(self): res = self.frame.copy() res3 = res.set_value('foobar', 'baz', 'sam') - self.assert_(res3['baz'].dtype == np.object_) + self.assertEqual(res3['baz'].dtype, np.object_) res = self.frame.copy() res3 = res.set_value('foobar', 'baz', True) - self.assert_(res3['baz'].dtype == np.object_) + self.assertEqual(res3['baz'].dtype, np.object_) res = self.frame.copy() res3 = res.set_value('foobar', 'baz', 5) @@ -2135,10 +2135,10 @@ def test_column_contains_typeerror(self): def test_constructor(self): df = DataFrame() - self.assert_(len(df.index) == 0) + self.assertEqual(len(df.index), 0) df = DataFrame(data={}) - self.assert_(len(df.index) == 0) + self.assertEqual(len(df.index), 0) def test_constructor_mixed(self): index, data = tm.getMixedTypeDict() @@ -2150,7 +2150,7 @@ def test_constructor_mixed(self): def test_constructor_cast_failure(self): foo = DataFrame({'a': ['a', 'b', 'c']}, dtype=np.float64) - self.assert_(foo['a'].dtype == object) + self.assertEqual(foo['a'].dtype, object) # GH 3010, constructing with odd arrays df = DataFrame(np.ones((4,2))) @@ -2178,13 +2178,13 @@ def test_constructor_dtype_list_data(self): df = DataFrame([[1, '2'], [None, 'a']], dtype=object) self.assert_(df.ix[1, 0] is None) - self.assert_(df.ix[0, 1] == '2') + self.assertEqual(df.ix[0, 1], '2') def test_constructor_list_frames(self): # GH 3243 result = DataFrame([DataFrame([])]) - self.assert_(result.shape == (1,0)) + self.assertEqual(result.shape, (1,0)) result = DataFrame([DataFrame(dict(A = lrange(5)))]) tm.assert_isinstance(result.iloc[0,0], DataFrame) @@ -2257,7 +2257,7 @@ def test_constructor_overflow_int64(self): dtype=np.uint64) result = DataFrame({'a': values}) - self.assert_(result['a'].dtype == object) + self.assertEqual(result['a'].dtype, object) # #2355 data_scores = [(6311132704823138710, 273), (2685045978526272070, 23), @@ -2267,7 +2267,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.assertEqual(df_crawls['uid'].dtype, object) def test_constructor_ordereddict(self): import random @@ -2426,13 +2426,13 @@ def test_constructor_dict_cast(self): } frame = DataFrame(test_data, dtype=float) self.assertEqual(len(frame), 3) - self.assert_(frame['B'].dtype == np.float64) - self.assert_(frame['A'].dtype == np.float64) + self.assertEqual(frame['B'].dtype, np.float64) + self.assertEqual(frame['A'].dtype, np.float64) frame = DataFrame(test_data) self.assertEqual(len(frame), 3) - self.assert_(frame['B'].dtype == np.object_) - self.assert_(frame['A'].dtype == np.float64) + self.assertEqual(frame['B'].dtype, np.object_) + self.assertEqual(frame['A'].dtype, np.float64) # can't cast to float test_data = { @@ -2441,8 +2441,8 @@ def test_constructor_dict_cast(self): } frame = DataFrame(test_data, dtype=float) self.assertEqual(len(frame), 20) - self.assert_(frame['A'].dtype == np.object_) - self.assert_(frame['B'].dtype == np.float64) + self.assertEqual(frame['A'].dtype, np.object_) + self.assertEqual(frame['B'].dtype, np.float64) def test_constructor_dict_dont_upcast(self): d = {'Col1': {'Row1': 'A String', 'Row2': np.nan}} @@ -2478,7 +2478,7 @@ def _check_basic_constructor(self, empty): # cast type frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2], dtype=np.int64) - self.assert_(frame.values.dtype == np.int64) + self.assertEqual(frame.values.dtype, np.int64) # wrong size axis labels msg = r'Shape of passed values is \(3, 2\), indices imply \(3, 1\)' @@ -2506,10 +2506,10 @@ def _check_basic_constructor(self, empty): # 0-length axis frame = DataFrame(empty((0, 3))) - self.assert_(len(frame.index) == 0) + self.assertEqual(len(frame.index), 0) frame = DataFrame(empty((3, 0))) - self.assert_(len(frame.columns) == 0) + self.assertEqual(len(frame.columns), 0) def test_constructor_ndarray(self): mat = np.zeros((2, 3), dtype=float) @@ -2547,7 +2547,7 @@ def test_constructor_maskedarray_nonfloat(self): # cast type frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2], dtype=np.float64) - self.assert_(frame.values.dtype == np.float64) + self.assertEqual(frame.values.dtype, np.float64) # Check non-masked values mat2 = ma.copy(mat) @@ -2569,7 +2569,7 @@ def test_constructor_maskedarray_nonfloat(self): # cast type frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2], dtype=np.int64) - self.assert_(frame.values.dtype == np.int64) + self.assertEqual(frame.values.dtype, np.int64) # Check non-masked values mat2 = ma.copy(mat) @@ -2591,7 +2591,7 @@ def test_constructor_maskedarray_nonfloat(self): # cast type frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2], dtype=object) - self.assert_(frame.values.dtype == object) + self.assertEqual(frame.values.dtype, object) # Check non-masked values mat2 = ma.copy(mat) @@ -2649,26 +2649,26 @@ def test_constructor_corner(self): # empty but with specified dtype df = DataFrame(index=lrange(10), columns=['a', 'b'], dtype=object) - self.assert_(df.values.dtype == np.object_) + self.assertEqual(df.values.dtype, np.object_) # does not error but ends up float df = DataFrame(index=lrange(10), columns=['a', 'b'], dtype=int) - self.assert_(df.values.dtype == np.object_) + self.assertEqual(df.values.dtype, np.object_) # #1783 empty dtype object df = DataFrame({}, columns=['foo', 'bar']) - self.assert_(df.values.dtype == np.object_) + self.assertEqual(df.values.dtype, np.object_) def test_constructor_scalar_inference(self): data = {'int': 1, 'bool': True, 'float': 3., 'complex': 4j, 'object': 'foo'} df = DataFrame(data, index=np.arange(10)) - self.assert_(df['int'].dtype == np.int64) - self.assert_(df['bool'].dtype == np.bool_) - self.assert_(df['float'].dtype == np.float64) - self.assert_(df['complex'].dtype == np.complex128) - self.assert_(df['object'].dtype == np.object_) + self.assertEqual(df['int'].dtype, np.int64) + self.assertEqual(df['bool'].dtype, np.bool_) + self.assertEqual(df['float'].dtype, np.float64) + self.assertEqual(df['complex'].dtype, np.complex128) + self.assertEqual(df['object'].dtype, np.object_) def test_constructor_arrays_and_scalars(self): df = DataFrame({'a': randn(10), 'b': True}) @@ -2683,7 +2683,7 @@ def test_constructor_DataFrame(self): assert_frame_equal(df, self.frame) df_casted = DataFrame(self.frame, dtype=np.int64) - self.assert_(df_casted.values.dtype == np.int64) + self.assertEqual(df_casted.values.dtype, np.int64) def test_constructor_more(self): # used to be in test_matrix.py @@ -2725,7 +2725,7 @@ def test_constructor_more(self): index=np.arange(10)) self.assertEqual(len(dm.columns), 2) - self.assert_(dm.values.dtype == np.float64) + self.assertEqual(dm.values.dtype, np.float64) def test_constructor_empty_list(self): df = DataFrame([], index=[]) @@ -2737,7 +2737,7 @@ def test_constructor_list_of_lists(self): l = [[1, 'a'], [2, 'b']] df = DataFrame(data=l, columns=["num", "str"]) self.assert_(com.is_integer_dtype(df['num'])) - self.assert_(df['str'].dtype == np.object_) + self.assertEqual(df['str'].dtype, np.object_) # GH 4851 # list of 0-dim ndarrays @@ -2936,7 +2936,7 @@ def test_constructor_orient(self): def test_constructor_Series_named(self): a = Series([1, 2, 3], index=['a', 'b', 'c'], name='x') df = DataFrame(a) - self.assert_(df.columns[0] == 'x') + self.assertEqual(df.columns[0], 'x') self.assert_(df.index.equals(a.index)) # ndarray like @@ -2956,7 +2956,7 @@ def test_constructor_Series_named(self): # #2234 a = Series([], name='x') df = DataFrame(a) - self.assert_(df.columns[0] == 'x') + self.assertEqual(df.columns[0], 'x') # series with name and w/o s1 = Series(arr,name='x') @@ -2980,12 +2980,12 @@ def test_constructor_Series_differently_indexed(self): df1 = DataFrame(s1, index=other_index) exp1 = DataFrame(s1.reindex(other_index)) - self.assert_(df1.columns[0] == 'x') + self.assertEqual(df1.columns[0], 'x') assert_frame_equal(df1, exp1) df2 = DataFrame(s2, index=other_index) exp2 = DataFrame(s2.reindex(other_index)) - self.assert_(df2.columns[0] == 0) + self.assertEqual(df2.columns[0], 0) self.assert_(df2.index.equals(other_index)) assert_frame_equal(df2, exp2) @@ -3402,7 +3402,7 @@ def test_constructor_with_datetimes(self): ind = date_range(start="2000-01-01", freq="D", periods=10) datetimes = [ts.to_pydatetime() for ts in ind] datetime_s = Series(datetimes) - self.assert_(datetime_s.dtype == 'M8[ns]') + self.assertEqual(datetime_s.dtype, 'M8[ns]') df = DataFrame({'datetime_s':datetime_s}) result = df.get_dtype_counts() expected = Series({ datetime64name : 1 }) @@ -3526,16 +3526,16 @@ def test_operators_timedelta64(self): # min result = diffs.min() - self.assert_(result[0] == diffs.ix[0,'A']) - self.assert_(result[1] == diffs.ix[0,'B']) + self.assertEqual(result[0], diffs.ix[0,'A']) + self.assertEqual(result[1], diffs.ix[0,'B']) result = diffs.min(axis=1) self.assert_((result == diffs.ix[0,'B']).all() == True) # max result = diffs.max() - self.assert_(result[0] == diffs.ix[2,'A']) - self.assert_(result[1] == diffs.ix[2,'B']) + self.assertEqual(result[0], diffs.ix[2,'A']) + self.assertEqual(result[1], diffs.ix[2,'B']) result = diffs.max(axis=1) self.assert_((result == diffs['A']).all() == True) @@ -3585,7 +3585,7 @@ def test_operators_timedelta64(self): df = DataFrame({'time' : date_range('20130102',periods=5), 'time2' : date_range('20130105',periods=5) }) df['off1'] = df['time2']-df['time'] - self.assert_(df['off1'].dtype == 'timedelta64[ns]') + self.assertEqual(df['off1'].dtype, 'timedelta64[ns]') df['off2'] = df['time']-df['time2'] df._consolidate_inplace() @@ -3620,7 +3620,7 @@ def test_astype(self): # mixed casting def _check_cast(df, v): - self.assert_(list(set([ s.dtype.name for _, s in compat.iteritems(df) ]))[0] == v) + self.assertEqual(list(set([ s.dtype.name for _, s in compat.iteritems(df) ]))[0], v) mn = self.all_mixed._get_numeric_data().copy() mn['little_float'] = np.array(12345.,dtype='float16') @@ -3741,10 +3741,10 @@ def test_to_records_dt64(self): df = DataFrame([["one", "two", "three"], ["four", "five", "six"]], index=pan.date_range("2012-01-01", "2012-01-02")) - self.assert_(df.to_records()['index'][0] == df.index[0]) + self.assertEqual(df.to_records()['index'][0], df.index[0]) rs = df.to_records(convert_datetime64=False) - self.assert_(rs['index'][0] == df.index.values[0]) + self.assertEqual(rs['index'][0], df.index.values[0]) def test_to_records_with_multindex(self): # GH3189 @@ -3872,10 +3872,10 @@ def test_from_records_decimal(self): tuples = [(Decimal('1.5'),), (Decimal('2.5'),), (None,)] df = DataFrame.from_records(tuples, columns=['a']) - self.assert_(df['a'].dtype == object) + self.assertEqual(df['a'].dtype, object) df = DataFrame.from_records(tuples, columns=['a'], coerce_float=True) - self.assert_(df['a'].dtype == np.float64) + self.assertEqual(df['a'].dtype, np.float64) self.assert_(np.isnan(df['a'].values[-1])) def test_from_records_duplicates(self): @@ -3896,12 +3896,12 @@ def create_dict(order_id): documents.append({'order_id': 10, 'quantity': 5}) result = DataFrame.from_records(documents, index='order_id') - self.assert_(result.index.name == 'order_id') + self.assertEqual(result.index.name, 'order_id') # MultiIndex result = DataFrame.from_records(documents, index=['order_id', 'quantity']) - self.assert_(result.index.names == ('order_id', 'quantity')) + self.assertEqual(result.index.names, ('order_id', 'quantity')) def test_from_records_misc_brokenness(self): # #2179 @@ -4017,7 +4017,7 @@ def test_join_str_datetime(self): tst = A.join(C, on='aa') - self.assert_(len(tst.columns) == 3) + self.assertEqual(len(tst.columns), 3) def test_from_records_sequencelike(self): df = DataFrame({'A' : np.array(np.random.randn(6), dtype = np.float64), @@ -4405,7 +4405,7 @@ def test_pop(self): self.frame['foo'] = 'bar' foo = self.frame.pop('foo') self.assert_('foo' not in self.frame) - # TODO self.assert_(self.frame.columns.name == 'baz') + # TODO self.assertEqual(self.frame.columns.name, 'baz') def test_pop_non_unique_cols(self): df = DataFrame({0: [0, 1], 1: [0, 1], 2: [4, 5]}) @@ -4655,14 +4655,14 @@ def _check_bin_op(op): result = op(df1, df2) expected = DataFrame(op(df1.values, df2.values), index=df1.index, columns=df1.columns) - self.assert_(result.values.dtype == np.bool_) + self.assertEqual(result.values.dtype, np.bool_) assert_frame_equal(result, expected) def _check_unary_op(op): result = op(df1) expected = DataFrame(op(df1.values), index=df1.index, columns=df1.columns) - self.assert_(result.values.dtype == np.bool_) + self.assertEqual(result.values.dtype, np.bool_) assert_frame_equal(result, expected) df1 = {'a': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True}, @@ -4703,7 +4703,7 @@ def test_logical_typeerror(self): def test_constructor_lists_to_object_dtype(self): # from #1074 d = DataFrame({'a': [np.nan, False]}) - self.assert_(d['a'].dtype == np.object_) + self.assertEqual(d['a'].dtype, np.object_) self.assert_(d['a'][1] is False) def test_constructor_with_nas(self): @@ -4775,10 +4775,10 @@ def test_first_last_valid(self): frame = DataFrame({'foo': mat}, index=self.frame.index) index = frame.first_valid_index() - self.assert_(index == frame.index[5]) + self.assertEqual(index, frame.index[5]) index = frame.last_valid_index() - self.assert_(index == frame.index[-6]) + self.assertEqual(index, frame.index[-6]) def test_arith_flex_frame(self): ops = ['add', 'sub', 'mul', 'div', 'truediv', 'pow', 'floordiv', 'mod'] @@ -5321,7 +5321,7 @@ def test_boolean_comparison(self): assert_array_equal(result,expected.values) self.assertRaises(ValueError, lambda : df == b_c) - self.assert_((df.values == b_c) is False) + self.assertFalse((df.values == b_c)) # with alignment df = DataFrame(np.arange(6).reshape((3,2)),columns=list('AB'),index=list('abc')) @@ -5843,7 +5843,7 @@ def _make_frame(names=None): exp.index = [] self.assert_(recons.columns.equals(exp.columns)) - self.assert_(len(recons) == 0) + self.assertEqual(len(recons), 0) def test_to_csv_float32_nanrep(self): df = DataFrame(np.random.randn(1, 4).astype(np.float32)) @@ -5854,7 +5854,7 @@ def test_to_csv_float32_nanrep(self): with open(path) as f: lines = f.readlines() - self.assert_(lines[1].split(',')[2] == '999') + self.assertEqual(lines[1].split(',')[2], '999') def test_to_csv_withcommas(self): @@ -6127,7 +6127,7 @@ def test_info_wide(self): set_option('display.max_info_columns', 101) io = StringIO() df.info(buf=io) - self.assert_(rs == xp) + self.assertEqual(rs, xp) reset_option('display.max_info_columns') def test_info_duplicate_columns(self): @@ -6166,7 +6166,7 @@ def test_convert_objects(self): oops = self.mixed_frame.T.T converted = oops.convert_objects() assert_frame_equal(converted, self.mixed_frame) - self.assert_(converted['A'].dtype == np.float64) + self.assertEqual(converted['A'].dtype, np.float64) # force numeric conversion self.mixed_frame['H'] = '1.' @@ -6178,19 +6178,19 @@ def test_convert_objects(self): self.mixed_frame['K'] = '1' self.mixed_frame.ix[0:5,['J','K']] = 'garbled' converted = self.mixed_frame.convert_objects(convert_numeric=True) - self.assert_(converted['H'].dtype == 'float64') - self.assert_(converted['I'].dtype == 'int64') - self.assert_(converted['J'].dtype == 'float64') - self.assert_(converted['K'].dtype == 'float64') - self.assert_(len(converted['J'].dropna()) == l-5) - self.assert_(len(converted['K'].dropna()) == l-5) + self.assertEqual(converted['H'].dtype, 'float64') + self.assertEqual(converted['I'].dtype, 'int64') + self.assertEqual(converted['J'].dtype, 'float64') + self.assertEqual(converted['K'].dtype, 'float64') + self.assertEqual(len(converted['J'].dropna()), l-5) + self.assertEqual(len(converted['K'].dropna()), l-5) # via astype converted = self.mixed_frame.copy() converted['H'] = converted['H'].astype('float64') converted['I'] = converted['I'].astype('int64') - self.assert_(converted['H'].dtype == 'float64') - self.assert_(converted['I'].dtype == 'int64') + self.assertEqual(converted['H'].dtype, 'float64') + self.assertEqual(converted['I'].dtype, 'int64') # via astype, but errors converted = self.mixed_frame.copy() @@ -6371,14 +6371,14 @@ def test_at_time_between_time_datetimeindex(self): expected2 = df.ix[ainds] assert_frame_equal(result, expected) assert_frame_equal(result, expected2) - self.assert_(len(result) == 4) + self.assertEqual(len(result), 4) result = df.between_time(bkey.start, bkey.stop) expected = df.ix[bkey] expected2 = df.ix[binds] assert_frame_equal(result, expected) assert_frame_equal(result, expected2) - self.assert_(len(result) == 12) + self.assertEqual(len(result), 12) result = df.copy() result.ix[akey] = 0 @@ -6520,8 +6520,8 @@ def test_corr_nooverlap(self): rs = df.corr(meth) self.assert_(isnull(rs.ix['A', 'B'])) self.assert_(isnull(rs.ix['B', 'A'])) - self.assert_(rs.ix['A', 'A'] == 1) - self.assert_(rs.ix['B', 'B'] == 1) + self.assertEqual(rs.ix['A', 'A'], 1) + self.assertEqual(rs.ix['B', 'B'], 1) def test_corr_constant(self): _skip_if_no_scipy() @@ -8063,7 +8063,7 @@ def test_xs(self): } frame = DataFrame(test_data) xs = frame.xs('1') - self.assert_(xs.dtype == np.object_) + self.assertEqual(xs.dtype, np.object_) self.assertEqual(xs['A'], 1) self.assertEqual(xs['B'], '1') @@ -8191,7 +8191,7 @@ def test_reindex(self): for col, series in compat.iteritems(newFrame): self.assert_(tm.equalContents(series.index, newFrame.index)) emptyFrame = self.frame.reindex(Index([])) - self.assert_(len(emptyFrame.index) == 0) + self.assertEqual(len(emptyFrame.index), 0) # Cython code should be unit-tested directly nonContigFrame = self.frame.reindex(self.ts1.index[::2]) @@ -8234,7 +8234,7 @@ def test_reindex(self): # copy with no axes result = self.frame.reindex() assert_frame_equal(result,self.frame) - self.assert_((result is self.frame) == False) + self.assertFalse(result is self.frame) def test_reindex_name_remains(self): s = Series(random.rand(10)) @@ -8242,27 +8242,27 @@ def test_reindex_name_remains(self): i = Series(np.arange(10), name='iname') df = df.reindex(i) - self.assert_(df.index.name == 'iname') + self.assertEqual(df.index.name, 'iname') df = df.reindex(Index(np.arange(10), name='tmpname')) - self.assert_(df.index.name == 'tmpname') + self.assertEqual(df.index.name, 'tmpname') s = Series(random.rand(10)) df = DataFrame(s.T, index=np.arange(len(s))) i = Series(np.arange(10), name='iname') df = df.reindex(columns=i) - self.assert_(df.columns.name == 'iname') + self.assertEqual(df.columns.name, 'iname') def test_reindex_int(self): smaller = self.intframe.reindex(self.intframe.index[::2]) - self.assert_(smaller['A'].dtype == np.int64) + self.assertEqual(smaller['A'].dtype, np.int64) bigger = smaller.reindex(self.intframe.index) - self.assert_(bigger['A'].dtype == np.float64) + self.assertEqual(bigger['A'].dtype, np.float64) smaller = self.intframe.reindex(columns=['A', 'B']) - self.assert_(smaller['A'].dtype == np.int64) + self.assertEqual(smaller['A'].dtype, np.int64) def test_reindex_like(self): other = self.frame.reindex(index=self.frame.index[:10], @@ -8292,8 +8292,8 @@ def test_reindex_axes(self): index_freq = df.reindex(index=time_freq).index.freq both_freq = df.reindex(index=time_freq, columns=some_cols).index.freq seq_freq = df.reindex(index=time_freq).reindex(columns=some_cols).index.freq - self.assert_(index_freq == both_freq) - self.assert_(index_freq == seq_freq) + self.assertEqual(index_freq, both_freq) + self.assertEqual(index_freq, seq_freq) def test_reindex_fill_value(self): df = DataFrame(np.random.randn(10, 4)) @@ -8623,7 +8623,7 @@ def _check_set(df, cond, check_dtypes = True): for k, v in compat.iteritems(df.dtypes): if issubclass(v.type,np.integer) and not cond[k].all(): v = np.dtype('float64') - self.assert_(dfi[k].dtype == v) + self.assertEqual(dfi[k].dtype, v) for df in [ default_frame, self.mixed_frame, self.mixed_float, self.mixed_int ]: @@ -8747,7 +8747,7 @@ def test_transpose(self): mixed_T = mixed.T for col, s in compat.iteritems(mixed_T): - self.assert_(s.dtype == np.object_) + self.assertEqual(s.dtype, np.object_) def test_transpose_get_view(self): dft = self.frame.T @@ -8877,7 +8877,7 @@ def test_diff_mixed_dtype(self): df['A'] = np.array([1, 2, 3, 4, 5], dtype=object) result = df.diff() - self.assert_(result[0].dtype == np.float64) + self.assertEqual(result[0].dtype, np.float64) def test_diff_neg_n(self): rs = self.tsframe.diff(-1) @@ -8935,7 +8935,7 @@ def test_shift(self): # shift by DateOffset shiftedFrame = self.tsframe.shift(5, freq=datetools.BDay()) - self.assert_(len(shiftedFrame) == len(self.tsframe)) + self.assertEqual(len(shiftedFrame), len(self.tsframe)) shiftedFrame2 = self.tsframe.shift(5, freq='B') assert_frame_equal(shiftedFrame, shiftedFrame2) @@ -9336,11 +9336,11 @@ def test_applymap(self): # GH 2909, object conversion to float in constructor? df = DataFrame(data=[1,'a']) result = df.applymap(lambda x: x) - self.assert_(result.dtypes[0] == object) + self.assertEqual(result.dtypes[0], object) df = DataFrame(data=[1.,'a']) result = df.applymap(lambda x: x) - self.assert_(result.dtypes[0] == object) + self.assertEqual(result.dtypes[0], object) # GH2786 df = DataFrame(np.random.random((3,4))) @@ -10076,11 +10076,11 @@ def test_bool_describe_in_mixed_frame(self): bool_describe = df.describe()['bool_data'] # Both the min and the max values should stay booleans - self.assert_(bool_describe['min'].dtype == np.bool_) - self.assert_(bool_describe['max'].dtype == np.bool_) + self.assertEqual(bool_describe['min'].dtype, np.bool_) + self.assertEqual(bool_describe['max'].dtype, np.bool_) - self.assert_(bool_describe['min'] == False) - self.assert_(bool_describe['max'] == True) + self.assertFalse(bool_describe['min']) + self.assertTrue(bool_describe['max']) # For numeric operations, like mean or median, the values True/False are cast to # the integer values 1 and 0 @@ -10144,7 +10144,7 @@ def test_stat_operators_attempt_obj_array(self): for df in [df1, df2]: for meth in methods: - self.assert_(df.values.dtype == np.object_) + self.assertEqual(df.values.dtype, np.object_) result = getattr(df, meth)(1) expected = getattr(df.astype('f8'), meth)(1) assert_series_equal(result, expected) @@ -10331,8 +10331,8 @@ def wrapper(x): # check dtypes if check_dtype: lcd_dtype = frame.values.dtype - self.assert_(lcd_dtype == result0.dtype) - self.assert_(lcd_dtype == result1.dtype) + self.assertEqual(lcd_dtype, result0.dtype) + self.assertEqual(lcd_dtype, result1.dtype) # result = f(axis=1) # comp = frame.apply(alternative, axis=1).reindex(result.index) @@ -10745,11 +10745,11 @@ def test_reindex_boolean(self): columns=[0, 2]) reindexed = frame.reindex(np.arange(10)) - self.assert_(reindexed.values.dtype == np.object_) + self.assertEqual(reindexed.values.dtype, np.object_) self.assert_(isnull(reindexed[0][1])) reindexed = frame.reindex(columns=lrange(3)) - self.assert_(reindexed.values.dtype == np.object_) + self.assertEqual(reindexed.values.dtype, np.object_) self.assert_(isnull(reindexed[1]).all()) def test_reindex_objects(self): @@ -10768,7 +10768,7 @@ def test_reindex_corner(self): # ints are weird smaller = self.intframe.reindex(columns=['A', 'B', 'E']) - self.assert_(smaller['E'].dtype == np.float64) + self.assertEqual(smaller['E'].dtype, np.float64) def test_reindex_axis(self): cols = ['A', 'B', 'E'] @@ -11031,10 +11031,10 @@ def test_reset_index_right_dtype(self): df = DataFrame(s1) resetted = s1.reset_index() - self.assert_(resetted['time'].dtype == np.float64) + self.assertEqual(resetted['time'].dtype, np.float64) resetted = df.reset_index() - self.assert_(resetted['time'].dtype == np.float64) + self.assertEqual(resetted['time'].dtype, np.float64) def test_reset_index_multiindex_col(self): vals = np.random.randn(3, 3).astype(object) @@ -11098,41 +11098,41 @@ def test_as_matrix_numeric_cols(self): self.frame['foo'] = 'bar' values = self.frame.as_matrix(['A', 'B', 'C', 'D']) - self.assert_(values.dtype == np.float64) + self.assertEqual(values.dtype, np.float64) def test_as_matrix_lcd(self): # mixed lcd values = self.mixed_float.as_matrix(['A', 'B', 'C', 'D']) - self.assert_(values.dtype == np.float64) + self.assertEqual(values.dtype, np.float64) values = self.mixed_float.as_matrix(['A', 'B', 'C' ]) - self.assert_(values.dtype == np.float32) + self.assertEqual(values.dtype, np.float32) values = self.mixed_float.as_matrix(['C']) - self.assert_(values.dtype == np.float16) + self.assertEqual(values.dtype, np.float16) values = self.mixed_int.as_matrix(['A','B','C','D']) - self.assert_(values.dtype == np.int64) + self.assertEqual(values.dtype, np.int64) values = self.mixed_int.as_matrix(['A','D']) - self.assert_(values.dtype == np.int64) + self.assertEqual(values.dtype, np.int64) # guess all ints are cast to uints.... values = self.mixed_int.as_matrix(['A','B','C']) - self.assert_(values.dtype == np.int64) + self.assertEqual(values.dtype, np.int64) values = self.mixed_int.as_matrix(['A','C']) - self.assert_(values.dtype == np.int32) + self.assertEqual(values.dtype, np.int32) values = self.mixed_int.as_matrix(['C','D']) - self.assert_(values.dtype == np.int64) + self.assertEqual(values.dtype, np.int64) values = self.mixed_int.as_matrix(['A']) - self.assert_(values.dtype == np.int32) + self.assertEqual(values.dtype, np.int32) values = self.mixed_int.as_matrix(['C']) - self.assert_(values.dtype == np.uint8) + self.assertEqual(values.dtype, np.uint8) def test_constructor_with_convert(self): # this is actually mostly a test of lib.maybe_convert_objects @@ -11214,8 +11214,8 @@ def test_construction_with_mixed(self): # mixed-type frames self.mixed_frame['datetime'] = datetime.now() self.mixed_frame['timedelta'] = timedelta(days=1,seconds=1) - self.assert_(self.mixed_frame['datetime'].dtype == 'M8[ns]') - self.assert_(self.mixed_frame['timedelta'].dtype == 'm8[ns]') + self.assertEqual(self.mixed_frame['datetime'].dtype, 'M8[ns]') + self.assertEqual(self.mixed_frame['timedelta'].dtype, 'm8[ns]') result = self.mixed_frame.get_dtype_counts().order() expected = Series({ 'float64' : 4, 'object' : 1, @@ -11313,7 +11313,7 @@ def test_columns_with_dups(self): df = pan.concat([ df_float, df_int, df_bool, df_object, df_dt ], axis=1) result = df._data._set_ref_locs() - self.assert_(len(result) == len(df.columns)) + self.assertEqual(len(result), len(df.columns)) # testing iget for i in range(len(df.columns)): @@ -11357,7 +11357,7 @@ def test_cast_internals(self): def test_consolidate(self): self.frame['E'] = 7. consolidated = self.frame.consolidate() - self.assert_(len(consolidated._data.blocks) == 1) + self.assertEqual(len(consolidated._data.blocks), 1) # Ensure copy, do I want this? recons = consolidated.consolidate() @@ -11365,9 +11365,9 @@ def test_consolidate(self): assert_frame_equal(recons, consolidated) self.frame['F'] = 8. - self.assert_(len(self.frame._data.blocks) == 3) + self.assertEqual(len(self.frame._data.blocks), 3) self.frame.consolidate(inplace=True) - self.assert_(len(self.frame._data.blocks) == 1) + self.assertEqual(len(self.frame._data.blocks), 1) def test_consolidate_inplace(self): frame = self.frame.copy() @@ -11472,7 +11472,7 @@ def test_boolean_indexing_mixed(self): def test_sum_bools(self): df = DataFrame(index=lrange(1), columns=lrange(10)) bools = isnull(df) - self.assert_(bools.sum(axis=1)[0] == 10) + self.assertEqual(bools.sum(axis=1)[0], 10) def test_fillna_col_reordering(self): idx = lrange(20) @@ -11480,7 +11480,7 @@ def test_fillna_col_reordering(self): data = np.random.rand(20, 5) df = DataFrame(index=lrange(20), columns=cols, data=data) filled = df.fillna(method='ffill') - self.assert_(df.columns.tolist() == filled.columns.tolist()) + self.assertEqual(df.columns.tolist(), filled.columns.tolist()) def test_take(self): diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index 60c51c09915f3..eb7f178df39d8 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -229,7 +229,7 @@ def check_metadata(self, x, y=None): if y is None: self.assert_(v is None) else: - self.assert_(v == getattr(y,m,None)) + self.assertEqual(v, getattr(y,m,None)) def test_metadata_propagation(self): # check that the metadata matches up on the resulting ops diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 6a80c9f053c71..64a5d981f6cf6 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -197,9 +197,9 @@ def test_first_last_nth_dtypes(self): idx = lrange(10) idx.append(9) s = Series(data=lrange(11), index=idx, name='IntCol') - self.assert_(s.dtype == 'int64') + self.assertEqual(s.dtype, 'int64') f = s.groupby(level=0).first() - self.assert_(f.dtype == 'int64') + self.assertEqual(f.dtype, 'int64') def test_grouper_index_types(self): # related GH5375 @@ -954,7 +954,7 @@ def test_frame_groupby(self): # iterate for weekday, group in grouped: - self.assert_(group.index[0].weekday() == weekday) + self.assertEqual(group.index[0].weekday(), weekday) # groups / group_indices groups = grouped.groups @@ -998,26 +998,26 @@ def test_frame_set_name_single(self): grouped = self.df.groupby('A') result = grouped.mean() - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') result = self.df.groupby('A', as_index=False).mean() - self.assert_(result.index.name != 'A') + self.assertNotEqual(result.index.name, 'A') result = grouped.agg(np.mean) - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') result = grouped.agg({'C': np.mean, 'D': np.std}) - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') result = grouped['C'].mean() - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') result = grouped['C'].agg(np.mean) - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') result = grouped['C'].agg([np.mean, np.std]) - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') result = grouped['C'].agg({'foo': np.mean, 'bar': np.std}) - self.assert_(result.index.name == 'A') + self.assertEqual(result.index.name, 'A') def test_multi_iter(self): s = Series(np.arange(6)) @@ -1033,8 +1033,8 @@ def test_multi_iter(self): ('b', '2', s[[3, 5]])] for i, ((one, two), three) in enumerate(iterated): e1, e2, e3 = expected[i] - self.assert_(e1 == one) - self.assert_(e2 == two) + self.assertEqual(e1, one) + self.assertEqual(e2, two) assert_series_equal(three, e3) def test_multi_iter_frame(self): @@ -1056,8 +1056,8 @@ def test_multi_iter_frame(self): ('b', '2', df.ix[idx[[1]]])] for i, ((one, two), three) in enumerate(iterated): e1, e2, e3 = expected[i] - self.assert_(e1 == one) - self.assert_(e2 == two) + self.assertEqual(e1, one) + self.assertEqual(e2, two) assert_frame_equal(three, e3) # don't iterate through groups with no data @@ -1567,8 +1567,8 @@ def test_groupby_level(self): expected0 = expected0.reindex(frame.index.levels[0]) expected1 = expected1.reindex(frame.index.levels[1]) - self.assert_(result0.index.name == 'first') - self.assert_(result1.index.name == 'second') + self.assertEqual(result0.index.name, 'first') + self.assertEqual(result1.index.name, 'second') assert_frame_equal(result0, expected0) assert_frame_equal(result1, expected1) @@ -1622,12 +1622,12 @@ def test_groupby_level_apply(self): frame = self.mframe result = frame.groupby(level=0).count() - self.assert_(result.index.name == 'first') + self.assertEqual(result.index.name, 'first') result = frame.groupby(level=1).count() - self.assert_(result.index.name == 'second') + self.assertEqual(result.index.name, 'second') result = frame['A'].groupby(level=0).count() - self.assert_(result.index.name == 'first') + self.assertEqual(result.index.name, 'first') def test_groupby_level_mapper(self): frame = self.mframe @@ -2001,7 +2001,7 @@ def f(group): grouped = df.groupby('c') result = grouped.apply(f) - self.assert_(result['d'].dtype == np.float64) + self.assertEqual(result['d'].dtype, np.float64) for key, group in grouped: res = f(group) @@ -2084,11 +2084,11 @@ def convert_force_pure(x): grouped = s.groupby(labels) result = grouped.agg(convert_fast) - self.assert_(result.dtype == np.object_) + self.assertEqual(result.dtype, np.object_) tm.assert_isinstance(result[0], Decimal) result = grouped.agg(convert_force_pure) - self.assert_(result.dtype == np.object_) + self.assertEqual(result.dtype, np.object_) tm.assert_isinstance(result[0], Decimal) def test_apply_with_mixed_dtype(self): @@ -2227,7 +2227,7 @@ def test_int32_overflow(self): left = df.groupby(['A', 'B', 'C', 'D']).sum() right = df.groupby(['D', 'C', 'B', 'A']).sum() - self.assert_(len(left) == len(right)) + self.assertEqual(len(left), len(right)) def test_int64_overflow(self): B = np.concatenate((np.arange(1000), np.arange(1000), @@ -2257,8 +2257,9 @@ def test_int64_overflow(self): expected = df.groupby(tups).sum()['values'] for k, v in compat.iteritems(expected): - self.assert_(left[k] == right[k[::-1]] == v) - self.assert_(len(left) == len(right)) + self.assertEqual(left[k], right[k[::-1]]) + self.assertEqual(left[k], v) + self.assertEqual(len(left), len(right)) def test_groupby_sort_multi(self): df = DataFrame({'a': ['foo', 'bar', 'baz'], @@ -2550,7 +2551,7 @@ def test_no_dummy_key_names(self): result = self.df.groupby([self.df['A'].values, self.df['B'].values]).sum() - self.assert_(result.index.names == (None, None)) + self.assertEqual(result.index.names, (None, None)) def test_groupby_categorical(self): levels = ['foo', 'bar', 'baz', 'qux'] @@ -2567,7 +2568,7 @@ def test_groupby_categorical(self): expected.index.name = 'myfactor' assert_frame_equal(result, expected) - self.assert_(result.index.name == cats.name) + self.assertEqual(result.index.name, cats.name) grouped = data.groupby(cats) desc_result = grouped.describe()
Work on #6175 to specialize assert_'s. Tests still pass locally. A work-in-progress.
https://api.github.com/repos/pandas-dev/pandas/pulls/6261
2014-02-05T01:54:36Z
2014-02-05T12:16:52Z
2014-02-05T12:16:52Z
2014-06-19T04:52:19Z
BUG: bug in xs for a Series with a multiindex (GH6258)
diff --git a/doc/source/release.rst b/doc/source/release.rst index cf4037303dcfa..c6a901252903f 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -74,6 +74,7 @@ Bug Fixes - Bug in version string gen. for dev versions with shallow clones / install from tarball (:issue:`6127`) - Inconsistent tz parsing Timestamp/to_datetime for current year (:issue:`5958`) - Indexing bugs with reordered indexes (:issue:`6252`, :issue:`6254`) +- Bug in ``.xs`` with a Series multiindex (:issue:`6258`, :issue:`5684`) pandas 0.13.1 ------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e5b2be99f6362..2ee96d660eb87 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1262,21 +1262,17 @@ def xs(self, key, axis=0, level=None, copy=True, drop_level=True): if not copy and not isinstance(loc, slice): raise ValueError('Cannot retrieve view (copy=False)') - # level = 0 - loc_is_slice = isinstance(loc, slice) - if not loc_is_slice: - indexer = [slice(None)] * self.ndim - indexer[axis] = loc - indexer = tuple(indexer) - else: - indexer = loc + # convert to a label indexer if needed + if isinstance(loc, slice): lev_num = labels._get_level_number(level) if labels.levels[lev_num].inferred_type == 'integer': - indexer = self.index[loc] + loc = labels[loc] + + # create the tuple of the indexer + indexer = [slice(None)] * self.ndim + indexer[axis] = loc + indexer = tuple(indexer) - # select on the correct axis - if axis == 1 and loc_is_slice: - indexer = slice(None), indexer result = self.ix[indexer] setattr(result, result._get_axis_name(axis), new_ax) return result diff --git a/pandas/core/index.py b/pandas/core/index.py index bf485e40da92b..3b58b27c7569f 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -3236,7 +3236,7 @@ def _get_level_indexer(self, key, level=0): labels = self.labels[level] if level > 0 or self.lexsort_depth == 0: - return labels == loc + return np.array(labels == loc,dtype=bool) else: # sorted, so can return slice object -> view i = labels.searchsorted(loc, side='left') diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 0f62b1576d316..14fce28849874 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -951,6 +951,24 @@ def test_series_getitem_multiindex(self): expected = Series([2,3],index=[1,2]) assert_series_equal(result,expected) + # GH6258 + s = Series([1,3,4,1,3,4], + index=MultiIndex.from_product([list('AB'), + list(date_range('20130903',periods=3))])) + result = s.xs('20130903',level=1) + expected = Series([1,1],index=list('AB')) + assert_series_equal(result,expected) + + # GH5684 + idx = MultiIndex.from_tuples([('a', 'one'), ('a', 'two'), + ('b', 'one'), ('b', 'two')]) + s = Series([1, 2, 3, 4], index=idx) + s.index.set_names(['L1', 'L2'], inplace=True) + result = s.xs('one', level='L2') + expected = Series([1, 3], index=['a', 'b']) + expected.index.set_names(['L1'], inplace=True) + assert_series_equal(result, expected) + def test_ix_general(self): # ix general issues
closes #6258 closes #5684
https://api.github.com/repos/pandas-dev/pandas/pulls/6259
2014-02-04T23:03:45Z
2014-02-05T02:08:12Z
2014-02-05T02:08:12Z
2014-06-16T02:27:27Z
BUG: Indexing bugs with reordered indexes (GH6252, GH6254)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 7707c945f7a54..cf4037303dcfa 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -73,6 +73,7 @@ Bug Fixes - Bug in version string gen. for dev versions with shallow clones / install from tarball (:issue:`6127`) - Inconsistent tz parsing Timestamp/to_datetime for current year (:issue:`5958`) +- Indexing bugs with reordered indexes (:issue:`6252`, :issue:`6254`) pandas 0.13.1 ------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 2c58dd34939e7..e88f1972b5f7d 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -633,7 +633,8 @@ def setitem(self, indexer, value): # if we are an exact match (ex-broadcasting), # then use the resultant dtype elif len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and np.prod(arr_value.shape) == np.prod(values.shape): - values = arr_value.reshape(values.shape) + values[indexer] = value + values = values.astype(arr_value.dtype) # set else: diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 435b0ca5d722f..4a641cad68885 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -646,6 +646,32 @@ def test_loc_setitem_frame(self): result = df.ix[:,1:] assert_frame_equal(result, expected) + # GH 6254 + # setting issue + df = DataFrame(index=[3, 5, 4], columns=['A']) + df.loc[[4, 3, 5], 'A'] = [1, 2, 3] + expected = DataFrame(dict(A = Series([1,2,3],index=[4, 3, 5]))).reindex(index=[3,5,4]) + assert_frame_equal(df, expected) + + # GH 6252 + # setting with an empty frame + keys1 = ['@' + str(i) for i in range(5)] + val1 = np.arange(5) + + keys2 = ['@' + str(i) for i in range(4)] + val2 = np.arange(4) + + index = list(set(keys1).union(keys2)) + df = DataFrame(index = index) + df['A'] = nan + df.loc[keys1, 'A'] = val1 + + df['B'] = nan + df.loc[keys2, 'B'] = val2 + + expected = DataFrame(dict(A = Series(val1,index=keys1), B = Series(val2,index=keys2))).reindex(index=index) + assert_frame_equal(df, expected) + def test_loc_setitem_frame_multiples(self): # multiple setting
closes #6252 closes #6254 ``` In [1]: df = DataFrame(index=[3, 5, 4], columns=['A']) In [2]: df.loc[[4, 3, 5], 'A'] = [1, 2, 3] In [3]: df Out[3]: A 3 2 5 3 4 1 [3 rows x 1 columns] ``` ``` In [4]: keys1 = ['@' + str(i) for i in range(5)] In [5]: val1 = np.arange(5) In [6]: keys2 = ['@' + str(i) for i in range(4)] In [7]: val2 = np.arange(4) In [8]: index = list(set(keys1).union(keys2)) In [9]: df = DataFrame(index = index) In [10]: df['A'] = nan In [11]: df.loc[keys1, 'A'] = val1 In [12]: df['B'] = nan In [13]: df.loc[keys2, 'B'] = val2 In [14]: df Out[14]: A B @2 2 2 @3 3 3 @0 0 0 @1 1 1 @4 4 NaN [5 rows x 2 columns] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6256
2014-02-04T19:36:49Z
2014-02-04T19:54:21Z
2014-02-04T19:54:21Z
2014-07-16T08:51:48Z
Update indexing.rst
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 6e6bb1aa012ee..0c4b57358d3d1 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -23,7 +23,7 @@ Indexing and Selecting Data The axis labeling information in pandas objects serves many purposes: - Identifies data (i.e. provides *metadata*) using known indicators, - important for for analysis, visualization, and interactive console display + important for analysis, visualization, and interactive console display - Enables automatic and explicit data alignment - Allows intuitive getting and setting of subsets of the data set
Just removing a typo: 'for' was written twice.
https://api.github.com/repos/pandas-dev/pandas/pulls/6255
2014-02-04T18:29:18Z
2014-02-04T18:47:26Z
2014-02-04T18:47:26Z
2014-06-24T22:55:00Z
fix ipython directive, py3 and recent ipython changes
diff --git a/doc/source/conf.py b/doc/source/conf.py index 642a4438f4a3b..ee007e3489e3a 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -13,7 +13,7 @@ import sys import os import re -from pandas.compat import u +from pandas.compat import u, PY3 # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -78,7 +78,10 @@ if ds: print("I'm about to DELETE the following:\n%s\n" % list(sorted(ds))) sys.stdout.write("WARNING: I'd like to delete those to speed up processing (yes/no)? ") - answer = raw_input() + if PY3: + answer = input() + else: + answer = raw_input() if answer.lower().strip() in ('y','yes'): for f in ds: diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py index ff2379eb7b9eb..3f9be95609874 100644 --- a/doc/sphinxext/ipython_directive.py +++ b/doc/sphinxext/ipython_directive.py @@ -344,7 +344,11 @@ def process_input_line(self, line, store_history=True): splitter.push(line) more = splitter.push_accepts_more() if not more: - source_raw = splitter.source_raw_reset()[1] + try: + source_raw = splitter.source_raw_reset()[1] + except: + # recent ipython #4504 + source_raw = splitter.raw_reset() self.IP.run_cell(source_raw, store_history=store_history) finally: sys.stdout = stdout
Made py3 fixes to conf.py. Docs now compile on PY3 (good job @phaebz, @kermit666 and joris). Also worked around recent breaking change to ipython https://github.com/ipython/ipython/pull/4504, which somewhat deflates my theory that by having our own copy we can avoid having other packages changes break our build (they can, if they change the packages it depends on).
https://api.github.com/repos/pandas-dev/pandas/pulls/6250
2014-02-04T11:35:35Z
2014-02-04T11:35:39Z
2014-02-04T11:35:39Z
2014-06-13T02:06:51Z
ENH: add support for Python 3.4 ast.NameConstant
diff --git a/pandas/computation/expr.py b/pandas/computation/expr.py index 7ebffef7368a0..ed4195b691815 100644 --- a/pandas/computation/expr.py +++ b/pandas/computation/expr.py @@ -548,6 +548,9 @@ def visit_UnaryOp(self, node, **kwargs): def visit_Name(self, node, **kwargs): return self.term_type(node.id, self.env, **kwargs) + def visit_NameConstant(self, node, **kwargs): + return self.const_type(node.value, self.env) + def visit_Num(self, node, **kwargs): return self.const_type(node.n, self.env)
Python 3.4 created a "NameConstant AST class to represent None, True, and False literals" (http://docs.python.org/3.4/whatsnew/changelog.html). Pandas-0.13.1.win-amd64-py3.4 fails a few tests with `AttributeError: '...ExprVisitor' object has no attribute 'visit_NameConstant'`. The suggested change fixes those test errors but I am not sure that it is the best/correct fix. ``` ====================================================================== ERROR: test_scalar_unary (pandas.computation.tests.test_eval.TestEvalNumexprPandas) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 678, in test_scalar_unary pd.eval('~True', parser=self.parser, engine=self.engine), ~True) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 545, in visit_UnaryOp operand = self.visit(node.operand) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_scalar_unary (pandas.computation.tests.test_eval.TestEvalNumexprPython) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 678, in test_scalar_unary pd.eval('~True', parser=self.parser, engine=self.engine), ~True) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 545, in visit_UnaryOp operand = self.visit(node.operand) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PythonExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_scalar_unary (pandas.computation.tests.test_eval.TestEvalPythonPandas) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 678, in test_scalar_unary pd.eval('~True', parser=self.parser, engine=self.engine), ~True) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 545, in visit_UnaryOp operand = self.visit(node.operand) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_scalar_unary (pandas.computation.tests.test_eval.TestEvalPythonPython) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 678, in test_scalar_unary pd.eval('~True', parser=self.parser, engine=self.engine), ~True) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 545, in visit_UnaryOp operand = self.visit(node.operand) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PythonExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_bool_ops_with_constants (pandas.computation.tests.test_eval.TestOperationsNumExprPandas) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1086, in test_bool_ops_with_constants res = self.eval(ex) File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1046, in eval return pd.eval(*args, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 716, in visit_BoolOp return reduce(visitor, operands) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 708, in visitor lhs = self._try_visit_binop(x) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 704, in _try_visit_binop return self.visit(bop) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_simple_bool_ops (pandas.computation.tests.test_eval.TestOperationsNumExprPandas) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1078, in test_simple_bool_ops res = self.eval(ex) File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1046, in eval return pd.eval(*args, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 716, in visit_BoolOp return reduce(visitor, operands) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 708, in visitor lhs = self._try_visit_binop(x) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 704, in _try_visit_binop return self.visit(bop) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_bool_ops_with_constants (pandas.computation.tests.test_eval.TestOperationsNumExprPython) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1389, in test_bool_ops_with_constants res = self.eval(ex) File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1046, in eval return pd.eval(*args, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 536, in visit_BinOp op, op_class, left, right = self._possibly_transform_eq_ne(node) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 492, in _possibly_transform_eq_ne left = self.visit(node.left, side='left') File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PythonExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_bool_ops_with_constants (pandas.computation.tests.test_eval.TestOperationsPythonPandas) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1086, in test_bool_ops_with_constants res = self.eval(ex) File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1046, in eval return pd.eval(*args, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 716, in visit_BoolOp return reduce(visitor, operands) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 708, in visitor lhs = self._try_visit_binop(x) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 704, in _try_visit_binop return self.visit(bop) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_simple_bool_ops (pandas.computation.tests.test_eval.TestOperationsPythonPandas) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1078, in test_simple_bool_ops res = self.eval(ex) File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1046, in eval return pd.eval(*args, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 716, in visit_BoolOp return reduce(visitor, operands) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 708, in visitor lhs = self._try_visit_binop(x) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 704, in _try_visit_binop return self.visit(bop) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_bool_ops_with_constants (pandas.computation.tests.test_eval.TestOperationsPythonPython) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1389, in test_bool_ops_with_constants res = self.eval(ex) File "X:\Python34\lib\site-packages\pandas\computation\tests\test_eval.py", line 1046, in eval return pd.eval(*args, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\eval.py", line 207, in eval truediv=truediv) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 762, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 536, in visit_BinOp op, op_class, left, right = self._possibly_transform_eq_ne(node) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 492, in _possibly_transform_eq_ne left = self.visit(node.left, side='left') File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'PythonExprVisitor' object has no attribute 'visit_NameConstant' ====================================================================== ERROR: test_select_dtypes (pandas.io.tests.test_pytables.TestHDFStore) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\pandas\io\tests\test_pytables.py", line 2939, in test_select_dtypes result = store.select('df', Term('boolv == %s' % str(v)), columns = ['A','boolv']) File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 664, in select auto_close=auto_close).get_values() File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 1338, in get_values results = self.func(self.start, self.stop) File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 653, in func columns=columns, **kwargs) File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 3788, in read if not self.read_axes(where=where, **kwargs): File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 3047, in read_axes self.selection = Selection(self, where=where, **kwargs) File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 4263, in __init__ self.terms = self.generate(where) File "X:\Python34\lib\site-packages\pandas\io\pytables.py", line 4276, in generate return Expr(where, queryables=q, encoding=self.table.encoding) File "X:\Python34\lib\site-packages\pandas\computation\pytables.py", line 518, in __init__ self.terms = self.parse() File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 781, in parse return self._visitor.visit(self.expr) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 455, in visit_Module return self.visit(expr, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 458, in visit_Expr return self.visit(node.value, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 689, in visit_Compare return self.visit(binop) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 449, in visit return visitor(node, **kwargs) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 536, in visit_BinOp op, op_class, left, right = self._possibly_transform_eq_ne(node) File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 494, in _possibly_transform_eq_ne right = self.visit(node.right, side='right') File "X:\Python34\lib\site-packages\pandas\computation\expr.py", line 448, in visit visitor = getattr(self, method) AttributeError: 'ExprVisitor' object has no attribute 'visit_NameConstant' ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6243
2014-02-03T21:08:43Z
2014-02-04T14:31:19Z
2014-02-04T14:31:19Z
2014-06-14T10:19:39Z
BUG: Fix ImportError on Python 3.4b2 and 3.4b3
diff --git a/pandas/src/ujson/python/ujson.c b/pandas/src/ujson/python/ujson.c index 33b01b341c20a..2eb8a80c0325c 100644 --- a/pandas/src/ujson/python/ujson.c +++ b/pandas/src/ujson/python/ujson.c @@ -78,7 +78,7 @@ static struct PyModuleDef moduledef = { NULL /* m_free */ }; -#define PYMODINITFUNC PyObject *PyInit_json(void) +#define PYMODINITFUNC PyMODINIT_FUNC PyInit_json(void) #define PYMODULE_CREATE() PyModule_Create(&moduledef) #define MODINITERROR return NULL
See http://bugs.python.org/issue20166 ``` ERROR: Failure: ImportError (dynamic module does not define init function (PyInit_json)) ---------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python34\lib\site-packages\nose\failure.py", line 39, in runTest raise self.exc_val.with_traceback(self.tb) File "X:\Python34\lib\site-packages\nose\loader.py", line 402, in loadTestsFromName module = resolve_name(addr.module) File "X:\Python34\lib\site-packages\nose\util.py", line 311, in resolve_name module = __import__('.'.join(parts_copy)) File "X:\Python34\lib\site-packages\pandas\__init__.py", line 44, in <module> from pandas.io.api import * File "X:\Python34\lib\site-packages\pandas\io\api.py", line 7, in <module> from pandas.io.excel import ExcelFile, ExcelWriter, read_excel File "X:\Python34\lib\site-packages\pandas\io\excel.py", line 14, in <module> from pandas import json ImportError: dynamic module does not define init function (PyInit_json) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6241
2014-02-03T18:19:59Z
2014-02-03T20:30:58Z
2014-02-03T20:30:58Z
2014-06-24T20:53:44Z
BLD: various test_perf fixes
diff --git a/vb_suite/test_perf.py b/vb_suite/test_perf.py index bb3a0d123f9b1..66e50269f00c6 100755 --- a/vb_suite/test_perf.py +++ b/vb_suite/test_perf.py @@ -70,7 +70,7 @@ class RevParseAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): import subprocess - cmd = 'git rev-parse --short {0}'.format(values) + cmd = 'git rev-parse --short -verify {0}^{{commit}}'.format(values) rev_parse = subprocess.check_output(cmd, shell=True) setattr(namespace, self.dest, rev_parse.strip()) @@ -157,6 +157,11 @@ def __call__(self, parser, namespace, values, option_string=None): action='store_true', help='when specified with -N, prints the output of describe() per vbench results. ' ) +parser.add_argument('--temp-dir', + metavar="PATH", + default=None, + help='Specify temp work dir to use. ccache depends on builds being invoked from consistent directory.' ) + parser.add_argument('-q', '--quiet', default=False, action='store_true', @@ -192,7 +197,8 @@ def profile_comparative(benchmarks): from vbench.db import BenchmarkDB from vbench.git import GitRepo from suite import BUILD, DB_PATH, PREPARE, dependencies - TMP_DIR = tempfile.mkdtemp() + + TMP_DIR = args.temp_dir or tempfile.mkdtemp() try: @@ -434,6 +440,10 @@ def print_report(df,h_head=None,h_msg="",h_baseline=None,b_msg=""): stats_footer = "\n" if args.stats : + try: + pd.options.display.expand_frame_repr=False + except: + pass stats_footer += str(df.T.describe().T) + "\n\n" s+= stats_footer
- The git ref parsing didn't handle annotated tags well, returning a bad hash if you tried `test_perf -t HEAD -b v0.13.0` and got a weird error, fixed. (git weirdness, fyi @cpcloud) - try to Disable frame_expand_repr when printing stats, pasting results for comparison is much easier that way. - Added --temp-dir to name a specific (rather then randomized) scratch directory for vbench, the randomized temp. dir was preventing ccache from doing it's job. Highly recommended that you always invoke test_perf with a consistent `--temp-dir my-benching-dir`. This took down the comparative runs from 5 minutes to less then 60 seconds on my box. cc @jreback, @yarikoptic. xref https://github.com/pydata/pandas/issues/6199
https://api.github.com/repos/pandas-dev/pandas/pulls/6235
2014-02-03T04:39:18Z
2014-02-03T04:39:46Z
2014-02-03T04:39:46Z
2014-06-26T19:23:40Z
BLD: Build and publish docs (sans API) as part of Travis jobs
diff --git a/.travis.yml b/.travis.yml index f5785f5039c4d..cfec13f5cf7de 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,6 +8,8 @@ env: - secure: "TWGKPL4FGtWjCQ427QrSffaQBSCPy1QzPdhtYKAW9AlDo/agdp9RyZRQr8WTlyZ5AOG18X8MDdi0EcpFnyfDNd4thCLyZOntxwltlVV2yNNvnird3XRKUV1F2DD42L64wna04M2KYxpCKhEQ84gEnCH1DGD4g1NnR6fYuEYNSTU=" - secure: "NvgIWe14pv4SJ5BQhw6J0zIpCTFH4fVpzr9pRzM2tD8yf/3cspX3uyXTt4owiqtjoQ3aQGNnhWtVlmSwlgJrwu7KUaE9IPtlsENYDniAj2oJgejjx02d367pHtMB/9e3+4b2fWUsFNJgWw0ordiIT0p1lzHRdQ9ut4l/Yn/lkJs=" - secure: "D3ASNRu32pV79lv/Nl0dBm2ldZiTgbb6boOrN0SzIKsQU3yBwedpqX6EI6KjpVg17lGhhhFXGzL2Gz1qjU3/+m6aMvekxHgpfuc0AlEFCEqenWPxIdDDrUkdfJoCvfQQPd5oxChfHgqaEDLjuqHy1ZEgnJ2/L/6dwZ4fUt62hMk=" + # pandas-docs-bot GH + - secure: "PCzUFR8CHmw9lH84p4ygnojdF7Z8U5h7YfY0RyT+5K/aiQ1ZTU3ZkDTPI0/rR5FVMxsEEKEQKMcc5fvqW0PeD7Q2wRmluloKgT9w4EVEJ1ppKf7lITPcvZR2QgVOvjv4AfDtibLHFNiaSjzoqyJVjM4igjOu8WTlF3JfZcmOQjQ=" matrix: include: @@ -30,6 +32,7 @@ matrix: - FULL_DEPS=true - CLIPBOARD_GUI=gtk2 - JOB_NAME: "27_nslow" # ScatterCI Build name, 20 chars max + - DOC_BUILD=true # if rst files were changed, build docs in parallel with tests - python: 3.2 env: - NOSE_ARGS="not slow" @@ -75,6 +78,7 @@ before_script: script: - echo "script" - ci/script.sh + - if [ -f /tmp/doc.log ]; then cat /tmp/doc.log; fi after_script: - ci/print_versions.py diff --git a/ci/build_docs.sh b/ci/build_docs.sh new file mode 100755 index 0000000000000..583b36857c70c --- /dev/null +++ b/ci/build_docs.sh @@ -0,0 +1,49 @@ +#!/bin/bash + + +cd "$TRAVIS_BUILD_DIR" + +git show --pretty="format:" --name-only HEAD~5.. --first-parent | grep -P "rst|txt|doc" + +if [ "$?" != "0" ]; then + echo "Skipping doc build, none were modified" + # nope, skip docs build + exit 0 +fi + + +if [ x"$DOC_BUILD" != x"" ]; then + # we're running network tests, let's build the docs in the meantim + echo "Will build docs" + pip install sphinx==1.1.3 ipython==1.1.0 + + mv "$TRAVIS_BUILD_DIR"/doc /tmp + cd /tmp/doc + + rm /tmp/doc/source/api.rst # no R + rm /tmp/doc/source/r_interface.rst # no R + + echo ############################### > /tmp/doc.log + echo # Log file for the doc build # > /tmp/doc.log + echo ############################### > /tmp/doc.log + echo "" > /tmp/doc.log + echo -e "y\n" | ./make.py --no-api 2>&1 + + cd /tmp/doc/build/html + git config --global user.email "pandas-docs-bot@localhost.foo" + git config --global user.name "pandas-docs-bot" + + git init + touch README + git add README + git commit -m "Initial commit" --allow-empty + git branch gh-pages + git checkout gh-pages + touch .nojekyll + git add --all . + git commit -m "Version" --allow-empty + git remote add origin https://$GH_TOKEN@github.com/pandas-docs/pandas-docs-travis + git push origin gh-pages -f +fi + +exit 0 diff --git a/ci/install.sh b/ci/install.sh index 53994f2659952..77755a26393c0 100755 --- a/ci/install.sh +++ b/ci/install.sh @@ -98,5 +98,6 @@ export PATH=/usr/lib/ccache:/usr/lib64/ccache:$PATH which gcc ccache -z time pip install $(find dist | grep gz | head -n 1) - +# restore cython +time pip install $PIP_ARGS $(cat ci/requirements-${wheel_box}.txt | grep -i cython) true diff --git a/ci/ironcache/get.py b/ci/ironcache/get.py index 45ce4165cea76..a4663472b955c 100644 --- a/ci/ironcache/get.py +++ b/ci/ironcache/get.py @@ -9,13 +9,16 @@ import base64 from hashlib import sha1 from iron_cache import * +import traceback as tb key='KEY.%s.%s' %(os.environ.get('TRAVIS_REPO_SLUG','unk'), os.environ.get('JOB_NAME','unk')) +print(key) + if sys.version_info[0] > 2: - key = sha1(bytes(key,encoding='utf8')).hexdigest()[:8]+'.' -else: - key = sha1(key).hexdigest()[:8]+'.' + key = bytes(key,encoding='utf8') + +key = sha1(key).hexdigest()[:8]+'.' b = b'' cache = IronCache() @@ -23,8 +26,15 @@ print("getting %s" % key+str(i)) try: item = cache.get(cache="travis", key=key+str(i)) - b += bytes(base64.b64decode(item.value)) - except: + v = item.value + if sys.version_info[0] > 2: + v = bytes(v,encoding='utf8') + b += bytes(base64.b64decode(v)) + except Exception as e: + try: + print(tb.format_exc(e)) + except: + print("exception during exception, oh my") break with open(os.path.join(os.environ.get('HOME',''),"ccache.7z"),'wb') as f: diff --git a/ci/ironcache/put.py b/ci/ironcache/put.py index 0faf173483f23..f6aef3a327e87 100644 --- a/ci/ironcache/put.py +++ b/ci/ironcache/put.py @@ -12,10 +12,15 @@ key='KEY.%s.%s' %(os.environ.get('TRAVIS_REPO_SLUG','unk'), os.environ.get('JOB_NAME','unk')) + +key='KEY.%s.%s' %(os.environ.get('TRAVIS_REPO_SLUG','unk'), + os.environ.get('JOB_NAME','unk')) +print(key) + if sys.version_info[0] > 2: - key = sha1(bytes(key,encoding='utf8')).hexdigest()[:8]+'.' -else: - key = sha1(key).hexdigest()[:8]+'.' + key = bytes(key,encoding='utf8') + +key = sha1(key).hexdigest()[:8]+'.' os.chdir(os.environ.get('HOME')) diff --git a/ci/script.sh b/ci/script.sh index 6980e06fd0217..7632196d783fb 100755 --- a/ci/script.sh +++ b/ci/script.sh @@ -12,5 +12,13 @@ if [ -n "$LOCALE_OVERRIDE" ]; then cd "$curdir" fi +# conditionally build and upload docs to GH/pandas-docs/pandas-docs/travis +"$TRAVIS_BUILD_DIR"/ci/build_docs.sh 2>&1 > /tmp/doc.log & +# doc build log will be shown after tests + echo nosetests -v --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml nosetests -v --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml + + +# wait until subprocesses finish (build_docs.sh) +wait
(also fixed caching on py3) Now that travis is down to 5 minutes https://github.com/pydata/pandas/pull/6227, and doc builds have been accelerated as well #6179, it's possible to include a doc build as part of our CI process without incurring long build times. This PR runs the build process in the background so that we parallelize with the I/O heavy parts of the test suite, the final result is a build that's still much faster then where we were last week. If no docs were modified by the commit, the doc build is skipped. Compiled Docs (without API reference or R section) are pushed immediately to http://pandas-docs.github.io/pandas-docs-travis/ and can be seen there a few minutes after the CI job is finished following a commit to master. The version string on the docs is broken,pending #6217. Here's to shorter cycles :dancers: .
https://api.github.com/repos/pandas-dev/pandas/pulls/6233
2014-02-02T18:06:49Z
2014-02-02T18:07:02Z
2014-02-02T18:07:02Z
2014-06-26T00:39:57Z
TST: add tests for algos.factorize (GH6212)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index b5be5b1a7c552..44cd2d8906a5b 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -129,6 +129,10 @@ def factorize(values, sort=False, order=None, na_sentinel=-1): Returns ------- + labels : the indexer to the original array + uniques : the unique values + + note: an array of Periods will ignore sort as it returns an always sorted PeriodIndex """ from pandas.tseries.period import PeriodIndex vals = np.asarray(values) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 027e7c5fab191..4529b5e97adf2 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -44,6 +44,78 @@ def test_strings(self): expected = Series(np.array([1, 0, np.nan, 0, 1, 2, np.nan])) tm.assert_series_equal(result,expected) +class TestFactorize(tm.TestCase): + _multiprocess_can_split_ = True + + def test_basic(self): + + labels, uniques = algos.factorize(['a', 'b', 'b', 'a', + 'a', 'c', 'c', 'c']) + self.assert_(np.array_equal(labels, np.array([ 0, 1, 1, 0, 0, 2, 2, 2],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array(['a','b','c'], dtype=object))) + + labels, uniques = algos.factorize(['a', 'b', 'b', 'a', + 'a', 'c', 'c', 'c'], sort=True) + self.assert_(np.array_equal(labels, np.array([ 0, 1, 1, 0, 0, 2, 2, 2],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array(['a','b','c'], dtype=object))) + + labels, uniques = algos.factorize(list(reversed(range(5)))) + self.assert_(np.array_equal(labels, np.array([0, 1, 2, 3, 4], dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([ 4, 3, 2, 1, 0],dtype=np.int64))) + + labels, uniques = algos.factorize(list(reversed(range(5))), sort=True) + self.assert_(np.array_equal(labels, np.array([ 4, 3, 2, 1, 0],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([0, 1, 2, 3, 4], dtype=np.int64))) + + labels, uniques = algos.factorize(list(reversed(np.arange(5.)))) + self.assert_(np.array_equal(labels, np.array([0., 1., 2., 3., 4.], dtype=np.float64))) + self.assert_(np.array_equal(uniques, np.array([ 4, 3, 2, 1, 0],dtype=np.int64))) + + labels, uniques = algos.factorize(list(reversed(np.arange(5.))), sort=True) + self.assert_(np.array_equal(labels, np.array([ 4, 3, 2, 1, 0],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([0., 1., 2., 3., 4.], dtype=np.float64))) + + def test_mixed(self): + + # doc example reshaping.rst + x = Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) + labels, uniques = algos.factorize(x) + + self.assert_(np.array_equal(labels, np.array([ 0, 0, -1, 1, 2, 3],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array(['A', 'B', 3.14, np.inf], dtype=object))) + + labels, uniques = algos.factorize(x, sort=True) + self.assert_(np.array_equal(labels, np.array([ 2, 2, -1, 3, 0, 1],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([3.14, np.inf, 'A', 'B'], dtype=object))) + + def test_datelike(self): + + # M8 + v1 = pd.Timestamp('20130101 09:00:00.00004') + v2 = pd.Timestamp('20130101') + x = Series([v1,v1,v1,v2,v2,v1]) + labels, uniques = algos.factorize(x) + self.assert_(np.array_equal(labels, np.array([ 0,0,0,1,1,0],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([v1.value,v2.value],dtype='M8[ns]'))) + + labels, uniques = algos.factorize(x, sort=True) + self.assert_(np.array_equal(labels, np.array([ 1,1,1,0,0,1],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([v2.value,v1.value],dtype='M8[ns]'))) + + # period + v1 = pd.Period('201302',freq='M') + v2 = pd.Period('201303',freq='M') + x = Series([v1,v1,v1,v2,v2,v1]) + + # periods are not 'sorted' as they are converted back into an index + labels, uniques = algos.factorize(x) + self.assert_(np.array_equal(labels, np.array([ 0,0,0,1,1,0],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([v1, v2],dtype=object))) + + labels, uniques = algos.factorize(x,sort=True) + self.assert_(np.array_equal(labels, np.array([ 0,0,0,1,1,0],dtype=np.int64))) + self.assert_(np.array_equal(uniques, np.array([v1, v2],dtype=object))) + class TestUnique(tm.TestCase): _multiprocess_can_split_ = True
tests for issues in #6212 / #6231
https://api.github.com/repos/pandas-dev/pandas/pulls/6231
2014-02-02T15:28:47Z
2014-02-02T15:39:34Z
2014-02-02T15:39:34Z
2014-06-15T15:59:41Z
DOC/PY3: Python 3 docs example compat for range, StringIO and datetime
diff --git a/doc/source/comparison_with_r.rst b/doc/source/comparison_with_r.rst index a5b8fabac11ac..253eafb36653f 100644 --- a/doc/source/comparison_with_r.rst +++ b/doc/source/comparison_with_r.rst @@ -99,7 +99,7 @@ this: .. ipython:: python s = pd.Series(np.arange(5),dtype=np.float32) - Series(pd.match(s,[2,4],np.nan)) + pd.Series(pd.match(s,[2,4],np.nan)) For more details and examples see :ref:`the reshaping documentation <indexing.basics.indexing_isin>`. @@ -279,7 +279,7 @@ In Python, since ``a`` is a list, you can simply use list comprehension. .. ipython:: python - a = np.array(range(1,24)+[np.NAN]).reshape(2,3,4) + a = np.array(list(range(1,24))+[np.NAN]).reshape(2,3,4) DataFrame([tuple(list(x)+[val]) for x, val in np.ndenumerate(a)]) |meltlist|_ @@ -298,7 +298,7 @@ In Python, this list would be a list of tuples, so .. ipython:: python - a = list(enumerate(range(1,5)+[np.NAN])) + a = list(enumerate(list(range(1,5))+[np.NAN])) DataFrame(a) For more details and examples see :ref:`the Into to Data Structures diff --git a/doc/source/enhancingperf.rst b/doc/source/enhancingperf.rst index 066fcce64c5ac..34166343817a4 100644 --- a/doc/source/enhancingperf.rst +++ b/doc/source/enhancingperf.rst @@ -384,7 +384,7 @@ First let's create 4 decent-sized arrays to play with: from numpy.random import randn import numpy as np nrows, ncols = 20000, 100 - df1, df2, df3, df4 = [DataFrame(randn(nrows, ncols)) for _ in xrange(4)] + df1, df2, df3, df4 = [DataFrame(randn(nrows, ncols)) for _ in range(4)] Now let's compare adding them together using plain ol' Python versus diff --git a/doc/source/io.rst b/doc/source/io.rst index 5f114ec3d3c08..34af31747ca4a 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -7,7 +7,7 @@ import os import csv - from StringIO import StringIO + from pandas.compat import StringIO, BytesIO import pandas as pd ExcelWriter = pd.ExcelWriter @@ -58,6 +58,11 @@ The corresponding ``writer`` functions are object methods that are accessed like * :ref:`to_clipboard<io.clipboard>` * :ref:`to_pickle<io.pickle>` +.. note:: + For examples that use the ``StringIO`` class, make sure you import it + according to your Python version, i.e. ``from StringIO import StringIO`` for + Python 2 and ``from io import StringIO`` for Python 3. + .. _io.read_csv_table: CSV & Text files @@ -278,7 +283,6 @@ used as the column names: .. ipython:: python - from StringIO import StringIO data = 'a,b,c\n1,2,3\n4,5,6\n7,8,9' print(data) pd.read_csv(StringIO(data)) @@ -327,7 +331,7 @@ result in byte strings being decoded to unicode in the result: .. ipython:: python data = b'word,length\nTr\xc3\xa4umen,7\nGr\xc3\xbc\xc3\x9fe,5'.decode('utf8').encode('latin-1') - df = pd.read_csv(StringIO(data), encoding='latin-1') + df = pd.read_csv(BytesIO(data), encoding='latin-1') df df['word'][1] @@ -1561,8 +1565,6 @@ You can even pass in an instance of ``StringIO`` if you so desire .. ipython:: python - from cStringIO import StringIO - with open(file_path, 'r') as f: sio = StringIO(f.read()) @@ -2627,7 +2629,7 @@ chunks. store.append('dfeq', dfeq, data_columns=['number']) def chunks(l, n): - return [l[i:i+n] for i in xrange(0, len(l), n)] + return [l[i:i+n] for i in range(0, len(l), n)] evens = [2,4,6,8,10] coordinates = store.select_as_coordinates('dfeq','number=evens') diff --git a/doc/source/remote_data.rst b/doc/source/remote_data.rst index 535674721a575..16edf64802908 100644 --- a/doc/source/remote_data.rst +++ b/doc/source/remote_data.rst @@ -7,7 +7,6 @@ import os import csv - from StringIO import StringIO import pandas as pd import numpy as np @@ -49,7 +48,7 @@ Yahoo! Finance import pandas.io.data as web import datetime start = datetime.datetime(2010, 1, 1) - end = datetime.datetime(2013, 01, 27) + end = datetime.datetime(2013, 1, 27) f=web.DataReader("F", 'yahoo', start, end) f.ix['2010-01-04'] @@ -63,7 +62,7 @@ Google Finance import pandas.io.data as web import datetime start = datetime.datetime(2010, 1, 1) - end = datetime.datetime(2013, 01, 27) + end = datetime.datetime(2013, 1, 27) f=web.DataReader("F", 'google', start, end) f.ix['2010-01-04'] @@ -77,7 +76,7 @@ FRED import pandas.io.data as web import datetime start = datetime.datetime(2010, 1, 1) - end = datetime.datetime(2013, 01, 27) + end = datetime.datetime(2013, 1, 27) gdp=web.DataReader("GDP", "fred", start, end) gdp.ix['2013-01-01'] diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst index ce8f0013e9268..8f0686dedb9d6 100644 --- a/doc/source/reshaping.rst +++ b/doc/source/reshaping.rst @@ -436,6 +436,11 @@ To encode 1-d values as an enumerated type use ``factorize``: Note that ``factorize`` is similar to ``numpy.unique``, but differs in its handling of NaN: +.. note:: + The following ``numpy.unique`` will fail under Python 3 with a ``TypeError`` + because of an ordering bug. See also + `Here <https://github.com/numpy/numpy/issues/641>`__ + .. ipython:: python pd.factorize(x, sort=True) diff --git a/doc/source/v0.10.0.txt b/doc/source/v0.10.0.txt index 2e59c420fbd01..93ab3b912030d 100644 --- a/doc/source/v0.10.0.txt +++ b/doc/source/v0.10.0.txt @@ -3,7 +3,7 @@ .. ipython:: python :suppress: - from StringIO import StringIO + from pandas.compat import StringIO v0.10.0 (December 17, 2012) --------------------------- diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 4f06b6ea8369e..ac0a14f45b69e 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -698,7 +698,7 @@ Experimental nrows, ncols = 20000, 100 df1, df2, df3, df4 = [DataFrame(randn(nrows, ncols)) - for _ in xrange(4)] + for _ in range(4)] .. ipython:: python diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt index 9b39be08d0984..b48f555f9691a 100644 --- a/doc/source/v0.13.1.txt +++ b/doc/source/v0.13.1.txt @@ -141,7 +141,7 @@ API changes .. ipython:: python def applied_func(col): - print "Apply function being called with:", col + print("Apply function being called with: ", col) return col.sum() empty = DataFrame(columns=['a', 'b']) diff --git a/doc/source/v0.9.0.txt b/doc/source/v0.9.0.txt index b0c2c2455ab77..2b385a7e7b8f0 100644 --- a/doc/source/v0.9.0.txt +++ b/doc/source/v0.9.0.txt @@ -1,5 +1,10 @@ .. _whatsnew_0900: +.. ipython:: python + :suppress: + + from pandas.compat import StringIO + v0.9.0 (October 7, 2012) ------------------------ @@ -36,8 +41,6 @@ API changes .. ipython:: python - from StringIO import StringIO - data = '0,0,1\n1,1,0\n0,1,0' df = read_csv(StringIO(data), header=None) df diff --git a/doc/source/v0.9.1.txt b/doc/source/v0.9.1.txt index 7de000c255d4c..6718a049a0ab9 100644 --- a/doc/source/v0.9.1.txt +++ b/doc/source/v0.9.1.txt @@ -1,5 +1,10 @@ .. _whatsnew_0901: +.. ipython:: python + :suppress: + + from pandas.compat import StringIO + v0.9.1 (November 14, 2012) -------------------------- @@ -132,7 +137,6 @@ API changes data = 'A,B,C\n00001,001,5\n00002,002,6' - from cStringIO import StringIO read_csv(StringIO(data), converters={'A' : lambda x: x.strip()})
related is #6212 Fixes examples in documentation to be compatible with Python 3. Also tested it locally under Python 2. - Turned occurrences of `(x)range()` to `range()` for iteration and to `list(range())` for list concat. - Fixed leading zero argument(s) as in e.g. `datetime(2013, 01, 27)`. - Removed explicit `StringIO` and `cStringIO` imports in examples (uses suppressed pandas.compat imports) and added a note on py2/3 library reorganization. - Fixed `StringIO` for binary data to the more explicit `BytesIO`. - Fixed `NameError` for missing `pd.` in `pd.Series`. - Added note for failing `numpy.unique` example, see also #6229. I am not sure about the `BytesIO` though. Maybe good to put a note saying this is Python 3 way to do it and users on 2.x should use the old `StringIO` instead. In general, should we favor Python 3 doc versions in such cases and add notes for Python 2.x users? What do you think?
https://api.github.com/repos/pandas-dev/pandas/pulls/6230
2014-02-02T14:57:14Z
2014-02-04T09:23:23Z
2014-02-04T09:23:23Z
2014-06-15T16:36:13Z
BLD: fix travis speedup
diff --git a/.travis.yml b/.travis.yml index a635480d74196..f5785f5039c4d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -67,6 +67,7 @@ install: - echo "install" - ci/prep_ccache.sh - ci/install.sh + - ci/submit_ccache.sh before_script: - mysql -e 'create database pandas_nosetest;' @@ -79,4 +80,3 @@ after_script: - ci/print_versions.py - ci/print_skipped.py /tmp/nosetests.xml - ci/after_script.sh - - ci/submit_ccache.sh diff --git a/ci/install.sh b/ci/install.sh index 424284a5288ec..53994f2659952 100755 --- a/ci/install.sh +++ b/ci/install.sh @@ -94,11 +94,9 @@ fi time python setup.py sdist pip uninstall cython -y -cat pandas/version.py - export PATH=/usr/lib/ccache:/usr/lib64/ccache:$PATH which gcc -ccache -z # reset stats +ccache -z time pip install $(find dist | grep gz | head -n 1) true diff --git a/ci/ironcache/get.py b/ci/ironcache/get.py index bfbaa34b6757c..45ce4165cea76 100644 --- a/ci/ironcache/get.py +++ b/ci/ironcache/get.py @@ -7,10 +7,15 @@ import time import json import base64 - +from hashlib import sha1 from iron_cache import * -key='KEY'+os.environ.get('JOB_NAME','')+"." +key='KEY.%s.%s' %(os.environ.get('TRAVIS_REPO_SLUG','unk'), + os.environ.get('JOB_NAME','unk')) +if sys.version_info[0] > 2: + key = sha1(bytes(key,encoding='utf8')).hexdigest()[:8]+'.' +else: + key = sha1(key).hexdigest()[:8]+'.' b = b'' cache = IronCache() diff --git a/ci/ironcache/put.py b/ci/ironcache/put.py index 06d8896b289d5..0faf173483f23 100644 --- a/ci/ironcache/put.py +++ b/ci/ironcache/put.py @@ -7,10 +7,16 @@ import time import json import base64 - +from hashlib import sha1 from iron_cache import * -key='KEY'+os.environ.get('JOB_NAME','')+"." +key='KEY.%s.%s' %(os.environ.get('TRAVIS_REPO_SLUG','unk'), + os.environ.get('JOB_NAME','unk')) +if sys.version_info[0] > 2: + key = sha1(bytes(key,encoding='utf8')).hexdigest()[:8]+'.' +else: + key = sha1(key).hexdigest()[:8]+'.' + os.chdir(os.environ.get('HOME')) cache = IronCache() diff --git a/ci/prep_ccache.sh b/ci/prep_ccache.sh index ffff9d7ac0a37..843e94d4733c0 100755 --- a/ci/prep_ccache.sh +++ b/ci/prep_ccache.sh @@ -8,7 +8,6 @@ if [ "$IRON_TOKEN" ]; then python ci/ironcache/get.py ccache -C - ccache -M 120M if [ -f ~/ccache.7z ]; then echo "Cache retrieved"
![build_times](https://f.cloud.github.com/assets/1820866/2059980/e08f7ee8-8bee-11e3-89cf-cf519cd24773.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/6227
2014-02-02T09:46:44Z
2014-02-02T09:46:51Z
2014-02-02T09:46:51Z
2014-07-03T12:58:59Z
ENH: pd.read_clipboard detects tab-separated data (excel) GH6223
diff --git a/doc/source/release.rst b/doc/source/release.rst index 35c22fdf03d9a..fce4b6a5e47eb 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -56,12 +56,16 @@ New features API Changes ~~~~~~~~~~~ + Experimental Features ~~~~~~~~~~~~~~~~~~~~~ Improvements to existing features ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +- pd.read_clipboard will, if 'sep' is unspecified, try to detect data copied from a spreadsheet + and parse accordingly. (:issue:`6223`) + .. _release.bug_fixes-0.14.0: Bug Fixes diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt index 3ae33a909eca4..879e6466611cb 100644 --- a/doc/source/v0.14.0.txt +++ b/doc/source/v0.14.0.txt @@ -28,10 +28,13 @@ There are no deprecations of prior behavior in 0.14.0 Enhancements ~~~~~~~~~~~~ +- pd.read_clipboard will, if 'sep' is unspecified, try to detect data copied from a spreadsheet + and parse accordingly. (:issue:`6223`) + + Performance ~~~~~~~~~~~ - Experimental ~~~~~~~~~~~~ diff --git a/pandas/io/clipboard.py b/pandas/io/clipboard.py index e90d9ddef707a..52d950ef5b598 100644 --- a/pandas/io/clipboard.py +++ b/pandas/io/clipboard.py @@ -14,12 +14,29 @@ def read_clipboard(**kwargs): # pragma: no cover ------- parsed : DataFrame """ - if kwargs.get('sep') is None and kwargs.get('delim_whitespace') is None: - kwargs['sep'] = '\s+' from pandas.util.clipboard import clipboard_get from pandas.io.parsers import read_table text = clipboard_get() + # Excel copies into clipboard with \t seperation + # inspect no more then the 10 first lines, if they + # all contain an equal number (>0) of tabs, infer + # that this came from excel and set 'sep' accordingly + lines = text[:10000].split('\n')[:-1][:10] + + # Need to remove leading white space, since read_table + # accepts: + # a b + # 0 1 2 + # 1 3 4 + + counts = set([x.lstrip().count('\t') for x in lines]) + if len(lines)>1 and len(counts) == 1 and counts.pop() != 0: + kwargs['sep'] = '\t' + + if kwargs.get('sep') is None and kwargs.get('delim_whitespace') is None: + kwargs['sep'] = '\s+' + # try to decode (if needed on PY3) if compat.PY3: try: diff --git a/pandas/io/tests/test_clipboard.py b/pandas/io/tests/test_clipboard.py index 3556dfd999d40..482c81fc8e7c0 100644 --- a/pandas/io/tests/test_clipboard.py +++ b/pandas/io/tests/test_clipboard.py @@ -2,6 +2,7 @@ from numpy.random import randint import nose +import pandas as pd from pandas import DataFrame from pandas import read_clipboard @@ -65,3 +66,37 @@ def test_round_trip_frame_string(self): def test_round_trip_frame(self): for dt in self.data_types: self.check_round_trip_frame(dt) + + def test_read_clipboard_infer_excel(self): + from textwrap import dedent + from pandas.util.clipboard import clipboard_set + + text = dedent(""" + John James Charlie Mingus + 1 2 + 4 Harry Carney + """.strip()) + clipboard_set(text) + df = pd.read_clipboard() + + # excel data is parsed correctly + self.assertEqual(df.iloc[1][1], 'Harry Carney') + + # having diff tab counts doesn't trigger it + text = dedent(""" + a\t b + 1 2 + 3 4 + """.strip()) + clipboard_set(text) + res = pd.read_clipboard() + + text = dedent(""" + a b + 1 2 + 3 4 + """.strip()) + clipboard_set(text) + exp = pd.read_clipboard() + + tm.assert_frame_equal(res, exp)
#6223
https://api.github.com/repos/pandas-dev/pandas/pulls/6226
2014-02-02T07:05:23Z
2014-02-04T08:57:33Z
2014-02-04T08:57:33Z
2014-06-13T00:04:07Z
BUG/TST: groupby with mixed string/int grouper failing in python3 (GH6212)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 90fbb620ea5fd..5fde8ed577f94 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -180,6 +180,7 @@ Bug Fixes - Bug in ``nanops.var`` with ``ddof=1`` and 1 elements would sometimes return ``inf`` rather than ``nan`` on some platforms (:issue:`6136`) - Bug in Series and DataFrame bar plots ignoring the ``use_index`` keyword (:issue:`6209`) + - Bug in groupby with mixed str/int under python3 fixed; ``argsort`` was failing (:issue:`6212`) pandas 0.13.0 ------------- diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 729d4e4059595..d82846bd8cafd 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -10,6 +10,7 @@ import pandas.algos as algos import pandas.hashtable as htable import pandas.compat as compat +from pandas.compat import filter, string_types def match(to_match, values, na_sentinel=-1): """ @@ -32,7 +33,7 @@ def match(to_match, values, na_sentinel=-1): match : ndarray of integers """ values = com._asarray_tuplesafe(values) - if issubclass(values.dtype.type, compat.string_types): + if issubclass(values.dtype.type, string_types): values = np.array(values, dtype='O') f = lambda htype, caster: _match_generic(to_match, values, htype, caster) @@ -143,7 +144,20 @@ def factorize(values, sort=False, order=None, na_sentinel=-1): uniques = uniques.to_array() if sort and len(uniques) > 0: - sorter = uniques.argsort() + try: + sorter = uniques.argsort() + except: + # unorderable in py3 if mixed str/int + t = hash_klass(len(uniques)) + t.map_locations(com._ensure_object(uniques)) + + # order ints before strings + ordered = np.concatenate([ + np.sort(np.array([ e for i, e in enumerate(uniques) if f(e) ],dtype=object)) for f in [ lambda x: not isinstance(x,string_types), + lambda x: isinstance(x,string_types) ] + ]) + sorter = t.lookup(com._ensure_object(ordered)) + reverse_indexer = np.empty(len(sorter), dtype=np.int_) reverse_indexer.put(sorter, np.arange(len(sorter))) diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 3b53e8737d166..6a80c9f053c71 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -2106,6 +2106,28 @@ def test_apply_with_mixed_dtype(self): result2 = df.groupby("c2", as_index=False).mean().c2 assert_series_equal(result1,result2) + def test_groupby_aggregation_mixed_dtype(self): + + # GH 6212 + expected = DataFrame({ + 'v1': [5,5,7,np.nan,3,3,4,1], + 'v2': [55,55,77,np.nan,33,33,44,11]}, + index=MultiIndex.from_tuples([(1,95),(1,99),(2,95),(2,99),('big','damp'), + ('blue','dry'),('red','red'),('red','wet')], + names=['by1','by2'])) + + df = DataFrame({ + 'v1': [1,3,5,7,8,3,5,np.nan,4,5,7,9], + 'v2': [11,33,55,77,88,33,55,np.nan,44,55,77,99], + 'by1': ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12], + 'by2': ["wet", "dry", 99, 95, np.nan, "damp", 95, 99, "red", 99, np.nan, + np.nan] + }) + + g = df.groupby(['by1','by2']) + result = g[['v1','v2']].mean() + assert_frame_equal(result,expected) + def test_groupby_list_infer_array_like(self): result = self.df.groupby(list(self.df['A'])).mean() expected = self.df.groupby(self.df['A']).mean()
closes #6212
https://api.github.com/repos/pandas-dev/pandas/pulls/6222
2014-02-01T16:18:48Z
2014-02-01T18:12:17Z
2014-02-01T18:12:17Z
2014-06-26T12:23:43Z
TST: run clipboard tests explicitly
diff --git a/doc/source/release.rst b/doc/source/release.rst index 90fbb620ea5fd..d77ea1ebd414c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -180,6 +180,8 @@ Bug Fixes - Bug in ``nanops.var`` with ``ddof=1`` and 1 elements would sometimes return ``inf`` rather than ``nan`` on some platforms (:issue:`6136`) - Bug in Series and DataFrame bar plots ignoring the ``use_index`` keyword (:issue:`6209`) + - Disabled clipboard tests until release time (run locally with ``nosetests + -A disabled`` (:issue:`6048`). pandas 0.13.0 ------------- diff --git a/pandas/io/tests/test_clipboard.py b/pandas/io/tests/test_clipboard.py index 3556dfd999d40..8aeedb6572fc4 100644 --- a/pandas/io/tests/test_clipboard.py +++ b/pandas/io/tests/test_clipboard.py @@ -7,7 +7,7 @@ from pandas import read_clipboard from pandas import get_option from pandas.util import testing as tm -from pandas.util.testing import makeCustomDataframe as mkdf +from pandas.util.testing import makeCustomDataframe as mkdf, disabled try: @@ -16,6 +16,7 @@ raise nose.SkipTest("no clipboard found") +@disabled class TestClipboard(tm.TestCase): @classmethod def setUpClass(cls): @@ -37,7 +38,7 @@ def setUpClass(cls): max_rows = get_option('display.max_rows') cls.data['longdf'] = mkdf(max_rows+1, 3, data_gen_f=lambda *args: randint(2), c_idx_type='s', r_idx_type='i', - c_idx_names=[None], r_idx_names=[None]) + c_idx_names=[None], r_idx_names=[None]) cls.data_types = list(cls.data.keys()) @classmethod diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 93262e7ad5582..1068ce1809039 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -996,7 +996,7 @@ def dec(f): 60, # urllib.error.URLError: [Errno 60] Connection timed out ) -# Both of the above shouldn't mask reasl issues such as 404's +# Both of the above shouldn't mask real issues such as 404's # or refused connections (changed DNS). # But some tests (test_data yahoo) contact incredibly flakey # servers. @@ -1396,3 +1396,8 @@ def skip_if_no_ne(engine='numexpr'): if ne.__version__ < LooseVersion('2.0'): raise nose.SkipTest("numexpr version too low: " "%s" % ne.__version__) + + +def disabled(t): + t.disabled = True + return t
closes #6317
https://api.github.com/repos/pandas-dev/pandas/pulls/6221
2014-02-01T15:14:40Z
2014-02-16T18:23:26Z
2014-02-16T18:23:26Z
2014-06-27T15:12:54Z
BLD: more fast travis
diff --git a/ci/prep_ccache.sh b/ci/prep_ccache.sh index c64da5d838834..ffff9d7ac0a37 100755 --- a/ci/prep_ccache.sh +++ b/ci/prep_ccache.sh @@ -8,7 +8,7 @@ if [ "$IRON_TOKEN" ]; then python ci/ironcache/get.py ccache -C - ccache -M 60M + ccache -M 120M if [ -f ~/ccache.7z ]; then echo "Cache retrieved" @@ -21,6 +21,17 @@ if [ "$IRON_TOKEN" ]; then rm -rf $HOME/ccache fi + + # did the last commit change cython files? + git show --pretty="format:" --name-only HEAD~5.. --first-parent | grep -P "pyx|pxd" + + if [ "$?" != "0" ]; then + # nope, reuse cython files + echo "Will reuse cached cython file" + touch "$TRAVIS_BUILD_DIR"/pandas/*.c + touch "$TRAVIS_BUILD_DIR"/pandas/src/*.c + touch "$TRAVIS_BUILD_DIR"/pandas/*.cpp + fi fi exit 0 diff --git a/ci/submit_ccache.sh b/ci/submit_ccache.sh index bf118ff750fa0..0440be74ea798 100755 --- a/ci/submit_ccache.sh +++ b/ci/submit_ccache.sh @@ -2,24 +2,22 @@ ccache -s +MISSES=$(ccache -s | grep "cache miss" | grep -Po "\d+") +echo "MISSES: $MISSES" + +if [ x"$MISSES" == x"0" ]; then + echo "No cache misses detected, skipping upload" + exit 0 +fi + if [ "$IRON_TOKEN" ]; then rm -rf ~/ccache.7z tar cf - $HOME/.ccache \ - | 7za a -si ~/ccache.7z - - # Caching the cython files could be be made to work. - # There's a timestamp issue to be handled (http://stackoverflow.com/questions/1964470) - # but you could get the build to reuse them. - # However, there's a race condition between travis cythonizing - # and a new commit being made on a GH server somewhere. - # and there's convenient causal link between the two we can - # take advantage of. - # Let's just wait another 60 seconds. - # "$TRAVIS_BUILD_DIR"/pandas/{index,algos,lib,tslib,parser,hashtable}.c \ - # "$TRAVIS_BUILD_DIR"/pandas/src/{sparse,testing}.c \ - # "$TRAVIS_BUILD_DIR"/pandas/msgpack.cpp \ - # | 7za a -si ~/ccache.7z + "$TRAVIS_BUILD_DIR"/pandas/{index,algos,lib,tslib,parser,hashtable}.c \ + "$TRAVIS_BUILD_DIR"/pandas/src/{sparse,testing}.c \ + "$TRAVIS_BUILD_DIR"/pandas/msgpack.cpp \ + | 7za a -si ~/ccache.7z split -b 500000 -d ~/ccache.7z ~/ccache.
A couple more optimizations to get the times closer to what was advertised.
https://api.github.com/repos/pandas-dev/pandas/pulls/6220
2014-02-01T12:09:25Z
2014-02-01T12:09:48Z
2014-02-01T12:09:48Z
2014-07-16T08:51:26Z
BLD: Cut Travis-CI build times by 30-50%
diff --git a/.travis.yml b/.travis.yml index d5286c38b830d..fe970c5e85c44 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,13 @@ language: python -python: - - 2.6 +env: + global: + # scatterci API key + - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ=" + # ironcache API key + - secure: "TWGKPL4FGtWjCQ427QrSffaQBSCPy1QzPdhtYKAW9AlDo/agdp9RyZRQr8WTlyZ5AOG18X8MDdi0EcpFnyfDNd4thCLyZOntxwltlVV2yNNvnird3XRKUV1F2DD42L64wna04M2KYxpCKhEQ84gEnCH1DGD4g1NnR6fYuEYNSTU=" + - secure: "NvgIWe14pv4SJ5BQhw6J0zIpCTFH4fVpzr9pRzM2tD8yf/3cspX3uyXTt4owiqtjoQ3aQGNnhWtVlmSwlgJrwu7KUaE9IPtlsENYDniAj2oJgejjx02d367pHtMB/9e3+4b2fWUsFNJgWw0ordiIT0p1lzHRdQ9ut4l/Yn/lkJs=" + - secure: "D3ASNRu32pV79lv/Nl0dBm2ldZiTgbb6boOrN0SzIKsQU3yBwedpqX6EI6KjpVg17lGhhhFXGzL2Gz1qjU3/+m6aMvekxHgpfuc0AlEFCEqenWPxIdDDrUkdfJoCvfQQPd5oxChfHgqaEDLjuqHy1ZEgnJ2/L/6dwZ4fUt62hMk=" matrix: include: @@ -10,7 +16,6 @@ matrix: - NOSE_ARGS="not slow and not network" - CLIPBOARD=xclip - LOCALE_OVERRIDE="it_IT.UTF-8" - - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ=" - JOB_NAME: "26_nslow_nnet" # ScatterCI Build name, 20 chars max - python: 2.7 env: @@ -18,31 +23,26 @@ matrix: - LOCALE_OVERRIDE="zh_CN.GB18030" - FULL_DEPS=true - JOB_TAG=_LOCALE - - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ=" - JOB_NAME: "27_slow_nnet_LOCALE" # ScatterCI Build name, 20 chars max - python: 2.7 env: - NOSE_ARGS="not slow" - FULL_DEPS=true - CLIPBOARD_GUI=gtk2 - - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ=" - JOB_NAME: "27_nslow" # ScatterCI Build name, 20 chars max - python: 3.2 env: - NOSE_ARGS="not slow" - FULL_DEPS=true - CLIPBOARD_GUI=qt4 - - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ=" - JOB_NAME: "32_nslow" # ScatterCI Build name, 20 chars max - python: 3.3 env: - NOSE_ARGS="not slow" - FULL_DEPS=true - CLIPBOARD=xsel - - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ=" - JOB_NAME: "33_nslow" # ScatterCI Build name, 20 chars max - exclude: - - python: 2.6 + # allow importing from site-packages, # so apt-get python-x works for system pythons @@ -55,15 +55,17 @@ before_install: - echo $VIRTUAL_ENV - df -h - date + - pwd - uname -a - - ci/before_install.sh - python -V + - ci/before_install.sh # Xvfb stuff for clipboard functionality; see the travis-ci documentation - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start install: - echo "install" + - ci/prep_ccache.sh - ci/install.sh before_script: @@ -71,9 +73,10 @@ before_script: script: - echo "script" - - ci/script.sh +# - ci/script.sh after_script: - ci/print_versions.py - ci/print_skipped.py /tmp/nosetests.xml - - ci/after_script.sh \ No newline at end of file + - ci/after_script.sh + - ci/submit_ccache.sh diff --git a/ci/install.sh b/ci/install.sh index cb0dff6e5c7d9..424284a5288ec 100755 --- a/ci/install.sh +++ b/ci/install.sh @@ -93,6 +93,12 @@ fi # build and install pandas time python setup.py sdist pip uninstall cython -y + +cat pandas/version.py + +export PATH=/usr/lib/ccache:/usr/lib64/ccache:$PATH +which gcc +ccache -z # reset stats time pip install $(find dist | grep gz | head -n 1) true diff --git a/ci/ironcache/get.py b/ci/ironcache/get.py new file mode 100644 index 0000000000000..bfbaa34b6757c --- /dev/null +++ b/ci/ironcache/get.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +import re +import os +import time +import json +import base64 + +from iron_cache import * + +key='KEY'+os.environ.get('JOB_NAME','')+"." + +b = b'' +cache = IronCache() +for i in range(20): + print("getting %s" % key+str(i)) + try: + item = cache.get(cache="travis", key=key+str(i)) + b += bytes(base64.b64decode(item.value)) + except: + break + +with open(os.path.join(os.environ.get('HOME',''),"ccache.7z"),'wb') as f: + f.write(b) diff --git a/ci/ironcache/put.py b/ci/ironcache/put.py new file mode 100644 index 0000000000000..06d8896b289d5 --- /dev/null +++ b/ci/ironcache/put.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +import re +import os +import time +import json +import base64 + +from iron_cache import * + +key='KEY'+os.environ.get('JOB_NAME','')+"." +os.chdir(os.environ.get('HOME')) + +cache = IronCache() + +i=0 + +for i, fname in enumerate(sorted([x for x in os.listdir('.') if re.match("ccache.\d+$",x)])): + print("Putting %s" % key+str(i)) + with open(fname,"rb") as f: + s= f.read() + value=base64.b64encode(s) + if isinstance(value, bytes): + value = value.decode('ascii') + item = cache.put(cache="travis", key=key+str(i), value=value,options=dict(expires_in=24*60*60)) + +# print("foo") +for i in range(i+1,20): + + try: + item = cache.delete(key+str(i),cache='travis') + print("Deleted %s" % key+str(i)) + except: + break + pass diff --git a/ci/prep_ccache.sh b/ci/prep_ccache.sh new file mode 100755 index 0000000000000..0046b71c0b1d9 --- /dev/null +++ b/ci/prep_ccache.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +if [ "$IRON_TOKEN" ]; then + sudo apt-get $APT_ARGS install ccache p7zip-full + # iron_cache, pending py3 fixes upstream + pip install -I --allow-external --allow-insecure git+https://github.com/y-p/iron_cache_python.git + + + python ci/ironcache/get.py + ccache -C + if [ -f ~/ccache.7z ]; then + echo "Cache retrieved" + cd $HOME + 7za e $HOME/ccache.7z + # ls -l $HOME + cd / + tar xvf $HOME/ccache + rm -rf $HOME/ccache.7z + rm -rf $HOME/ccache + + fi +fi + +exit 0 diff --git a/ci/submit_ccache.sh b/ci/submit_ccache.sh new file mode 100755 index 0000000000000..bf118ff750fa0 --- /dev/null +++ b/ci/submit_ccache.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +ccache -s + +if [ "$IRON_TOKEN" ]; then + rm -rf ~/ccache.7z + + tar cf - $HOME/.ccache \ + | 7za a -si ~/ccache.7z + + # Caching the cython files could be be made to work. + # There's a timestamp issue to be handled (http://stackoverflow.com/questions/1964470) + # but you could get the build to reuse them. + # However, there's a race condition between travis cythonizing + # and a new commit being made on a GH server somewhere. + # and there's convenient causal link between the two we can + # take advantage of. + # Let's just wait another 60 seconds. + # "$TRAVIS_BUILD_DIR"/pandas/{index,algos,lib,tslib,parser,hashtable}.c \ + # "$TRAVIS_BUILD_DIR"/pandas/src/{sparse,testing}.c \ + # "$TRAVIS_BUILD_DIR"/pandas/msgpack.cpp \ + # | 7za a -si ~/ccache.7z + + split -b 500000 -d ~/ccache.7z ~/ccache. + + python ci/ironcache/put.py +fi; + +exit 0
and some travis.yml cleanups after recent bug fixes by the travis guys.
https://api.github.com/repos/pandas-dev/pandas/pulls/6218
2014-02-01T09:43:37Z
2014-02-01T11:01:45Z
2014-02-01T11:01:45Z
2014-06-13T05:48:42Z
BLD: setup.py version strings. handle shallow clones and installing from sdist
diff --git a/doc/source/release.rst b/doc/source/release.rst index 247bd896809a7..35c22fdf03d9a 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -67,6 +67,8 @@ Improvements to existing features Bug Fixes ~~~~~~~~~ +- Bug in version string gen. for dev versions with shallow clones / install from tarball (:issue:`6127`) + pandas 0.13.1 ------------- diff --git a/setup.py b/setup.py index f820f3deb8a3e..6713e52733fd1 100755 --- a/setup.py +++ b/setup.py @@ -10,6 +10,7 @@ import sys import shutil import warnings +import re # may need to work around setuptools bug by providing a fake Pyrex try: @@ -196,6 +197,8 @@ def build_extensions(self): QUALIFIER = '' FULLVERSION = VERSION +write_version = True + if not ISRELEASED: import subprocess FULLVERSION += '.dev' @@ -212,14 +215,26 @@ def build_extensions(self): pass if pipe is None or pipe.returncode != 0: - warnings.warn("WARNING: Couldn't get git revision, using generic version string") + # no git, or not in git dir + if os.path.exists('pandas/version.py'): + warnings.warn("WARNING: Couldn't get git revision, using existing pandas/version.py") + write_version = False + else: + warnings.warn("WARNING: Couldn't get git revision, using generic version string") else: + # have git, in git dir, but may have used a shallow clone (travis does this) rev = so.strip() # makes distutils blow up on Python 2.7 if sys.version_info[0] >= 3: rev = rev.decode('ascii') - # use result of git describe as version string + if not rev.startswith('v') and re.match("[a-zA-Z0-9]{7,9}",rev): + # partial clone, manually construct version string + # this is the format before we started using git-describe + # to get an ordering on dev version strings. + rev ="v%s.dev-%s" % (VERSION, rev) + + # Strip leading v from tags format "vx.y.z" to get th version string FULLVERSION = rev.lstrip('v') else: @@ -241,6 +256,8 @@ def write_version_py(filename=None): finally: a.close() +if write_version: + write_version_py() class CleanCommand(Command): """Custom distutils command to clean the .so and .pyc files.""" @@ -527,8 +544,6 @@ def pxd(name): if _have_setuptools: setuptools_kwargs["test_suite"] = "nose.collector" -write_version_py() - # The build cache system does string matching below this point. # if you change something, be careful.
Travis exposed a corner case in the handling of version strings since the `git-describe` shakeup. Previously (0.10.1), version strings were of the form: ``` v0.10.1 # release v0.10.1.dev # dev, no git available v0.10.1.dev-abcd1234 # dev, git available ``` Now that we use git-describe, here's the case breakdown: - release - dev, no git - dev, no git and pandas/version.py exists (installing from sdist) # * - dev, git available - dev, git but shallow clone (no tags) (travis) # * the \* cases were hard to see coming (I didn't) and so the current logic does not handle them gracefully, and weird version strings result. Behavior summary following this PR: ``` v0.13.1 # release v0.13.1.dev # dev, no git available, matches old behavior v0.13.1.dev-abcd1234 # dev, git available but no tags (pip tarball), matches old behavior foo # dev, no git available, pandas/version.py exists and contains foo 0.13.0-509-ga134eb6 # dev, git available, tags available (normal dev situation), normal new behavior. ``` Slightly dangerous to merge shortly before a release, but it would be worse to keep this brokenness for months until 0.14 IMO.
https://api.github.com/repos/pandas-dev/pandas/pulls/6217
2014-02-01T07:36:21Z
2014-02-04T08:51:51Z
2014-02-04T08:51:51Z
2014-07-16T08:51:22Z
CLN: PEP8 cleanup of rpy/tests
diff --git a/pandas/rpy/tests/test_common.py b/pandas/rpy/tests/test_common.py index a2e6d08d07b58..2785a10e6a3af 100644 --- a/pandas/rpy/tests/test_common.py +++ b/pandas/rpy/tests/test_common.py @@ -17,6 +17,7 @@ class TestCommon(unittest.TestCase): + def test_convert_list(self): obj = r('list(a=1, b=2, c=3)') @@ -141,8 +142,8 @@ def test_timeseries(self): """ for name in ( 'austres', 'co2', 'fdeaths', 'freeny.y', 'JohnsonJohnson', - 'ldeaths', 'mdeaths', 'nottem', 'presidents', 'sunspot.month', 'sunspots', - 'UKDriverDeaths', 'UKgas', 'USAccDeaths', + 'ldeaths', 'mdeaths', 'nottem', 'presidents', 'sunspot.month', + 'sunspots', 'UKDriverDeaths', 'UKgas', 'USAccDeaths', 'airmiles', 'discoveries', 'EuStockMarkets', 'LakeHuron', 'lh', 'lynx', 'nhtemp', 'Nile', 'Seatbelts', 'sunspot.year', 'treering', 'uspop'): @@ -169,20 +170,30 @@ def test_table(self): 2: 'Setosa', 3: 'Setosa', 4: 'Setosa'}, - 'value': {0: '5.1', 1: '4.9', 2: '4.7', 3: '4.6', 4: '5.0'}}) + 'value': {0: '5.1', 1: '4.9', 2: '4.7', + 3: '4.6', 4: '5.0'}}) hec = pd.DataFrame( { - 'Eye': {0: 'Brown', 1: 'Brown', 2: 'Brown', 3: 'Brown', 4: 'Blue'}, - 'Hair': {0: 'Black', 1: 'Brown', 2: 'Red', 3: 'Blond', 4: 'Black'}, - 'Sex': {0: 'Male', 1: 'Male', 2: 'Male', 3: 'Male', 4: 'Male'}, - 'value': {0: '32.0', 1: '53.0', 2: '10.0', 3: '3.0', 4: '11.0'}}) + 'Eye': {0: 'Brown', 1: 'Brown', 2: 'Brown', + 3: 'Brown', 4: 'Blue'}, + 'Hair': {0: 'Black', 1: 'Brown', 2: 'Red', + 3: 'Blond', 4: 'Black'}, + 'Sex': {0: 'Male', 1: 'Male', 2: 'Male', + 3: 'Male', 4: 'Male'}, + 'value': {0: '32.0', 1: '53.0', 2: '10.0', + 3: '3.0', 4: '11.0'}}) titanic = pd.DataFrame( { - 'Age': {0: 'Child', 1: 'Child', 2: 'Child', 3: 'Child', 4: 'Child'}, - 'Class': {0: '1st', 1: '2nd', 2: '3rd', 3: 'Crew', 4: '1st'}, - 'Sex': {0: 'Male', 1: 'Male', 2: 'Male', 3: 'Male', 4: 'Female'}, - 'Survived': {0: 'No', 1: 'No', 2: 'No', 3: 'No', 4: 'No'}, - 'value': {0: '0.0', 1: '0.0', 2: '35.0', 3: '0.0', 4: '0.0'}}) + 'Age': {0: 'Child', 1: 'Child', 2: 'Child', + 3: 'Child', 4: 'Child'}, + 'Class': {0: '1st', 1: '2nd', 2: '3rd', + 3: 'Crew', 4: '1st'}, + 'Sex': {0: 'Male', 1: 'Male', 2: 'Male', + 3: 'Male', 4: 'Female'}, + 'Survived': {0: 'No', 1: 'No', 2: 'No', + 3: 'No', 4: 'No'}, + 'value': {0: '0.0', 1: '0.0', 2: '35.0', + 3: '0.0', 4: '0.0'}}) for name, expected in zip(('HairEyeColor', 'Titanic', 'iris3'), (hec, titanic, iris3)): df = com.load_data(name)
Fixes pep8 errors in test_common.py in rpy/tests. Ran autopep8, then fixed remaining errors manually. Test still passes locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/6216
2014-02-01T04:20:49Z
2014-02-17T20:42:35Z
null
2014-07-21T13:38:13Z
DOC: Fix typo in Melt section
diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst index 9c289c4c39129..ce8f0013e9268 100644 --- a/doc/source/reshaping.rst +++ b/doc/source/reshaping.rst @@ -229,7 +229,7 @@ Another way to transform is to use the ``wide_to_long`` panel data convenience f "X" : dict(zip(range(3), np.random.randn(3))) }) dft["id"] = dft.index - df + dft pd.wide_to_long(dft, ["A", "B"], i="id", j="year") Combining with stats and GroupBy
Example in "Melt" documentation was referring to the wrong DataFrame.
https://api.github.com/repos/pandas-dev/pandas/pulls/6211
2014-01-31T19:40:05Z
2014-01-31T20:07:50Z
2014-01-31T20:07:50Z
2014-06-14T10:23:30Z
BUG: dont ignore use_index kw in bar plot
diff --git a/doc/source/release.rst b/doc/source/release.rst index b194bff2ece59..420a94b194c55 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -179,6 +179,7 @@ Bug Fixes specificed column spec (:issue:`6169`) - Bug in ``nanops.var`` with ``ddof=1`` and 1 elements would sometimes return ``inf`` rather than ``nan`` on some platforms (:issue:`6136`) + - Bug in Series and DataFrame bar plots ignoring the ``use_index`` keyword (:issue:`6209`) pandas 0.13.0 ------------- diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 1fee318059b7f..2902621a1e944 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -162,6 +162,14 @@ def test_bar_log(self): ax = Series([200, 500]).plot(log=True, kind='bar') assert_array_equal(ax.yaxis.get_ticklocs(), expected) + @slow + def test_bar_ignore_index(self): + df = Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) + ax = df.plot(kind='bar', use_index=False) + expected = ['0', '1', '2', '3'] + result = [x.get_text() for x in ax.get_xticklabels()] + self.assertEqual(result, expected) + def test_rotation(self): df = DataFrame(randn(5, 5)) ax = df.plot(rot=30) diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 5162e75540ee2..d8f1f92249648 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1572,8 +1572,11 @@ def _make_plot(self): def _post_plot_logic(self): for ax in self.axes: - str_index = [com.pprint_thing(key) for key in self.data.index] - + if self.use_index: + str_index = [com.pprint_thing(key) for key in self.data.index] + else: + str_index = [com.pprint_thing(key) for key in + range(self.data.shape[0])] name = self._get_index_name() if self.kind == 'bar': ax.set_xlim([self.ax_pos[0] - 0.25, self.ax_pos[-1] + 1])
Closes https://github.com/pydata/pandas/issues/6209 Here's the fixed output for the same example from the issue: `df.plot(kind='bar', use_index=False)`: ![line_false_fixed](https://f.cloud.github.com/assets/1312546/2053850/603f044e-8aad-11e3-86e3-3f3bf38a5683.png) I thew it in `.13.1`, can push to `.14` if need be.
https://api.github.com/repos/pandas-dev/pandas/pulls/6210
2014-01-31T19:25:17Z
2014-01-31T21:30:11Z
2014-01-31T21:30:11Z
2016-11-03T12:37:46Z
DOC: add links to other pages to contributing.rst
diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index d54b2afec80db..6d76c6e4efd6c 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -4,4 +4,13 @@ Contributing to pandas ********************** +See the following links: + +- `The developer pages on the website + <http://pandas.pydata.org/developers.html>`_ +- `Guidelines on bug reports and pull requests + <https://github.com/pydata/pandas/blob/master/CONTRIBUTING.md>`_ +- `Some extra tips on using git + <https://github.com/pydata/pandas/wiki/Using-Git>`_ + .. include:: ../README.rst
Awaiting for that the different developer pages could be reworked and added to this page, I thought to at least add some links here. So if people go from the docs to this page, they get redirected to the relevant pages.
https://api.github.com/repos/pandas-dev/pandas/pulls/6207
2014-01-31T16:11:13Z
2014-02-02T15:43:52Z
2014-02-02T15:43:52Z
2014-07-10T00:09:58Z
DOC: styling clean-up of docstrings (part 2: series and generic.py)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 25770a0cddf52..e5b2be99f6362 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -809,8 +809,9 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch', - columns : dict like {column -> {index -> value}} - values : just the values array - date_format : type of date conversion, epoch or iso - epoch = epoch milliseconds, iso = ISO8601, default is epoch + date_format : {'epoch', 'iso'} + Type of date conversion. `epoch` = epoch milliseconds, + `iso`` = ISO8601, default is epoch. double_precision : The number of decimal places to use when encoding floating point values, default 10. force_ascii : force encoded string to be ASCII, default True. @@ -845,7 +846,8 @@ def to_hdf(self, path_or_buf, key, **kwargs): Parameters ---------- path_or_buf : the path (string) or buffer to put the store - key : string, an indentifier for the group in the store + key : string + indentifier for the group in the store mode : optional, {'a', 'w', 'r', 'r+'}, default 'a' ``'r'`` @@ -2079,8 +2081,8 @@ def fillna(self, value=None, method=None, axis=0, inplace=False, column (for a DataFrame). (values not in the dict/Series will not be filled). This value cannot be a list. axis : {0, 1}, default 0 - 0: fill column-by-column - 1: fill row-by-row + * 0: fill column-by-column + * 1: fill row-by-row inplace : boolean, default False If True, fill in place. Note: this will modify any other views on this object, (e.g. a no-copy slice for a column in a @@ -2440,9 +2442,9 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, 'polynomial', 'spline' 'piecewise_polynomial', 'pchip'} * 'linear': ignore the index and treat the values as equally - spaced. default + spaced. default * 'time': interpolation works on daily and higher resolution - data to interpolate given length of interval + 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 @@ -2450,10 +2452,10 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, '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 + 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 @@ -2745,20 +2747,23 @@ def resample(self, rule, how=None, axis=0, fill_method=None, Parameters ---------- - rule : the offset string or object representing target conversion - how : string, method for down- or re-sampling, default to 'mean' for - downsampling + rule : string + the offset string or object representing target conversion + how : string + method for down- or re-sampling, default to 'mean' for + downsampling axis : int, optional, default 0 - fill_method : string, fill_method for upsampling, default None + fill_method : string, default None + fill_method for upsampling closed : {'right', 'left'} Which side of bin interval is closed label : {'right', 'left'} Which bin edge label to label bucket with convention : {'start', 'end', 's', 'e'} - kind: "period"/"timestamp" - loffset: timedelta + kind : "period"/"timestamp" + loffset : timedelta Adjust the resampled time labels - limit: int, default None + limit : int, default None Maximum size gap to when reindexing with fill_method base : int, default 0 For frequencies that evenly subdivide 1 day, the "origin" of the diff --git a/pandas/core/series.py b/pandas/core/series.py index 762d8aed5c697..8873af08cc5f3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -95,6 +95,7 @@ class Series(generic.NDFrame): """ One-dimensional ndarray with axis labels (including time series). + Labels need not be unique but must be any hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical @@ -117,7 +118,8 @@ class Series(generic.NDFrame): dict. dtype : numpy.dtype or None If None, dtype will be inferred - copy : boolean, default False, copy input data + copy : boolean, default False + Copy input data """ _metadata = ['name'] @@ -807,7 +809,8 @@ def set_value(self, label, value): def reset_index(self, level=None, drop=False, name=None, inplace=False): """ - Analogous to the DataFrame.reset_index function, see docstring there. + Analogous to the :meth:`pandas.DataFrame.reset_index` function, see + docstring there. Parameters ---------- @@ -1133,7 +1136,7 @@ def value_counts(self, normalize=False, sort=True, ascending=False, Parameters ---------- - normalize: boolean, default False + normalize : boolean, default False If True then the Series returned will contain the relative frequencies of the unique values. sort : boolean, default True @@ -1161,7 +1164,7 @@ def mode(self): Parameters ---------- sort : bool, default True - if True, will lexicographically sort values, if False skips + If True, will lexicographically sort values, if False skips sorting. Result ordering when ``sort=False`` is not defined. Returns @@ -1398,9 +1401,9 @@ def corr(self, other, method='pearson', ---------- other : Series method : {'pearson', 'kendall', 'spearman'} - pearson : standard correlation coefficient - kendall : Kendall Tau correlation coefficient - spearman : Spearman rank correlation + * pearson : standard correlation coefficient + * kendall : Kendall Tau correlation coefficient + * spearman : Spearman rank correlation min_periods : int, optional Minimum number of observations needed to have a valid result @@ -1663,7 +1666,7 @@ def sort(self, axis=0, kind='quicksort', order=None, ascending=True): See Also -------- - pandas.Series.order + Series.order """ # GH 5856/5863 @@ -1750,10 +1753,10 @@ def rank(self, method='average', na_option='keep', ascending=True): Parameters ---------- method : {'average', 'min', 'max', 'first'} - average: average rank of group - min: lowest rank in group - max: highest rank in group - first: ranks assigned in order they appear in the array + * average: average rank of group + * min: lowest rank in group + * max: highest rank in group + * first: ranks assigned in order they appear in the array na_option : {'keep'} keep: leave NA values where they are ascending : boolean, default True @@ -2260,7 +2263,7 @@ def dropna(self, axis=0, inplace=False, **kwargs): Returns ------- valid : Series - inplace : bool (default False) + inplace : boolean, default False Do operation in place. """ axis = self._get_axis_number(axis or 0)
Rediscovered an old branch: some clean-up of docstrings in series/generic.py.
https://api.github.com/repos/pandas-dev/pandas/pulls/6206
2014-01-31T15:28:19Z
2014-01-31T16:11:38Z
2014-01-31T16:11:38Z
2014-07-16T08:51:15Z
BUG: Add type promotion support for eval() expressions with many properties
diff --git a/doc/source/release.rst b/doc/source/release.rst index 5f7d87ea03f67..ae95c882fe356 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -76,6 +76,7 @@ Bug Fixes - Indexing bugs with reordered indexes (:issue:`6252`, :issue:`6254`) - Bug in ``.xs`` with a Series multiindex (:issue:`6258`, :issue:`5684`) - Bug in conversion of a string types to a DatetimeIndex with a specified frequency (:issue:`6273`, :issue:`6274`) +- Bug in ``eval`` where type-promotion failed for large expressions (:issue:`6205`) pandas 0.13.1 ------------- diff --git a/pandas/computation/align.py b/pandas/computation/align.py index 9fe563574bbd4..1685f66c15416 100644 --- a/pandas/computation/align.py +++ b/pandas/computation/align.py @@ -10,6 +10,7 @@ import pandas as pd from pandas import compat import pandas.core.common as com +from pandas.computation.common import _result_type_many def _align_core_single_unary_op(term): @@ -85,11 +86,11 @@ def wrapper(terms): # only scalars or indexes if all(isinstance(term.value, pd.Index) or term.isscalar for term in terms): - return np.result_type(*term_values), None + return _result_type_many(*term_values), None # no pandas objects if not _any_pandas_objects(terms): - return np.result_type(*term_values), None + return _result_type_many(*term_values), None return f(terms) return wrapper @@ -199,7 +200,7 @@ def _align(terms): # if all resolved variables are numeric scalars if all(term.isscalar for term in terms): - return np.result_type(*(term.value for term in terms)).type, None + return _result_type_many(*(term.value for term in terms)).type, None # perform the main alignment typ, axes = _align_core(terms) diff --git a/pandas/computation/common.py b/pandas/computation/common.py index 9af2197a4fd69..0d5e639032b94 100644 --- a/pandas/computation/common.py +++ b/pandas/computation/common.py @@ -1,5 +1,6 @@ import numpy as np import pandas as pd +from pandas.compat import reduce def _ensure_decoded(s): @@ -9,5 +10,18 @@ def _ensure_decoded(s): return s +def _result_type_many(*arrays_and_dtypes): + """ wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32) + argument limit """ + try: + return np.result_type(*arrays_and_dtypes) + except ValueError: + # length 0 or length > NPY_MAXARGS both throw a ValueError, so check + # which one we're dealing with + if len(arrays_and_dtypes) == 0: + raise ValueError('at least one array or dtype is required') + return reduce(np.result_type, arrays_and_dtypes) + + class NameResolutionError(NameError): pass diff --git a/pandas/computation/ops.py b/pandas/computation/ops.py index 8d7bd0a819e79..270ba92d4483a 100644 --- a/pandas/computation/ops.py +++ b/pandas/computation/ops.py @@ -13,7 +13,7 @@ from pandas.compat import PY3, string_types, text_type import pandas.core.common as com from pandas.core.base import StringMixin -from pandas.computation.common import _ensure_decoded +from pandas.computation.common import _ensure_decoded, _result_type_many _reductions = 'sum', 'prod' @@ -240,7 +240,7 @@ def return_type(self): # clobber types to bool if the op is a boolean operator if self.op in (_cmp_ops_syms + _bool_ops_syms): return np.bool_ - return np.result_type(*(term.type for term in com.flatten(self))) + return _result_type_many(*(term.type for term in com.flatten(self))) @property def isscalar(self): diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py index b1cafca190bb0..dbc190df9c33a 100644 --- a/pandas/computation/tests/test_eval.py +++ b/pandas/computation/tests/test_eval.py @@ -1575,6 +1575,18 @@ def test_invalid_numexpr_version(): yield check_invalid_numexpr_version, engine, parser +def check_many_exprs(engine, parser): + a = 1 + expr = ' * '.join('a' * 33) + expected = 1 + res = pd.eval(expr, engine=engine, parser=parser) + tm.assert_equal(res, expected) + +def test_many_exprs(): + for engine, parser in ENGINES_PARSERS: + yield check_many_exprs, engine, parser + + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
This commit modifies the call to numpy.result_type to get around the NPY_MAXARGS limit, which at the moment is 32. Instead of passing a generator of all types involved in an expression, the type promotion is done on a pair-wise basis with a call to reduce. This fixes bugs for code such as the following: ``` from numpy.random import randn from pandas import DataFrame d = DataFrame(randn(10, 2), columns=list('ab')) # Evaluates fine print(d.eval('*'.join(['a'] * 32))) # Fails to evaluate due to NumPy argument limits print(d.eval('*'.join(['a'] * 33))) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6205
2014-01-31T14:54:46Z
2014-02-06T14:59:23Z
2014-02-06T14:59:23Z
2014-06-12T21:23:08Z
BUG: bug in nanops.var with ddof=1 and 1 elements would sometimes return inf rather than nan (GH6136)
diff --git a/doc/source/release.rst b/doc/source/release.rst index b9115c79354a6..b194bff2ece59 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -177,6 +177,8 @@ Bug Fixes - Consistency with dtypes in setting an empty DataFrame (:issue:`6171`) - Bug in selecting on a multi-index ``HDFStore`` even in the prescence of under specificed column spec (:issue:`6169`) + - Bug in ``nanops.var`` with ``ddof=1`` and 1 elements would sometimes return ``inf`` + rather than ``nan`` on some platforms (:issue:`6136`) pandas 0.13.0 ------------- diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 2722905bf49c0..636532bc5fbf9 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -302,14 +302,25 @@ def nanvar(values, axis=None, skipna=True, ddof=1): else: count = float(values.size - mask.sum()) + d = count-ddof if skipna: values = values.copy() np.putmask(values, mask, 0) + # always return NaN, never inf + if np.isscalar(count): + if count <= ddof: + count = np.nan + d = np.nan + else: + mask = count <= ddof + if mask.any(): + np.putmask(d, mask, np.nan) + np.putmask(count, mask, np.nan) + X = _ensure_numeric(values.sum(axis)) XX = _ensure_numeric((values ** 2).sum(axis)) - return np.fabs((XX - X ** 2 / count) / (count - ddof)) - + return np.fabs((XX - X ** 2 / count) / d) @bottleneck_switch() def nanmin(values, axis=None, skipna=True): diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index d31717ec8c165..00f1b826303c9 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -1832,6 +1832,14 @@ def test_var_std(self): expected = np.var(self.ts.values, ddof=4) assert_almost_equal(result, expected) + # 1 - element series with ddof=1 + s = self.ts.iloc[[0]] + result = s.var(ddof=1) + self.assert_(isnull(result)) + + result = s.std(ddof=1) + self.assert_(isnull(result)) + def test_skew(self): _skip_if_no_scipy()
closes #6136
https://api.github.com/repos/pandas-dev/pandas/pulls/6204
2014-01-31T14:49:40Z
2014-01-31T16:25:25Z
2014-01-31T16:25:24Z
2014-07-16T08:51:11Z
small py3 fixes
diff --git a/doc/make.py b/doc/make.py index fc9a33b07fc3d..88e5a939eef46 100755 --- a/doc/make.py +++ b/doc/make.py @@ -321,7 +321,7 @@ def generate_index(api=True, single=False, **kwds): with open("source/index.rst.template") as f: t = Template(f.read()) - with open("source/index.rst","wb") as f: + with open("source/index.rst","w") as f: f.write(t.render(api=api,single=single,**kwds)) import argparse diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py index 86050a346f4f3..9bbe622a0843c 100644 --- a/doc/sphinxext/ipython_directive.py +++ b/doc/sphinxext/ipython_directive.py @@ -256,6 +256,8 @@ def set_encodings(self, encodings): def write(self,data): #py 3 compat here + if sys.version > '3': + unicode = str if isinstance(data,unicode): return super(DecodingStringIO, self).write(data) else:
@y-p correcting those small fixes I mentioned in the comments of your commit.
https://api.github.com/repos/pandas-dev/pandas/pulls/6203
2014-01-31T14:37:33Z
2014-02-01T12:36:25Z
null
2014-07-08T13:14:57Z
BUG: correctly select on a multi-index even in the prescence of under specificed column spec (GH6169)
diff --git a/doc/source/release.rst b/doc/source/release.rst index d701d1dacc16d..b9115c79354a6 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -175,6 +175,8 @@ Bug Fixes - Bug in ``HDFStore`` on appending a dataframe with multi-indexed columns to an existing table (:issue:`6167`) - Consistency with dtypes in setting an empty DataFrame (:issue:`6171`) + - Bug in selecting on a multi-index ``HDFStore`` even in the prescence of under + specificed column spec (:issue:`6169`) pandas 0.13.0 ------------- diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index bb487f5102e0a..8bae83dce7546 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3289,6 +3289,12 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, def process_axes(self, obj, columns=None): """ process axes filters """ + # make sure to include levels if we have them + if columns is not None and self.is_multi_index: + for n in self.levels: + if n not in columns: + columns.insert(0, n) + # reorder by any non_index_axes & limit to the select columns for axis, labels in self.non_index_axes: obj = _reindex_axis(obj, axis, labels, columns) @@ -3305,6 +3311,12 @@ def process_filter(field, filt): # see if the field is the name of an axis if field == axis_name: + + # if we have a multi-index, then need to include + # the levels + if self.is_multi_index: + filt = filt + Index(self.levels) + takers = op(axis_values, filt) return obj.ix._getitem_axis(takers, axis=axis_number) @@ -3951,13 +3963,9 @@ def write(self, obj, data_columns=None, **kwargs): return super(AppendableMultiFrameTable, self).write( obj=obj, data_columns=data_columns, **kwargs) - def read(self, columns=None, **kwargs): - if columns is not None: - for n in self.levels: - if n not in columns: - columns.insert(0, n) - df = super(AppendableMultiFrameTable, self).read( - columns=columns, **kwargs) + def read(self, **kwargs): + + df = super(AppendableMultiFrameTable, self).read(**kwargs) df = df.set_index(self.levels) # remove names for 'level_%d' @@ -3967,7 +3975,6 @@ def read(self, columns=None, **kwargs): return df - class AppendablePanelTable(AppendableTable): """ suppor the new appendable table formats """ diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 9c56ee468f6ac..dc218b530db64 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -1673,6 +1673,36 @@ def make_index(names=None): store.append('df',df) tm.assert_frame_equal(store.select('df'),df) + def test_select_columns_in_where(self): + + # GH 6169 + # recreate multi-indexes when columns is passed + # in the `where` argument + index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], + ['one', 'two', 'three']], + labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], + [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=['foo_name', 'bar_name']) + + # With a DataFrame + df = DataFrame(np.random.randn(10, 3), index=index, + columns=['A', 'B', 'C']) + + with ensure_clean_store(self.path) as store: + store.put('df', df, format='table') + expected = df[['A']] + + tm.assert_frame_equal(store.select('df', columns=['A']), expected) + + tm.assert_frame_equal(store.select('df', where="columns=['A']"), expected) + + # With a Series + s = Series(np.random.randn(10), index=index, + name='A') + with ensure_clean_store(self.path) as store: + store.put('s', s, format='table') + tm.assert_series_equal(store.select('s', where="columns=['A']"),s) + def test_pass_spec_to_storer(self): df = tm.makeDataFrame()
closes #6169
https://api.github.com/repos/pandas-dev/pandas/pulls/6202
2014-01-31T13:05:52Z
2014-01-31T13:32:00Z
2014-01-31T13:32:00Z
2014-06-19T08:34:35Z
Change more assert_'s to specialized forms
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index a84f4f6d2cb21..214b7fb928dec 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -77,7 +77,7 @@ def test_is_unique_monotonic(self): def test_index_unique(self): uniques = self.dups.index.unique() - self.assert_(uniques.dtype == 'M8[ns]') # sanity + self.assertEqual(uniques.dtype, 'M8[ns]') # sanity # #2563 self.assertTrue(isinstance(uniques, DatetimeIndex)) @@ -117,7 +117,7 @@ def test_duplicate_dates_indexing(self): # new index ts[datetime(2000,1,6)] = 0 - self.assert_(ts[datetime(2000,1,6)] == 0) + self.assertEqual(ts[datetime(2000,1,6)], 0) def test_range_slice(self): idx = DatetimeIndex(['1/1/2000', '1/2/2000', '1/2/2000', '1/3/2000', @@ -385,7 +385,7 @@ def _check_rng(rng): def test_ctor_str_intraday(self): rng = DatetimeIndex(['1-1-2000 00:00:01']) - self.assert_(rng[0].second == 1) + self.assertEqual(rng[0].second, 1) def test_series_ctor_plus_datetimeindex(self): rng = date_range('20090415', '20090519', freq='B') @@ -601,7 +601,7 @@ def test_frame_add_datetime64_col_other_units(self): ex_vals = to_datetime(vals.astype('O')) - self.assert_(df[unit].dtype == ns_dtype) + self.assertEqual(df[unit].dtype, ns_dtype) self.assert_((df[unit].values == ex_vals).all()) # Test insertion into existing datetime64 column @@ -799,11 +799,11 @@ def test_string_na_nat_conversion(self): def test_to_datetime_iso8601(self): result = to_datetime(["2012-01-01 00:00:00"]) exp = Timestamp("2012-01-01 00:00:00") - self.assert_(result[0] == exp) + self.assertEqual(result[0], exp) result = to_datetime(['20121001']) # bad iso 8601 exp = Timestamp('2012-10-01') - self.assert_(result[0] == exp) + self.assertEqual(result[0], exp) def test_to_datetime_default(self): rs = to_datetime('2001') @@ -874,12 +874,12 @@ def test_to_datetime_types(self): # ints result = Timestamp(0) expected = to_datetime(0) - self.assert_(result == expected) + self.assertEqual(result, expected) # GH 3888 (strings) expected = to_datetime(['2012'])[0] result = to_datetime('2012') - self.assert_(result == expected) + self.assertEqual(result, expected) ### array = ['2012','20120101','20120101 12:01:01'] array = ['20120101','20120101 12:01:01'] @@ -890,7 +890,7 @@ def test_to_datetime_types(self): ### currently fails ### ### result = Timestamp('2012') ### expected = to_datetime('2012') - ### self.assert_(result == expected) + ### self.assertEqual(result, expected) def test_to_datetime_unprocessable_input(self): # GH 4928 @@ -1014,8 +1014,8 @@ def test_index_to_datetime(self): def test_to_datetime_freq(self): xp = bdate_range('2000-1-1', periods=10, tz='UTC') rs = xp.to_datetime() - self.assert_(xp.freq == rs.freq) - self.assert_(xp.tzinfo == rs.tzinfo) + self.assertEqual(xp.freq, rs.freq) + self.assertEqual(xp.tzinfo, rs.tzinfo) def test_range_misspecified(self): # GH #1095 @@ -1097,11 +1097,11 @@ def test_date_range_gen_error(self): def test_first_subset(self): ts = _simple_ts('1/1/2000', '1/1/2010', freq='12h') result = ts.first('10d') - self.assert_(len(result) == 20) + self.assertEqual(len(result), 20) ts = _simple_ts('1/1/2000', '1/1/2010') result = ts.first('10d') - self.assert_(len(result) == 10) + self.assertEqual(len(result), 10) result = ts.first('3M') expected = ts[:'3/31/2000'] @@ -1117,11 +1117,11 @@ def test_first_subset(self): def test_last_subset(self): ts = _simple_ts('1/1/2000', '1/1/2010', freq='12h') result = ts.last('10d') - self.assert_(len(result) == 20) + self.assertEqual(len(result), 20) ts = _simple_ts('1/1/2000', '1/1/2010') result = ts.last('10d') - self.assert_(len(result) == 10) + self.assertEqual(len(result), 10) result = ts.last('21D') expected = ts['12/12/2009':] @@ -1152,7 +1152,7 @@ def test_repeat(self): result = rng.repeat(5) self.assert_(result.freq is None) - self.assert_(len(result) == 5 * len(rng)) + self.assertEqual(len(result), 5 * len(rng)) def test_at_time(self): rng = date_range('1/1/2000', '1/5/2000', freq='5min') @@ -1194,7 +1194,7 @@ def test_at_time(self): rng = date_range('1/1/2012', freq='23Min', periods=384) ts = Series(np.random.randn(len(rng)), rng) rs = ts.at_time('16:00') - self.assert_(len(rs) == 0) + self.assertEqual(len(rs), 0) def test_at_time_frame(self): rng = date_range('1/1/2000', '1/5/2000', freq='5min') @@ -1224,7 +1224,7 @@ def test_at_time_frame(self): rng = date_range('1/1/2012', freq='23Min', periods=384) ts = DataFrame(np.random.randn(len(rng), 2), rng) rs = ts.at_time('16:00') - self.assert_(len(rs) == 0) + self.assertEqual(len(rs), 0) def test_between_time(self): rng = date_range('1/1/2000', '1/5/2000', freq='5min') @@ -1241,7 +1241,7 @@ def test_between_time(self): if not inc_end: exp_len -= 4 - self.assert_(len(filtered) == exp_len) + self.assertEqual(len(filtered), exp_len) for rs in filtered.index: t = rs.time() if inc_start: @@ -1273,7 +1273,7 @@ def test_between_time(self): if not inc_end: exp_len -= 4 - self.assert_(len(filtered) == exp_len) + self.assertEqual(len(filtered), exp_len) for rs in filtered.index: t = rs.time() if inc_start: @@ -1301,7 +1301,7 @@ def test_between_time_frame(self): if not inc_end: exp_len -= 4 - self.assert_(len(filtered) == exp_len) + self.assertEqual(len(filtered), exp_len) for rs in filtered.index: t = rs.time() if inc_start: @@ -1333,7 +1333,7 @@ def test_between_time_frame(self): if not inc_end: exp_len -= 4 - self.assert_(len(filtered) == exp_len) + self.assertEqual(len(filtered), exp_len) for rs in filtered.index: t = rs.time() if inc_start: @@ -1350,7 +1350,7 @@ def test_dti_constructor_preserve_dti_freq(self): rng = date_range('1/1/2000', '1/2/2000', freq='5min') rng2 = DatetimeIndex(rng) - self.assert_(rng.freq == rng2.freq) + self.assertEqual(rng.freq, rng2.freq) def test_normalize(self): rng = date_range('1/1/2000 9:30', periods=10, freq='D') @@ -1414,7 +1414,7 @@ def test_to_period_tz(self): result = ts.to_period()[0] expected = ts[0].to_period() - self.assert_(result == expected) + self.assertEqual(result, expected) self.assert_(ts.to_period().equals(xp)) ts = date_range('1/1/2000', '4/1/2000', tz=UTC) @@ -1422,7 +1422,7 @@ def test_to_period_tz(self): result = ts.to_period()[0] expected = ts[0].to_period() - self.assert_(result == expected) + self.assertEqual(result, expected) self.assert_(ts.to_period().equals(xp)) ts = date_range('1/1/2000', '4/1/2000', tz=tzlocal()) @@ -1430,7 +1430,7 @@ def test_to_period_tz(self): result = ts.to_period()[0] expected = ts[0].to_period() - self.assert_(result == expected) + self.assertEqual(result, expected) self.assert_(ts.to_period().equals(xp)) def test_frame_to_period(self): @@ -1528,13 +1528,13 @@ def test_timestamp_from_ordinal(self): # GH 3042 dt = datetime(2011, 4, 16, 0, 0) ts = Timestamp.fromordinal(dt.toordinal()) - self.assert_(ts.to_pydatetime() == dt) + self.assertEqual(ts.to_pydatetime(), dt) # with a tzinfo stamp = Timestamp('2011-4-16', tz='US/Eastern') dt_tz = stamp.to_pydatetime() ts = Timestamp.fromordinal(dt_tz.toordinal(),tz='US/Eastern') - self.assert_(ts.to_pydatetime() == dt_tz) + self.assertEqual(ts.to_pydatetime(), dt_tz) def test_datetimeindex_integers_shift(self): rng = date_range('1/1/2000', periods=20) @@ -1585,7 +1585,7 @@ def test_append_concat(self): rng2 = rng.copy() rng1.name = 'foo' rng2.name = 'bar' - self.assert_(rng1.append(rng1).name == 'foo') + self.assertEqual(rng1.append(rng1).name, 'foo') self.assert_(rng1.append(rng2).name is None) def test_append_concat_tz(self): @@ -1863,7 +1863,7 @@ def test_000constructor_resolution(self): t1 = Timestamp((1352934390 * 1000000000) + 1000000 + 1000 + 1) idx = DatetimeIndex([t1]) - self.assert_(idx.nanosecond[0] == t1.nanosecond) + self.assertEqual(idx.nanosecond[0], t1.nanosecond) def test_constructor_coverage(self): rng = date_range('1/1/2000', periods=10.5) @@ -1955,7 +1955,7 @@ def test_union_coverage(self): result = ordered[:0].union(ordered) self.assert_(result.equals(ordered)) - self.assert_(result.freq == ordered.freq) + self.assertEqual(result.freq, ordered.freq) def test_union_bug_1730(self): rng_a = date_range('1/1/2012', periods=4, freq='3H') @@ -2047,7 +2047,7 @@ def test_insert(self): idx = date_range('1/1/2000', periods=3, freq='M') result = idx.insert(3, datetime(2000, 4, 30)) - self.assert_(result.freqstr == 'M') + self.assertEqual(result.freqstr, 'M') def test_map_bug_1677(self): index = DatetimeIndex(['2012-04-25 09:30:00.393000']) @@ -2221,7 +2221,7 @@ def test_datetimeindex_diff(self): periods=100) dti2 = DatetimeIndex(freq='Q-JAN', start=datetime(1997, 12, 31), periods=98) - self.assert_(len(dti1.diff(dti2)) == 2) + self.assertEqual(len(dti1.diff(dti2)), 2) def test_fancy_getitem(self): dti = DatetimeIndex(freq='WOM-1FRI', start=datetime(2005, 1, 1), @@ -2333,7 +2333,7 @@ def test_dti_reset_index_round_trip(self): dti = DatetimeIndex(start='1/1/2001', end='6/1/2001', freq='D') d1 = DataFrame({'v': np.random.rand(len(dti))}, index=dti) d2 = d1.reset_index() - self.assert_(d2.dtypes[0] == np.dtype('M8[ns]')) + self.assertEqual(d2.dtypes[0], np.dtype('M8[ns]')) d3 = d2.set_index('index') assert_frame_equal(d1, d3, check_names=False) @@ -2371,7 +2371,7 @@ def test_series_set_value(self): # s = Series(index[:1], index[:1]) # s2 = s.set_value(dates[1], index[1]) - # self.assert_(s2.values.dtype == 'M8[ns]') + # self.assertEqual(s2.values.dtype, 'M8[ns]') @slow def test_slice_locs_indexerror(self): @@ -2388,7 +2388,7 @@ def setUp(self): def test_auto_conversion(self): series = Series(list(date_range('1/1/2000', periods=10))) - self.assert_(series.dtype == 'M8[ns]') + self.assertEqual(series.dtype, 'M8[ns]') def test_constructor_cant_cast_datetime64(self): self.assertRaises(TypeError, Series, @@ -2461,7 +2461,7 @@ def test_union(self): rng2 = date_range('1/1/1980', '12/1/2001', freq='MS') s2 = Series(np.random.randn(len(rng2)), rng2) df = DataFrame({'s1': s1, 's2': s2}) - self.assert_(df.index.values.dtype == np.dtype('M8[ns]')) + self.assertEqual(df.index.values.dtype, np.dtype('M8[ns]')) def test_intersection(self): rng = date_range('6/1/2000', '6/15/2000', freq='D') @@ -2476,10 +2476,10 @@ def test_intersection(self): # empty same freq GH2129 rng = date_range('6/1/2000', '6/15/2000', freq='T') result = rng[0:0].intersection(rng) - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) result = rng.intersection(rng[0:0]) - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) def test_date_range_bms_bug(self): # #1645 @@ -2517,27 +2517,27 @@ def compare(x,y): def test_basics_nanos(self): val = np.int64(946684800000000000).view('M8[ns]') stamp = Timestamp(val.view('i8') + 500) - self.assert_(stamp.year == 2000) - self.assert_(stamp.month == 1) - self.assert_(stamp.microsecond == 0) - self.assert_(stamp.nanosecond == 500) + self.assertEqual(stamp.year, 2000) + self.assertEqual(stamp.month, 1) + self.assertEqual(stamp.microsecond, 0) + self.assertEqual(stamp.nanosecond, 500) def test_unit(self): def check(val,unit=None,h=1,s=1,us=0): stamp = Timestamp(val, unit=unit) - self.assert_(stamp.year == 2000) - self.assert_(stamp.month == 1) - self.assert_(stamp.day == 1) - self.assert_(stamp.hour == h) + self.assertEqual(stamp.year, 2000) + self.assertEqual(stamp.month, 1) + self.assertEqual(stamp.day, 1) + self.assertEqual(stamp.hour, h) if unit != 'D': - self.assert_(stamp.minute == 1) - self.assert_(stamp.second == s) - self.assert_(stamp.microsecond == us) + self.assertEqual(stamp.minute, 1) + self.assertEqual(stamp.second, s) + self.assertEqual(stamp.microsecond, us) else: - self.assert_(stamp.minute == 0) - self.assert_(stamp.second == 0) - self.assert_(stamp.microsecond == 0) - self.assert_(stamp.nanosecond == 0) + self.assertEqual(stamp.minute, 0) + self.assertEqual(stamp.second, 0) + self.assertEqual(stamp.microsecond, 0) + self.assertEqual(stamp.nanosecond, 0) ts = Timestamp('20000101 01:01:01') val = ts.value @@ -2592,7 +2592,7 @@ def test_comparison(self): val = Timestamp(stamp) - self.assert_(val == val) + self.assertEqual(val, val) self.assert_(not val != val) self.assert_(not val < val) self.assert_(val <= val) @@ -2600,7 +2600,7 @@ def test_comparison(self): self.assert_(val >= val) other = datetime(2012, 5, 18) - self.assert_(val == other) + self.assertEqual(val, other) self.assert_(not val != other) self.assert_(not val < other) self.assert_(val <= other) @@ -2609,7 +2609,7 @@ def test_comparison(self): other = Timestamp(stamp + 100) - self.assert_(not val == other) + self.assertNotEqual(val, other) self.assert_(val != other) self.assert_(val < other) self.assert_(val <= other) @@ -2641,7 +2641,7 @@ def test_cant_compare_tz_naive_w_aware(self): def test_delta_preserve_nanos(self): val = Timestamp(long(1337299200000000123)) result = val + timedelta(1) - self.assert_(result.nanosecond == val.nanosecond) + self.assertEqual(result.nanosecond, val.nanosecond) def test_frequency_misc(self): self.assertEquals(fmod.get_freq_group('T'), @@ -2763,7 +2763,7 @@ def test_slice_year(self): result = rng.get_loc('2009') expected = slice(3288, 3653) - self.assert_(result == expected) + self.assertEqual(result, expected) def test_slice_quarter(self): dti = DatetimeIndex(freq='D', start=datetime(2000, 6, 1), periods=500) @@ -2801,7 +2801,7 @@ def test_partial_slice(self): assert_series_equal(result, expected) result = s['2005-1-1'] - self.assert_(result == s.irow(0)) + self.assertEqual(result, s.irow(0)) self.assertRaises(Exception, s.__getitem__, '2004-12-31') @@ -2825,7 +2825,7 @@ def test_partial_slice_hourly(self): 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.assertEqual(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): @@ -2839,7 +2839,7 @@ def test_partial_slice_minutely(self): 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.assertEqual(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): @@ -2899,7 +2899,7 @@ def test_date_range_normalize(self): '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) + self.assertEqual(val.time(), the_time) def test_timedelta(self): # this is valid too @@ -2944,23 +2944,23 @@ 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) + self.assertEqual(result.freq, rng.freq) result = rng[:50].union(rng[30:100]) - self.assert_(result.freq == rng.freq) + self.assertEqual(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') + self.assertEqual(result.freqstr, 'D') nofreq = DatetimeIndex(list(rng[25:75])) result = rng[:50].union(nofreq) - self.assert_(result.freq == rng.freq) + self.assertEqual(result.freq, rng.freq) result = rng[:50].intersection(nofreq) - self.assert_(result.freq == rng.freq) + self.assertEqual(result.freq, rng.freq) def test_min_max(self): rng = date_range('1/1/2000', '12/31/2000') @@ -3060,7 +3060,7 @@ def test_to_datetime_format(self): if isinstance(expected, Series): assert_series_equal(result, Series(expected)) elif isinstance(expected, Timestamp): - self.assert_(result == expected) + self.assertEqual(result, expected) else: self.assert_(result.equals(expected)) @@ -3094,7 +3094,7 @@ def test_to_datetime_format_microsecond(self): format = '%d-%b-%Y %H:%M:%S.%f' result = to_datetime(val, format=format) exp = dt.datetime.strptime(val, format) - self.assert_(result == exp) + self.assertEqual(result, exp) def test_to_datetime_format_time(self): data = [ diff --git a/pandas/tseries/tests/test_timeseries_legacy.py b/pandas/tseries/tests/test_timeseries_legacy.py index 2e8418d8f50b2..3155f0f6e1a80 100644 --- a/pandas/tseries/tests/test_timeseries_legacy.py +++ b/pandas/tseries/tests/test_timeseries_legacy.py @@ -113,7 +113,7 @@ def test_unpickle_legacy_len0_daterange(self): self.assert_(result.index.equals(ex_index)) tm.assert_isinstance(result.index.freq, offsets.BDay) - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) def test_arithmetic_interaction(self): index = self.frame.index @@ -167,7 +167,7 @@ def test_unpickle_daterange(self): rng = read_pickle(filepath) tm.assert_isinstance(rng[0], datetime) tm.assert_isinstance(rng.offset, offsets.BDay) - self.assert_(rng.values.dtype == object) + self.assertEqual(rng.values.dtype, object) def test_setops(self): index = self.frame.index @@ -248,12 +248,12 @@ def test_legacy_time_rules(self): 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()) + self.assertEqual(left, datetools.Milli()) + self.assertEqual(right, datetools.MonthBegin()) def test_rule_aliases(self): rule = datetools.to_offset('10us') - self.assert_(rule == datetools.Micro(10)) + self.assertEqual(rule, datetools.Micro(10)) class TestLegacyCompat(unittest.TestCase):
Work on #6175 to specialize asserts for test_timeseries[_legacy].py. A work-in-progress.
https://api.github.com/repos/pandas-dev/pandas/pulls/6201
2014-01-31T12:49:45Z
2014-02-04T09:02:30Z
2014-02-04T09:02:30Z
2014-06-24T18:01:39Z
BUG/TST raise a more detailed error when GH6169 occurs, added a test
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index bb487f5102e0a..9d1ce4f4b82bc 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3958,8 +3958,16 @@ def read(self, columns=None, **kwargs): columns.insert(0, n) df = super(AppendableMultiFrameTable, self).read( columns=columns, **kwargs) - df = df.set_index(self.levels) - + try: + df = df.set_index(self.levels) + except KeyError: + if kwargs.get('where') is not None and 'columns' in kwargs.get('where').expr: + raise KeyError( + "Indexes columns were not retrieved because you passed " + "a `where` argument containing columns specification. " + "(see http://github.com/pydata/pandas/issues/6169), try passing " + "the columns specification through the `columns` keyword instead" + ) # remove names for 'level_%d' df.index = df.index.set_names([ None if self._re_levels.search(l) else l for l in df.index.names diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 9c56ee468f6ac..29f536b3bf5d9 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -1673,6 +1673,33 @@ def make_index(names=None): store.append('df',df) tm.assert_frame_equal(store.select('df'),df) + def test_select_columns_in_where(self): + + # GH 6169 + # recreate multi-indexes when columns is passed + # in the `where` argument + index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], + ['one', 'two', 'three']], + labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], + [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=['foo_name', 'bar_name']) + + # With a DataFrame + df = DataFrame(np.random.randn(10, 3), index=index, + columns=['A', 'B', 'C']) + + with ensure_clean_store(self.path) as store: + store.put('df', df, format='table') + tm.assert_frame_equal(store.select('df', where="columns=['A']"),df['A'], + check_index_type=True,check_column_type=True) + # With a Serie + s = Series(np.random.randn(10), index=index, + name='A') + with ensure_clean_store(self.path) as store: + store.put('s', s) + tm.assert_frame_equal(store.select('s', where="columns=['A']"),s, + check_index_type=True,check_column_type=True) + def test_pass_spec_to_storer(self): df = tm.makeDataFrame()
Raise a detailed error when a `columns` argument is passed through 'where' to select a multiIndexed Dataframe from an HDF store. Wrote a test showcasing the bug ``` modified: pandas/io/pytables.py modified: pandas/io/tests/test_pytables.py ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6200
2014-01-31T11:21:08Z
2014-01-31T13:07:29Z
null
2014-01-31T13:33:55Z
CLN: Change some assert_'s to specialized foms
diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py index 0af3b6281530b..d1efa12953caa 100644 --- a/pandas/tseries/tests/test_daterange.py +++ b/pandas/tseries/tests/test_daterange.py @@ -364,18 +364,18 @@ def test_range_tz(self): dr = date_range(start=start, periods=3) self.assert_(dr.tz == tz('US/Eastern')) - self.assert_(dr[0] == start) - self.assert_(dr[2] == end) + self.assertEqual(dr[0], start) + self.assertEqual(dr[2], end) dr = date_range(end=end, periods=3) - self.assert_(dr.tz == tz('US/Eastern')) - self.assert_(dr[0] == start) - self.assert_(dr[2] == end) + self.assertEqual(dr.tz, tz('US/Eastern')) + self.assertEqual(dr[0], start) + self.assertEqual(dr[2], end) dr = date_range(start=start, end=end) - self.assert_(dr.tz == tz('US/Eastern')) - self.assert_(dr[0] == start) - self.assert_(dr[2] == end) + self.assertEqual(dr.tz, tz('US/Eastern')) + self.assertEqual(dr[0], start) + self.assertEqual(dr[2], end) def test_month_range_union_tz(self): _skip_if_no_pytz() diff --git a/pandas/tseries/tests/test_frequencies.py b/pandas/tseries/tests/test_frequencies.py index 8d95e22e4c6f2..b17a1c11efad7 100644 --- a/pandas/tseries/tests/test_frequencies.py +++ b/pandas/tseries/tests/test_frequencies.py @@ -99,18 +99,18 @@ def test_raise_if_too_few(self): def test_business_daily(self): index = _dti(['12/31/1998', '1/3/1999', '1/4/1999']) - self.assert_(infer_freq(index) == 'B') + self.assertEqual(infer_freq(index), 'B') def test_day(self): self._check_tick(timedelta(1), 'D') def test_day_corner(self): index = _dti(['1/1/2000', '1/2/2000', '1/3/2000']) - self.assert_(infer_freq(index) == 'D') + self.assertEqual(infer_freq(index), 'D') def test_non_datetimeindex(self): dates = to_datetime(['1/1/2000', '1/2/2000', '1/3/2000']) - self.assert_(infer_freq(dates) == 'D') + self.assertEqual(infer_freq(dates), 'D') def test_hour(self): self._check_tick(timedelta(hours=1), 'H') @@ -141,7 +141,7 @@ def _check_tick(self, base_delta, code): exp_freq = '%d%s' % (i, code) else: exp_freq = code - self.assert_(infer_freq(index) == exp_freq) + self.assertEqual(infer_freq(index), exp_freq) index = _dti([b + base_delta * 7] + [b + base_delta * j for j in range(3)]) @@ -174,7 +174,7 @@ def test_monthly(self): def test_monthly_ambiguous(self): rng = _dti(['1/31/2000', '2/29/2000', '3/31/2000']) - self.assert_(rng.inferred_freq == 'M') + self.assertEqual(rng.inferred_freq, 'M') def test_business_monthly(self): self._check_generated_range('1/1/2000', 'BM') @@ -196,7 +196,7 @@ def test_business_annual(self): def test_annual_ambiguous(self): rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002']) - self.assert_(rng.inferred_freq == 'A-JAN') + self.assertEqual(rng.inferred_freq, 'A-JAN') def _check_generated_range(self, start, freq): freq = freq.upper() @@ -220,7 +220,7 @@ def _check_generated_range(self, start, freq): gen = date_range(start, periods=5, freq=freq) index = _dti(gen.values) if not freq.startswith('Q-'): - self.assert_(infer_freq(index) == gen.freqstr) + self.assertEqual(infer_freq(index), gen.freqstr) else: inf_freq = infer_freq(index) self.assert_((inf_freq == 'Q-DEC' and @@ -236,15 +236,15 @@ def _check_generated_range(self, start, freq): def test_infer_freq(self): rng = period_range('1959Q2', '2009Q3', freq='Q') rng = Index(rng.to_timestamp('D', how='e').asobject) - self.assert_(rng.inferred_freq == 'Q-DEC') + self.assertEqual(rng.inferred_freq, 'Q-DEC') rng = period_range('1959Q2', '2009Q3', freq='Q-NOV') rng = Index(rng.to_timestamp('D', how='e').asobject) - self.assert_(rng.inferred_freq == 'Q-NOV') + self.assertEqual(rng.inferred_freq, 'Q-NOV') rng = period_range('1959Q2', '2009Q3', freq='Q-OCT') rng = Index(rng.to_timestamp('D', how='e').asobject) - self.assert_(rng.inferred_freq == 'Q-OCT') + self.assertEqual(rng.inferred_freq, 'Q-OCT') def test_not_monotonic(self): rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002']) diff --git a/pandas/tseries/tests/test_offsets.py b/pandas/tseries/tests/test_offsets.py index a3c63966948ee..6e553959f3ee5 100644 --- a/pandas/tseries/tests/test_offsets.py +++ b/pandas/tseries/tests/test_offsets.py @@ -151,7 +151,7 @@ def test_eq(self): offset2 = DateOffset(days=365) self.assert_(offset1 != offset2) - self.assert_(not (offset1 == offset2)) + self.assertNotEqual(offset1, offset2) class TestBusinessDay(TestBase): @@ -703,7 +703,7 @@ def test_onOffset(self): for week, weekday, date, expected in test_cases: offset = WeekOfMonth(week=week, weekday=weekday) - self.assert_(offset.onOffset(date) == expected) + self.assertEqual(offset.onOffset(date), expected) class TestLastWeekOfMonth(TestBase): _offset = LastWeekOfMonth @@ -722,13 +722,13 @@ def test_offset(self): offset_sat = LastWeekOfMonth(n=1, weekday=5) one_day_before = (last_sat + timedelta(days=-1)) - self.assert_(one_day_before + offset_sat == last_sat) + self.assertEqual(one_day_before + offset_sat, last_sat) one_day_after = (last_sat + timedelta(days=+1)) - self.assert_(one_day_after + offset_sat == next_sat) + self.assertEqual(one_day_after + offset_sat, next_sat) #Test On that day - self.assert_(last_sat + offset_sat == next_sat) + self.assertEqual(last_sat + offset_sat, next_sat) #### Thursday @@ -737,22 +737,22 @@ def test_offset(self): next_thurs = datetime(2013,2,28) one_day_before = last_thurs + timedelta(days=-1) - self.assert_(one_day_before + offset_thur == last_thurs) + self.assertEqual(one_day_before + offset_thur, last_thurs) one_day_after = last_thurs + timedelta(days=+1) - self.assert_(one_day_after + offset_thur == next_thurs) + self.assertEqual(one_day_after + offset_thur, next_thurs) # Test on that day - self.assert_(last_thurs + offset_thur == next_thurs) + self.assertEqual(last_thurs + offset_thur, next_thurs) three_before = last_thurs + timedelta(days=-3) - self.assert_(three_before + offset_thur == last_thurs) + self.assertEqual(three_before + offset_thur, last_thurs) two_after = last_thurs + timedelta(days=+2) - self.assert_(two_after + offset_thur == next_thurs) + self.assertEqual(two_after + offset_thur, next_thurs) offset_sunday = LastWeekOfMonth(n=1, weekday=WeekDay.SUN) - self.assert_(datetime(2013,7,31) + offset_sunday == datetime(2013,8,25)) + self.assertEqual(datetime(2013,7,31) + offset_sunday, datetime(2013,8,25)) def test_onOffset(self): test_cases = [ diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index ca0eba59fe5fe..21e9756da9ad6 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -465,25 +465,25 @@ def test_constructor_corner(self): def test_constructor_infer_freq(self): p = Period('2007-01-01') - self.assert_(p.freq == 'D') + self.assertEqual(p.freq, 'D') p = Period('2007-01-01 07') - self.assert_(p.freq == 'H') + self.assertEqual(p.freq, 'H') p = Period('2007-01-01 07:10') - self.assert_(p.freq == 'T') + self.assertEqual(p.freq, 'T') p = Period('2007-01-01 07:10:15') - self.assert_(p.freq == 'S') + self.assertEqual(p.freq, 'S') p = Period('2007-01-01 07:10:15.123') - self.assert_(p.freq == 'L') + self.assertEqual(p.freq, 'L') p = Period('2007-01-01 07:10:15.123000') - self.assert_(p.freq == 'L') + self.assertEqual(p.freq, 'L') p = Period('2007-01-01 07:10:15.123400') - self.assert_(p.freq == 'U') + self.assertEqual(p.freq, 'U') def noWrap(item): @@ -1368,7 +1368,7 @@ def test_indexing(self): s = Series(randn(10), index=index) expected = s[index[0]] result = s.iat[0] - self.assert_(expected == result) + self.assertEqual(expected, result) def test_frame_setitem(self): rng = period_range('1/1/2000', periods=5) @@ -1772,12 +1772,12 @@ def test_asfreq_ts(self): result = ts.asfreq('D', how='end') df_result = df.asfreq('D', how='end') exp_index = index.asfreq('D', how='end') - self.assert_(len(result) == len(ts)) + self.assertEqual(len(result), len(ts)) self.assert_(result.index.equals(exp_index)) self.assert_(df_result.index.equals(exp_index)) result = ts.asfreq('D', how='start') - self.assert_(len(result) == len(ts)) + self.assertEqual(len(result), len(ts)) self.assert_(result.index.equals(index.asfreq('D', how='start'))) def test_badinput(self): @@ -1818,7 +1818,7 @@ def test_pindex_qaccess(self): pi = PeriodIndex(['2Q05', '3Q05', '4Q05', '1Q06', '2Q06'], freq='Q') s = Series(np.random.rand(len(pi)), index=pi).cumsum() # Todo: fix these accessors! - self.assert_(s['05Q4'] == s[2]) + self.assertEqual(s['05Q4'], s[2]) def test_period_dt64_round_trip(self): dti = date_range('1/1/2000', '1/7/2002', freq='B') @@ -1843,21 +1843,21 @@ def test_to_period_quarterlyish(self): for off in offsets: rng = date_range('01-Jan-2012', periods=8, freq=off) prng = rng.to_period() - self.assert_(prng.freq == 'Q-DEC') + self.assertEqual(prng.freq, 'Q-DEC') def test_to_period_annualish(self): offsets = ['BA', 'AS', 'BAS'] for off in offsets: rng = date_range('01-Jan-2012', periods=8, freq=off) prng = rng.to_period() - self.assert_(prng.freq == 'A-DEC') + self.assertEqual(prng.freq, 'A-DEC') def test_to_period_monthish(self): offsets = ['MS', 'EOM', 'BM'] for off in offsets: rng = date_range('01-Jan-2012', periods=8, freq=off) prng = rng.to_period() - self.assert_(prng.freq == 'M') + self.assertEqual(prng.freq, 'M') def test_no_multiples(self): self.assertRaises(ValueError, period_range, '1989Q3', periods=10, @@ -1894,7 +1894,7 @@ def test_iteration(self): result = list(index) tm.assert_isinstance(result[0], Period) - self.assert_(result[0].freq == index.freq) + self.assertEqual(result[0].freq, index.freq) def test_take(self): index = PeriodIndex(start='1/1/10', end='12/31/12', freq='D') @@ -1902,9 +1902,9 @@ def test_take(self): taken = index.take([5, 6, 8, 12]) taken2 = index[[5, 6, 8, 12]] tm.assert_isinstance(taken, PeriodIndex) - self.assert_(taken.freq == index.freq) + self.assertEqual(taken.freq, index.freq) tm.assert_isinstance(taken2, PeriodIndex) - self.assert_(taken2.freq == index.freq) + self.assertEqual(taken2.freq, index.freq) def test_joins(self): index = period_range('1/1/2000', '1/20/2000', freq='D') @@ -1913,7 +1913,7 @@ def test_joins(self): joined = index.join(index[:-5], how=kind) tm.assert_isinstance(joined, PeriodIndex) - self.assert_(joined.freq == index.freq) + self.assertEqual(joined.freq, index.freq) def test_join_self(self): index = period_range('1/1/2000', '1/20/2000', freq='D') @@ -2128,7 +2128,7 @@ def test_get_loc_msg(self): try: idx.get_loc(bad_period) except KeyError as inst: - self.assert_(inst.args[0] == bad_period) + self.assertEqual(inst.args[0], bad_period) def test_append_concat(self): # #1815 diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index e55dd96d64ca0..3c6f97b73a6b4 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -81,7 +81,7 @@ def test_nonnumeric_exclude(self): df = DataFrame({'A': ["x", "y", "z"], 'B': [1,2,3]}, idx) ax = df.plot() # it works - self.assert_(len(ax.get_lines()) == 1) #B was plotted + self.assertEqual(len(ax.get_lines()), 1) #B was plotted plt.close(plt.gcf()) self.assertRaises(TypeError, df['A'].plot) @@ -390,7 +390,7 @@ def test_finder_monthly(self): 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] diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index 289c0391fca23..59be80f7012d7 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -90,7 +90,7 @@ def test_resample_basic(self): expected = Series([s[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()], index=date_range('1/1/2000', periods=4, freq='5min')) assert_series_equal(result, expected) - self.assert_(result.index.name == 'index') + self.assertEqual(result.index.name, 'index') result = s.resample('5min', how='mean', closed='left', label='right') expected = Series([s[:5].mean(), s[5:10].mean(), s[10:].mean()], @@ -158,7 +158,7 @@ def test_resample_basic_from_daily(self): self.assertEquals(result.irow(0), s['1/2/2005']) self.assertEquals(result.irow(1), s['1/3/2005']) self.assertEquals(result.irow(5), s['1/9/2005']) - self.assert_(result.index.name == 'index') + self.assertEqual(result.index.name, 'index') def test_resample_frame_basic(self): df = tm.makeTimeDataFrame() @@ -201,7 +201,7 @@ def test_resample_loffset(self): loffset=Minute(1)) assert_series_equal(result, expected) - self.assert_(result.index.freq == Minute(5)) + self.assertEqual(result.index.freq, Minute(5)) # from daily dti = DatetimeIndex( @@ -228,7 +228,7 @@ def test_resample_upsample(self): self.assertEquals(result[0], s[0]) self.assertEquals(result[-1], s[-1]) - self.assert_(result.index.name == 'index') + self.assertEqual(result.index.name, 'index') def test_upsample_with_limit(self): rng = date_range('1/1/2000', periods=3, freq='5t') @@ -305,7 +305,7 @@ def test_resample_reresample(self): result = bs.resample('8H') self.assertEquals(len(result), 22) tm.assert_isinstance(result.index.freq, offsets.DateOffset) - self.assert_(result.index.freq == offsets.Hour(8)) + self.assertEqual(result.index.freq, offsets.Hour(8)) def test_resample_timestamp_to_period(self): ts = _simple_ts('1/1/1990', '1/1/2000') @@ -491,12 +491,12 @@ def test_resample_empty(self): ts = _simple_ts('1/1/2000', '2/1/2000')[:0] result = ts.resample('A') - self.assert_(len(result) == 0) - self.assert_(result.index.freqstr == 'A-DEC') + self.assertEqual(len(result), 0) + self.assertEqual(result.index.freqstr, 'A-DEC') result = ts.resample('A', kind='period') - self.assert_(len(result) == 0) - self.assert_(result.index.freqstr == 'A-DEC') + self.assertEqual(len(result), 0) + self.assertEqual(result.index.freqstr, 'A-DEC') xp = DataFrame() rs = xp.resample('A') @@ -549,7 +549,7 @@ def test_resample_anchored_intraday(self): ts = _simple_ts('2012-04-29 23:00', '2012-04-30 5:00', freq='h') resampled = ts.resample('M') - self.assert_(len(resampled) == 1) + self.assertEqual(len(resampled), 1) def test_resample_anchored_monthstart(self): ts = _simple_ts('1/1/2000', '12/31/2002') @@ -572,13 +572,13 @@ def test_corner_cases(self): len0pts = _simple_pts('2007-01', '2010-05', freq='M')[:0] # it works result = len0pts.resample('A-DEC') - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) # resample to periods ts = _simple_ts('2000-04-28', '2000-04-30 11:00', freq='h') result = ts.resample('M', kind='period') - self.assert_(len(result) == 1) - self.assert_(result.index[0] == Period('2000-04', freq='M')) + self.assertEqual(len(result), 1) + self.assertEqual(result.index[0], Period('2000-04', freq='M')) def test_anchored_lowercase_buglet(self): dates = date_range('4/16/2012 20:00', periods=50000, freq='s') @@ -889,7 +889,7 @@ def test_resample_empty(self): ts = _simple_pts('1/1/2000', '2/1/2000')[:0] result = ts.resample('A') - self.assert_(len(result) == 0) + self.assertEqual(len(result), 0) def test_resample_irregular_sparse(self): dr = date_range(start='1/1/2012', freq='5min', periods=1000) diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index 3d8ee87f6c42f..8863a50e86c2e 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -32,21 +32,21 @@ def setUp(self): 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.assertEqual(ct(0), np.timedelta64(0,'ns')) + self.assertEqual(ct(10), np.timedelta64(10,'ns')) + self.assertEqual(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]')) + self.assertEqual(ct(10,unit='us'), np.timedelta64(10,'us').astype('m8[ns]')) + self.assertEqual(ct(10,unit='ms'), np.timedelta64(10,'ms').astype('m8[ns]')) + self.assertEqual(ct(10,unit='s'), np.timedelta64(10,'s').astype('m8[ns]')) + self.assertEqual(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]')) + self.assertEqual(ct(timedelta(seconds=1)), np.timedelta64(1,'s').astype('m8[ns]')) + self.assertEqual(ct(timedelta(microseconds=1)), np.timedelta64(1,'us').astype('m8[ns]')) + self.assertEqual(ct(timedelta(days=1)), np.timedelta64(1,'D').astype('m8[ns]')) def test_short_format_converters(self): _skip_if_numpy_not_friendly() @@ -54,43 +54,43 @@ def test_short_format_converters(self): 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'))) + self.assertEqual(ct('10'), np.timedelta64(10,'ns')) + self.assertEqual(ct('10ns'), np.timedelta64(10,'ns')) + self.assertEqual(ct('100'), np.timedelta64(100,'ns')) + self.assertEqual(ct('100ns'), np.timedelta64(100,'ns')) + + self.assertEqual(ct('1000'), np.timedelta64(1000,'ns')) + self.assertEqual(ct('1000ns'), np.timedelta64(1000,'ns')) + self.assertEqual(ct('1000NS'), np.timedelta64(1000,'ns')) + + self.assertEqual(ct('10us'), np.timedelta64(10000,'ns')) + self.assertEqual(ct('100us'), np.timedelta64(100000,'ns')) + self.assertEqual(ct('1000us'), np.timedelta64(1000000,'ns')) + self.assertEqual(ct('1000Us'), np.timedelta64(1000000,'ns')) + self.assertEqual(ct('1000uS'), np.timedelta64(1000000,'ns')) + + self.assertEqual(ct('1ms'), np.timedelta64(1000000,'ns')) + self.assertEqual(ct('10ms'), np.timedelta64(10000000,'ns')) + self.assertEqual(ct('100ms'), np.timedelta64(100000000,'ns')) + self.assertEqual(ct('1000ms'), np.timedelta64(1000000000,'ns')) + + self.assertEqual(ct('-1s'), -np.timedelta64(1000000000,'ns')) + self.assertEqual(ct('1s'), np.timedelta64(1000000000,'ns')) + self.assertEqual(ct('10s'), np.timedelta64(10000000000,'ns')) + self.assertEqual(ct('100s'), np.timedelta64(100000000000,'ns')) + self.assertEqual(ct('1000s'), np.timedelta64(1000000000000,'ns')) + + self.assertEqual(ct('1d'), conv(np.timedelta64(1,'D'))) + self.assertEqual(ct('-1d'), -conv(np.timedelta64(1,'D'))) + self.assertEqual(ct('1D'), conv(np.timedelta64(1,'D'))) + self.assertEqual(ct('10D'), conv(np.timedelta64(10,'D'))) + self.assertEqual(ct('100D'), conv(np.timedelta64(100,'D'))) + self.assertEqual(ct('1000D'), conv(np.timedelta64(1000,'D'))) + self.assertEqual(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'))) + self.assertEqual(ct(' 10000D '), conv(np.timedelta64(10000,'D'))) + self.assertEqual(ct(' - 10000D '), -conv(np.timedelta64(10000,'D'))) # invalid self.assertRaises(ValueError, ct, '1foo') @@ -103,18 +103,18 @@ 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.assertEqual(ct('1days'), conv(d1)) + self.assertEqual(ct('1days,'), conv(d1)) + self.assertEqual(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.assertEqual(ct('00:00:01'), conv(np.timedelta64(1,'s'))) + self.assertEqual(ct('06:00:01'), conv(np.timedelta64(6*3600+1,'s'))) + self.assertEqual(ct('06:00:01.0'), conv(np.timedelta64(6*3600+1,'s'))) + self.assertEqual(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'))) + self.assertEqual(ct('- 1days, 00:00:01'), -conv(d1+np.timedelta64(1,'s'))) + self.assertEqual(ct('1days, 06:00:01'), conv(d1+np.timedelta64(6*3600+1,'s'))) + self.assertEqual(ct('1days, 06:00:01.01'), conv(d1+np.timedelta64(1000*(6*3600+1)+10,'ms'))) # invalid self.assertRaises(ValueError, ct, '- 1days, 00') @@ -122,8 +122,8 @@ def conv(v): def test_nat_converters(self): _skip_if_numpy_not_friendly() - self.assert_(to_timedelta('nat',box=False) == tslib.iNaT) - self.assert_(to_timedelta('nan',box=False) == tslib.iNaT) + self.assertEqual(to_timedelta('nat',box=False), tslib.iNaT) + self.assertEqual(to_timedelta('nan',box=False), tslib.iNaT) def test_to_timedelta(self): _skip_if_numpy_not_friendly() @@ -132,12 +132,12 @@ def conv(v): return v.astype('m8[ns]') d1 = np.timedelta64(1,'D') - self.assert_(to_timedelta('1 days 06:05:01.00003',box=False) == conv(d1+np.timedelta64(6*3600+5*60+1,'s')+np.timedelta64(30,'us'))) - self.assert_(to_timedelta('15.5us',box=False) == conv(np.timedelta64(15500,'ns'))) + self.assertEqual(to_timedelta('1 days 06:05:01.00003',box=False), conv(d1+np.timedelta64(6*3600+5*60+1,'s')+np.timedelta64(30,'us'))) + self.assertEqual(to_timedelta('15.5us',box=False), conv(np.timedelta64(15500,'ns'))) # empty string result = to_timedelta('',box=False) - self.assert_(result == tslib.iNaT) + self.assertEqual(result, tslib.iNaT) result = to_timedelta(['', '']) self.assert_(isnull(result).all()) @@ -150,7 +150,7 @@ def conv(v): # ints result = np.timedelta64(0,'ns') expected = to_timedelta(0,box=False) - self.assert_(result == expected) + self.assertEqual(result, expected) # Series expected = Series([timedelta(days=1), timedelta(days=1, seconds=1)]) @@ -166,12 +166,12 @@ def conv(v): v = timedelta(seconds=1) result = to_timedelta(v,box=False) expected = np.timedelta64(timedelta(seconds=1)) - self.assert_(result == expected) + self.assertEqual(result, expected) v = np.timedelta64(timedelta(seconds=1)) result = to_timedelta(v,box=False) expected = np.timedelta64(timedelta(seconds=1)) - self.assert_(result == expected) + self.assertEqual(result, expected) def test_to_timedelta_via_apply(self): _skip_if_numpy_not_friendly() @@ -221,10 +221,10 @@ def test_to_timedelta_on_missing_values(self): assert_series_equal(actual, expected) actual = pd.to_timedelta(np.nan) - self.assert_(actual == timedelta_NaT) + self.assertEqual(actual, timedelta_NaT) actual = pd.to_timedelta(pd.NaT) - self.assert_(actual == timedelta_NaT) + self.assertEqual(actual, timedelta_NaT) def test_timedelta_ops_with_missing_values(self): _skip_if_numpy_not_friendly() @@ -242,9 +242,9 @@ def test_timedelta_ops_with_missing_values(self): NA = np.nan actual = scalar1 + scalar1 - self.assert_(actual == scalar2) + self.assertEqual(actual, scalar2) actual = scalar2 - scalar1 - self.assert_(actual == scalar1) + self.assertEqual(actual, scalar1) actual = s1 + s1 assert_series_equal(actual, s2)
Work on #6175 to specialize asserts. A work-in-progress.
https://api.github.com/repos/pandas-dev/pandas/pulls/6198
2014-01-31T05:13:40Z
2014-02-04T09:07:22Z
null
2014-06-12T10:44:58Z
CLN/TST: #6175, specializing assert_ (WIP)
diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py index 0af3b6281530b..d1efa12953caa 100644 --- a/pandas/tseries/tests/test_daterange.py +++ b/pandas/tseries/tests/test_daterange.py @@ -364,18 +364,18 @@ def test_range_tz(self): dr = date_range(start=start, periods=3) self.assert_(dr.tz == tz('US/Eastern')) - self.assert_(dr[0] == start) - self.assert_(dr[2] == end) + self.assertEqual(dr[0], start) + self.assertEqual(dr[2], end) dr = date_range(end=end, periods=3) - self.assert_(dr.tz == tz('US/Eastern')) - self.assert_(dr[0] == start) - self.assert_(dr[2] == end) + self.assertEqual(dr.tz, tz('US/Eastern')) + self.assertEqual(dr[0], start) + self.assertEqual(dr[2], end) dr = date_range(start=start, end=end) - self.assert_(dr.tz == tz('US/Eastern')) - self.assert_(dr[0] == start) - self.assert_(dr[2] == end) + self.assertEqual(dr.tz, tz('US/Eastern')) + self.assertEqual(dr[0], start) + self.assertEqual(dr[2], end) def test_month_range_union_tz(self): _skip_if_no_pytz() diff --git a/pandas/tseries/tests/test_frequencies.py b/pandas/tseries/tests/test_frequencies.py index 8d95e22e4c6f2..b17a1c11efad7 100644 --- a/pandas/tseries/tests/test_frequencies.py +++ b/pandas/tseries/tests/test_frequencies.py @@ -99,18 +99,18 @@ def test_raise_if_too_few(self): def test_business_daily(self): index = _dti(['12/31/1998', '1/3/1999', '1/4/1999']) - self.assert_(infer_freq(index) == 'B') + self.assertEqual(infer_freq(index), 'B') def test_day(self): self._check_tick(timedelta(1), 'D') def test_day_corner(self): index = _dti(['1/1/2000', '1/2/2000', '1/3/2000']) - self.assert_(infer_freq(index) == 'D') + self.assertEqual(infer_freq(index), 'D') def test_non_datetimeindex(self): dates = to_datetime(['1/1/2000', '1/2/2000', '1/3/2000']) - self.assert_(infer_freq(dates) == 'D') + self.assertEqual(infer_freq(dates), 'D') def test_hour(self): self._check_tick(timedelta(hours=1), 'H') @@ -141,7 +141,7 @@ def _check_tick(self, base_delta, code): exp_freq = '%d%s' % (i, code) else: exp_freq = code - self.assert_(infer_freq(index) == exp_freq) + self.assertEqual(infer_freq(index), exp_freq) index = _dti([b + base_delta * 7] + [b + base_delta * j for j in range(3)]) @@ -174,7 +174,7 @@ def test_monthly(self): def test_monthly_ambiguous(self): rng = _dti(['1/31/2000', '2/29/2000', '3/31/2000']) - self.assert_(rng.inferred_freq == 'M') + self.assertEqual(rng.inferred_freq, 'M') def test_business_monthly(self): self._check_generated_range('1/1/2000', 'BM') @@ -196,7 +196,7 @@ def test_business_annual(self): def test_annual_ambiguous(self): rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002']) - self.assert_(rng.inferred_freq == 'A-JAN') + self.assertEqual(rng.inferred_freq, 'A-JAN') def _check_generated_range(self, start, freq): freq = freq.upper() @@ -220,7 +220,7 @@ def _check_generated_range(self, start, freq): gen = date_range(start, periods=5, freq=freq) index = _dti(gen.values) if not freq.startswith('Q-'): - self.assert_(infer_freq(index) == gen.freqstr) + self.assertEqual(infer_freq(index), gen.freqstr) else: inf_freq = infer_freq(index) self.assert_((inf_freq == 'Q-DEC' and @@ -236,15 +236,15 @@ def _check_generated_range(self, start, freq): def test_infer_freq(self): rng = period_range('1959Q2', '2009Q3', freq='Q') rng = Index(rng.to_timestamp('D', how='e').asobject) - self.assert_(rng.inferred_freq == 'Q-DEC') + self.assertEqual(rng.inferred_freq, 'Q-DEC') rng = period_range('1959Q2', '2009Q3', freq='Q-NOV') rng = Index(rng.to_timestamp('D', how='e').asobject) - self.assert_(rng.inferred_freq == 'Q-NOV') + self.assertEqual(rng.inferred_freq, 'Q-NOV') rng = period_range('1959Q2', '2009Q3', freq='Q-OCT') rng = Index(rng.to_timestamp('D', how='e').asobject) - self.assert_(rng.inferred_freq == 'Q-OCT') + self.assertEqual(rng.inferred_freq, 'Q-OCT') def test_not_monotonic(self): rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002']) diff --git a/pandas/tseries/tests/test_offsets.py b/pandas/tseries/tests/test_offsets.py index a3c63966948ee..6e553959f3ee5 100644 --- a/pandas/tseries/tests/test_offsets.py +++ b/pandas/tseries/tests/test_offsets.py @@ -151,7 +151,7 @@ def test_eq(self): offset2 = DateOffset(days=365) self.assert_(offset1 != offset2) - self.assert_(not (offset1 == offset2)) + self.assertNotEqual(offset1, offset2) class TestBusinessDay(TestBase): @@ -703,7 +703,7 @@ def test_onOffset(self): for week, weekday, date, expected in test_cases: offset = WeekOfMonth(week=week, weekday=weekday) - self.assert_(offset.onOffset(date) == expected) + self.assertEqual(offset.onOffset(date), expected) class TestLastWeekOfMonth(TestBase): _offset = LastWeekOfMonth @@ -722,13 +722,13 @@ def test_offset(self): offset_sat = LastWeekOfMonth(n=1, weekday=5) one_day_before = (last_sat + timedelta(days=-1)) - self.assert_(one_day_before + offset_sat == last_sat) + self.assertEqual(one_day_before + offset_sat, last_sat) one_day_after = (last_sat + timedelta(days=+1)) - self.assert_(one_day_after + offset_sat == next_sat) + self.assertEqual(one_day_after + offset_sat, next_sat) #Test On that day - self.assert_(last_sat + offset_sat == next_sat) + self.assertEqual(last_sat + offset_sat, next_sat) #### Thursday @@ -737,22 +737,22 @@ def test_offset(self): next_thurs = datetime(2013,2,28) one_day_before = last_thurs + timedelta(days=-1) - self.assert_(one_day_before + offset_thur == last_thurs) + self.assertEqual(one_day_before + offset_thur, last_thurs) one_day_after = last_thurs + timedelta(days=+1) - self.assert_(one_day_after + offset_thur == next_thurs) + self.assertEqual(one_day_after + offset_thur, next_thurs) # Test on that day - self.assert_(last_thurs + offset_thur == next_thurs) + self.assertEqual(last_thurs + offset_thur, next_thurs) three_before = last_thurs + timedelta(days=-3) - self.assert_(three_before + offset_thur == last_thurs) + self.assertEqual(three_before + offset_thur, last_thurs) two_after = last_thurs + timedelta(days=+2) - self.assert_(two_after + offset_thur == next_thurs) + self.assertEqual(two_after + offset_thur, next_thurs) offset_sunday = LastWeekOfMonth(n=1, weekday=WeekDay.SUN) - self.assert_(datetime(2013,7,31) + offset_sunday == datetime(2013,8,25)) + self.assertEqual(datetime(2013,7,31) + offset_sunday, datetime(2013,8,25)) def test_onOffset(self): test_cases = [ diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index ca0eba59fe5fe..21e9756da9ad6 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -465,25 +465,25 @@ def test_constructor_corner(self): def test_constructor_infer_freq(self): p = Period('2007-01-01') - self.assert_(p.freq == 'D') + self.assertEqual(p.freq, 'D') p = Period('2007-01-01 07') - self.assert_(p.freq == 'H') + self.assertEqual(p.freq, 'H') p = Period('2007-01-01 07:10') - self.assert_(p.freq == 'T') + self.assertEqual(p.freq, 'T') p = Period('2007-01-01 07:10:15') - self.assert_(p.freq == 'S') + self.assertEqual(p.freq, 'S') p = Period('2007-01-01 07:10:15.123') - self.assert_(p.freq == 'L') + self.assertEqual(p.freq, 'L') p = Period('2007-01-01 07:10:15.123000') - self.assert_(p.freq == 'L') + self.assertEqual(p.freq, 'L') p = Period('2007-01-01 07:10:15.123400') - self.assert_(p.freq == 'U') + self.assertEqual(p.freq, 'U') def noWrap(item): @@ -1368,7 +1368,7 @@ def test_indexing(self): s = Series(randn(10), index=index) expected = s[index[0]] result = s.iat[0] - self.assert_(expected == result) + self.assertEqual(expected, result) def test_frame_setitem(self): rng = period_range('1/1/2000', periods=5) @@ -1772,12 +1772,12 @@ def test_asfreq_ts(self): result = ts.asfreq('D', how='end') df_result = df.asfreq('D', how='end') exp_index = index.asfreq('D', how='end') - self.assert_(len(result) == len(ts)) + self.assertEqual(len(result), len(ts)) self.assert_(result.index.equals(exp_index)) self.assert_(df_result.index.equals(exp_index)) result = ts.asfreq('D', how='start') - self.assert_(len(result) == len(ts)) + self.assertEqual(len(result), len(ts)) self.assert_(result.index.equals(index.asfreq('D', how='start'))) def test_badinput(self): @@ -1818,7 +1818,7 @@ def test_pindex_qaccess(self): pi = PeriodIndex(['2Q05', '3Q05', '4Q05', '1Q06', '2Q06'], freq='Q') s = Series(np.random.rand(len(pi)), index=pi).cumsum() # Todo: fix these accessors! - self.assert_(s['05Q4'] == s[2]) + self.assertEqual(s['05Q4'], s[2]) def test_period_dt64_round_trip(self): dti = date_range('1/1/2000', '1/7/2002', freq='B') @@ -1843,21 +1843,21 @@ def test_to_period_quarterlyish(self): for off in offsets: rng = date_range('01-Jan-2012', periods=8, freq=off) prng = rng.to_period() - self.assert_(prng.freq == 'Q-DEC') + self.assertEqual(prng.freq, 'Q-DEC') def test_to_period_annualish(self): offsets = ['BA', 'AS', 'BAS'] for off in offsets: rng = date_range('01-Jan-2012', periods=8, freq=off) prng = rng.to_period() - self.assert_(prng.freq == 'A-DEC') + self.assertEqual(prng.freq, 'A-DEC') def test_to_period_monthish(self): offsets = ['MS', 'EOM', 'BM'] for off in offsets: rng = date_range('01-Jan-2012', periods=8, freq=off) prng = rng.to_period() - self.assert_(prng.freq == 'M') + self.assertEqual(prng.freq, 'M') def test_no_multiples(self): self.assertRaises(ValueError, period_range, '1989Q3', periods=10, @@ -1894,7 +1894,7 @@ def test_iteration(self): result = list(index) tm.assert_isinstance(result[0], Period) - self.assert_(result[0].freq == index.freq) + self.assertEqual(result[0].freq, index.freq) def test_take(self): index = PeriodIndex(start='1/1/10', end='12/31/12', freq='D') @@ -1902,9 +1902,9 @@ def test_take(self): taken = index.take([5, 6, 8, 12]) taken2 = index[[5, 6, 8, 12]] tm.assert_isinstance(taken, PeriodIndex) - self.assert_(taken.freq == index.freq) + self.assertEqual(taken.freq, index.freq) tm.assert_isinstance(taken2, PeriodIndex) - self.assert_(taken2.freq == index.freq) + self.assertEqual(taken2.freq, index.freq) def test_joins(self): index = period_range('1/1/2000', '1/20/2000', freq='D') @@ -1913,7 +1913,7 @@ def test_joins(self): joined = index.join(index[:-5], how=kind) tm.assert_isinstance(joined, PeriodIndex) - self.assert_(joined.freq == index.freq) + self.assertEqual(joined.freq, index.freq) def test_join_self(self): index = period_range('1/1/2000', '1/20/2000', freq='D') @@ -2128,7 +2128,7 @@ def test_get_loc_msg(self): try: idx.get_loc(bad_period) except KeyError as inst: - self.assert_(inst.args[0] == bad_period) + self.assertEqual(inst.args[0], bad_period) def test_append_concat(self): # #1815
Helping with the specialization request. Work-in-progress. Updated tests pass locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/6197
2014-01-31T03:47:29Z
2014-02-04T09:11:25Z
null
2014-02-18T03:25:07Z
CLN: Small spelling fixes in find_undoc_args.py
diff --git a/scripts/find_undoc_args.py b/scripts/find_undoc_args.py index f6bcd43185fa6..f00273bc75199 100755 --- a/scripts/find_undoc_args.py +++ b/scripts/find_undoc_args.py @@ -19,7 +19,7 @@ parser.add_argument('-m', '--module', metavar='MODULE', type=str,required=True, help='name of package to import and examine',action='store') parser.add_argument('-G', '--github_repo', metavar='REPO', type=str,required=False, - help='github project where the the coe lives, e.g. "pydata/pandas"', + help='github project where the the code lives, e.g. "pydata/pandas"', default=None,action='store') args = parser.parse_args() @@ -109,7 +109,7 @@ def main(): if not args.path: args.path=os.path.dirname(module.__file__) collect=[cmp_docstring_sig(e) for e in entry_gen(module,module.__name__)] - # only include if there are missing arguments in the docstring (less false positives) + # only include if there are missing arguments in the docstring (fewer false positives) # and there are at least some documented arguments collect = [e for e in collect if e.undoc_names and len(e.undoc_names) != e.nsig_names] collect.sort(key=lambda x:x.path)
Cleaning up some small typos.
https://api.github.com/repos/pandas-dev/pandas/pulls/6196
2014-01-31T02:11:32Z
2014-01-31T03:53:49Z
2014-01-31T03:53:49Z
2014-06-24T21:34:54Z
DOC: contributing.rst, document fast doc building
diff --git a/doc/README.rst b/doc/README.rst index 29c4113f90909..a1e32c7014648 100644 --- a/doc/README.rst +++ b/doc/README.rst @@ -133,6 +133,16 @@ If you want to do a full clean build, do:: python make.py build +Staring with 0.13.1 you can tell ``make.py`` to compile only a single section +of the docs, greatly reducing the turn-around time for checking your changes. + + python make.py --no-api # omit autosummary and api section + python make.py --single indexing # compile the docs with only a single + # section, that which is in indexing.rst + +For comparision, a full doc build may take 10 minutes. a ``-no-api`` build +may take 3 minutes and a single section may take 15 seconds. + Where to start? ---------------
@jreback, don't say you didn't know about this feature later.
https://api.github.com/repos/pandas-dev/pandas/pulls/6193
2014-01-30T21:54:28Z
2014-01-30T21:54:38Z
2014-01-30T21:54:38Z
2014-06-26T23:16:21Z
BLD/TST: @network, inspect formatted expection rather then str(e)
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 378befb0c0922..a044b388c00c4 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -145,7 +145,6 @@ def test_get_quote_string(self): @network def test_get_quote_stringlist(self): - raise nose.SkipTest('unreliable test') df = web.get_quote_yahoo(['GOOG', 'AAPL', 'GOOG']) assert_series_equal(df.ix[0], df.ix[2]) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index c1d06eac4abf5..41bad7f87f0da 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -12,6 +12,7 @@ import subprocess import locale import unittest +import traceback from datetime import datetime from functools import wraps, partial @@ -978,9 +979,10 @@ def dec(f): # skip tests on exceptions with this message _network_error_messages = ( - 'urlopen error timed out', - 'timeout: timed out', - 'socket.timeout: timed out', + # 'urlopen error timed out', + # 'timeout: timed out', + # 'socket.timeout: timed out', + 'timed out', 'HTTP Error 503: Service Unavailable', ) @@ -1138,7 +1140,12 @@ def wrapper(*args, **kwargs): raise SkipTest("Skipping test due to known errno" " and error %s" % e) - if any([m.lower() in str(e).lower() for m in _skip_on_messages]): + try: + e_str = traceback.format_exc(e) + except: + e_str = str(e) + + if any([m.lower() in e_str.lower() for m in _skip_on_messages]): raise SkipTest("Skipping test because exception message is known" " and error %s" % e)
@jreback, here's the next attempt. I guess the output we see from pdb and str(e) are not the same thing, so this compares the strings against a properly formatted exception (I ommited the traceback, shouldn't be relevent). I'l rerun this on travis 15 times or so before merging. https://github.com/pydata/pandas/issues/6144
https://api.github.com/repos/pandas-dev/pandas/pulls/6192
2014-01-30T21:46:29Z
2014-01-30T23:40:28Z
2014-01-30T23:40:28Z
2014-06-26T02:15:16Z
TST: buggy tests on sparc/debian platforms
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index aa553e93e72b8..649d391820147 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -71,7 +71,6 @@ def test_read_dta1(self): def test_read_dta2(self): if LooseVersion(sys.version) < '2.7': raise nose.SkipTest('datetime interp under 2.6 is faulty') - skip_if_not_little_endian() expected = DataFrame.from_records( [ @@ -117,8 +116,10 @@ def test_read_dta2(self): np.testing.assert_equal( len(w), 1) # should get a warning for that format. - tm.assert_frame_equal(parsed, expected) - tm.assert_frame_equal(parsed_13, expected) + # buggy test because of the NaT comparison on certain platforms + # + #tm.assert_frame_equal(parsed, expected) + #tm.assert_frame_equal(parsed_13, expected) def test_read_dta3(self): parsed = self.read_dta(self.dta3) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index f57f29e876000..210e56e453b8f 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3974,7 +3974,11 @@ def test_from_records_with_datetimes(self): arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] dtypes = [('EXPIRY', '<M8[ns]')] - recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + try: + recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + except (ValueError): + raise nose.SkipTest("known failure of numpy rec array creation") + result = DataFrame.from_records(recarray) assert_frame_equal(result,expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/6191
2014-01-30T20:56:56Z
2014-01-30T21:13:10Z
2014-01-30T21:13:10Z
2014-06-25T23:36:28Z
ENH: Import testing into main namespace.
diff --git a/pandas/__init__.py b/pandas/__init__.py index ff5588e778284..442c6b08c9dce 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -51,3 +51,4 @@ from pandas.tools.tile import cut, qcut from pandas.core.reshape import melt from pandas.util.print_versions import show_versions +import pandas.util.testing
Unfortunately I won't be able to use this in production until 2020 when we require 0.14, but this would make some things a bit easier for projects that use pandas as a library.
https://api.github.com/repos/pandas-dev/pandas/pulls/6188
2014-01-30T14:54:52Z
2014-02-18T20:07:16Z
2014-02-18T20:07:16Z
2014-07-16T08:50:53Z
BLD: ipython_directive, handle non-ascii execution results
diff --git a/doc/source/conf.py b/doc/source/conf.py index bda0601da98b4..563c93d2c2234 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -285,6 +285,16 @@ 'wiki': ('https://github.com/pydata/pandas/wiki/%s', 'wiki ')} +ipython_exec_lines = [ + 'import numpy as np', + 'import pandas as pd', + # This ensures correct rendering on system with console encoding != utf8 + # (windows). It forces pandas to encode it's output reprs using utf8 + # whereever the docs are built. The docs' target is the browser, not + # the console, so this is fine. + 'pd.options.display.encoding="utf8"' + ] + # remove the docstring of the flags attribute (inherited from numpy ndarray) # because these give doc build errors (see GH issue 5331) def remove_flags_docstring(app, what, name, obj, options, lines): diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py index fab7d6402fb98..86050a346f4f3 100644 --- a/doc/sphinxext/ipython_directive.py +++ b/doc/sphinxext/ipython_directive.py @@ -99,6 +99,7 @@ - Skipper Seabold, refactoring, cleanups, pure python addition """ from __future__ import print_function +from __future__ import unicode_literals #----------------------------------------------------------------------------- # Imports @@ -245,12 +246,35 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout): return block +class DecodingStringIO(StringIO, object): + def __init__(self,buf='',encodings=('utf8',), *args, **kwds): + super(DecodingStringIO, self).__init__(buf, *args, **kwds) + self.set_encodings(encodings) + + def set_encodings(self, encodings): + self.encodings = encodings + + def write(self,data): + #py 3 compat here + if isinstance(data,unicode): + return super(DecodingStringIO, self).write(data) + else: + for enc in self.encodings: + try: + data = data.decode(enc) + return super(DecodingStringIO, self).write(data) + except : + pass + # default to brute utf8 if no encoding succeded + return super(DecodingStringIO, self).write(data.decode('utf8', 'replace')) + + class EmbeddedSphinxShell(object): """An embedded IPython instance to run inside Sphinx""" def __init__(self, exec_lines=None,state=None): - self.cout = StringIO() + self.cout = DecodingStringIO(u'') if exec_lines is None: exec_lines = [] @@ -323,14 +347,6 @@ def process_input_line(self, line, store_history=True): self.IP.run_cell(source_raw, store_history=store_history) finally: sys.stdout = stdout - buflist = self.cout.buflist - for i in range(len(buflist)): - try: - # print(buflist[i]) - if not isinstance(buflist[i], unicode): - buflist[i] = buflist[i].decode('utf8','replace') - except: - pass def process_image(self, decorator): """ @@ -380,11 +396,12 @@ def process_input(self, data, input_prompt, lineno): is_savefig = decorator is not None and \ decorator.startswith('@savefig') - # #>>> required for cython magic to work - # def _remove_first_space_if_any(line): - # return line[1:] if line.startswith(' ') else line + # set the encodings to be used by DecodingStringIO + # to convert the execution output into unicode if + # needed. this attrib is set by IpythonDirective.run() + # based on the specified block options, defaulting to ['ut + self.cout.set_encodings(self.output_encoding) - # input_lines = lmap(_remove_first_space_if_any, input.split('\n')) input_lines = input.split('\n') if len(input_lines) > 1: @@ -716,7 +733,8 @@ class IPythonDirective(Directive): 'verbatim' : directives.flag, 'doctest' : directives.flag, 'okexcept': directives.flag, - 'okwarning': directives.flag + 'okwarning': directives.flag, + 'output_encoding': directives.unchanged_required } shell = None @@ -817,6 +835,8 @@ def run(self): self.shell.is_okexcept = 'okexcept' in options self.shell.is_okwarning = 'okwarning' in options + self.shell.output_encoding = [options.get('output_encoding', 'utf8')] + # handle pure python code if 'python' in self.arguments: content = self.content
@jorisvandenbossche I think this is a clean solution to the non-utf8 output problem we discussed, specifically the example in io.rst. This PR should produce the right output on windows and be more amenable to py3 compat work too. If you confirm that it's good I feel this is clean enough to try and get upstream, completing the upstreaming effort. related #5530, https://github.com/pydata/pandas/pull/5925#issuecomment-32407859
https://api.github.com/repos/pandas-dev/pandas/pulls/6185
2014-01-30T04:57:14Z
2014-01-31T02:02:18Z
2014-01-31T02:02:18Z
2014-07-16T08:50:51Z
TST: fix test_reshape.py
diff --git a/pandas/tests/test_reshape.py b/pandas/tests/test_reshape.py index b48fb29de0289..b04fb979e6c8e 100644 --- a/pandas/tests/test_reshape.py +++ b/pandas/tests/test_reshape.py @@ -119,7 +119,7 @@ def test_custom_var_and_value_name(self): var_name=self.var_name, value_name=self.value_name) self.assertEqual(result17.columns.tolist(), ['id1', 'id2', 'var', 'val']) - result18 = melt(df, id_vars=['id1', 'id2'], + result18 = melt(self.df, id_vars=['id1', 'id2'], value_vars='A', var_name=self.var_name, value_name=self.value_name) self.assertEqual(result18.columns.tolist(), ['id1', 'id2', 'var', 'val']) @@ -127,14 +127,14 @@ def test_custom_var_and_value_name(self): value_vars=['A', 'B'], var_name=self.var_name, value_name=self.value_name) expected19 = DataFrame({'id1': self.df['id1'].tolist() * 2, 'id2': self.df['id2'].tolist() * 2, - var_name: ['A']*10 + ['B']*10, - value_name: self.df['A'].tolist() + self.df['B'].tolist()}, + self.var_name: ['A']*10 + ['B']*10, + self.value_name: self.df['A'].tolist() + self.df['B'].tolist()}, columns=['id1', 'id2', self.var_name, self.value_name]) tm.assert_frame_equal(result19, expected19) - def test_custom_var_and_value_name(self): - self.df.columns.name = 'foo' - result20 = melt(self.df) + df20 = self.df.copy() + df20.columns.name = 'foo' + result20 = melt(df20) self.assertEqual(result20.columns.tolist(), ['foo', 'value']) def test_col_level(self):
Fixes #6081 issues in test_reshape.py -- most of `test_custom_var_and_value_name` wasn't being executed (hiding some bugs in the test code too) because it was being shadowed by another method of the same name.
https://api.github.com/repos/pandas-dev/pandas/pulls/6184
2014-01-30T04:44:14Z
2014-01-31T14:53:15Z
2014-01-31T14:53:15Z
2014-07-16T08:50:50Z
BLD: commit automated cron script for setting up linux/py2 doc build env
diff --git a/ci/cron/go_doc.sh b/ci/cron/go_doc.sh new file mode 100755 index 0000000000000..89659577d0e7f --- /dev/null +++ b/ci/cron/go_doc.sh @@ -0,0 +1,99 @@ +#!/bin/bash + +# This is a one-command cron job for setting up +# a virtualenv-based, linux-based, py2-based environment +# for building the Pandas documentation. +# +# The first run will install all required deps from pypi +# into the venv including monsters like scipy. +# You may want to set it up yourself to speed up the +# process. +# +# This is meant to be run as a cron job under a dedicated +# user account whose HOME directory contains this script. +# a CI directory will be created under it and all files +# stored within it. +# +# The hardcoded dep versions will gradually become obsolete +# You may need to tweak them +# +# @y-p, Jan/2014 + +# disto latex is sometimes finicky. Optionall use +# a local texlive install +export PATH=/mnt/debian/texlive/2013/bin/x86_64-linux:$PATH + +# Having ccache will speed things up +export PATH=/usr/lib64/ccache/:$PATH + +# limit disk usage +ccache -M 200M + +BASEDIR="$HOME/CI" +REPO_URL="https://github.com/pydata/pandas" +REPO_LOC="$BASEDIR/pandas" + +if [ ! -d $BASEDIR ]; then + mkdir -p $BASEDIR + virtualenv $BASEDIR/venv +fi + +source $BASEDIR/venv/bin/activate + +pip install numpy==1.7.2 +pip install cython==0.20.0 +pip install python-dateutil==2.2 +pip install --pre pytz==2013.9 +pip install sphinx==1.1.3 +pip install numexpr==2.2.2 + +pip install matplotlib==1.3.0 +pip install lxml==3.2.5 +pip install beautifulsoup4==4.3.2 +pip install html5lib==0.99 + +# You'll need R as well +pip install rpy2==2.3.9 + +pip install tables==3.0.0 +pip install bottleneck==0.7.0 +pip install ipython==0.13.2 + +# only if you have too +pip install scipy==0.13.2 + +pip install openpyxl==1.6.2 +pip install xlrd==0.9.2 +pip install xlwt==0.7.5 +pip install xlsxwriter==0.5.1 +pip install sqlalchemy==0.8.3 + +if [ ! -d "$REPO_LOC" ]; then + git clone "$REPO_URL" "$REPO_LOC" +fi + +cd "$REPO_LOC" +git reset --hard +git clean -df +git checkout master +git pull origin +make + +source $BASEDIR/venv/bin/activate +export PATH="/usr/lib64/ccache/:$PATH" +pip uninstall pandas -yq +pip install "$REPO_LOC" + +cd "$REPO_LOC"/doc + +python make.py clean +python make.py html +if [ ! $? == 0 ]; then + exit 1 +fi +python make.py zip_html +# usually requires manual intervention +# python make.py latex + +# If you have access: +# python make.py upload_dev
I wrote it, so I guess others might find it useful as well. It's actually a single script for setting up a full py2 venv for pandas with all deps as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/6180
2014-01-30T01:38:26Z
2014-01-30T01:38:33Z
2014-01-30T01:38:33Z
2014-06-16T19:14:53Z
BLD/DOC: Faster doc building via jinja2 and conf.py logic
diff --git a/.gitignore b/.gitignore index edc6a54cf4345..25f1efd830f5c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ doc/source/generated doc/source/_static doc/source/vbench doc/source/vbench.rst +doc/source/index.rst doc/build/html/index.html *flymake* scikits diff --git a/doc/make.py b/doc/make.py index 3ba48799fd430..16ffdc49edbdc 100755 --- a/doc/make.py +++ b/doc/make.py @@ -21,6 +21,8 @@ import shutil import sys import sphinx +import argparse +import jinja2 os.environ['PYTHONPATH'] = '..' @@ -77,7 +79,7 @@ def build_pandas(): os.system('python setup.py clean') os.system('python setup.py build_ext --inplace') os.chdir('doc') - + def build_prev(ver): if os.system('git checkout v%s' % ver) != 1: os.chdir('..') @@ -267,22 +269,77 @@ def _get_config(): # current_dir = os.getcwd() # os.chdir(os.path.dirname(os.path.join(current_dir, __file__))) -if len(sys.argv) > 2: - ftype = sys.argv[1] - ver = sys.argv[2] - - if ftype == 'build_previous': - build_prev(ver) - if ftype == 'upload_previous': - upload_prev(ver) -elif len(sys.argv) > 1: - for arg in sys.argv[1:]: - func = funcd.get(arg) - if func is None: - raise SystemExit('Do not know how to handle %s; valid args are %s' % ( - arg, list(funcd.keys()))) - func() -else: - small_docs = False - all() +import argparse +argparser = argparse.ArgumentParser(description=""" +Pandas documentation builder +""".strip()) + +# argparser.add_argument('-arg_name', '--arg_name', +# metavar='label for arg help', +# type=str|etc, +# nargs='N|*|?|+|argparse.REMAINDER', +# required=False, +# #choices='abc', +# help='help string', +# action='store|store_true') + +# args = argparser.parse_args() + +#print args.accumulate(args.integers) + +def generate_index(api=True, single=False, **kwds): + from jinja2 import Template + with open("source/index.rst.template") as f: + t = Template(f.read()) + + with open("source/index.rst","wb") as f: + f.write(t.render(api=api,single=single,**kwds)) + +import argparse +argparser = argparse.ArgumentParser(description="Pandas documentation builder", + epilog="Targets : %s" % funcd.keys()) + +argparser.add_argument('--no-api', + default=False, + help='Ommit api and autosummary', + action='store_true') +argparser.add_argument('--single', + metavar='FILENAME', + type=str, + default=False, + help='filename of section to compile, e.g. "indexing"') + +def main(): + args, unknown = argparser.parse_known_args() + sys.argv = [sys.argv[0]] + unknown + if args.single: + args.single = os.path.basename(args.single).split(".rst")[0] + + if 'clean' in unknown: + args.single=False + + generate_index(api=not args.no_api and not args.single, single=args.single) + + if len(sys.argv) > 2: + ftype = sys.argv[1] + ver = sys.argv[2] + + if ftype == 'build_previous': + build_prev(ver) + if ftype == 'upload_previous': + upload_prev(ver) + elif len(sys.argv) == 2: + for arg in sys.argv[1:]: + func = funcd.get(arg) + if func is None: + raise SystemExit('Do not know how to handle %s; valid args are %s' % ( + arg, list(funcd.keys()))) + func() + else: + small_docs = False + all() # os.chdir(current_dir) + +if __name__ == '__main__': + import sys + sys.exit(main()) diff --git a/doc/source/conf.py b/doc/source/conf.py index 30d47d0a306a0..bda0601da98b4 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -12,6 +12,7 @@ import sys import os +import re from pandas.compat import u # If extensions (or modules to document with autodoc) are in another directory, @@ -46,11 +47,50 @@ 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', - 'sphinx.ext.autosummary', 'matplotlib.sphinxext.only_directives', 'matplotlib.sphinxext.plot_directive', ] + + +with open("index.rst") as f: + lines = f.readlines() + +# only include the slow autosummary feature if we're building the API section +# of the docs + +# JP: added from sphinxdocs +autosummary_generate = False + +if any([re.match("\s*api\s*",l) for l in lines]): + extensions.append('sphinx.ext.autosummary') + autosummary_generate = True + +ds = [] +for f in os.listdir(os.path.dirname(__file__)): + if (not f.endswith(('.rst'))) or (f.startswith('.')) or os.path.basename(f) == 'index.rst': + continue + + _f = f.split('.rst')[0] + if not any([re.match("\s*%s\s*$" % _f,l) for l in lines]): + ds.append(f) + +if ds: + print("I'm about to DELETE the following:\n%s\n" % list(sorted(ds))) + sys.stdout.write("WARNING: I'd like to delete those to speed up proccesing (yes/no)? ") + answer = raw_input() + + if answer.lower().strip() in ('y','yes'): + for f in ds: + f = os.path.join(os.path.join(os.path.dirname(__file__),f)) + f= os.path.abspath(f) + try: + print("Deleting %s" % f) + os.unlink(f) + except: + print("Error deleting %s" % f) + pass + # Add any paths that contain templates here, relative to this directory. templates_path = ['../_templates'] @@ -80,9 +120,6 @@ # The full version, including alpha/beta/rc tags. release = version -# JP: added from sphinxdocs -autosummary_generate = True - # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None diff --git a/doc/source/index.rst b/doc/source/index.rst.template similarity index 96% rename from doc/source/index.rst rename to doc/source/index.rst.template index c2d4d338d3367..01f654192b549 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst.template @@ -109,6 +109,10 @@ See the package overview for more detail about what's in the library. .. toctree:: :maxdepth: 3 + {% if single -%} + {{ single }} + {% endif -%} + {%if not single -%} whatsnew install faq @@ -136,6 +140,11 @@ See the package overview for more detail about what's in the library. ecosystem comparison_with_r comparison_with_sql + {% endif -%} + {% if api -%} api + {% endif -%} + {%if not single -%} contributing release + {% endif -%}
``` ~/src/pandas/doc/ λ ./make.py clean ;time ./make.py ; 993.28s ``` ``` ~/src/pandas/doc/ λ ./make.py clean ;time ./make.py --no-api ; 255.12s ``` ``` ~/src/pandas/doc/ λ ./make.py clean ;time ./make.py --single indexing ; 8.08s ``` @jorisvandenbossche , please review.
https://api.github.com/repos/pandas-dev/pandas/pulls/6179
2014-01-30T01:15:30Z
2014-01-30T19:40:23Z
2014-01-30T19:40:23Z
2014-06-12T20:04:58Z
ENH: select column/coordinates/multiple with start/stop/selection
diff --git a/doc/source/release.rst b/doc/source/release.rst index d3814ab324e92..4291ed1b6c357 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -60,6 +60,7 @@ API Changes indexed. These will be excluded. This will make pandas conform more with pandas/numpy indexing of out-of-bounds values. A single indexer that is out-of-bounds and drops the dimensions of the object will still raise ``IndexError`` (:issue:`6296`) +- ``select_as_multiple`` will always raise a ``KeyError``, when a key or the selector is not found (:issue:`6177`) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ @@ -86,6 +87,9 @@ Bug Fixes - Bug in conversion of a string types to a DatetimeIndex with a specified frequency (:issue:`6273`, :issue:`6274`) - Bug in ``eval`` where type-promotion failed for large expressions (:issue:`6205`) - Bug in interpolate with inplace=True (:issue:`6281`) +- ``HDFStore.remove`` now handles start and stop (:issue:`6177`) +- ``HDFStore.select_as_multiple`` handles start and stop the same way as ``select`` (:issue:`6177`) +- ``HDFStore.select_as_coordinates`` and ``select_column`` works where clauses that result in filters (:issue:`6177`) pandas 0.13.1 ------------- diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d0dd292adfe67..85a9cf4ea0f9f 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -724,8 +724,9 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, Exceptions ---------- - raise if any of the keys don't refer to tables or if they are not ALL - THE SAME DIMENSIONS + raises KeyError if keys or selector is not found or keys is empty + raises TypeError if keys is not a list or tuple + raises ValueError if the tables are not ALL THE SAME DIMENSIONS """ # default to single select @@ -748,12 +749,13 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, # collect the tables tbls = [self.get_storer(k) for k in keys] + s = self.get_storer(selector) # validate rows nrows = None - for t, k in zip(tbls, keys): + for t, k in itertools.chain([(s,selector)], zip(tbls, keys)): if t is None: - raise TypeError("Invalid table [%s]" % k) + raise KeyError("Invalid table [%s]" % k) if not t.is_table: raise TypeError( "object [%s] is not a table, and cannot be used in all " @@ -766,22 +768,17 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, raise ValueError( "all tables must have exactly the same nrows!") - # select coordinates from the selector table - try: - c = self.select_as_coordinates( - selector, where, start=start, stop=stop) - nrows = len(c) - except Exception: - raise ValueError("invalid selector [%s]" % selector) + # axis is the concentation axes + axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0] def func(_start, _stop): - - # collect the returns objs - objs = [t.read(where=c[_start:_stop], columns=columns) - for t in tbls] - - # axis is the concentation axes - axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0] + if where is not None: + c = s.read_coordinates(where=where, start=_start, stop=_stop, **kwargs) + else: + c = None + + objs = [t.read(where=c, start=_start, stop=_stop, + columns=columns, **kwargs) for t in tbls] # concat and return return concat(objs, axis=axis, @@ -860,7 +857,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 +2136,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 @@ -3381,9 +3376,15 @@ 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 Index(self.selection.select_coords()) + coords = self.selection.select_coords() + if self.selection.filter is not None: + for field, op, filt in self.selection.filter.format(): + data = self.read_column(field, start=coords.min(), stop=coords.max()+1) + coords = coords[op(data.iloc[coords-coords.min()], filt).values] - def read_column(self, column, where=None, **kwargs): + return Index(coords) + + def read_column(self, column, where=None, start=None, stop=None, **kwargs): """return a single column from the table, generally only indexables are interesting """ @@ -3411,7 +3412,7 @@ def read_column(self, column, where=None, **kwargs): # column must be an indexable or a data column c = getattr(self.table.cols, column) a.set_info(self.info) - return Series(a.convert(c[:], nan_rep=self.nan_rep, + return Series(a.convert(c[start:stop], nan_rep=self.nan_rep, encoding=self.encoding).take_data()) raise KeyError("column [%s] not found in the table" % column) @@ -3712,12 +3713,19 @@ 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: + # pytables<3.0 would remove a single row with stop=None + if stop is None: + stop = self.nrows + nrows = self.table.removeRows(start=start, stop=stop) + self.table.flush() return nrows # infer the data kind @@ -3726,7 +3734,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 @@ -4303,13 +4311,25 @@ def select_coords(self): """ generate the selection """ - if self.condition is None: - return np.arange(self.table.nrows) + start, stop = self.start, self.stop + nrows = self.table.nrows + if start is None: + start = 0 + elif start < 0: + start += nrows + if self.stop is None: + stop = nrows + elif stop < 0: + stop += nrows - return self.table.table.getWhereList(self.condition.format(), - start=self.start, stop=self.stop, - sort=True) + if self.condition is not None: + return self.table.table.getWhereList(self.condition.format(), + start=start, stop=stop, + sort=True) + elif self.coordinates is not None: + return self.coordinates + return np.arange(start, stop) # utilities ### diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 3c8e40fb1566a..3c5662a6fe268 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -2195,6 +2195,69 @@ def test_remove_where(self): # self.assertRaises(ValueError, store.remove, # 'wp2', [('column', ['A', 'D'])]) + def test_remove_startstop(self): + # GH #4835 and #6177 + + 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: @@ -3449,6 +3512,25 @@ def f(): result = store.select_column('df3', 'string') tm.assert_almost_equal(result.values, df3['string'].values) + # start/stop + result = store.select_column('df3', 'string', start=2) + tm.assert_almost_equal(result.values, df3['string'].values[2:]) + + result = store.select_column('df3', 'string', start=-2) + tm.assert_almost_equal(result.values, df3['string'].values[-2:]) + + result = store.select_column('df3', 'string', stop=2) + tm.assert_almost_equal(result.values, df3['string'].values[:2]) + + result = store.select_column('df3', 'string', stop=-2) + tm.assert_almost_equal(result.values, df3['string'].values[:-2]) + + result = store.select_column('df3', 'string', start=2, stop=-2) + tm.assert_almost_equal(result.values, df3['string'].values[2:-2]) + + result = store.select_column('df3', 'string', start=-2, stop=2) + tm.assert_almost_equal(result.values, df3['string'].values[-2:2]) + def test_coordinates(self): df = tm.makeTimeDataFrame() @@ -3519,6 +3601,12 @@ def test_coordinates(self): self.assertRaises(ValueError, store.select, 'df',where=np.arange(len(df)),start=5) self.assertRaises(ValueError, store.select, 'df',where=np.arange(len(df)),start=5,stop=10) + # selection with filter + selection = date_range('20000101',periods=500) + result = store.select('df', where='index in selection') + expected = df[df.index.isin(selection)] + tm.assert_frame_equal(result,expected) + # list df = DataFrame(np.random.randn(10,2)) store.append('df2',df) @@ -3533,6 +3621,11 @@ def test_coordinates(self): expected = df.loc[where] tm.assert_frame_equal(result,expected) + # start/stop + result = store.select('df2', start=5, stop=10) + expected = df[5:10] + tm.assert_frame_equal(result,expected) + def test_append_to_multiple(self): df1 = tm.makeTimeDataFrame() df2 = tm.makeTimeDataFrame().rename(columns=lambda x: "%s_2" % x) @@ -3603,11 +3696,11 @@ def test_select_as_multiple(self): None, where=['A>0', 'B>0'], selector='df1') self.assertRaises(Exception, store.select_as_multiple, [None], where=['A>0', 'B>0'], selector='df1') - self.assertRaises(TypeError, store.select_as_multiple, + self.assertRaises(KeyError, store.select_as_multiple, ['df1','df3'], where=['A>0', 'B>0'], selector='df1') self.assertRaises(KeyError, store.select_as_multiple, ['df3'], where=['A>0', 'B>0'], selector='df1') - self.assertRaises(ValueError, store.select_as_multiple, + self.assertRaises(KeyError, store.select_as_multiple, ['df1','df2'], where=['A>0', 'B>0'], selector='df4') # default select
select_as_multiple/column/coordinate and remove behaves strange on combinations of where clauses and start/stop keyword arguments so I started fixing this. I changed select_as_multiple to select coordinates inside the TableIterator, so it will work on large tables. Moreover select_as_multiple always throws a KeyError when either a key or the selector is not available in the file. Closes #4835.
https://api.github.com/repos/pandas-dev/pandas/pulls/6177
2014-01-29T20:47:11Z
2014-02-09T13:31:35Z
2014-02-09T13:31:35Z
2014-06-13T12:19:31Z
CLN: clear up some cython warnings
diff --git a/pandas/algos.pyx b/pandas/algos.pyx index d916de32b7cd3..64df9df0205ff 100644 --- a/pandas/algos.pyx +++ b/pandas/algos.pyx @@ -1630,7 +1630,8 @@ def roll_generic(ndarray[float64_t, cast=True] input, int win, int minp, object func): cdef ndarray[double_t] output, counts, bufarr cdef Py_ssize_t i, n - cdef float64_t *buf, *oldbuf + cdef float64_t *buf + cdef float64_t *oldbuf if not input.flags.c_contiguous: input = input.copy('C') diff --git a/pandas/src/generate_code.py b/pandas/src/generate_code.py index 70b68eae7564a..45c40ee7b900f 100644 --- a/pandas/src/generate_code.py +++ b/pandas/src/generate_code.py @@ -1,5 +1,8 @@ from __future__ import print_function -from pandas.compat import range, cStringIO as StringIO +# we only need to be able to run this file on 2.7 +# don't introduce a pandas/pandas.compat import +# or we get a bootstrapping problem +from StringIO import StringIO import os header = """ @@ -92,7 +95,8 @@ def take_2d_axis0_%(name)s_%(dest)s(ndarray[%(c_type_in)s, ndim=2] values, IF %(can_copy)s: cdef: - %(c_type_out)s *v, *o + %(c_type_out)s *v + %(c_type_out)s *o #GH3130 if (values.strides[1] == out.strides[1] and @@ -141,7 +145,8 @@ def take_2d_axis1_%(name)s_%(dest)s(ndarray[%(c_type_in)s, ndim=2] values, IF %(can_copy)s: cdef: - %(c_type_out)s *v, *o + %(c_type_out)s *v + %(c_type_out)s *o #GH3130 if (values.strides[0] == out.strides[0] and diff --git a/pandas/src/generated.pyx b/pandas/src/generated.pyx index 985781ee6b70a..22f56ef14267e 100644 --- a/pandas/src/generated.pyx +++ b/pandas/src/generated.pyx @@ -2596,8 +2596,10 @@ def take_2d_axis0_bool_bool(ndarray[uint8_t, ndim=2] values, IF True: cdef: - uint8_t *v, *o + uint8_t *v + uint8_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(uint8_t) and sizeof(uint8_t) * n >= 256): @@ -2639,8 +2641,10 @@ def take_2d_axis0_bool_object(ndarray[uint8_t, ndim=2] values, IF False: cdef: - object *v, *o + object *v + object *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(object) and sizeof(object) * n >= 256): @@ -2682,8 +2686,10 @@ def take_2d_axis0_int8_int8(ndarray[int8_t, ndim=2] values, IF True: cdef: - int8_t *v, *o + int8_t *v + int8_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int8_t) and sizeof(int8_t) * n >= 256): @@ -2725,8 +2731,10 @@ def take_2d_axis0_int8_int32(ndarray[int8_t, ndim=2] values, IF False: cdef: - int32_t *v, *o + int32_t *v + int32_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int32_t) and sizeof(int32_t) * n >= 256): @@ -2768,8 +2776,10 @@ def take_2d_axis0_int8_int64(ndarray[int8_t, ndim=2] values, IF False: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -2811,8 +2821,10 @@ def take_2d_axis0_int8_float64(ndarray[int8_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -2854,8 +2866,10 @@ def take_2d_axis0_int16_int16(ndarray[int16_t, ndim=2] values, IF True: cdef: - int16_t *v, *o + int16_t *v + int16_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int16_t) and sizeof(int16_t) * n >= 256): @@ -2897,8 +2911,10 @@ def take_2d_axis0_int16_int32(ndarray[int16_t, ndim=2] values, IF False: cdef: - int32_t *v, *o + int32_t *v + int32_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int32_t) and sizeof(int32_t) * n >= 256): @@ -2940,8 +2956,10 @@ def take_2d_axis0_int16_int64(ndarray[int16_t, ndim=2] values, IF False: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -2983,8 +3001,10 @@ def take_2d_axis0_int16_float64(ndarray[int16_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3026,8 +3046,10 @@ def take_2d_axis0_int32_int32(ndarray[int32_t, ndim=2] values, IF True: cdef: - int32_t *v, *o + int32_t *v + int32_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int32_t) and sizeof(int32_t) * n >= 256): @@ -3069,8 +3091,10 @@ def take_2d_axis0_int32_int64(ndarray[int32_t, ndim=2] values, IF False: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -3112,8 +3136,10 @@ def take_2d_axis0_int32_float64(ndarray[int32_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3155,8 +3181,10 @@ def take_2d_axis0_int64_int64(ndarray[int64_t, ndim=2] values, IF True: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -3198,8 +3226,10 @@ def take_2d_axis0_int64_float64(ndarray[int64_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3241,8 +3271,10 @@ def take_2d_axis0_float32_float32(ndarray[float32_t, ndim=2] values, IF True: cdef: - float32_t *v, *o + float32_t *v + float32_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float32_t) and sizeof(float32_t) * n >= 256): @@ -3284,8 +3316,10 @@ def take_2d_axis0_float32_float64(ndarray[float32_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3327,8 +3361,10 @@ def take_2d_axis0_float64_float64(ndarray[float64_t, ndim=2] values, IF True: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3370,8 +3406,10 @@ def take_2d_axis0_object_object(ndarray[object, ndim=2] values, IF False: cdef: - object *v, *o + object *v + object *o + #GH3130 if (values.strides[1] == out.strides[1] and values.strides[1] == sizeof(object) and sizeof(object) * n >= 256): @@ -3417,8 +3455,10 @@ def take_2d_axis1_bool_bool(ndarray[uint8_t, ndim=2] values, IF True: cdef: - uint8_t *v, *o + uint8_t *v + uint8_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(uint8_t) and sizeof(uint8_t) * n >= 256): @@ -3463,8 +3503,10 @@ def take_2d_axis1_bool_object(ndarray[uint8_t, ndim=2] values, IF False: cdef: - object *v, *o + object *v + object *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(object) and sizeof(object) * n >= 256): @@ -3509,8 +3551,10 @@ def take_2d_axis1_int8_int8(ndarray[int8_t, ndim=2] values, IF True: cdef: - int8_t *v, *o + int8_t *v + int8_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int8_t) and sizeof(int8_t) * n >= 256): @@ -3555,8 +3599,10 @@ def take_2d_axis1_int8_int32(ndarray[int8_t, ndim=2] values, IF False: cdef: - int32_t *v, *o + int32_t *v + int32_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int32_t) and sizeof(int32_t) * n >= 256): @@ -3601,8 +3647,10 @@ def take_2d_axis1_int8_int64(ndarray[int8_t, ndim=2] values, IF False: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -3647,8 +3695,10 @@ def take_2d_axis1_int8_float64(ndarray[int8_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3693,8 +3743,10 @@ def take_2d_axis1_int16_int16(ndarray[int16_t, ndim=2] values, IF True: cdef: - int16_t *v, *o + int16_t *v + int16_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int16_t) and sizeof(int16_t) * n >= 256): @@ -3739,8 +3791,10 @@ def take_2d_axis1_int16_int32(ndarray[int16_t, ndim=2] values, IF False: cdef: - int32_t *v, *o + int32_t *v + int32_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int32_t) and sizeof(int32_t) * n >= 256): @@ -3785,8 +3839,10 @@ def take_2d_axis1_int16_int64(ndarray[int16_t, ndim=2] values, IF False: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -3831,8 +3887,10 @@ def take_2d_axis1_int16_float64(ndarray[int16_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -3877,8 +3935,10 @@ def take_2d_axis1_int32_int32(ndarray[int32_t, ndim=2] values, IF True: cdef: - int32_t *v, *o + int32_t *v + int32_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int32_t) and sizeof(int32_t) * n >= 256): @@ -3923,8 +3983,10 @@ def take_2d_axis1_int32_int64(ndarray[int32_t, ndim=2] values, IF False: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -3969,8 +4031,10 @@ def take_2d_axis1_int32_float64(ndarray[int32_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -4015,8 +4079,10 @@ def take_2d_axis1_int64_int64(ndarray[int64_t, ndim=2] values, IF True: cdef: - int64_t *v, *o + int64_t *v + int64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(int64_t) and sizeof(int64_t) * n >= 256): @@ -4061,8 +4127,10 @@ def take_2d_axis1_int64_float64(ndarray[int64_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -4107,8 +4175,10 @@ def take_2d_axis1_float32_float32(ndarray[float32_t, ndim=2] values, IF True: cdef: - float32_t *v, *o + float32_t *v + float32_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float32_t) and sizeof(float32_t) * n >= 256): @@ -4153,8 +4223,10 @@ def take_2d_axis1_float32_float64(ndarray[float32_t, ndim=2] values, IF False: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -4199,8 +4271,10 @@ def take_2d_axis1_float64_float64(ndarray[float64_t, ndim=2] values, IF True: cdef: - float64_t *v, *o + float64_t *v + float64_t *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(float64_t) and sizeof(float64_t) * n >= 256): @@ -4245,8 +4319,10 @@ def take_2d_axis1_object_object(ndarray[object, ndim=2] values, IF False: cdef: - object *v, *o + object *v + object *o + #GH3130 if (values.strides[0] == out.strides[0] and values.strides[0] == sizeof(object) and sizeof(object) * n >= 256): diff --git a/pandas/src/numpy.pxd b/pandas/src/numpy.pxd index f61c8762a1e50..9ab3b9b1b81ae 100644 --- a/pandas/src/numpy.pxd +++ b/pandas/src/numpy.pxd @@ -870,7 +870,8 @@ cdef extern from "numpy/ufuncobject.h": void **data int ntypes int check_return - char *name, *types + char *name + char *types char *doc void *ptr PyObject *obj
cython 20 is out, and complains about syntax. Holding off till 0.14, on general principle.
https://api.github.com/repos/pandas-dev/pandas/pulls/6176
2014-01-29T20:10:38Z
2014-02-04T08:52:23Z
2014-02-04T08:52:23Z
2014-06-18T17:57:58Z
More @network fixes
diff --git a/pandas/io/tests/__init__.py b/pandas/io/tests/__init__.py index e69de29bb2d1d..e6089154cd5e5 100644 --- a/pandas/io/tests/__init__.py +++ b/pandas/io/tests/__init__.py @@ -0,0 +1,4 @@ + +def setUp(): + import socket + socket.setdefaulttimeout(5) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 49361501c5975..f9acb94602a92 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -967,7 +967,13 @@ def dec(f): return wrapper +# skip tests on exceptions with this message +_network_error_messages = ( + 'urlopen error timed out', + 'timeout: timed out' + ) +# or this e.errno/e.reason.errno _network_errno_vals = ( 101, # Network is unreachable 110, # Connection timed out @@ -976,6 +982,12 @@ def dec(f): 60, # urllib.error.URLError: [Errno 60] Connection timed out ) +# Both of the above shouldn't mask reasl issues such as 404's +# or refused connections (changed DNS). +# But some tests (test_data yahoo) contact incredibly flakey +# servers. + +# and conditionally raise on these exception types _network_error_classes = (IOError, httplib.HTTPException) if sys.version_info[:2] >= (3,3): @@ -1010,7 +1022,9 @@ def network(t, url="http://www.google.com", raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT, check_before_test=False, error_classes=_network_error_classes, - skip_errnos=_network_errno_vals): + skip_errnos=_network_errno_vals, + _skip_on_messages=_network_error_messages, + ): """ Label a test as requiring network connection and, if an error is encountered, only raise if it does not find a network connection. @@ -1108,6 +1122,10 @@ def wrapper(*args, **kwargs): raise SkipTest("Skipping test due to known errno" " and error %s" % e) + if any([m.lower() in str(e).lower() for m in _skip_on_messages]): + raise SkipTest("Skipping test because exception message is known" + " and error %s" % e) + if raise_on_error or can_connect(url, error_classes): raise else:
More fixes to @network to handle the incredibly unreliable yahoo servers. This should do it. The mind boggles that a billion-dollar company can have a QoS this bad. N.B. the default socket timeout setting. It's not required for this because I believe travis has some firewall rules that timeout net connections, but it's nicer when running locally where connections can hang for much longer. 15 seconds is very generous so I hope it's not disruptive. cc @jreback, @jtratner
https://api.github.com/repos/pandas-dev/pandas/pulls/6174
2014-01-29T17:31:14Z
2014-01-29T17:31:38Z
2014-01-29T17:31:38Z
2014-06-22T03:44:52Z
BUG: Consistency with dtypes in setting an empty DataFrame (GH6171)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 21ee81d4da79d..8f885c9c5d32c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -174,6 +174,7 @@ Bug Fixes being thrown away (:issue:`6148`). - Bug in ``HDFStore`` on appending a dataframe with multi-indexed columns to an existing table (:issue:`6167`) + - Consistency with dtypes in setting an empty DataFrame (:issue:`6171`) pandas 0.13.0 ------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index fdff3ab99df22..2c58dd34939e7 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1421,7 +1421,18 @@ def set(self, item, value, check=False): return except: pass - self.values[loc] = value + try: + self.values[loc] = value + except (ValueError): + + # broadcasting error + # see GH6171 + new_shape = list(value.shape) + new_shape[0] = len(self.items) + self.values = np.empty(tuple(new_shape),dtype=self.dtype) + self.values.fill(np.nan) + self.values[loc] = value + def _maybe_downcast(self, blocks, downcast=None): diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 44d90c78e07d1..435b0ca5d722f 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1987,6 +1987,23 @@ def f(): expected = DataFrame(0,index=[0],columns=['a']) assert_frame_equal(df, expected) + # GH 6171 + # consistency on empty frames + df = DataFrame(columns=['x', 'y']) + df['x'] = [1, 2] + expected = DataFrame(dict(x = [1,2], y = [np.nan,np.nan])) + assert_frame_equal(df, expected, check_dtype=False) + + df = DataFrame(columns=['x', 'y']) + df['x'] = ['1', '2'] + expected = DataFrame(dict(x = ['1','2'], y = [np.nan,np.nan]),dtype=object) + assert_frame_equal(df, expected) + + df = DataFrame(columns=['x', 'y']) + df.loc[0, 'x'] = 1 + expected = DataFrame(dict(x = [1], y = [np.nan])) + assert_frame_equal(df, expected, check_dtype=False) + def test_cache_updating(self): # GH 4939, make sure to update the cache on setitem
closes #6171
https://api.github.com/repos/pandas-dev/pandas/pulls/6172
2014-01-29T16:48:25Z
2014-01-29T17:23:04Z
2014-01-29T17:23:04Z
2014-06-24T03:11:45Z
BUG: parsing multi-column headers in read_csv (GH6051)
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 612840e82e3ff..904347acbb655 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -2568,6 +2568,52 @@ def read_table(self, *args, **kwds): kwds['buffer_lines'] = 2 return read_table(*args, **kwds) + def test_list_of_one_header(self): + data = """A,B,C +1,2,3 +4,5,6 +7,8,9 +""" + df = self.read_csv(StringIO(data), header=[0]) + + values = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + expected = DataFrame(values, columns=['A', 'B', 'C']) + + tm.assert_frame_equal(df, expected) + + def test_list_of_multiple_headers(self): + data = """A,B,C +a,b,c +1,2,3 +4,5,6 +7,8,9 +""" + df = self.read_csv(StringIO(data), header=[0,1]) + + values = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + expected_columns = pd.MultiIndex.from_arrays([['A', 'B', 'C'], ['a', 'b', 'c']]) + expected = DataFrame(values, columns=expected_columns) + + tm.assert_frame_equal(df, expected) + + def test_list_of_multiple_headers_with_duplicated_column_pairs(self): + data = """A,A,A,A,A,B,B +a,b,b,b,c,c,c +1,2,3,4,5,6,7 +1,2,3,4,5,6,7 +1,2,3,4,5,6,7 +""" + df = self.read_csv(StringIO(data), header=[0,1]) + + values = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]] + expected_columns = pd.MultiIndex.from_arrays([ + ['A', 'A', 'A', 'A', 'A', 'B', 'B'], + ['a', 'b', 'b.1', 'b.2', 'c', 'c', 'c.1']]) + expected = DataFrame(values, columns=expected_columns) + + tm.assert_frame_equal(df, expected) + + def test_compact_ints(self): data = ('0,1,0,0\n' '1,1,0,0\n' diff --git a/pandas/parser.pyx b/pandas/parser.pyx index bb93097debf71..c4df3581e03cc 100644 --- a/pandas/parser.pyx +++ b/pandas/parser.pyx @@ -30,6 +30,7 @@ import numpy as np cimport util import pandas.lib as lib +from pandas.compat import lzip import time import os @@ -460,7 +461,8 @@ cdef class TextReader: self.parser_start = 0 self.header = [] else: - if isinstance(header, list) and len(header): + if isinstance(header, list) and len(header) >= 2: + # FIXME # need to artifically skip the final line # which is still a header line header = list(header) @@ -473,6 +475,11 @@ cdef class TextReader: self.has_mi_columns = 1 self.header = header else: + # if the header is a list with length 1 + # set the header as the only element in the list + if isinstance(header, list) and len(header) == 1: + header = header[0] + self.parser.header_start = header self.parser.header_end = header self.parser.header = header @@ -586,6 +593,7 @@ cdef class TextReader: char *errors = "strict" header = [] + is_duplicated = False if self.parser.header_start >= 0: @@ -633,6 +641,9 @@ cdef class TextReader: count = counts.get(name, 0) if count > 0 and self.mangle_dupe_cols and not self.has_mi_columns: this_header.append('%s.%d' % (name, count)) + + # for warning later + is_duplicated = True else: this_header.append(name) counts[name] = count + 1 @@ -653,6 +664,43 @@ cdef class TextReader: data_line = hr + 1 header.append(this_header) + # + # Append a seq number for the duplicated columns pairs + # + # i.e. [['a', 'a', 'a', 'b'], + # ['A', 'A', 'B', 'C']] + # ==> + # [['a', 'a', 'b', 'b'], + # ['A', 'A.1', 'B', 'C']] + # + if self.has_mi_columns: + + # zip the header, so that we can easily find the duplicated pair + header = lzip(*header) + + counts = {} + for i, column in enumerate(header): + + # Check whether the column is duplicated + count = counts.get(column, 0) + if count > 0: + # + # FIXME + # Since we've added an extra header line (search FIXME in this page) + # Append an incremental seq number to the second-last element + # + tmp_column = list(column) + tmp_column[-2] = '%s.%d' % (tmp_column[-2], count) + header[i] = tuple(tmp_column) + + # for warning later + is_duplicated = True + + counts[column] = count + 1 + + # unzip the header + header = lzip(*header) + if self.names is not None: header = [ self.names ] @@ -710,6 +758,9 @@ cdef class TextReader: elif self.allow_leading_cols and passed_count < field_count: self.leading_cols = field_count - passed_count + if self.mangle_dupe_cols and is_duplicated: + warnings.warn('Duplicated columns have been mangled', DtypeWarning) + return header, field_count cdef _implicit_index_count(self):
closes #6051 Bug: `mangle_dupe_cols` cannot work while the header is a list. Originally, `has_mi_columns` will be set as 1 while the header is a list. And the `mangle_dupe_cols` things would not work when `has_mi_columns` == 1. This pull request is to 1. for the list with single element, for example [0], the `has_mi_columns` will be set as 0, and the header will do the original `mangle_dupe_cols` things as the header is a single integer. 2. for the list with more than one element, append the sequence number in the last element of the duplicated multi-column For example ``` Male,Male,Male,Male,Male,Female,Female A,B,B,B,C,D,D 1,2,3,4,5,6,7 1,2,3,4,5,6,7 1,2,3,4,5,6,7 1,2,3,4,5,6,7 1,2,3,4,5,6,7 1,2,3,4,5,6,7 ``` would be converted to ``` In [2]: pd.read_csv('woo.csv', header=[0,1]) Out[2]: Male Female A B B.1 B.2 C D D.1 0 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 1 2 3 4 5 6 7 3 1 2 3 4 5 6 7 4 1 2 3 4 5 6 7 5 1 2 3 4 5 6 7 [6 rows x 7 columns] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6170
2014-01-29T15:47:23Z
2015-01-18T21:40:11Z
null
2023-05-11T01:12:23Z
append to existing table with mulitindex fix
diff --git a/doc/source/release.rst b/doc/source/release.rst index e867f0f27a646..21ee81d4da79d 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -172,6 +172,8 @@ Bug Fixes string comparisons (:issue:`6155`). - Fixed a bug in ``query`` where the index of a single-element ``Series`` was being thrown away (:issue:`6148`). + - Bug in ``HDFStore`` on appending a dataframe with multi-indexed columns to + an existing table (:issue:`6167`) pandas 0.13.0 ------------- diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b08be80dcb16a..bb487f5102e0a 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3068,9 +3068,9 @@ def validate_data_columns(self, data_columns, min_itemsize): axis, axis_labels = self.non_index_axes[0] info = self.info.get(axis, dict()) - if info.get('type') == 'MultiIndex' and data_columns is not None: + if info.get('type') == 'MultiIndex' and data_columns: raise ValueError("cannot use a multi-index on axis [{0}] with " - "data_columns".format(axis)) + "data_columns {1}".format(axis, data_columns)) # evaluate the passed data_columns, True == use all columns # take only valide axis labels diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index f7d01cb1bec96..9c56ee468f6ac 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -1613,6 +1613,13 @@ def test_column_multiindex(self): self.assertRaises(ValueError, store.put, 'df2',df,format='table',data_columns=['A']) self.assertRaises(ValueError, store.put, 'df3',df,format='table',data_columns=True) + # appending multi-column on existing table (see GH 6167) + with ensure_clean_store(self.path) as store: + store.append('df2', df) + store.append('df2', df) + + tm.assert_frame_equal(store['df2'], concat((df,df))) + # non_index_axes name df = DataFrame(np.arange(12).reshape(3,4), columns=Index(list('ABCD'),name='foo'))
Appending to an existing table with a multiindex failed as data_columns is set to [] but compared with None
https://api.github.com/repos/pandas-dev/pandas/pulls/6167
2014-01-29T10:59:31Z
2014-01-29T15:39:38Z
2014-01-29T15:39:38Z
2014-06-16T09:44:30Z
BUG: long str unconvert fix
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 85a9cf4ea0f9f..7ff407094a0a5 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -40,6 +40,7 @@ import pandas.tslib as tslib from contextlib import contextmanager +from distutils.version import LooseVersion # versioning attribute _version = '0.10.1' @@ -47,6 +48,7 @@ # PY3 encoding if we don't specify _default_encoding = 'UTF-8' +_np_version_under_172 = LooseVersion(np.__version__) < '1.7.2' def _ensure_decoded(s): """ if we have bytes, decode them to unicde """ @@ -4165,7 +4167,6 @@ def _convert_string_array(data, encoding, itemsize=None): data = np.array(data, dtype="S%d" % itemsize) return data - def _unconvert_string_array(data, nan_rep=None, encoding=None): """ deserialize a string array, possibly decoding """ shape = data.shape @@ -4175,8 +4176,14 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None): # where the passed encoding is actually None) encoding = _ensure_encoding(encoding) if encoding is not None and len(data): + if _np_version_under_172: + itemsize = lib.max_len_string_array(data) + dtype = (str, itemsize) + else: + dtype = str + try: - data = data.astype(string_types).astype(object) + data = data.astype(dtype).astype(object) except: f = np.vectorize(lambda x: x.decode(encoding), otypes=[np.object]) data = f(data) diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index dcdd5408c3376..51c254b2d422f 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -176,6 +176,17 @@ def roundtrip(key, obj,**kwargs): finally: safe_remove(self.path) + def test_long_strings(self): + df = DataFrame({'a': [tm.rands(100) for _ in range(10)]}, + index=[tm.rands(100) for _ in range(10)]) + + with ensure_clean_store(self.path) as store: + store.append('df', df, data_columns=['a']) + + result = store.select('df') + assert_frame_equal(df, result) + + def test_api(self): # GH4584
When storing long strings in hdf5, they get truncated at 64bytes when converted back to strings. The fix computes the itemsize of the strings and uses it before converting to strings. It would be possible to use the attribute information of the table, but that would require changes in the calling code. Test that failed without the patch is included.
https://api.github.com/repos/pandas-dev/pandas/pulls/6166
2014-01-29T08:45:05Z
2014-04-06T16:59:32Z
null
2014-06-24T10:39:07Z
4304r if_exists == 'fail' should actually work
diff --git a/doc/source/release.rst b/doc/source/release.rst index 9324d8b28f107..6166b68390a2e 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -152,6 +152,7 @@ Bug Fixes - Possible segfault when chained indexing with an object array under numpy 1.7.1 (:issue:`6026`, :issue:`6056`) - Bug in setting using fancy indexing a single element with a non-scalar (e.g. a list), (:issue:`6043`) + - ``to_sql`` did not respect ``if_exists`` (:issue:`4110` :issue:`4304`) - Regression in ``.get(None)`` indexing from 0.12 (:issue:`5652`) - Subtle ``iloc`` indexing bug, surfaced in (:issue:`6059`) - Bug with insert of strings into DatetimeIndex (:issue:`5818`) diff --git a/pandas/io/sql.py b/pandas/io/sql.py index e269d14f72712..5e83a0921189b 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -200,15 +200,25 @@ def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs): if_exists = 'append' else: if_exists = 'fail' + + if if_exists not in ('fail', 'replace', 'append'): + raise ValueError("'%s' is not valid for if_exists" % if_exists) + exists = table_exists(name, con, flavor) if if_exists == 'fail' and exists: raise ValueError("Table '%s' already exists." % name) - #create or drop-recreate if necessary + # creation/replacement dependent on the table existing and if_exist criteria create = None - if exists and if_exists == 'replace': - create = "DROP TABLE %s" % name - elif not exists: + if exists: + if if_exists == 'fail': + raise ValueError("Table '%s' already exists." % name) + elif if_exists == 'replace': + cur = con.cursor() + cur.execute("DROP TABLE %s;" % name) + cur.close() + create = get_schema(frame, name, flavor) + else: create = get_schema(frame, name, flavor) if create is not None: diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index 83864878ff6d3..ef9917c9a02f7 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -240,6 +240,65 @@ def test_onecolumn_of_integer(self): result = sql.read_frame("select * from mono_df",con_x) tm.assert_frame_equal(result,mono_df) + def test_if_exists(self): + df_if_exists_1 = DataFrame({'col1': [1, 2], 'col2': ['A', 'B']}) + df_if_exists_2 = DataFrame({'col1': [3, 4, 5], 'col2': ['C', 'D', 'E']}) + table_name = 'table_if_exists' + sql_select = "SELECT * FROM %s" % table_name + + def clean_up(test_table_to_drop): + """ + Drops tables created from individual tests + so no dependencies arise from sequential tests + """ + if sql.table_exists(test_table_to_drop, self.db, flavor='sqlite'): + cur = self.db.cursor() + cur.execute("DROP TABLE %s" % test_table_to_drop) + cur.close() + + # test if invalid value for if_exists raises appropriate error + self.assertRaises(ValueError, + sql.write_frame, + frame=df_if_exists_1, + con=self.db, + name=table_name, + flavor='sqlite', + if_exists='notvalidvalue') + clean_up(table_name) + + # test if_exists='fail' + sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name, + flavor='sqlite', if_exists='fail') + self.assertRaises(ValueError, + sql.write_frame, + frame=df_if_exists_1, + con=self.db, + name=table_name, + flavor='sqlite', + if_exists='fail') + + # test if_exists='replace' + sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name, + flavor='sqlite', if_exists='replace') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(1, 'A'), (2, 'B')]) + sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name, + flavor='sqlite', if_exists='replace') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(3, 'C'), (4, 'D'), (5, 'E')]) + clean_up(table_name) + + # test if_exists='append' + sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name, + flavor='sqlite', if_exists='fail') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(1, 'A'), (2, 'B')]) + sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name, + flavor='sqlite', if_exists='append') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]) + clean_up(table_name) + class TestMySQL(tm.TestCase): @@ -483,6 +542,66 @@ def test_keyword_as_column_names(self): sql.write_frame(df, con = self.db, name = 'testkeywords', if_exists='replace', flavor='mysql') + def test_if_exists(self): + _skip_if_no_MySQLdb() + df_if_exists_1 = DataFrame({'col1': [1, 2], 'col2': ['A', 'B']}) + df_if_exists_2 = DataFrame({'col1': [3, 4, 5], 'col2': ['C', 'D', 'E']}) + table_name = 'table_if_exists' + sql_select = "SELECT * FROM %s" % table_name + + def clean_up(test_table_to_drop): + """ + Drops tables created from individual tests + so no dependencies arise from sequential tests + """ + if sql.table_exists(test_table_to_drop, self.db, flavor='mysql'): + cur = self.db.cursor() + cur.execute("DROP TABLE %s" % test_table_to_drop) + cur.close() + + # test if invalid value for if_exists raises appropriate error + self.assertRaises(ValueError, + sql.write_frame, + frame=df_if_exists_1, + con=self.db, + name=table_name, + flavor='mysql', + if_exists='notvalidvalue') + clean_up(table_name) + + # test if_exists='fail' + sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name, + flavor='mysql', if_exists='fail') + self.assertRaises(ValueError, + sql.write_frame, + frame=df_if_exists_1, + con=self.db, + name=table_name, + flavor='mysql', + if_exists='fail') + + # test if_exists='replace' + sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name, + flavor='mysql', if_exists='replace') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(1, 'A'), (2, 'B')]) + sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name, + flavor='mysql', if_exists='replace') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(3, 'C'), (4, 'D'), (5, 'E')]) + clean_up(table_name) + + # test if_exists='append' + sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name, + flavor='mysql', if_exists='fail') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(1, 'A'), (2, 'B')]) + sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name, + flavor='mysql', if_exists='append') + self.assertEqual(sql.tquery(sql_select, con=self.db), + [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')]) + clean_up(table_name) + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
fixes #4110 #4304 #4304 rebased and passes travis. cc @y-p
https://api.github.com/repos/pandas-dev/pandas/pulls/6164
2014-01-29T06:49:35Z
2014-01-29T20:26:50Z
2014-01-29T20:26:50Z
2014-06-20T19:03:14Z
BUG: allow single element bool queries
diff --git a/doc/source/release.rst b/doc/source/release.rst index a79182af13955..e867f0f27a646 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -170,6 +170,8 @@ Bug Fixes a datetimelike (:issue:`6152`) - Fixed a stack overflow bug in ``query``/``eval`` during lexicographic string comparisons (:issue:`6155`). + - Fixed a bug in ``query`` where the index of a single-element ``Series`` was + being thrown away (:issue:`6148`). pandas 0.13.0 ------------- diff --git a/pandas/computation/align.py b/pandas/computation/align.py index 757524965bbef..9fe563574bbd4 100644 --- a/pandas/computation/align.py +++ b/pandas/computation/align.py @@ -81,16 +81,12 @@ def wrapper(terms): return _align_core_single_unary_op(terms[0]) term_values = (term.value for term in terms) + # only scalars or indexes if all(isinstance(term.value, pd.Index) or term.isscalar for term in terms): return np.result_type(*term_values), None - # single element ndarrays - all_has_size = all(hasattr(term.value, 'size') for term in terms) - if all_has_size and all(term.value.size == 1 for term in terms): - return np.result_type(*term_values), None - # no pandas objects if not _any_pandas_objects(terms): return np.result_type(*term_values), None diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 4578375ab7dad..29edbd4273fec 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -12860,6 +12860,20 @@ def test_query_lex_compare_strings(self): for parser, engine in product(PARSERS, ENGINES): yield self.check_query_lex_compare_strings, parser, engine + def check_query_single_element_booleans(self, parser, engine): + tm.skip_if_no_ne(engine) + columns = 'bid', 'bidsize', 'ask', 'asksize' + data = np.random.randint(2, size=(1, len(columns))).astype(bool) + df = DataFrame(data, columns=columns) + res = df.query('bid & ask', engine=engine, parser=parser) + expected = df[df.bid & df.ask] + assert_frame_equal(res, expected) + + def test_query_single_element_booleans(self): + for parser, engine in product(PARSERS, ENGINES): + yield self.check_query_single_element_booleans, parser, engine + + class TestDataFrameEvalNumExprPandas(tm.TestCase): @classmethod
closes #6148
https://api.github.com/repos/pandas-dev/pandas/pulls/6163
2014-01-29T03:26:59Z
2014-01-29T03:54:13Z
2014-01-29T03:54:13Z
2014-06-21T19:28:05Z
BUG/API: df['col'] = value and df.loc[:,'col'] = value are now completely equivalent
diff --git a/doc/source/release.rst b/doc/source/release.rst index 1cb5bf39ba9a7..804ca6c465bdb 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -63,6 +63,8 @@ API Changes values. A single indexer that is out-of-bounds and drops the dimensions of the object will still raise ``IndexError`` (:issue:`6296`) - ``select_as_multiple`` will always raise a ``KeyError``, when a key or the selector is not found (:issue:`6177`) +- ``df['col'] = value`` and ``df.loc[:,'col'] = value`` are now completely equivalent; + previously the ``.loc`` would not necessarily coerce the dtype of the resultant series (:issue:`6149`) Experimental Features ~~~~~~~~~~~~~~~~~~~~~ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index f8ce855e6bfdc..ea7214d4cd020 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -394,10 +394,18 @@ def setter(item, v): s = self.obj[item] 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(indexer=pi, value=v) - s._maybe_update_cacher(clear=True) + # perform the equivalent of a setitem on the info axis + # as we have a null slice which means essentially reassign to the columns + # of a multi-dim object + # GH6149 + if isinstance(pi, tuple) and all(_is_null_slice(idx) for idx in pi): + s = v + else: + # set the item, possibly having a dtype change + s = s.copy() + s._data = s._data.setitem(indexer=pi, value=v) + s._maybe_update_cacher(clear=True) + self.obj[item] = s def can_do_equal_len(): diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index b54e87f5d5696..8ffa5f8b1bba0 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -690,6 +690,52 @@ def test_loc_general(self): assert_series_equal(result,expected) self.assertEqual(result.dtype, object) + def test_loc_setitem_consistency(self): + + # GH 6149 + # coerce similary for setitem and loc when rows have a null-slice + expected = DataFrame({ 'date': Series(0,index=range(5),dtype=np.int64), + 'val' : Series(range(5),dtype=np.int64) }) + + df = DataFrame({ 'date': date_range('2000-01-01','2000-01-5'), + 'val' : Series(range(5),dtype=np.int64) }) + df.loc[:,'date'] = 0 + assert_frame_equal(df,expected) + + df = DataFrame({ 'date': date_range('2000-01-01','2000-01-5'), + 'val' : Series(range(5),dtype=np.int64) }) + df.loc[:,'date'] = np.array(0,dtype=np.int64) + assert_frame_equal(df,expected) + + df = DataFrame({ 'date': date_range('2000-01-01','2000-01-5'), + 'val' : Series(range(5),dtype=np.int64) }) + df.loc[:,'date'] = np.array([0,0,0,0,0],dtype=np.int64) + assert_frame_equal(df,expected) + + expected = DataFrame({ 'date': Series('foo',index=range(5)), + 'val' : Series(range(5),dtype=np.int64) }) + df = DataFrame({ 'date': date_range('2000-01-01','2000-01-5'), + 'val' : Series(range(5),dtype=np.int64) }) + df.loc[:,'date'] = 'foo' + assert_frame_equal(df,expected) + + expected = DataFrame({ 'date': Series(1.0,index=range(5)), + 'val' : Series(range(5),dtype=np.int64) }) + df = DataFrame({ 'date': date_range('2000-01-01','2000-01-5'), + 'val' : Series(range(5),dtype=np.int64) }) + df.loc[:,'date'] = 1.0 + assert_frame_equal(df,expected) + + # empty (essentially noops) + expected = DataFrame(columns=['x', 'y']) + df = DataFrame(columns=['x', 'y']) + df.loc[:, 'x'] = 1 + assert_frame_equal(df,expected) + + df = DataFrame(columns=['x', 'y']) + df['x'] = 1 + assert_frame_equal(df,expected) + def test_loc_setitem_frame(self): df = self.frame_labels
previously the .loc would not necessarily coerce the dtype of the resultant series closes #6149
https://api.github.com/repos/pandas-dev/pandas/pulls/6159
2014-01-29T02:40:04Z
2014-02-15T23:16:11Z
2014-02-15T23:16:11Z
2014-06-26T12:23:34Z
BUG: allow lex string comparisons
diff --git a/doc/source/enhancingperf.rst b/doc/source/enhancingperf.rst index ddf1fa62b2d61..066fcce64c5ac 100644 --- a/doc/source/enhancingperf.rst +++ b/doc/source/enhancingperf.rst @@ -464,19 +464,20 @@ evaluate an expression in the "context" of a ``DataFrame``. Any expression that is a valid :func:`~pandas.eval` expression is also a valid ``DataFrame.eval`` expression, with the added benefit that *you don't have to -prefix the name of the* ``DataFrame`` *to the column you're interested in +prefix the name of the* ``DataFrame`` *to the column(s) you're interested in evaluating*. -In addition, you can perform in-line assignment of columns within an expression. -This can allow for *formulaic evaluation*. Only a signle assignement is permitted. -It can be a new column name or an existing column name. It must be a string-like. +In addition, you can perform assignment of columns within an expression. +This allows for *formulaic evaluation*. Only a single assignment is permitted. +The assignment target can be a new column name or an existing column name, and +it must be a valid Python identifier. .. ipython:: python - df = DataFrame(dict(a = range(5), b = range(5,10))) - df.eval('c=a+b') - df.eval('d=a+b+c') - df.eval('a=1') + df = DataFrame(dict(a=range(5), b=range(5, 10))) + df.eval('c = a + b') + df.eval('d = a + b + c') + df.eval('a = 1') df Local Variables @@ -616,3 +617,20 @@ different engines. This plot was created using a ``DataFrame`` with 3 columns each containing floating point values generated using ``numpy.random.randn()``. + +Technical Minutia +~~~~~~~~~~~~~~~~~ +- Expressions that would result in an object dtype (including simple + variable evaluation) have to be evaluated in Python space. The main reason + for this behavior is to maintain backwards compatbility with versions of + numpy < 1.7. In those versions of ``numpy`` a call to ``ndarray.astype(str)`` + will truncate any strings that are more than 60 characters in length. Second, + we can't pass ``object`` arrays to ``numexpr`` thus string comparisons must + be evaluated in Python space. +- The upshot is that this *only* applies to object-dtype'd expressions. So, + if you have an expression--for example--that's a string comparison + ``and``-ed together with another boolean expression that's from a numeric + comparison, the numeric comparison will be evaluated by ``numexpr``. In fact, + in general, :func:`~pandas.query`/:func:`~pandas.eval` will "pick out" the + subexpressions that are ``eval``-able by ``numexpr`` and those that must be + evaluated in Python space transparently to the user. diff --git a/doc/source/release.rst b/doc/source/release.rst index 2caad982f044b..a79182af13955 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -168,6 +168,8 @@ Bug Fixes - Bug in DataFrame construction with recarray and non-ns datetime dtype (:issue:`6140`) - Bug in ``.loc`` setitem indexing with a datafrme on rhs, multiple item setting, and a datetimelike (:issue:`6152`) + - Fixed a stack overflow bug in ``query``/``eval`` during lexicographic + string comparisons (:issue:`6155`). pandas 0.13.0 ------------- diff --git a/pandas/computation/expr.py b/pandas/computation/expr.py index c16205ff34b1f..7ebffef7368a0 100644 --- a/pandas/computation/expr.py +++ b/pandas/computation/expr.py @@ -508,7 +508,8 @@ def _possibly_eval(self, binop, eval_in_python): def _possibly_evaluate_binop(self, op, op_class, lhs, rhs, eval_in_python=('in', 'not in'), - maybe_eval_in_python=('==', '!=')): + maybe_eval_in_python=('==', '!=', '<', '>', + '<=', '>=')): res = op(lhs, rhs) if self.engine != 'pytables': diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 50c5cca935553..4578375ab7dad 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -12841,6 +12841,25 @@ def test_query_with_nested_string(self): for parser, engine in product(PARSERS, ENGINES): yield self.check_query_with_nested_strings, parser, engine + def check_query_lex_compare_strings(self, parser, engine): + tm.skip_if_no_ne(engine=engine) + import operator as opr + + a = Series(tm.choice(list('abcde'), 20)) + b = Series(np.arange(a.size)) + df = DataFrame({'X': a, 'Y': b}) + + ops = {'<': opr.lt, '>': opr.gt, '<=': opr.le, '>=': opr.ge} + + for op, func in ops.items(): + res = df.query('X %s "d"' % op, engine=engine, parser=parser) + expected = df[func(df.X, 'd')] + assert_frame_equal(res, expected) + + def test_query_lex_compare_strings(self): + for parser, engine in product(PARSERS, ENGINES): + yield self.check_query_lex_compare_strings, parser, engine + class TestDataFrameEvalNumExprPandas(tm.TestCase): @classmethod
closes #6155
https://api.github.com/repos/pandas-dev/pandas/pulls/6158
2014-01-29T02:25:33Z
2014-01-29T03:24:59Z
2014-01-29T03:24:59Z
2014-06-16T01:40:36Z
Updated docs to reflect a pagination bug that was fixed. Closes: issue #6068
diff --git a/doc/source/io.rst b/doc/source/io.rst index 4c3a97500e789..4f0c797581899 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3246,9 +3246,9 @@ To add more rows to this, simply: To use this module, you will need a BigQuery account. See <https://cloud.google.com/products/big-query> for details. - As of 10/10/13, there is a bug in Google's API preventing result sets - from being larger than 100,000 rows. A patch is scheduled for the week of - 10/14/13. + As of 1/28/14, a known bug is present that could possibly cause data duplication in the resultant dataframe. A fix is imminent, + but any client changes will not make it into 0.13.1. See: + http://stackoverflow.com/questions/20984592/bigquery-results-not-including-page-token/21009144?noredirect=1#comment32090677_21009144 .. _io.stata: diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index cacb849591bb9..ebf4f17ffb852 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -204,9 +204,6 @@ def _parse_data(client, job, index_col=None, col_order=None): pagination API. We are using the most flexible iteration method that we could find in the bq.py/bigquery_client.py API's, but these have undergone large amounts of change recently. - - We have encountered bugs with this functionality, see: - http://stackoverflow.com/questions/19145587/bq-py-not-paging-results """ # dtype Map -
Closes https://github.com/pydata/pandas/issues/6096
https://api.github.com/repos/pandas-dev/pandas/pulls/6157
2014-01-29T01:47:21Z
2014-01-29T02:13:14Z
2014-01-29T02:13:14Z
2014-06-13T13:20:42Z
TST: rec arrays don't support datetimes in creation on certain platforms, related (GH6140)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index f9218d34f6ec5..50c5cca935553 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3967,7 +3967,14 @@ def test_from_records_with_datetimes(self): arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] dtypes = [('EXPIRY', '<M8[ns]')] - recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + + # this may fail on certain platforms because of a numpy issue + # related GH6140 + try: + recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + except (ValueError): + raise nose.SkipTest('rec arrays with datetimes not supported') + result = DataFrame.from_records(recarray) assert_frame_equal(result,expected) diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 83e36d9da3830..44d90c78e07d1 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -650,19 +650,19 @@ def test_loc_setitem_frame_multiples(self): # multiple setting df = DataFrame({ 'A' : ['foo','bar','baz'], - 'B' : range(3) }) + 'B' : Series(range(3),dtype=np.int64) }) df.loc[0:1] = df.loc[1:2] expected = DataFrame({ 'A' : ['bar','baz','baz'], - 'B' : [1,2,2] }) + 'B' : Series([1,2,2],dtype=np.int64) }) assert_frame_equal(df, expected) # multiple setting with frame on rhs (with M8) df = DataFrame({ 'date' : date_range('2000-01-01','2000-01-5'), - 'val' : range(5) }) + 'val' : Series(range(5),dtype=np.int64) }) expected = DataFrame({ 'date' : [Timestamp('20000101'),Timestamp('20000102'),Timestamp('20000101'), Timestamp('20000102'),Timestamp('20000103')], - 'val' : [0,1,0,1,2] }) + 'val' : Series([0,1,0,1,2],dtype=np.int64) }) df.loc[2:4] = df.loc[0:2] assert_frame_equal(df, expected)
related #6140, #6142
https://api.github.com/repos/pandas-dev/pandas/pulls/6156
2014-01-29T00:59:07Z
2014-01-29T01:34:23Z
2014-01-29T01:34:23Z
2014-06-19T22:41:01Z
PERF: perf regression index construction from series (GH6150)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 7e11a0b036a6c..9d2c7a4078f95 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -104,6 +104,7 @@ Improvements to existing features - add ability to recognize '%p' format code (am/pm) to date parsers when the specific format is supplied (:issue:`5361`) - Fix performance regression in JSON IO (:issue:`5765`) + - performance regression in Index construction from Series (:issue:`6150`) .. _release.bug_fixes-0.13.1: diff --git a/pandas/core/index.py b/pandas/core/index.py index c42d7a29bb8f6..bf485e40da92b 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -15,7 +15,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, is_float, is_integer +from pandas.core.common import _values_from_object, is_float, is_integer, ABCSeries from pandas.core.config import get_option # simplify @@ -105,7 +105,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, return subarr from pandas.tseries.period import PeriodIndex - if isinstance(data, np.ndarray): + if isinstance(data, (np.ndarray, ABCSeries)): if issubclass(data.dtype.type, np.datetime64): from pandas.tseries.index import DatetimeIndex result = DatetimeIndex(data, copy=copy, name=name, **kwargs) @@ -212,7 +212,7 @@ def _coerce_to_ndarray(cls, data): cls._scalar_data_error(data) # other iterable of some kind - if not isinstance(data, (list, tuple)): + if not isinstance(data, (ABCSeries, list, tuple)): data = list(data) data = np.asarray(data) return data @@ -767,7 +767,7 @@ def asof(self, label): For a sorted index, return the most recent label up to and including the passed label. Return NaN if not found """ - if isinstance(label, (Index, np.ndarray)): + if isinstance(label, (Index, ABCSeries, np.ndarray)): raise TypeError('%s' % type(label)) if label not in self: @@ -1535,7 +1535,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, (ABCSeries, np.ndarray)): raise KeyError("cannot peform a slice operation " "on a non-unique non-monotonic index") diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 4834438914446..5cd3b8a87c974 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, - notnull) + notnull, ABCSeries) from pandas.core.index import Index, Int64Index, _Identity import pandas.compat as compat from pandas.compat import u @@ -52,9 +52,9 @@ def f(self): def _join_i8_wrapper(joinf, with_indexers=True): @staticmethod def wrapper(left, right): - if isinstance(left, np.ndarray): + if isinstance(left, (np.ndarray, ABCSeries)): left = left.view('i8', type=np.ndarray) - if isinstance(right, np.ndarray): + if isinstance(right, (np.ndarray, ABCSeries)): right = right.view('i8', type=np.ndarray) results = joinf(left, right) if with_indexers: @@ -77,7 +77,7 @@ def wrapper(self, other): other = DatetimeIndex(other) elif isinstance(other, compat.string_types): other = _to_m8(other, tz=self.tz) - elif not isinstance(other, np.ndarray): + elif not isinstance(other, (np.ndarray, ABCSeries)): other = _ensure_datetime64(other) result = func(other) @@ -195,7 +195,7 @@ def __new__(cls, data=None, tz=tz, normalize=normalize, closed=closed, infer_dst=infer_dst) - if not isinstance(data, np.ndarray): + if not isinstance(data, (np.ndarray, ABCSeries)): if np.isscalar(data): raise ValueError('DatetimeIndex() must be called with a ' 'collection of some kind, %s was passed' @@ -228,6 +228,8 @@ def __new__(cls, data=None, yearfirst=yearfirst) if issubclass(data.dtype.type, np.datetime64): + if isinstance(data, ABCSeries): + data = data.values if isinstance(data, DatetimeIndex): if tz is None: tz = data.tz @@ -1400,7 +1402,7 @@ def freqstr(self): nanosecond = _field_accessor('nanosecond', 'ns') weekofyear = _field_accessor('weekofyear', 'woy') week = weekofyear - dayofweek = _field_accessor('dayofweek', 'dow', + dayofweek = _field_accessor('dayofweek', 'dow', "The day of the week with Monday=0, Sunday=6") weekday = dayofweek dayofyear = _field_accessor('dayofyear', 'doy') diff --git a/vb_suite/ctors.py b/vb_suite/ctors.py index 2eaf961108ce9..6af8e65b8f57d 100644 --- a/vb_suite/ctors.py +++ b/vb_suite/ctors.py @@ -29,3 +29,11 @@ """ ctor_index_array_string = Benchmark('Index(data)', setup=setup) + +# index constructors +setup = common_setup + """ +s = Series([Timestamp('20110101'),Timestamp('20120101'),Timestamp('20130101')]*1000) +""" +index_from_series_ctor = Benchmark('Index(s)', setup=setup) + +dtindex_from_series_ctor = Benchmark('DatetimeIndex(s)', setup=setup)
closes #6150
https://api.github.com/repos/pandas-dev/pandas/pulls/6153
2014-01-28T23:17:21Z
2014-01-29T00:48:24Z
2014-01-29T00:48:24Z
2014-06-22T09:52:31Z
BUG: fix loc setitem with a dataframe on rhs, multiple items, and a datetimelike
diff --git a/doc/source/release.rst b/doc/source/release.rst index 7e11a0b036a6c..32921cb5f955b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -165,6 +165,8 @@ Bug Fixes - Bug in ``DataFrame.apply`` when using mixed datelike reductions (:issue:`6125`) - Bug in ``DataFrame.append`` when appending a row with different columns (:issue:`6129`) - Bug in DataFrame construction with recarray and non-ns datetime dtype (:issue:`6140`) + - Bug in ``.loc`` setitem indexing with a datafrme on rhs, multiple item setting, and + a datetimelike (:issue:`6152`) pandas 0.13.0 ------------- diff --git a/pandas/core/common.py b/pandas/core/common.py index 5b82f6e140b6b..134e43bcd006a 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -275,6 +275,10 @@ def notnull(obj): return not res return -res +def _is_null_datelike_scalar(other): + """ test whether the object is a null datelike, e.g. Nat + but guard against passing a non-scalar """ + return (np.isscalar(other) and (isnull(other) or other == tslib.iNaT)) or other is pd.NaT or other is None def array_equivalent(left, right): """ diff --git a/pandas/core/internals.py b/pandas/core/internals.py index c97b9b28de18f..fdff3ab99df22 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -10,7 +10,7 @@ from pandas.core.common import (_possibly_downcast_to_dtype, isnull, notnull, _NS_DTYPE, _TD_DTYPE, ABCSeries, is_list_like, ABCSparseSeries, _infer_dtype_from_scalar, - _values_from_object) + _values_from_object, _is_null_datelike_scalar) from pandas.core.index import (Index, MultiIndex, _ensure_index, _handle_legacy_indexes) from pandas.core.indexing import (_check_slice_bounds, _maybe_convert_indices, @@ -1275,7 +1275,7 @@ def masker(v): values = masker(values) - if isnull(other) or (np.isscalar(other) and other == tslib.iNaT): + if _is_null_datelike_scalar(other): other = np.nan elif isinstance(other, np.timedelta64): other = _coerce_scalar_to_timedelta_type(other, unit='s').item() @@ -1586,7 +1586,7 @@ def _try_coerce_args(self, values, other): we are going to compare vs i8, so coerce to integer values is always ndarra like, other may not be """ values = values.view('i8') - if isnull(other) or (np.isscalar(other) and other == tslib.iNaT): + if _is_null_datelike_scalar(other): other = tslib.iNaT elif isinstance(other, datetime): other = lib.Timestamp(other).asm8.view('i8') diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index d448eb42ff153..83e36d9da3830 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -646,6 +646,27 @@ def test_loc_setitem_frame(self): result = df.ix[:,1:] assert_frame_equal(result, expected) + def test_loc_setitem_frame_multiples(self): + + # multiple setting + df = DataFrame({ 'A' : ['foo','bar','baz'], + 'B' : range(3) }) + df.loc[0:1] = df.loc[1:2] + expected = DataFrame({ 'A' : ['bar','baz','baz'], + 'B' : [1,2,2] }) + assert_frame_equal(df, expected) + + + # multiple setting with frame on rhs (with M8) + df = DataFrame({ 'date' : date_range('2000-01-01','2000-01-5'), + 'val' : range(5) }) + expected = DataFrame({ 'date' : [Timestamp('20000101'),Timestamp('20000102'),Timestamp('20000101'), + Timestamp('20000102'),Timestamp('20000103')], + 'val' : [0,1,0,1,2] }) + + df.loc[2:4] = df.loc[0:2] + assert_frame_equal(df, expected) + def test_iloc_getitem_frame(self): df = DataFrame(np.random.randn(10, 4), index=lrange(0, 20, 2), columns=lrange(0,8,2))
https://api.github.com/repos/pandas-dev/pandas/pulls/6152
2014-01-28T22:44:56Z
2014-01-28T23:24:00Z
2014-01-28T23:24:00Z
2014-06-16T17:43:55Z
BLD/TST: catch more spurious errors in @network decorator
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index a6c0deb6d7827..a044b388c00c4 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -396,10 +396,9 @@ def test_read_famafrench(self): class TestFred(tm.TestCase): @network def test_fred(self): - """ - Throws an exception when DataReader can't get a 200 response from - FRED. - """ + + # Throws an exception when DataReader can't get a 200 response from + # FRED. start = datetime(2010, 1, 1) end = datetime(2013, 1, 27) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 03e11bd6661dd..3dbdb3b02c7fc 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -968,8 +968,17 @@ def dec(f): return wrapper -_network_error_classes = IOError, httplib.HTTPException +_network_errno_vals = ( + 101, # Network is unreachable + 110, # Connection timed out + 104, # Connection reset Error + 54, # Connection reset by peer + ) +_network_error_classes = (IOError, httplib.HTTPException) + +if sys.version_info[:2] >= (3,3): + _network_error_classes += (TimeoutError,) def can_connect(url, error_classes=_network_error_classes): """Try to connect to the given url. True if succeeds, False if IOError @@ -998,7 +1007,9 @@ def can_connect(url, error_classes=_network_error_classes): @optional_args def network(t, url="http://www.google.com", raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT, - check_before_test=False, error_classes=_network_error_classes): + check_before_test=False, + error_classes=_network_error_classes, + skip_errnos=_network_errno_vals): """ Label a test as requiring network connection and, if an error is encountered, only raise if it does not find a network connection. @@ -1084,7 +1095,12 @@ def wrapper(*args, **kwargs): raise SkipTest try: return t(*args, **kwargs) - except error_classes as e: + except Exception as e: + errno = getattr(e,'errno',None) + + if not isinstance(e, error_classes) and not errno in skip_errnos: + raise + if raise_on_error or can_connect(url, error_classes): raise else:
add more Exception classes, and add checking for errnos. We'll soon hit fundamental facts on errors in distributed systems. #6144, hopefully.
https://api.github.com/repos/pandas-dev/pandas/pulls/6151
2014-01-28T22:28:13Z
2014-01-28T22:28:44Z
2014-01-28T22:28:44Z
2014-06-26T02:13:51Z
ENH: Add unique and nunique to GroupBy whitelist
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 1d3d4717c6bdb..7bd49a8b3a304 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -75,7 +75,7 @@ _series_apply_whitelist = \ (_common_apply_whitelist - set(['boxplot'])) | \ - frozenset(['dtype', 'value_counts']) + frozenset(['dtype', 'value_counts', 'unique', 'nunique']) _dataframe_apply_whitelist = \ _common_apply_whitelist | frozenset(['dtypes', 'corrwith']) diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 9ce7f30c2401e..3b53e8737d166 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -3335,6 +3335,7 @@ def test_groupby_whitelist(self): 'corr', 'cov', 'value_counts', 'diff', + 'unique', 'nunique', ]) for obj, whitelist in zip((df, s),
Series.unique and Series.nunique are useful methods for querying the unique elements (or number of unique elements) in each group when used in conjunction with DataFrame.GroupBy. This commit addresses closes pydata/pandas#6146.
https://api.github.com/repos/pandas-dev/pandas/pulls/6147
2014-01-28T18:05:47Z
2014-01-28T18:21:12Z
2014-01-28T18:21:12Z
2014-06-22T16:55:55Z
BUG: Bug in DataFrame construction with recarray and non-ns datetime dtype (GH6140)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 2d21f52d6b4cd..7e11a0b036a6c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -164,6 +164,7 @@ Bug Fixes index/columns (:issue:`6121`) - Bug in ``DataFrame.apply`` when using mixed datelike reductions (:issue:`6125`) - Bug in ``DataFrame.append`` when appending a row with different columns (:issue:`6129`) + - Bug in DataFrame construction with recarray and non-ns datetime dtype (:issue:`6140`) pandas 0.13.0 ------------- diff --git a/pandas/core/common.py b/pandas/core/common.py index 30ce5166b71e7..5b82f6e140b6b 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -41,9 +41,7 @@ class AmbiguousIndexError(PandasError, KeyError): _POSSIBLY_CAST_DTYPES = set([np.dtype(t).name - for t in ['M8[ns]', '>M8[ns]', '<M8[ns]', - 'm8[ns]', '>m8[ns]', '<m8[ns]', - 'O', 'int8', + for t in ['O', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']]) @@ -1612,6 +1610,14 @@ def _possibly_convert_objects(values, convert_dates=True, def _possibly_castable(arr): + # return False to force a non-fastpath + + # check datetime64[ns]/timedelta64[ns] are valid + # otherwise try to coerce + kind = arr.dtype.kind + if kind == 'M' or kind == 'm': + return arr.dtype in _DATELIKE_DTYPES + return arr.dtype.name not in _POSSIBLY_CAST_DTYPES @@ -1681,12 +1687,30 @@ def _possibly_cast_to_datetime(value, dtype, coerce=False): else: + is_array = isinstance(value, np.ndarray) + + # catch a datetime/timedelta that is not of ns variety + # and no coercion specified + if (is_array and value.dtype.kind in ['M','m']): + dtype = value.dtype + + if dtype.kind == 'M' and dtype != _NS_DTYPE: + try: + value = tslib.array_to_datetime(value) + except: + raise + + elif dtype.kind == 'm' and dtype != _TD_DTYPE: + from pandas.tseries.timedeltas import \ + _possibly_cast_to_timedelta + value = _possibly_cast_to_timedelta(value, coerce='compat') + # only do this if we have an array and the dtype of the array is not # setup already we are not an integer/object, so don't bother with this # conversion - if (isinstance(value, np.ndarray) and not - (issubclass(value.dtype.type, np.integer) or - value.dtype == np.object_)): + elif (is_array and not ( + issubclass(value.dtype.type, np.integer) or + value.dtype == np.object_)): pass else: diff --git a/pandas/core/series.py b/pandas/core/series.py index a3bf9be71af3c..762d8aed5c697 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2536,7 +2536,10 @@ def _try_cast(arr, take_fast_path): else: subarr = _try_cast(data, True) else: - subarr = _try_cast(data, True) + # don't coerce Index types + # e.g. indexes can have different conversions (so don't fast path them) + # GH 6140 + subarr = _try_cast(data, not isinstance(data, Index)) if copy: subarr = data.copy() diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 77e8cb8d04268..f9218d34f6ec5 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -4,6 +4,7 @@ # pylint: disable-msg=W0612,E1101 from copy import deepcopy from datetime import datetime, timedelta, time +import sys import operator import re import csv @@ -3956,6 +3957,27 @@ def test_from_records_empty_with_nonempty_fields_gh3682(self): assert_array_equal(df.index, Index([], name='id')) self.assertEqual(df.index.name, 'id') + def test_from_records_with_datetimes(self): + if sys.version < LooseVersion('2.7'): + raise nose.SkipTest('rec arrays dont work properly with py2.6') + + # construction with a null in a recarray + # GH 6140 + expected = DataFrame({ 'EXPIRY' : [datetime(2005, 3, 1, 0, 0), None ]}) + + arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] + dtypes = [('EXPIRY', '<M8[ns]')] + recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + result = DataFrame.from_records(recarray) + assert_frame_equal(result,expected) + + # coercion should work too + arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] + dtypes = [('EXPIRY', '<M8[m]')] + recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + result = DataFrame.from_records(recarray) + assert_frame_equal(result,expected) + def test_to_records_floats(self): df = DataFrame(np.random.rand(10, 10)) df.to_records() @@ -5138,8 +5160,6 @@ def test_combineSeries(self): #_check_mixed_int(added, dtype = dict(A = 'int32', B = 'float64', C = 'int32', D = 'int64')) # TimeSeries - import sys - buf = StringIO() tmp = sys.stderr sys.stderr = buf
closes #6140
https://api.github.com/repos/pandas-dev/pandas/pulls/6142
2014-01-28T13:20:58Z
2014-01-28T15:39:16Z
2014-01-28T15:39:16Z
2014-06-19T22:42:08Z
BLD: use newer versions of numexpr with numpy 1.8
diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt index 186d13c6dec7c..c7cf69bc92927 100644 --- a/ci/requirements-2.7.txt +++ b/ci/requirements-2.7.txt @@ -4,7 +4,7 @@ xlwt==0.7.5 numpy==1.8.0 cython==0.19.1 bottleneck==0.6.0 -numexpr==2.0.1 +numexpr==2.2.2 tables==2.3.1 matplotlib==1.1.1 openpyxl==1.6.2
https://api.github.com/repos/pandas-dev/pandas/pulls/6141
2014-01-28T13:19:13Z
2014-01-28T13:19:18Z
2014-01-28T13:19:18Z
2014-06-14T09:36:10Z
[DOC] install.rst: numexpr and anaconda warnings
diff --git a/doc/source/install.rst b/doc/source/install.rst index 631973934cc3b..68577ff913e77 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -74,8 +74,9 @@ Dependencies Recommended Dependencies ~~~~~~~~~~~~~~~~~~~~~~~~ - * `numexpr <http://code.google.com/p/numexpr/>`__: for accelerating certain numerical operations. - ``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups. + * `numexpr <http://code.google.com/p/numexpr/>`__, version 2 or higher: for accelerating certain numerical operations. + ``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups. Version 2.3 or higher + is highly recommended for NumPy 1.8.0+ users. * `bottleneck <http://berkeleyanalytics.com/bottleneck>`__: for accelerating certain types of ``nan`` evaluations. ``bottleneck`` uses specialized cython routines to achieve large speedups. @@ -134,12 +135,15 @@ Optional Dependencies `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 + 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>` + * If you're using `Anaconda`_ distribution you may want to make sure that + both mandatory and recommended dependencies are up to date (`numpy` and + `numexpr` in particular); you may have to manually upgrade them. + Additionally, you should definitely read :ref:`the gotchas about HTML + parsing libraries <html-gotchas>`. .. note::
- Anaconda currently provides `pandas` v0.13, `numpy` 1.7.1 and `numexpr` 2.2.2 as the latest versions (#6056). - There seem to exist rare but evil lurking bugs when using `numexpr` <= 2.2.2 and `numpy` >= 1.8.0 (#6119).
https://api.github.com/repos/pandas-dev/pandas/pulls/6138
2014-01-28T10:19:13Z
2014-01-28T15:42:35Z
null
2014-06-19T09:31:18Z
PERF: fix JSON performance regression from 0.12 (GH5765)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 9324d8b28f107..d4b2ee612965f 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -119,6 +119,7 @@ Bug Fixes - Regresssion in handling of empty Series as indexers to Series (:issue:`5877`) - Bug in internal caching, related to (:issue:`5727`) - Testing bug in reading json/msgpack from a non-filepath on windows under py3 (:issue:`5874`) + - Fix performance regression in JSON IO (:issue:`5765`) - Bug when assigning to .ix[tuple(...)] (:issue:`5896`) - Bug in fully reindexing a Panel (:issue:`5905`) - Bug in idxmin/max with object dtypes (:issue:`5914`) diff --git a/pandas/src/ujson/lib/ultrajsondec.c b/pandas/src/ujson/lib/ultrajsondec.c index 85a8387547641..bae075b4376b1 100644 --- a/pandas/src/ujson/lib/ultrajsondec.c +++ b/pandas/src/ujson/lib/ultrajsondec.c @@ -894,15 +894,23 @@ JSOBJ JSON_DecodeObject(JSONObjectDecoder *dec, const char *buffer, size_t cbBuf ds.dec = dec; - locale = strdup(setlocale(LC_NUMERIC, NULL)); - if (!locale) + locale = setlocale(LC_NUMERIC, NULL); + if (strcmp(locale, "C")) { - return SetError(&ds, -1, "Could not reserve memory block"); + locale = strdup(locale); + if (!locale) + { + return SetError(&ds, -1, "Could not reserve memory block"); + } + setlocale(LC_NUMERIC, "C"); + ret = decode_any (&ds); + setlocale(LC_NUMERIC, locale); + free(locale); + } + else + { + ret = decode_any (&ds); } - setlocale(LC_NUMERIC, "C"); - ret = decode_any (&ds); - setlocale(LC_NUMERIC, locale); - free(locale); if (ds.escHeap) { diff --git a/pandas/src/ujson/lib/ultrajsonenc.c b/pandas/src/ujson/lib/ultrajsonenc.c index 17048bd86adc2..5e2a226ae8d63 100644 --- a/pandas/src/ujson/lib/ultrajsonenc.c +++ b/pandas/src/ujson/lib/ultrajsonenc.c @@ -917,16 +917,24 @@ char *JSON_EncodeObject(JSOBJ obj, JSONObjectEncoder *enc, char *_buffer, size_t enc->end = enc->start + _cbBuffer; enc->offset = enc->start; - locale = strdup(setlocale(LC_NUMERIC, NULL)); - if (!locale) + locale = setlocale(LC_NUMERIC, NULL); + if (strcmp(locale, "C")) { - SetError(NULL, enc, "Could not reserve memory block"); - return NULL; + locale = strdup(locale); + if (!locale) + { + SetError(NULL, enc, "Could not reserve memory block"); + return NULL; + } + setlocale(LC_NUMERIC, "C"); + encode (obj, enc, NULL, 0); + setlocale(LC_NUMERIC, locale); + free(locale); + } + else + { + encode (obj, enc, NULL, 0); } - setlocale(LC_NUMERIC, "C"); - encode (obj, enc, NULL, 0); - setlocale(LC_NUMERIC, locale); - free(locale); Buffer_Reserve(enc, 1); if (enc->errorMsg) diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c index 13d403cdb2b7b..f6cb5b9803e25 100644 --- a/pandas/src/ujson/python/objToJSON.c +++ b/pandas/src/ujson/python/objToJSON.c @@ -74,6 +74,8 @@ typedef struct __NpyArrContext npy_intp stride; npy_intp ndim; npy_intp index[NPY_MAXDIMS]; + int type_num; + PyArray_GetItemFunc* getitem; char** rowLabels; char** columnLabels; @@ -114,6 +116,10 @@ typedef struct __PyObjectEncoder // pass through the NpyArrContext when encoding multi-dimensional arrays NpyArrContext* npyCtxtPassthru; + // pass through a request for a specific encoding context + int requestType; + TypeContext* requestTypeContext; + int datetimeIso; PANDAS_DATETIMEUNIT datetimeUnit; @@ -182,6 +188,35 @@ void initObjToJSON(void) return NUMPY_IMPORT_ARRAY_RETVAL; } +TypeContext* createTypeContext() +{ + TypeContext *pc; + + pc = PyObject_Malloc(sizeof(TypeContext)); + if (!pc) + { + PyErr_NoMemory(); + return NULL; + } + pc->newObj = NULL; + pc->dictObj = NULL; + pc->itemValue = NULL; + pc->itemName = NULL; + pc->attrList = NULL; + pc->index = 0; + pc->size = 0; + pc->longValue = 0; + pc->cStr = NULL; + pc->npyarr = NULL; + pc->rowLabels = NULL; + pc->columnLabels = NULL; + pc->transpose = 0; + pc->rowLabelsLen = 0; + pc->columnLabelsLen = 0; + + return pc; +} + static void *PyIntToINT32(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen) { PyObject *obj = (PyObject *) _obj; @@ -288,6 +323,7 @@ static void *PyDateTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, s pandas_datetimestruct dts; PyObject *obj = (PyObject *) _obj; + PRINTMARK(); if (!convert_pydatetime_to_datetimestruct(obj, &dts, NULL, 1)) { @@ -310,6 +346,8 @@ static void *NpyDatetime64ToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue pandas_datetimestruct dts; PyObject *obj = (PyObject *) _obj; + PRINTMARK(); + pandas_datetime_to_datetimestruct(PyLong_AsLongLong(obj), PANDAS_FR_ns, &dts); return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen); } @@ -338,6 +376,26 @@ static void *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_ return outValue; } +void requestDateEncoding(PyObject* obj, PyObjectEncoder* pyenc) +{ + if (obj == Py_None) { + pyenc->requestType = JT_NULL; + return; + } + + if (pyenc->datetimeIso) + { + pyenc->requestType = JT_UTF8; + } + else + { + pyenc->requestType = JT_LONG; + } + pyenc->requestTypeContext = createTypeContext(); + pyenc->requestTypeContext->PyTypeToJSON = NpyDatetime64ToJSON; +} + + //============================================================================= // Numpy array iteration functions //============================================================================= @@ -374,9 +432,11 @@ void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) } npyarr->array = (PyObject*) obj; + npyarr->getitem = (PyArray_GetItemFunc*) PyArray_DESCR(obj)->f->getitem; npyarr->dataptr = PyArray_DATA(obj); npyarr->ndim = PyArray_NDIM(obj) - 1; npyarr->curdim = 0; + npyarr->type_num = PyArray_DESCR(obj)->type_num; if (GET_TC(tc)->transpose) { @@ -450,7 +510,9 @@ void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) int NpyArr_iterNextItem(JSOBJ _obj, JSONTypeContext *tc) { NpyArrContext* npyarr; + PRINTMARK(); + npyarr = GET_TC(tc)->npyarr; if (PyErr_Occurred()) @@ -469,7 +531,22 @@ int NpyArr_iterNextItem(JSOBJ _obj, JSONTypeContext *tc) return 0; } - GET_TC(tc)->itemValue = PyArray_ToScalar(npyarr->dataptr, npyarr->array); +#if NPY_API_VERSION < 0x00000007 + if(PyTypeNum_ISDATETIME(npyarr->type_num)) + { + GET_TC(tc)->itemValue = PyArray_ToScalar(npyarr->dataptr, npyarr->array); + } + else + { + GET_TC(tc)->itemValue = npyarr->getitem(npyarr->dataptr, npyarr->array); + } +#else + GET_TC(tc)->itemValue = npyarr->getitem(npyarr->dataptr, npyarr->array); + if(PyTypeNum_ISDATETIME(npyarr->type_num)) + { + requestDateEncoding(GET_TC(tc)->itemValue, (PyObjectEncoder*) tc->encoder); + } +#endif npyarr->dataptr += npyarr->stride; npyarr->index[npyarr->stridedim]++; @@ -1104,6 +1181,8 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in char** ret; char *dataptr, *cLabel, *origend, *origst, *origoffset; char labelBuffer[NPY_JSON_BUFSIZE]; + PyArray_GetItemFunc* getitem; + int type_num; PRINTMARK(); if (PyArray_SIZE(labels) < num) @@ -1132,10 +1211,27 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in stride = PyArray_STRIDE(labels, 0); dataptr = PyArray_DATA(labels); + getitem = (PyArray_GetItemFunc*) PyArray_DESCR(labels)->f->getitem; + type_num = PyArray_DESCR(labels)->type_num; for (i = 0; i < num; i++) { - item = PyArray_ToScalar(dataptr, labels); +#if NPY_API_VERSION < 0x00000007 + if(PyTypeNum_ISDATETIME(type_num)) + { + item = PyArray_ToScalar(dataptr, labels); + } + else + { + item = getitem(dataptr, labels); + } +#else + item = getitem(dataptr, labels); + if(PyTypeNum_ISDATETIME(type_num)) + { + requestDateEncoding(item, (PyObjectEncoder*) enc); + } +#endif if (!item) { NpyArr_freeLabels(ret, num); @@ -1202,39 +1298,28 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) obj = (PyObject*) _obj; enc = (PyObjectEncoder*) tc->encoder; - tc->prv = PyObject_Malloc(sizeof(TypeContext)); - pc = (TypeContext *) tc->prv; - if (!pc) + if (enc->requestType) { - tc->type = JT_INVALID; - PyErr_NoMemory(); + PRINTMARK(); + tc->type = enc->requestType; + tc->prv = enc->requestTypeContext; + + enc->requestType = 0; + enc->requestTypeContext = NULL; return; } - pc->newObj = NULL; - pc->dictObj = NULL; - pc->itemValue = NULL; - pc->itemName = NULL; - pc->attrList = NULL; - pc->index = 0; - pc->size = 0; - pc->longValue = 0; - pc->cStr = NULL; - pc->npyarr = NULL; - pc->rowLabels = NULL; - pc->columnLabels = NULL; - pc->transpose = 0; - pc->rowLabelsLen = 0; - pc->columnLabelsLen = 0; - - if (PyIter_Check(obj)) + pc = createTypeContext(); + if (!pc) { - PRINTMARK(); - goto ISITERABLE; + tc->type = JT_INVALID; + return; } + tc->prv = pc; if (PyIter_Check(obj) || PyArray_Check(obj)) { + PRINTMARK(); goto ISITERABLE; } @@ -1263,28 +1348,6 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) return; } else - if (PyArray_IsScalar(obj, Datetime)) - { - PRINTMARK(); - if (((PyDatetimeScalarObject*) obj)->obval == get_nat()) { - PRINTMARK(); - tc->type = JT_NULL; - return; - } - - PRINTMARK(); - pc->PyTypeToJSON = NpyDateTimeToJSON; - if (enc->datetimeIso) - { - tc->type = JT_UTF8; - } - else - { - tc->type = JT_LONG; - } - return; - } - else if (PyInt_Check(obj)) { PRINTMARK(); @@ -1297,29 +1360,18 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) return; } else - if (PyArray_IsScalar(obj, Bool)) - { - PRINTMARK(); - PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_BOOL)); - tc->type = (GET_TC(tc)->longValue) ? JT_TRUE : JT_FALSE; - return; - } - else - if (PyArray_IsScalar(obj, Integer)) + if (PyFloat_Check(obj)) { PRINTMARK(); - pc->PyTypeToJSON = PyLongToINT64; - tc->type = JT_LONG; - PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_INT64)); - - exc = PyErr_Occurred(); - - if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) + val = PyFloat_AS_DOUBLE (obj); + if (npy_isnan(val) || npy_isinf(val)) { - PRINTMARK(); - goto INVALID; + tc->type = JT_NULL; + } + else + { + pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE; } - return; } else @@ -1337,18 +1389,10 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) return; } else - if (PyFloat_Check(obj)) + if (obj == Py_None) { PRINTMARK(); - val = PyFloat_AS_DOUBLE (obj); - if (npy_isnan(val) || npy_isinf(val)) - { - tc->type = JT_NULL; - } - else - { - pc->PyTypeToJSON = PyFloatToDOUBLE; tc->type = JT_DOUBLE; - } + tc->type = JT_NULL; return; } else @@ -1359,13 +1403,6 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) return; } else - if (PyArray_IsScalar(obj, Float)) - { - PRINTMARK(); - pc->PyTypeToJSON = NpyFloatToDOUBLE; tc->type = JT_DOUBLE; - return; - } - else if (PyDateTime_Check(obj) || PyDate_Check(obj)) { if (PyObject_TypeCheck(obj, cls_nat)) @@ -1397,67 +1434,63 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) return; } else - if (obj == Py_None) + if (PyArray_IsScalar(obj, Datetime)) { PRINTMARK(); - tc->type = JT_NULL; - return; - } - - -ISITERABLE: - - if (PyDict_Check(obj)) - { + if (((PyDatetimeScalarObject*) obj)->obval == get_nat()) { PRINTMARK(); - tc->type = JT_OBJECT; - pc->iterBegin = Dict_iterBegin; - pc->iterEnd = Dict_iterEnd; - pc->iterNext = Dict_iterNext; - pc->iterGetValue = Dict_iterGetValue; - pc->iterGetName = Dict_iterGetName; - pc->dictObj = obj; - Py_INCREF(obj); - + tc->type = JT_NULL; return; + } + + PRINTMARK(); + pc->PyTypeToJSON = NpyDateTimeToJSON; + if (enc->datetimeIso) + { + tc->type = JT_UTF8; + } + else + { + tc->type = JT_LONG; + } + return; } else - if (PyList_Check(obj)) + if (PyArray_IsScalar(obj, Integer)) { + PRINTMARK(); + pc->PyTypeToJSON = PyLongToINT64; + tc->type = JT_LONG; + PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_INT64)); + + exc = PyErr_Occurred(); + + if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) + { PRINTMARK(); - tc->type = JT_ARRAY; - pc->iterBegin = List_iterBegin; - pc->iterEnd = List_iterEnd; - pc->iterNext = List_iterNext; - pc->iterGetValue = List_iterGetValue; - pc->iterGetName = List_iterGetName; - return; + goto INVALID; + } + + return; } else - if (PyTuple_Check(obj)) + if (PyArray_IsScalar(obj, Bool)) { - PRINTMARK(); - tc->type = JT_ARRAY; - pc->iterBegin = Tuple_iterBegin; - pc->iterEnd = Tuple_iterEnd; - pc->iterNext = Tuple_iterNext; - pc->iterGetValue = Tuple_iterGetValue; - pc->iterGetName = Tuple_iterGetName; - return; + PRINTMARK(); + PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_BOOL)); + tc->type = (GET_TC(tc)->longValue) ? JT_TRUE : JT_FALSE; + return; } else - if (PyAnySet_Check(obj)) + if (PyArray_IsScalar(obj, Float) || PyArray_IsScalar(obj, Double)) { PRINTMARK(); - tc->type = JT_ARRAY; - pc->iterBegin = Iter_iterBegin; - pc->iterEnd = Iter_iterEnd; - pc->iterNext = Iter_iterNext; - pc->iterGetValue = Iter_iterGetValue; - pc->iterGetName = Iter_iterGetName; + pc->PyTypeToJSON = NpyFloatToDOUBLE; tc->type = JT_DOUBLE; return; } - else + +ISITERABLE: + if (PyObject_TypeCheck(obj, cls_index)) { if (enc->outputFormat == SPLIT) @@ -1629,6 +1662,57 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) } return; } + else + if (PyDict_Check(obj)) + { + PRINTMARK(); + tc->type = JT_OBJECT; + pc->iterBegin = Dict_iterBegin; + pc->iterEnd = Dict_iterEnd; + pc->iterNext = Dict_iterNext; + pc->iterGetValue = Dict_iterGetValue; + pc->iterGetName = Dict_iterGetName; + pc->dictObj = obj; + Py_INCREF(obj); + + return; + } + else + if (PyList_Check(obj)) + { + PRINTMARK(); + tc->type = JT_ARRAY; + pc->iterBegin = List_iterBegin; + pc->iterEnd = List_iterEnd; + pc->iterNext = List_iterNext; + pc->iterGetValue = List_iterGetValue; + pc->iterGetName = List_iterGetName; + return; + } + else + if (PyTuple_Check(obj)) + { + PRINTMARK(); + tc->type = JT_ARRAY; + pc->iterBegin = Tuple_iterBegin; + pc->iterEnd = Tuple_iterEnd; + pc->iterNext = Tuple_iterNext; + pc->iterGetValue = Tuple_iterGetValue; + pc->iterGetName = Tuple_iterGetName; + return; + } + else + if (PyAnySet_Check(obj)) + { + PRINTMARK(); + tc->type = JT_ARRAY; + pc->iterBegin = Iter_iterBegin; + pc->iterEnd = Iter_iterEnd; + pc->iterNext = Iter_iterNext; + pc->iterGetValue = Iter_iterGetValue; + pc->iterGetName = Iter_iterGetName; + return; + } toDictFunc = PyObject_GetAttrString(obj, "toDict"); @@ -1810,6 +1894,8 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs) JSONObjectEncoder* encoder = (JSONObjectEncoder*) &pyEncoder; pyEncoder.npyCtxtPassthru = NULL; + pyEncoder.requestType = 0; + pyEncoder.requestTypeContext = NULL; pyEncoder.datetimeIso = 0; pyEncoder.datetimeUnit = PANDAS_FR_ms; pyEncoder.outputFormat = COLUMNS; diff --git a/vb_suite/packers.py b/vb_suite/packers.py index 9af6a6b1b0c4e..f2eac0e28cd44 100644 --- a/vb_suite/packers.py +++ b/vb_suite/packers.py @@ -92,3 +92,23 @@ def remove(f): packers_write_hdf_table = Benchmark("df.to_hdf(f,'df',table=True)", setup, cleanup="remove(f)", start_date=start_date) +#---------------------------------------------------------------------- +# json + +setup_int_index = """ +import numpy as np +df.index = np.arange(50000) +""" + +setup = common_setup + """ +df.to_json(f,orient='split') +""" +packers_read_json_date_index = Benchmark("pd.read_json(f, orient='split')", setup, start_date=start_date) +setup = setup + setup_int_index +packers_read_json = Benchmark("pd.read_json(f, orient='split')", setup, start_date=start_date) + +setup = common_setup + """ +""" +packers_write_json_date_index = Benchmark("df.to_json(f,orient='split')", setup, cleanup="remove(f)", start_date=start_date) +setup = setup + setup_int_index +packers_write_json = Benchmark("df.to_json(f,orient='split')", setup, cleanup="remove(f)", start_date=start_date)
This fixes the main JSON performance regression in v0.13 (closes #5765). The main bottleneck was the use of intermediate NumPy scalars (from PR #4498). I introduced code to avoid the use of NumPy scalars. Also: - checks current locale so locale fudging is only done if necessary - added numpy 1.6 preprocessor switches as it still requires the use of scalars due to its weird datetime handling - reorgranised some of the if/else checks in `objToJSON.c` based on likelihood. - added some JSON benchmarks to vbench to try and avoid future regressions. 0.12 ``` python In [1]: import pandas as pd, numpy as np In [2]: df = pd.DataFrame(np.random.rand(100000,10)) In [3]: %timeit df.to_json(orient='split') 10 loops, best of 3: 119 ms per loop In [4]: pd.__version__, np.__version__ Out[4]: ('0.12.0', '1.8.0') ``` This PR ``` python In [1]: import pandas as pd, numpy as np In [2]: df = pd.DataFrame(np.random.rand(100000,10)) In [3]: %timeit df.to_json(orient='split') 10 loops, best of 3: 119 ms per loop In [4]: pd.__version__, np.__version__ Out[4]: ('0.13.0-406-ga18e5e6', '1.8.0') ``` While this solves the main performance issue, using vbench this PR still appears to be a bit slower than v0.12 (~ 2 - 5%) but it's unclear where the slowdown is coming from. @jreback do you still have a windows box / vm that you could test on?
https://api.github.com/repos/pandas-dev/pandas/pulls/6137
2014-01-28T08:05:02Z
2014-01-28T12:40:18Z
2014-01-28T12:40:18Z
2014-06-14T21:42:59Z
ENH partial sorting for mi in sortlevel
diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt index 05569dbdba702..9654fe4a2e45d 100644 --- a/doc/source/v0.14.0.txt +++ b/doc/source/v0.14.0.txt @@ -436,6 +436,8 @@ Enhancements - ``quotechar``, ``doublequote``, and ``escapechar`` can now be specified when using ``DataFrame.to_csv`` (:issue:`5414`, :issue:`4528`) +- Partially sort by only the specified levels of a MultiIndex with the + ``sort_remaining`` boolean kwarg. (:issue:`3984`) - Added a ``to_julian_date`` function to ``TimeStamp`` and ``DatetimeIndex`` to convert to the Julian Date used primarily in astronomy. (:issue:`4041`) - ``DataFrame.to_stata`` will now check data for compatibility with Stata data types diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d330d4309b13e..f072d0a37cedc 100755 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2634,7 +2634,8 @@ def trans(v): else: return self.take(indexer, axis=axis, convert=False, is_copy=False) - def sortlevel(self, level=0, axis=0, ascending=True, inplace=False): + def sortlevel(self, level=0, axis=0, ascending=True, + inplace=False, sort_remaining=True): """ Sort multilevel index by chosen axis and primary level. Data will be lexicographically sorted by the chosen level followed by the other @@ -2647,6 +2648,8 @@ def sortlevel(self, level=0, axis=0, ascending=True, inplace=False): ascending : boolean, default True inplace : boolean, default False Sort the DataFrame without creating a new instance + sort_remaining : boolean, default True + Sort by the other levels too. Returns ------- @@ -2657,7 +2660,8 @@ def sortlevel(self, level=0, axis=0, ascending=True, inplace=False): if not isinstance(the_axis, MultiIndex): raise TypeError('can only sort by level with a hierarchical index') - new_axis, indexer = the_axis.sortlevel(level, ascending=ascending) + new_axis, indexer = the_axis.sortlevel(level, ascending=ascending, + sort_remaining=sort_remaining) if self._is_mixed_type and not inplace: ax = 'index' if axis == 0 else 'columns' diff --git a/pandas/core/index.py b/pandas/core/index.py index e8403bfe8b4f8..640f65e0f374c 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -3014,17 +3014,19 @@ def reorder_levels(self, order): def __getslice__(self, i, j): return self.__getitem__(slice(i, j)) - def sortlevel(self, level=0, ascending=True): + def sortlevel(self, level=0, ascending=True, sort_remaining=True): """ Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Parameters ---------- - level : int or str, default 0 + level : list-like, int or str, default 0 If a string is given, must be a name of the level + If list-like must be names or ints of levels. ascending : boolean, default True False to sort in descending order + sort_remaining : sort by the remaining levels after level. Returns ------- @@ -3033,16 +3035,27 @@ def sortlevel(self, level=0, ascending=True): from pandas.core.groupby import _indexer_from_factorized labels = list(self.labels) + shape = list(self.levshape) - level = self._get_level_number(level) - primary = labels.pop(level) + if isinstance(level, (str, int)): + level = [level] + level = [self._get_level_number(lev) for lev in level] - shape = list(self.levshape) - primshp = shape.pop(level) + # partition labels and shape + primary = tuple(labels.pop(lev - i) for i, lev in enumerate(level)) + primshp = tuple(shape.pop(lev - i) for i, lev in enumerate(level)) - indexer = _indexer_from_factorized((primary,) + tuple(labels), - (primshp,) + tuple(shape), + if sort_remaining: + primary += primary + tuple(labels) + primshp += primshp + tuple(shape) + sortorder = None + else: + sortorder = level[0] + + indexer = _indexer_from_factorized(primary, + primshp, compress=False) + if not ascending: indexer = indexer[::-1] @@ -3050,7 +3063,7 @@ def sortlevel(self, level=0, ascending=True): new_labels = [lab.take(indexer) for lab in self.labels] new_index = MultiIndex(labels=new_labels, levels=self.levels, - names=self.names, sortorder=level, + names=self.names, sortorder=sortorder, verify_integrity=False) return new_index, indexer diff --git a/pandas/core/series.py b/pandas/core/series.py index 70b73c56772aa..cfd69ac0c577b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1758,7 +1758,7 @@ def _try_kind_sort(arr): return self._constructor(arr[sortedIdx], index=self.index[sortedIdx])\ .__finalize__(self) - def sortlevel(self, level=0, ascending=True): + def sortlevel(self, level=0, ascending=True, sort_remaining=True): """ Sort Series with MultiIndex by chosen level. Data will be lexicographically sorted by the chosen level followed by the other @@ -1776,7 +1776,8 @@ def sortlevel(self, level=0, ascending=True): if not isinstance(self.index, MultiIndex): raise TypeError('can only sort by level with a hierarchical index') - new_index, indexer = self.index.sortlevel(level, ascending=ascending) + new_index, indexer = self.index.sortlevel(level, ascending=ascending, + sort_remaining=sort_remaining) new_values = self.values.take(indexer) return self._constructor(new_values, index=new_index).__finalize__(self) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index f273c794a7f05..d52579f8235e6 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -10083,6 +10083,15 @@ def test_sort_index_duplicates(self): result = df.sort_index(by=('a',1)) assert_frame_equal(result, expected) + def test_sortlevel(self): + mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) + df = DataFrame([[1, 2], [3, 4]], mi) + res = df.sortlevel('A', sort_remaining=False) + assert_frame_equal(df, res) + + res = df.sortlevel(['A', 'B'], sort_remaining=False) + assert_frame_equal(df, res) + def test_sort_datetimes(self): # GH 3461, argsort / lexsort differences for a datetime column diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index f4d90b533a0f7..e134560231431 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -2410,6 +2410,11 @@ def test_sortlevel(self): sorted_idx, _ = index.sortlevel(1, ascending=False) self.assert_(sorted_idx.equals(expected[::-1])) + def test_sortlevel_not_sort_remaining(self): + mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) + sorted_idx, _ = mi.sortlevel('A', sort_remaining=False) + self.assert_(sorted_idx.equals(mi)) + def test_sortlevel_deterministic(self): tuples = [('bar', 'one'), ('foo', 'two'), ('qux', 'two'), ('foo', 'one'), ('baz', 'two'), ('qux', 'one')] diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 5b088598dfcec..562fb34fd9a3c 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -5189,6 +5189,23 @@ def test_unstack(self): unstacked = s.unstack(0) assert_frame_equal(unstacked, expected) + def test_sortlevel(self): + mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) + s = Series([1, 2], mi) + backwards = s.iloc[[1, 0]] + + res = s.sortlevel('A') + assert_series_equal(backwards, res) + + res = s.sortlevel(['A', 'B']) + assert_series_equal(backwards, res) + + res = s.sortlevel('A', sort_remaining=False) + assert_series_equal(s, res) + + res = s.sortlevel(['A', 'B'], sort_remaining=False) + assert_series_equal(s, res) + def test_head_tail(self): assert_series_equal(self.series.head(), self.series[:5]) assert_series_equal(self.series.tail(), self.series[-5:])
fixes #3984. Still need to tweak the docstrings and stuff. But I think this is working. cc @jtratner
https://api.github.com/repos/pandas-dev/pandas/pulls/6135
2014-01-28T06:01:06Z
2014-05-02T12:51:32Z
2014-05-02T12:51:31Z
2014-06-12T13:29:23Z
ENH: add per axis, per level indexing with tuples using loc
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 780ad57ed8f13..4daf8031e79ea 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -61,8 +61,7 @@ def _get_label(self, label, axis=0): return self.obj[label] elif (isinstance(label, tuple) and isinstance(label[axis], slice)): - - raise IndexingError('no slices here') + raise IndexingError('no slices here, handle elsewhere') try: return self.obj._xs(label, axis=axis, copy=False) @@ -677,24 +676,32 @@ def _getitem_lowerdim(self, tup): # a bit kludgy if isinstance(ax0, MultiIndex): try: + # fast path for series or for tup devoid of slices return self._get_label(tup, axis=0) except TypeError: # slices are unhashable pass except Exception as e1: if isinstance(tup[0], (slice, Index)): - raise IndexingError + raise IndexingError("Handle elsewhere") # raise the error if we are not sorted if not ax0.is_lexsorted_for_tuple(tup): raise e1 - try: - loc = ax0.get_loc(tup[0]) - except KeyError: - raise e1 + + # GH911 introduced this clause, but the regression test + # added for it now passes even without it. Let's rock the boat. + # 2014/01/27 + + # # should we abort, or keep going? + # try: + # loc = ax0.get_loc(tup[0]) + # except KeyError: + # raise e1 + if len(tup) > self.obj.ndim: - raise IndexingError + raise IndexingError("Too many indexers. handle elsewhere") # to avoid wasted computation # df.ix[d1:d2, 0] -> columns first (True) @@ -707,9 +714,9 @@ def _getitem_lowerdim(self, tup): if not _is_list_like(section): return section - # might have been a MultiIndex elif section.ndim == self.ndim: - + # we're in the middle of slicing through a MultiIndex + # revise the key wrt to `section` by inserting an _NS new_key = tup[:i] + (_NS,) + tup[i + 1:] else: @@ -725,6 +732,7 @@ def _getitem_lowerdim(self, tup): if len(new_key) == 1: new_key, = new_key + # This is an elided recursive call to iloc/loc/etc' return getattr(section, self.name)[new_key] raise IndexingError('not applicable') @@ -1148,6 +1156,14 @@ def _getitem_axis(self, key, axis=0): raise ValueError('Cannot index with multidimensional key') return self._getitem_iterable(key, axis=axis) + elif isinstance(key, tuple) and isinstance(labels, MultiIndex) and \ + any([isinstance(x,slice) for x in key]): + # handle per-axis tuple containting label criteria for + # each level (or a prefix of levels), may contain + # (None) slices, list of labels or labels + specs = _tuple_to_mi_locs(labels,key) + g = _spec_to_array_indices(labels, specs) + return self.obj.iloc[g] else: self._has_valid_type(key, axis) return self._get_label(key, axis=axis) @@ -1511,3 +1527,177 @@ def _maybe_droplevels(index, key): pass return index + +def _tuple_to_mi_locs(ix,tup): + """Convert a tuple of slices/label lists/labels to a level-wise spec + + Parameters + ---------- + ix: a sufficiently lexsorted, unique/non-dupe MultIindex. + tup: a tuple of slices, labels or lists of labels. + slice(None) is acceptable, and the case of len(tup)<ix.nlevels + will have labels from trailing levels included. + + Returns + ------- + a list containing ix.nlevels elements of either: + - 2-tuple representing a (start,stop) slice + or + - a list of label positions. + + The positions are relative to the labels of the corresponding level, not to + the entire unrolled index. + + Example (This is *not* a doctest): + >>> mi = pd.MultiIndex.from_product([['A0', 'A1', 'A2'],['B0', 'B1']]) + >>> for x in mi.get_values(): print(x) + ('A0', 'B0') + ('A0', 'B1') + ('A1', 'B0') + ('A1', 'B1') + ('A2', 'B0') + ('A2', 'B1') + >>> _tuple_to_mi_locs(mi,(slice('A0','A2'),['B0', 'B1'])) + [(0, 2), [0, 1]] + + read as: + - All labels in position [0,1) in first level + - for each of those, all labels at positions 0 or 1. + + The same effective result can be achieved by specifying the None Slice, + or omitting it completely. Note the tuple (0,2) has replaced the list [0 1], + but the outcome is the same. + + >>> _tuple_to_mi_locs(mi,(slice('A0','A2'),slice(None))) + [(0, 2), (0,2)] + + >>> _tuple_to_mi_locs(mi,(slice('A0','A2'),)) + [(0, 2), (0,2)] + + """ + + + ranges = [] + + # ix must be lexsorted to at least as many levels + # as there are elements in `tup` + assert ix.is_lexsorted_for_tuple(tup) + assert ix.is_unique + assert isinstance(ix,MultiIndex) + + for i,k in enumerate(tup): + level = ix.levels[i] + + if _is_list_like(k): + # a collection of labels to include from this level + ranges.append([level.get_loc(x) for x in k]) + continue + if k == slice(None): + start = 0 + stop = len(level) + elif isinstance(k,slice): + start = level.get_loc(k.start) + stop = len(level) + if k.stop: + stop = level.get_loc(k.stop) + else: + # a single label + start = level.get_loc(k) + stop = start + + ranges.append((start,stop)) + + for i in range(i+1,len(ix.levels)): + # omitting trailing dims + # means include all values + level = ix.levels[i] + start = 0 + stop = len(level) + ranges.append((start,stop)) + + return ranges + +def _spec_to_array_indices(ix, specs): + """Convert a tuple of slices/label lists/labels to a level-wise spec + + Parameters + ---------- + ix: a sufficiently lexsorted, unique/non-dupe MultIindex. + specs: a list of 2-tuples/list of label positions. Specifically, The + output of _tuple_to_mi_locs. + len(specs) must matc ix.nlevels. + + Returns + ------- + a generator of row positions relative to ix, corresponding to specs. + Suitable for usage with `iloc`. + + Example (This is *not* a doctest): + >>> mi = pd.MultiIndex.from_product([['A0', 'A1', 'A2'],['B0', 'B1']]) + >>> for x in mi.get_values(): print(x) + ('A0', 'B0') + ('A0', 'B1') + ('A1', 'B0') + ('A1', 'B1') + ('A2', 'B0') + ('A2', 'B1') + + >>> specs = _tuple_to_mi_locs(mi,(slice('A0','A2'),['B0', 'B1'])) + >>> list(_spec_to_array_indices(mi, specs)) + [0, 1, 2, 3] + + Which are all the labels having 'A0' to 'A2' (non-inclusive) at level=0 + and 'B0' or 'B1' at level = 0 + + """ + assert ix.is_lexsorted_for_tuple(specs) + assert len(specs) == ix.nlevels + assert ix.is_unique + assert isinstance(ix,MultiIndex) + + # step size/increment for iteration at each level + giant_steps = np.cumprod(ix.levshape[::-1])[::-1] + giant_steps[:-1] = giant_steps[1:] + giant_steps[-1] = 1 + + def _iter_vectorize(specs, i=0): + step_size = giant_steps[i] + spec=specs[i] + if isinstance(spec,tuple): + # tuples are 2-tuples of (start,stop) label indices to include + valrange = compat.range(*spec) + elif isinstance(spec,list): + # lists are discrete label indicies to include + valrange = spec + + if len(specs)-1 == i: + return np.array(valrange) + else: + tmpl = np.array([v for v in _iter_vectorize(specs,i+1)]) + res=np.tile(tmpl,(len(valrange),1)) + steps=(np.array(valrange)*step_size).reshape((len(valrange),1)) + return (res+steps).flatten() + + + def _iter_generator(specs, i=0): + step_size = giant_steps[i] + spec=specs[i] + if isinstance(spec,tuple): + # tuples are 2-tuples of (start,stop) label indices to include + valrange = compat.range(*spec) + elif isinstance(spec,list): + # lists are discrete label indicies to include + valrange = spec + + if len(specs)-1 == i: + # base case + for v in valrange: + yield v + else: + for base in valrange: + base *= step_size + for v in _iter_generator(specs,i+1): + yield base + v + # validate + + return _iter_vectorize(specs)
Selection only. Did not check (nor care) about performance at this point. Full Tests, vbenches and docs to follow in due course. Please hold off on PEP8 comments or suggestions on how this could be made more complex. I'd like to get something functional, solid and understandable in master fairly early in 0.14. @jreback, I don't often wade this deep into the gore. Would welcome your review and suggestions. Example of setting usage: http://stackoverflow.com/questions/21539260/assign-to-multiindex-slice/21539479#21539479 xref: #5641, #3057, #4036, and others ``` python In [1]: ...: def mklbl(prefix,n): ...: return ["%s%s" % (prefix,i) for i in range(n)] ...: ...: ix =pd.MultiIndex.from_product([mklbl('A',5),mklbl('B',7),mklbl('C',4),mklbl('D',2)]) ...: df=pd.DataFrame(range(len(ix.get_values())),index=ix) In [5]: df Out[5]: 0 A0 B0 C0 D0 0 D1 1 C1 D0 2 D1 3 C2 D0 4 D1 5 C3 D0 6 D1 7 B1 C0 D0 8 D1 9 C1 D0 10 D1 11 ``` ``` python In [2]: df.loc[(slice('A1','A3'),slice(None), ['C1','C3']),:] Out[2]: 0 A1 B0 C1 D0 58 D1 59 C3 D0 62 D1 63 B1 C1 D0 66 D1 67 C3 D0 70 D1 71 B2 C1 D0 74 D1 75 C3 D0 78 D1 79 B3 C1 D0 82 D1 83 C3 D0 86 D1 87 B4 C1 D0 90 D1 91 C3 D0 94 D1 95 B5 C1 D0 98 D1 99 C3 D0 102 D1 103 B6 C1 D0 106 D1 107 C3 D0 110 D1 111 A2 B0 C1 D0 114 D1 115 C3 D0 118 D1 119 B1 C1 D0 122 D1 123 C3 D0 126 D1 127 B2 C1 D0 130 D1 131 C3 D0 134 D1 135 ... [56 rows x 1 columns] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6134
2014-01-27T23:12:15Z
2014-02-04T13:28:55Z
null
2014-06-13T23:55:57Z
DOC: clarify that ExcelFile is not deprecated but only moved (#5435)
diff --git a/doc/source/io.rst b/doc/source/io.rst index e12e6ff6d5956..4c3a97500e789 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -1802,28 +1802,32 @@ Not escaped: Excel files ----------- -The ``read_excel`` method can read Excel 2003 (``.xls``) and +The :func:`~pandas.read_excel` method can read Excel 2003 (``.xls``) and Excel 2007 (``.xlsx``) files using the ``xlrd`` Python module and use the same parsing code as the above to convert tabular data into a DataFrame. See the :ref:`cookbook<cookbook.excel>` for some advanced strategies -.. note:: +Besides ``read_excel`` you can also read Excel files using the ``ExcelFile`` +class. The following two command are equivalent: - The prior method of accessing Excel is now deprecated as of 0.12.0, - this will work but will be removed in a future version. +.. code-block:: python - .. code-block:: python + # using the ExcelFile class + xls = pd.ExcelFile('path_to_file.xls') + xls.parse('Sheet1', index_col=None, na_values=['NA']) - from pandas.io.parsers import ExcelFile - xls = ExcelFile('path_to_file.xls') - xls.parse('Sheet1', index_col=None, na_values=['NA']) + # using the read_excel function + read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA']) - Replaced by +The class based approach can be used to read multiple sheets or to introspect +the sheet names using the ``sheet_names`` attribute. - .. code-block:: python +.. note:: - read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA']) + The prior method of accessing ``ExcelFile`` has been moved from + ``pandas.io.parsers`` to the top level namespace starting from pandas + 0.12.0. .. versionadded:: 0.13
closes #5435. Clarified that ExcelFile is not deprecated but just moved. I don't use Excel myself, so can somebody check if it makes sense what I wrote? (@ For now, I didn't add ExcelFile to api.rst (but ExcelFile.parse is already in there, so it is already in some way mentioned), as I am not sure if all it's methods (`mro`?) should be public (this has possibly to be cleaned up first)
https://api.github.com/repos/pandas-dev/pandas/pulls/6133
2014-01-27T22:59:24Z
2014-01-28T01:05:02Z
2014-01-28T01:05:02Z
2014-07-16T08:49:48Z
ENH get_dummies str method
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index 638c8451bf8db..f1e0013dbc920 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -1155,7 +1155,6 @@ can also be used. Testing for Strings that Match or Contain a Pattern ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - You can check whether elements contain a pattern: .. ipython:: python @@ -1221,6 +1220,21 @@ Methods like ``match``, ``contains``, ``startswith``, and ``endswith`` take ``lower``,Equivalent to ``str.lower`` ``upper``,Equivalent to ``str.upper`` + +Getting indicator variables from seperated strings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can extract dummy variables from string columns. +For example if they are seperated by a ``'|'``: + + .. ipython:: python + + s = pd.Series(['a', 'a|b', np.nan, 'a|c']) + s.str.get_dummies(sep='|') + +See also ``pd.get_dummies``. + + .. _basics.sorting: Sorting by index and value diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt index e3e06357cea72..0d3bf839f5776 100644 --- a/doc/source/v0.13.1.txt +++ b/doc/source/v0.13.1.txt @@ -43,6 +43,14 @@ API changes - Add ``-NaN`` and ``-nan`` to the default set of NA values (:issue:`5952`). See :ref:`NA Values <io.na_values>`. +- Added ``Series.str.get_dummies`` vectorized string method (:issue:`6021`), to extract + dummy/indicator variables for seperated string columns: + + .. ipython:: python + + s = Series(['a', 'a|b', np.nan, 'a|c']) + s.str.get_dummies(sep='|') + - Added the ``NDFrame.equals()`` method to compare if two NDFrames are equal have equal axes, dtypes, and values. Added the ``array_equivalent`` function to compare if two ndarrays are diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py index 1244d0140a01b..f5ca96e2d827e 100644 --- a/pandas/core/reshape.py +++ b/pandas/core/reshape.py @@ -941,6 +941,8 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False): 1 0 1 0 2 0 0 1 + See also ``Series.str.get_dummies``. + """ # Series avoids inconsistent NaN handling cat = Categorical.from_array(Series(data)) diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 588a81e3cf80d..a41c06a6ad0b6 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -187,7 +187,6 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): else: f = lambda x: pat in x return _na_map(f, arr, na) - def str_startswith(arr, pat, na=np.nan): @@ -460,6 +459,46 @@ def f(x): return result +def str_get_dummies(arr, sep='|'): + """ + Split each string by sep and return a frame of dummy/indicator variables. + + Examples + -------- + >>> Series(['a|b', 'a', 'a|c']).str.get_dummies() + a b c + 0 1 1 0 + 1 1 0 0 + 2 1 0 1 + + >>> pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies() + a b c + 0 1 1 0 + 1 0 0 0 + 2 1 0 1 + + See also ``pd.get_dummies``. + + """ + # TODO remove this hack? + arr = arr.fillna('') + try: + arr = sep + arr + sep + except TypeError: + arr = sep + arr.astype(str) + sep + + tags = set() + for ts in arr.str.split(sep): + tags.update(ts) + tags = sorted(tags - set([""])) + + dummies = np.empty((len(arr), len(tags)), dtype=int) + + for i, t in enumerate(tags): + pat = sep + t + sep + dummies[:, i] = lib.map_infer(arr.values, lambda x: pat in x) + return DataFrame(dummies, arr.index, tags) + def str_join(arr, sep): """ @@ -843,7 +882,7 @@ def contains(self, pat, case=True, flags=0, na=np.nan, regex=True): result = str_contains(self.series, pat, case=case, flags=flags, na=na, regex=regex) return self._wrap_result(result) - + @copy(str_replace) def replace(self, pat, repl, n=-1, case=True, flags=0): result = str_replace(self.series, pat, repl, n=n, case=case, @@ -899,6 +938,11 @@ def rstrip(self, to_strip=None): result = str_rstrip(self.series, to_strip) return self._wrap_result(result) + @copy(str_get_dummies) + def get_dummies(self, sep='|'): + result = str_get_dummies(self.series, sep) + return self._wrap_result(result) + count = _pat_wrapper(str_count, flags=True) startswith = _pat_wrapper(str_startswith, na=True) endswith = _pat_wrapper(str_endswith, na=True) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 797e415ab9c31..6c9832ebc5c2b 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -366,7 +366,6 @@ def test_replace(self): result = values.str.replace("(?<=\w),(?=\w)", ", ", flags=re.UNICODE) tm.assert_series_equal(result, exp) - def test_repeat(self): values = Series(['a', 'b', NA, 'c', NA, 'd']) @@ -465,7 +464,7 @@ def test_extract(self): # Contains tests like those in test_match and some others. values = Series(['fooBAD__barBAD', NA, 'foo']) - er = [NA, NA] # empty row + er = [NA, NA] # empty row result = values.str.extract('.*(BAD[_]+).*(BAD)') exp = DataFrame([['BAD__', 'BAD'], er, er]) @@ -549,6 +548,19 @@ def test_extract(self): exp = DataFrame([['A', '1'], ['B', '2'], ['C', NA]], columns=['letter', 'number']) tm.assert_frame_equal(result, exp) + def test_get_dummies(self): + s = Series(['a|b', 'a|c', np.nan]) + result = s.str.get_dummies('|') + expected = DataFrame([[1, 1, 0], [1, 0, 1], [0, 0, 0]], + columns=list('abc')) + tm.assert_frame_equal(result, expected) + + s = Series(['a;b', 'a', 7]) + result = s.str.get_dummies(';') + expected = DataFrame([[0, 1, 1], [0, 1, 0], [1, 0, 0]], + columns=list('7ab')) + tm.assert_frame_equal(result, expected) + def test_join(self): values = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h']) result = values.str.split('_').str.join('_') diff --git a/vb_suite/strings.py b/vb_suite/strings.py index 287fd6d5bf2e2..459684ec0e435 100644 --- a/vb_suite/strings.py +++ b/vb_suite/strings.py @@ -45,6 +45,11 @@ def make_series(letters, strlen, size): strings_rstrip = Benchmark("many.str.rstrip('matchthis')", setup) strings_get = Benchmark("many.str.get(0)", setup) +setup = setup + """ +make_series(string.uppercase, strlen=10, size=10000).str.join('|') +""" +strings_get_dummies = Benchmark("s.str.get_dummies('|')", setup) + setup = common_setup + """ import pandas.util.testing as testing ser = pd.Series(testing.makeUnicodeIndex())
fixes #3695. ``` In [8]: s = pd.Series(['a|b', 'a|c', np.nan], list('ABC')) In [9]: s.str.get_dummies('|') Out[9]: a b c A 1 1 0 B 1 0 1 C 0 0 0 ``` _iterates over each tag filling in with str.contains._ Edit: This works pretty fast with "few" tags (since I'm iterating over each tag), which I think is the main usecase, but I'm sure some more perf can be eeked out: ``` In [6]: %timeit genres.str.get_dummies('|') 10 loops, best of 3: 20.9 ms per loop In [7]: %timeit genres.str.split('|').apply(lambda x: pd.Series(1., x)).fillna(0) 1 loops, best of 3: 623 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/6132
2014-01-27T21:04:44Z
2014-01-28T00:52:46Z
2014-01-28T00:52:46Z
2014-07-10T09:36:33Z
BUG: DataFrame.append when appending a row with different columns (GH6129)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 3f98d10a3990b..9324d8b28f107 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -162,7 +162,7 @@ Bug Fixes - Bug in propogating _ref_locs during construction of a DataFrame with dups index/columns (:issue:`6121`) - Bug in ``DataFrame.apply`` when using mixed datelike reductions (:issue:`6125`) - + - Bug in ``DataFrame.append`` when appending a row with different columns (:issue:`6129`) pandas 0.13.0 ------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ce2f4e900d681..4c19831c6cbe3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3513,9 +3513,12 @@ def append(self, other, ignore_index=False, verify_integrity=False): 'ignore_index=True') index = None if other.name is None else [other.name] - other = other.reindex(self.columns, copy=False) + combined_columns = self.columns.tolist() + ((self.columns | other.index) - self.columns).tolist() + other = other.reindex(combined_columns, copy=False) other = DataFrame(other.values.reshape((1, len(other))), - index=index, columns=self.columns).convert_objects() + index=index, columns=combined_columns).convert_objects() + if not self.columns.equals(combined_columns): + self = self.reindex(columns=combined_columns) elif isinstance(other, list) and not isinstance(other[0], DataFrame): other = DataFrame(other) if (self.columns.get_indexer(other.columns) >= 0).all(): diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index a0d90ac0920eb..78d6002bcea47 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -1163,6 +1163,14 @@ def test_append(self): self.assertRaises(ValueError, self.frame.append, self.frame, verify_integrity=True) + # new columns + # GH 6129 + df = DataFrame({'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}) + row = Series([5, 6, 7], index=['a', 'b', 'c'], name='z') + expected = DataFrame({'a': {'x': 1, 'y': 2, 'z': 5}, 'b': {'x': 3, 'y': 4, 'z': 6}, 'c' : {'z' : 7}}) + result = df.append(row) + assert_frame_equal(result, expected) + def test_append_length0_frame(self): df = DataFrame(columns=['A', 'B', 'C']) df3 = DataFrame(index=[0, 1], columns=['A', 'B'])
closes #6129
https://api.github.com/repos/pandas-dev/pandas/pulls/6130
2014-01-27T17:41:33Z
2014-01-27T17:58:11Z
2014-01-27T17:58:10Z
2014-06-26T02:45:54Z
BUG: DataFrame.apply when using mixed datelike reductions (GH6125)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 5088c380f74bc..3f98d10a3990b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -161,6 +161,8 @@ Bug Fixes are a slice (e.g. next to each other) (:issue:`6120`) - Bug in propogating _ref_locs during construction of a DataFrame with dups index/columns (:issue:`6121`) + - Bug in ``DataFrame.apply`` when using mixed datelike reductions (:issue:`6125`) + pandas 0.13.0 ------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 63993aa4713aa..ce2f4e900d681 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3341,10 +3341,16 @@ def _apply_raw(self, func, axis): def _apply_standard(self, func, axis, ignore_failures=False, reduce=True): + # skip if we are mixed datelike and trying reduce across axes + # GH6125 + if reduce and axis==1 and self._is_mixed_type and self._is_datelike_mixed_type: + reduce=False + # try to reduce first (by default) # this only matters if the reduction in values is of different dtype # e.g. if we want to apply to a SparseFrame, then can't directly reduce if reduce: + try: # the is the fast-path diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 29bfbbbd24be1..77e8cb8d04268 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -9215,6 +9215,28 @@ def transform2(row): self.assertEqual(e.args[1], 'occurred at index 4') self.assertEqual(e.args[0], "'float' object has no attribute 'startswith'") + def test_apply_bug(self): + + # GH 6125 + import datetime + positions = pd.DataFrame([[1, 'ABC0', 50], [1, 'YUM0', 20], + [1, 'DEF0', 20], [2, 'ABC1', 50], + [2, 'YUM1', 20], [2, 'DEF1', 20]], + columns=['a', 'market', 'position']) + def f(r): + return r['market'] + expected = positions.apply(f, axis=1) + + positions = DataFrame([[datetime.datetime(2013, 1, 1), 'ABC0', 50], + [datetime.datetime(2013, 1, 2), 'YUM0', 20], + [datetime.datetime(2013, 1, 3), 'DEF0', 20], + [datetime.datetime(2013, 1, 4), 'ABC1', 50], + [datetime.datetime(2013, 1, 5), 'YUM1', 20], + [datetime.datetime(2013, 1, 6), 'DEF1', 20]], + columns=['a', 'market', 'position']) + result = positions.apply(f, axis=1) + assert_series_equal(result,expected) + def test_swapaxes(self): df = DataFrame(np.random.randn(10, 5)) assert_frame_equal(df.T, df.swapaxes(0, 1))
closes #6125
https://api.github.com/repos/pandas-dev/pandas/pulls/6126
2014-01-27T15:34:23Z
2014-01-27T16:22:38Z
2014-01-27T16:22:38Z
2014-06-23T20:08:10Z
BUG: Bug in propogating _ref_locs during construction of a DataFrame with dups index/columns (GH6121)
diff --git a/doc/source/release.rst b/doc/source/release.rst index 2a6cdc636b34f..5088c380f74bc 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -159,6 +159,8 @@ Bug Fixes - Fixed missing arg validation in get_options_data (:issue:`6105`) - Bug in assignment with duplicate columns in a frame where the locations are a slice (e.g. next to each other) (:issue:`6120`) + - Bug in propogating _ref_locs during construction of a DataFrame with dups + index/columns (:issue:`6121`) pandas 0.13.0 ------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 3a31f99cdfd49..c97b9b28de18f 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -116,6 +116,25 @@ def ref_locs(self): self._ref_locs = indexer return self._ref_locs + def take_ref_locs(self, indexer): + """ + need to preserve the ref_locs and just shift them + return None if ref_locs is None + + see GH6509 + """ + + ref_locs = self._ref_locs + if ref_locs is None: + return None + + tindexer = np.ones(len(ref_locs),dtype=bool) + tindexer[indexer] = False + tindexer = tindexer.astype(int).cumsum()[indexer] + ref_locs = ref_locs[indexer] + ref_locs -= tindexer + return ref_locs + def reset_ref_locs(self): """ reset the block ref_locs """ self._ref_locs = np.empty(len(self.items), dtype='int64') @@ -866,13 +885,20 @@ def func(x): ndim=self.ndim, klass=self.__class__, fastpath=True)] return self._maybe_downcast(blocks, downcast) - def take(self, indexer, ref_items, axis=1): + def take(self, indexer, ref_items, new_axis, axis=1): if axis < 1: raise AssertionError('axis must be at least 1, got %d' % axis) new_values = com.take_nd(self.values, indexer, axis=axis, allow_fill=False) + + # need to preserve the ref_locs and just shift them + # GH6121 + ref_locs = None + if not new_axis.is_unique: + ref_locs = self._ref_locs + return [make_block(new_values, self.items, ref_items, ndim=self.ndim, - klass=self.__class__, fastpath=True)] + klass=self.__class__, placement=ref_locs, fastpath=True)] def get_values(self, dtype=None): return self.values @@ -1820,7 +1846,7 @@ def shift(self, indexer, periods, axis=0): new_values[periods:] = fill_value return [self.make_block(new_values)] - def take(self, indexer, ref_items, axis=1): + def take(self, indexer, ref_items, new_axis, axis=1): """ going to take our items along the long dimension""" if axis < 1: @@ -2601,18 +2627,7 @@ def get_slice(self, slobj, axis=0, raise_on_error=False): if len(self.blocks) == 1: blk = self.blocks[0] - - # see GH 6059 - ref_locs = blk._ref_locs - if ref_locs is not None: - - # need to preserve the ref_locs and just shift them - indexer = np.ones(len(ref_locs),dtype=bool) - indexer[slobj] = False - indexer = indexer.astype(int).cumsum()[slobj] - ref_locs = ref_locs[slobj] - ref_locs -= indexer - + ref_locs = blk.take_ref_locs(slobj) newb = make_block(blk._slice(slobj), new_items, new_items, klass=blk.__class__, fastpath=True, placement=ref_locs) @@ -3371,6 +3386,7 @@ def take(self, indexer, new_index=None, axis=1, verify=True): if axis < 1: raise AssertionError('axis must be at least 1, got %d' % axis) + self._consolidate_inplace() if isinstance(indexer, list): indexer = np.array(indexer) @@ -3388,8 +3404,12 @@ def take(self, indexer, new_index=None, axis=1, verify=True): new_index = self.axes[axis].take(indexer) new_axes[axis] = new_index - return self.apply('take', axes=new_axes, indexer=indexer, - ref_items=new_axes[0], axis=axis) + return self.apply('take', + axes=new_axes, + indexer=indexer, + ref_items=new_axes[0], + new_axis=new_axes[axis], + axis=axis) def merge(self, other, lsuffix=None, rsuffix=None): if not self._is_indexed_like(other): diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 21ea6505b683e..29bfbbbd24be1 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3303,6 +3303,21 @@ def check(result, expected=None): result = dfbool[['one', 'three', 'one']] check(result,expected) + # multi-axis dups + # GH 6121 + df = DataFrame(np.arange(25.).reshape(5,5), + index=['a', 'b', 'c', 'd', 'e'], + columns=['A', 'B', 'C', 'D', 'E']) + z = df[['A', 'C', 'A']].copy() + expected = z.ix[['a', 'c', 'a']] + + df = DataFrame(np.arange(25.).reshape(5,5), + index=['a', 'b', 'c', 'd', 'e'], + columns=['A', 'B', 'C', 'D', 'E']) + z = df[['A', 'C', 'A']] + result = z.ix[['a', 'c', 'a']] + check(result,expected) + def test_insert_benchmark(self): # from the vb_suite/frame_methods/frame_insert_columns N = 10
closes #6121
https://api.github.com/repos/pandas-dev/pandas/pulls/6123
2014-01-27T13:54:50Z
2014-01-27T14:17:59Z
2014-01-27T14:17:59Z
2014-06-22T13:28:39Z
BUG: Bug in assignment with duplicate columns in a frame where the locations are a slice
diff --git a/doc/source/release.rst b/doc/source/release.rst index 6593ba78ad3e6..2a6cdc636b34f 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -157,6 +157,8 @@ Bug Fixes - Bug with insert of strings into DatetimeIndex (:issue:`5818`) - Fixed unicode bug in to_html/HTML repr (:issue:`6098`) - Fixed missing arg validation in get_options_data (:issue:`6105`) + - Bug in assignment with duplicate columns in a frame where the locations + are a slice (e.g. next to each other) (:issue:`6120`) pandas 0.13.0 ------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 75c0a24b15e56..3a31f99cdfd49 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2969,7 +2969,7 @@ def _set_item(item, arr): # we are inserting one by one, so the index can go from unique # to non-unique during the loop, need to have _ref_locs defined # at all times - if np.isscalar(item) and com.is_list_like(loc): + if np.isscalar(item) and (com.is_list_like(loc) or isinstance(loc, slice)): # first delete from all blocks self.delete(item) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 2233f2749d3a8..21ea6505b683e 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3229,6 +3229,21 @@ def check(result, expected=None): result = getattr(df,op)(df) check(result,expected) + # multiple assignments that change dtypes + # the location indexer is a slice + # GH 6120 + df = DataFrame(np.random.randn(5,2), columns=['that', 'that']) + expected = DataFrame(1.0, index=range(5), columns=['that', 'that']) + + df['that'] = 1.0 + check(df, expected) + + df = DataFrame(np.random.rand(5,2), columns=['that', 'that']) + expected = DataFrame(1, index=range(5), columns=['that', 'that']) + + df['that'] = 1 + check(df, expected) + def test_column_dups_indexing(self): def check(result, expected=None):
closes #6120
https://api.github.com/repos/pandas-dev/pandas/pulls/6122
2014-01-27T12:41:28Z
2014-01-27T12:57:15Z
2014-01-27T12:57:15Z
2014-06-24T20:03:54Z
ENH: allow legend='reverse' in df.plot() GH6014
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 5162e75540ee2..73928f7080caf 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1227,6 +1227,15 @@ def _post_plot_logic(self): if self.legend: for ax in self.axes: ax.legend(loc='best') + leg = self.axes[0].get_legend() + if leg is not None: + lines = leg.get_lines() + labels = [x.get_text() for x in leg.get_texts()] + + if self.legend == 'reverse': + lines = reversed(lines) + labels = reversed(labels) + ax.legend(lines, labels, loc='best', title=self.legend_title) class ScatterPlot(MPLPlot): def __init__(self, data, x, y, **kwargs): @@ -1411,6 +1420,9 @@ def _make_legend(self, lines, labels): ax.legend(ext_lines, ext_labels, loc='best', title=self.legend_title) elif self.legend: + if self.legend == 'reverse': + lines = reversed(lines) + labels = reversed(labels) ax.legend(lines, labels, loc='best', title=self.legend_title) def _get_ax_legend(self, ax): @@ -1567,6 +1579,9 @@ def _make_plot(self): if self.legend and not self.subplots: patches = [r[0] for r in rects] + if self.legend == 'reverse': + patches = reversed(patches) + labels = reversed(labels) self.axes[0].legend(patches, labels, loc='best', title=self.legend_title) @@ -1639,7 +1654,7 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True, Title to use for the plot grid : boolean, default None (matlab style default) Axis grid lines - legend : boolean, default True + legend : False/True/'reverse' Place legend on axis subplots ax : matplotlib axis object, default None
![reverse](https://f.cloud.github.com/assets/1820866/2007133/009ee032-8732-11e3-920c-7bb53c754ed7.png) works for line plots, bar plots, and kde plots. scatter plots don't seem to have a legend. As usual, the plotting code is a tangled mess, I have no idea if this breaks something, testing seems like a herculean task and I'm scared to death that by being brave and merging this, I'm setting myself up to touch the plotting code again in the future, at least once. quite the deterrent. #6014
https://api.github.com/repos/pandas-dev/pandas/pulls/6118
2014-01-27T09:08:44Z
2014-02-07T10:30:39Z
2014-02-07T10:30:39Z
2014-06-13T01:27:07Z
TST: Add xlsm to Excel parsing tests.
diff --git a/pandas/io/tests/data/test.xlsm b/pandas/io/tests/data/test.xlsm new file mode 100644 index 0000000000000..4c873e55a5300 Binary files /dev/null and b/pandas/io/tests/data/test.xlsm differ diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 5335c7691195f..8e6ac3cf5bc2e 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -90,10 +90,10 @@ def test_parse_cols_int(self): _skip_if_no_openpyxl() _skip_if_no_xlrd() - suffix = ['', 'x'] + suffix = ['xls', 'xlsx', 'xlsm'] for s in suffix: - pth = os.path.join(self.dirpath, 'test.xls%s' % s) + pth = os.path.join(self.dirpath, 'test.%s' % s) xls = ExcelFile(pth) df = xls.parse('Sheet1', index_col=0, parse_dates=True, parse_cols=3) @@ -109,10 +109,10 @@ def test_parse_cols_list(self): _skip_if_no_openpyxl() _skip_if_no_xlrd() - suffix = ['', 'x'] + suffix = ['xls', 'xlsx', 'xlsm'] for s in suffix: - pth = os.path.join(self.dirpath, 'test.xls%s' % s) + pth = os.path.join(self.dirpath, 'test.%s' % s) xls = ExcelFile(pth) df = xls.parse('Sheet1', index_col=0, parse_dates=True, parse_cols=[0, 2, 3]) @@ -129,11 +129,11 @@ def test_parse_cols_str(self): _skip_if_no_openpyxl() _skip_if_no_xlrd() - suffix = ['', 'x'] + suffix = ['xls', 'xlsx', 'xlsm'] for s in suffix: - pth = os.path.join(self.dirpath, 'test.xls%s' % s) + pth = os.path.join(self.dirpath, 'test.%s' % s) xls = ExcelFile(pth) df = xls.parse('Sheet1', index_col=0, parse_dates=True, @@ -677,26 +677,26 @@ def test_excel_date_datetime_format(self): with ensure_clean(self.ext) as filename1: with ensure_clean(self.ext) as filename2: writer1 = ExcelWriter(filename1) - writer2 = ExcelWriter(filename2, + writer2 = ExcelWriter(filename2, date_format='DD.MM.YYYY', datetime_format='DD.MM.YYYY HH-MM-SS') df.to_excel(writer1, 'test1') df.to_excel(writer2, 'test1') - + writer1.close() writer2.close() reader1 = ExcelFile(filename1) reader2 = ExcelFile(filename2) - + rs1 = reader1.parse('test1', index_col=None) rs2 = reader2.parse('test1', index_col=None) - + tm.assert_frame_equal(rs1, rs2) # since the reader returns a datetime object for dates, we need - # to use df_expected to check the result + # to use df_expected to check the result tm.assert_frame_equal(rs2, df_expected) def test_to_excel_periodindex(self): diff --git a/setup.py b/setup.py index 1c82da240af4d..d5c52395a6bb0 100755 --- a/setup.py +++ b/setup.py @@ -567,6 +567,7 @@ def pxd(name): 'tests/data/*.txt', 'tests/data/*.xls', 'tests/data/*.xlsx', + 'tests/data/*.xlsm', 'tests/data/*.table', 'tests/data/*.html', 'tests/test_json/data/*.json'],
Added a test to verify that #4172 (failed read from an Excel `xlsm` file) is no longer an issue. The test extends 3 of the existing Excel reader tests to also read from an `xlsm` (macro) file.
https://api.github.com/repos/pandas-dev/pandas/pulls/6117
2014-01-27T08:11:41Z
2014-01-27T11:08:14Z
2014-01-27T11:08:14Z
2014-07-16T08:49:31Z
TST: add _skip_if_no_xlrd() to test GH5583
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 5335c7691195f..4895ff3b79308 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -663,6 +663,7 @@ def test_excel_roundtrip_datetime(self): # GH4133 - excel output format strings def test_excel_date_datetime_format(self): + _skip_if_no_xlrd() df = DataFrame([[date(2014, 1, 31), date(1999, 9, 24)], [datetime(1998, 5, 26, 23, 33, 4),
new test added in #5583 does not skip_xlrd() and caused failures on sparc. Noting that we don't seem to have min-dep coverage in travis. cc @Jaydyou wow. [that](https://github.com/pydata/pandas/pull/5995#issuecomment-33333749) sure payed itself off right quick. cc @yarikoptic
https://api.github.com/repos/pandas-dev/pandas/pulls/6115
2014-01-27T03:51:17Z
2014-01-27T03:51:24Z
2014-01-27T03:51:24Z
2014-07-16T08:49:30Z
BUG: get_options_data should validate it's arguments GH6105
diff --git a/doc/source/release.rst b/doc/source/release.rst index aa7b701ee39a3..6593ba78ad3e6 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -156,6 +156,7 @@ Bug Fixes - Subtle ``iloc`` indexing bug, surfaced in (:issue:`6059`) - Bug with insert of strings into DatetimeIndex (:issue:`5818`) - Fixed unicode bug in to_html/HTML repr (:issue:`6098`) + - Fixed missing arg validation in get_options_data (:issue:`6105`) pandas 0.13.0 ------------- diff --git a/pandas/io/data.py b/pandas/io/data.py index b3332df3c8866..eb182e77a5db5 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -632,6 +632,10 @@ def get_options_data(self, month=None, year=None, expiry=None): _OPTIONS_BASE_URL = 'http://finance.yahoo.com/q/op?s={sym}' def _get_option_data(self, month, year, expiry, table_loc, name): + if (month is None or year is None) and expiry is None: + msg = "You must specify either (`year` and `month`) or `expiry`." + raise ValueError(msg) + year, month = self._try_parse_dates(year, month, expiry) url = self._OPTIONS_BASE_URL.format(sym=self.symbol) diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index cbd7a0fb76ecc..a6c0deb6d7827 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -266,6 +266,12 @@ def test_get_options_data(self): assert len(calls)>1 assert len(puts)>1 + def test_get_options_data(self): + + # regression test GH6105 + self.assertRaises(ValueError,self.aapl.get_options_data,month=3) + self.assertRaises(ValueError,self.aapl.get_options_data,year=1992) + @network def test_get_near_stock_price(self): try:
closes #6105
https://api.github.com/repos/pandas-dev/pandas/pulls/6114
2014-01-27T03:11:33Z
2014-01-27T03:11:54Z
2014-01-27T03:11:54Z
2014-06-17T10:30:54Z
BUG: HTMLFormatter does not die on unicode frame GH6098
diff --git a/doc/source/release.rst b/doc/source/release.rst index d96a2ef973955..aa7b701ee39a3 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -155,6 +155,7 @@ Bug Fixes - Regression in ``.get(None)`` indexing from 0.12 (:issue:`5652`) - Subtle ``iloc`` indexing bug, surfaced in (:issue:`6059`) - Bug with insert of strings into DatetimeIndex (:issue:`5818`) + - Fixed unicode bug in to_html/HTML repr (:issue:`6098`) pandas 0.13.0 ------------- diff --git a/pandas/core/format.py b/pandas/core/format.py index fce0ef6a27889..6c66fc53b1f66 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -767,7 +767,7 @@ def _column_header(): levels)): name = self.columns.names[lnum] row = [''] * (row_levels - 1) + ['' if name is None - else str(name)] + else com.pprint_thing(name)] tags = {} j = len(row) diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 005abf25f6584..bf71f2e3b1431 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -719,6 +719,14 @@ def test_to_html_index_formatter(self): </table>""" self.assertEquals(result, expected) + def test_to_html_regression_GH6098(self): + df = DataFrame({u('clé1'): [u('a'), u('a'), u('b'), u('b'), u('a')], + u('clé2'): [u('1er'), u('2ème'), u('1er'), u('2ème'), u('1er')], + 'données1': np.random.randn(5), + 'données2': np.random.randn(5)}) + # it works + df.pivot_table(rows=[u('clé1')], cols=[u('clé2')])._repr_html_() + def test_nonunicode_nonascii_alignment(self): df = DataFrame([["aa\xc3\xa4\xc3\xa4", 1], ["bbbb", 2]]) rep_str = df.to_string()
closes #6098
https://api.github.com/repos/pandas-dev/pandas/pulls/6112
2014-01-27T02:12:49Z
2014-01-27T02:36:53Z
2014-01-27T02:36:53Z
2014-06-24T23:13:52Z
Replace network decorator with with_connectivity_check
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 80e33eb1717da..b2a2ced9323e8 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -971,106 +971,6 @@ def dec(f): _network_error_classes = IOError, httplib.HTTPException -@optional_args -def network(t, raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT, - error_classes=_network_error_classes, num_runs=2): - """ - Label a test as requiring network connection and skip test if it encounters a ``URLError``. - - In some cases it is not possible to assume network presence (e.g. Debian - build hosts). - - You can pass an optional ``raise_on_error`` argument to the decorator, in - which case it will always raise an error even if it's not a subclass of - ``error_classes``. - - Parameters - ---------- - t : callable - The test requiring network connectivity. - raise_on_error : bool, optional - If True, never catches errors. - error_classes : tuple, optional - error classes to ignore. If not in ``error_classes``, raises the error. - defaults to URLError. Be careful about changing the error classes here, - it may result in undefined behavior. - num_runs : int, optional - Number of times to run test. If fails on last try, will raise. Default - is 2 runs. - - Returns - ------- - t : callable - The decorated test `t`. - - Examples - -------- - A test can be decorated as requiring network like this:: - - >>> from pandas.util.testing import network - >>> from pandas.io.common import urlopen - >>> import nose - >>> @network - ... def test_network(): - ... with urlopen("rabbit://bonanza.com") as f: - ... pass - ... - >>> try: - ... test_network() - ... except nose.SkipTest: - ... print("SKIPPING!") - ... - SKIPPING! - - Alternatively, you can use set ``raise_on_error`` in order to get - the error to bubble up, e.g.:: - - >>> @network(raise_on_error=True) - ... def test_network(): - ... with urlopen("complaint://deadparrot.com") as f: - ... pass - ... - >>> test_network() - Traceback (most recent call last): - ... - URLError: <urlopen error unknown url type: complaint> - - And use ``nosetests -a '!network'`` to exclude running tests requiring - network connectivity. ``_RAISE_NETWORK_ERROR_DEFAULT`` in - ``pandas/util/testing.py`` sets the default behavior (currently False). - """ - from nose import SkipTest - - if num_runs < 1: - raise ValueError("Must set at least 1 run") - t.network = True - - @wraps(t) - def network_wrapper(*args, **kwargs): - if raise_on_error: - return t(*args, **kwargs) - else: - runs = 0 - - for _ in range(num_runs): - try: - try: - return t(*args, **kwargs) - except error_classes as e: - raise SkipTest("Skipping test %s" % e) - except SkipTest: - raise - except Exception as e: - if runs < num_runs - 1: - print("Failed: %r" % e) - else: - raise - - runs += 1 - - return network_wrapper - - def can_connect(url, error_classes=_network_error_classes): """Try to connect to the given url. True if succeeds, False if IOError raised @@ -1096,10 +996,9 @@ def can_connect(url, error_classes=_network_error_classes): @optional_args -def with_connectivity_check(t, url="http://www.google.com", - raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT, - check_before_test=False, - error_classes=_network_error_classes): +def network(t, url="http://www.google.com", + raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT, + check_before_test=False, error_classes=_network_error_classes): """ Label a test as requiring network connection and, if an error is encountered, only raise if it does not find a network connection. @@ -1138,9 +1037,22 @@ def with_connectivity_check(t, url="http://www.google.com", Example ------- - In this example, you see how it will raise the error if it can connect to - the url:: - >>> @with_connectivity_check("http://www.yahoo.com") + Tests decorated with @network will fail if it's possible to make a network + connection to another URL (defaults to google.com):: + + >>> from pandas.util.testing import network + >>> from pandas.io.common import urlopen + >>> @network + ... def test_network(): + ... with urlopen("rabbit://bonanza.com"): + ... pass + Traceback + ... + URLError: <urlopen error unknown url type: rabit> + + You can specify alternative URLs:: + + >>> @network("http://www.yahoo.com") ... def test_something_with_yahoo(): ... raise IOError("Failure Message") >>> test_something_with_yahoo() @@ -1148,8 +1060,10 @@ def with_connectivity_check(t, url="http://www.google.com", ... IOError: Failure Message - I you set check_before_test, it will check the url first and not run the test on failure:: - >>> @with_connectivity_check("failing://url.blaher", check_before_test=True) + If you set check_before_test, it will check the url first and not run the + test on failure:: + + >>> @network("failing://url.blaher", check_before_test=True) ... def test_something(): ... print("I ran!") ... raise ValueError("Failure") @@ -1157,6 +1071,8 @@ def with_connectivity_check(t, url="http://www.google.com", Traceback (most recent call last): ... SkipTest + + Errors not related to networking will always be raised. """ from nose import SkipTest t.network = True @@ -1178,6 +1094,9 @@ def wrapper(*args, **kwargs): return wrapper +with_connectivity_check = network + + class SimpleMock(object): """
Network decorator was ignoring test failures due to API changes in external services. Closes #5816.
https://api.github.com/repos/pandas-dev/pandas/pulls/6111
2014-01-26T22:20:36Z
2014-01-28T03:13:56Z
2014-01-28T03:13:56Z
2014-06-13T01:11:38Z
CLN: Eliminate handful of test docstrings, use nose -v on travis
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a764f9c1a5439..e4af6b601f9e5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,8 +63,10 @@ looking for a quick way to help out. - Add deprecation warnings where needed. - Performance matters. Make sure your PR hasn't introduced perf regressions by using `test_perf.sh`. - Docstrings follow the [numpydoc](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) format. + - Write tests. - When writing tests, use 2.6 compatible `self.assertFoo` methods. Some polyfills such as `assertRaises` can be found in `pandas.util.testing`. + - Do not attach doctrings to tests. Make the test itself readable and use comments if needed. - Generally, pandas source files should not contain attributions. You can include a "thanks to..." in the release changelog. The rest is `git blame`/`git log`. - When you start working on a PR, start by creating a new branch pointing at the latest diff --git a/ci/script.sh b/ci/script.sh index 361ad41901f37..0619de3d51b52 100755 --- a/ci/script.sh +++ b/ci/script.sh @@ -9,5 +9,5 @@ if [ -n "$LOCALE_OVERRIDE" ]; then python -c "$pycmd" fi -echo nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml -nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml +echo nosetests -v --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml +nosetests -v --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index bb442519805d4..cbd7a0fb76ecc 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -168,8 +168,7 @@ def test_get_components_dax(self): @network def test_get_components_nasdaq_100(self): - """as of 7/12/13 the conditional will test false because the link is - invalid""" + # as of 7/12/13 the conditional will test false because the link is invalid raise nose.SkipTest('unreliable test, receive partial components back for nasdaq_100') df = web.get_components_yahoo('^NDX') #NASDAQ-100 diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 4478cbc6a655b..c583858f051c5 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -3200,7 +3200,7 @@ def test_frame_select(self): # 'frame', [crit1, crit2]) def test_frame_select_complex(self): - """ select via complex criteria """ + # select via complex criteria df = tm.makeTimeDataFrame() df['string'] = 'foo' diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index 38770def8eb7c..83864878ff6d3 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -226,10 +226,9 @@ def test_keyword_as_column_names(self): sql.write_frame(df, con = self.db, name = 'testkeywords') def test_onecolumn_of_integer(self): - ''' - GH 3628 - a column_of_integers dataframe should transfer well to sql - ''' + # GH 3628 + # a column_of_integers dataframe should transfer well to sql + mono_df=DataFrame([1 , 2], columns=['c0']) sql.write_frame(mono_df, con = self.db, name = 'mono_df') # computing the sum via sql diff --git a/pandas/tests/test_config.py b/pandas/tests/test_config.py index 6d4486525f4eb..e60c9d5bd0fdf 100644 --- a/pandas/tests/test_config.py +++ b/pandas/tests/test_config.py @@ -250,7 +250,7 @@ def test_deprecate_option(self): # testing warning with catch_warning was only added in 2.6 if sys.version_info[:2] < (2, 6): - raise nose.SkipTest() + raise nose.SkipTest("Need py > 2.6") self.assertTrue(self.cf._is_deprecated('foo')) with warnings.catch_warnings(record=True) as w: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 6080d8f8368db..557880b695ba3 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -2599,11 +2599,9 @@ def test_constructor_maskedarray_nonfloat(self): self.assertEqual(False, frame['C'][2]) def test_constructor_mrecarray(self): - """ - Ensure mrecarray produces frame identical to dict of masked arrays - from GH3479 + # 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, @@ -11632,10 +11630,8 @@ def test_consolidate_datetime64(self): assert_array_equal(df.ending.values, ser_ending.index.values) def test_tslib_tz_convert_trans_pos_plus_1__bug(self): - """ - Regression test for tslib.tz_convert(vals, tz1, tz2). - See https://github.com/pydata/pandas/issues/4496 for details. - """ + # Regression test for tslib.tz_convert(vals, tz1, tz2). + # See https://github.com/pydata/pandas/issues/4496 for details. idx = pd.date_range(datetime(2011, 3, 26, 23), datetime(2011, 3, 27, 1), freq='1min') idx = idx.tz_localize('UTC') idx = idx.tz_convert('Europe/Moscow') diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index ec97f6292ee5c..d448eb42ff153 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -647,7 +647,6 @@ def test_loc_setitem_frame(self): assert_frame_equal(result, expected) def test_iloc_getitem_frame(self): - """ originally from test_frame.py""" df = DataFrame(np.random.randn(10, 4), index=lrange(0, 20, 2), columns=lrange(0,8,2)) result = df.iloc[2] @@ -793,7 +792,6 @@ def f(): self.assertRaises(ValueError, f) def test_iloc_setitem_series(self): - """ originally from test_series.py """ df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD')) df.iloc[1,1] = 1 diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 675852027ce6e..d31717ec8c165 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -1677,14 +1677,12 @@ def test_repr_name_iterable_indexable(self): repr(s) def test_repr_should_return_str(self): - """ - http://docs.python.org/py3k/reference/datamodel.html#object.__repr__ - http://docs.python.org/reference/datamodel.html#object.__repr__ - "...The return value must be a string object." + # http://docs.python.org/py3k/reference/datamodel.html#object.__repr__ + # http://docs.python.org/reference/datamodel.html#object.__repr__ + # ...The return value must be a string object. - (str on py2.x, str (unicode) on py3) + # (str on py2.x, str (unicode) on py3) - """ data = [8, 5, 3, 5] index1 = [u("\u03c3"), u("\u03c4"), u("\u03c5"), u("\u03c6")] df = Series(data, index=index1) diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index 707b052031d60..289c0391fca23 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -1045,7 +1045,7 @@ def test_all_values_single_bin(self): tm.assert_almost_equal(result[0], s.mean()) def test_resample_doesnt_truncate(self): - """Test for issue #3020""" + # Test for issue #3020 import pandas as pd dates = pd.date_range('01-Jan-2014','05-Jan-2014', freq='D') series = Series(1, index=dates) diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py index 6b571aca20afc..b7582619b577d 100644 --- a/pandas/tseries/tests/test_timezones.py +++ b/pandas/tseries/tests/test_timezones.py @@ -105,10 +105,8 @@ def test_timestamp_tz_localize(self): self.assertEquals(result, expected) def test_timestamp_constructed_by_date_and_tz(self): - """ - Fix Issue 2993, Timestamp cannot be constructed by datetime.date - and tz correctly - """ + # Fix Issue 2993, Timestamp cannot be constructed by datetime.date + # and tz correctly result = Timestamp(date(2012, 3, 11), tz='US/Eastern')
I'm being forced to do unspeakable thing in aid of pandas and these docstring outliers are getting in the way.
https://api.github.com/repos/pandas-dev/pandas/pulls/6110
2014-01-26T20:38:49Z
2014-01-26T21:15:06Z
2014-01-26T21:15:06Z
2014-07-16T08:49:23Z
TST: add tests for old version of numexpr
diff --git a/ci/requirements-2.6.txt b/ci/requirements-2.6.txt index 751d034ef97f5..8199fdd9b9648 100644 --- a/ci/requirements-2.6.txt +++ b/ci/requirements-2.6.txt @@ -5,3 +5,4 @@ pytz==2013b http://www.crummy.com/software/BeautifulSoup/bs4/download/4.2/beautifulsoup4-4.2.0.tar.gz html5lib==1.0b2 bigquery==2.0.17 +numexpr==1.4.2 diff --git a/ci/script.sh b/ci/script.sh index 0619de3d51b52..c7b9b0ce93baa 100755 --- a/ci/script.sh +++ b/ci/script.sh @@ -5,9 +5,12 @@ echo "inside $0" if [ -n "$LOCALE_OVERRIDE" ]; then export LC_ALL="$LOCALE_OVERRIDE"; echo "Setting LC_ALL to $LOCALE_OVERRIDE" + curdir="$(pwd)" + cd /tmp pycmd='import pandas; print("pandas detected console encoding: %s" % pandas.get_option("display.encoding"))' python -c "$pycmd" + cd "$curdir" fi -echo nosetests -v --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml -nosetests -v --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml +echo nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml +nosetests --exe -w /tmp -A "$NOSE_ARGS" pandas --with-xunit --xunit-file=/tmp/nosetests.xml diff --git a/pandas/computation/eval.py b/pandas/computation/eval.py index 163477b258e15..4cc68ac4770b3 100644 --- a/pandas/computation/eval.py +++ b/pandas/computation/eval.py @@ -3,13 +3,11 @@ """Top level ``eval`` module. """ -import numbers -import numpy as np from pandas.core import common as com -from pandas.compat import string_types from pandas.computation.expr import Expr, _parsers, _ensure_scope from pandas.computation.engines import _engines +from distutils.version import LooseVersion def _check_engine(engine): @@ -38,7 +36,13 @@ def _check_engine(engine): import numexpr except ImportError: raise ImportError("'numexpr' not found. Cannot use " - "engine='numexpr' if 'numexpr' is not installed") + "engine='numexpr' for query/eval " + "if 'numexpr' is not installed") + else: + ne_version = numexpr.__version__ + if ne_version < LooseVersion('2.0'): + raise ImportError("'numexpr' version is %s, " + "must be >= 2.0" % ne_version) def _check_parser(parser): diff --git a/pandas/computation/expressions.py b/pandas/computation/expressions.py index 035878e20c645..b379da9cd38bc 100644 --- a/pandas/computation/expressions.py +++ b/pandas/computation/expressions.py @@ -8,10 +8,11 @@ import numpy as np from pandas.core.common import _values_from_object +from distutils.version import LooseVersion try: import numexpr as ne - _NUMEXPR_INSTALLED = True + _NUMEXPR_INSTALLED = ne.__version__ >= LooseVersion('2.0') except ImportError: # pragma: no cover _NUMEXPR_INSTALLED = False diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py index 6cfb8ac45312f..b1cafca190bb0 100644 --- a/pandas/computation/tests/test_eval.py +++ b/pandas/computation/tests/test_eval.py @@ -2,6 +2,7 @@ import functools from itertools import product +from distutils.version import LooseVersion import nose from nose.tools import assert_raises, assert_true, assert_false, assert_equal @@ -17,13 +18,13 @@ from pandas.util.testing import makeCustomDataframe as mkdf from pandas.computation import pytables -from pandas.computation.expressions import _USE_NUMEXPR from pandas.computation.engines import _engines from pandas.computation.expr import PythonExprVisitor, PandasExprVisitor -from pandas.computation.ops import (_binary_ops_dict, _unary_ops_dict, +from pandas.computation.ops import (_binary_ops_dict, _special_case_arith_ops_syms, _arith_ops_syms, _bool_ops_syms) from pandas.computation.common import NameResolutionError + import pandas.computation.expr as expr import pandas.util.testing as tm from pandas.util.testing import (assert_frame_equal, randbool, @@ -35,11 +36,6 @@ _scalar_skip = 'in', 'not in' -def skip_if_no_ne(engine='numexpr'): - if not _USE_NUMEXPR and engine == 'numexpr': - raise nose.SkipTest("numexpr engine not installed or disabled") - - def engine_has_neg_frac(engine): return _engines[engine].has_neg_frac @@ -108,7 +104,7 @@ class TestEvalNumexprPandas(tm.TestCase): @classmethod def setUpClass(cls): super(TestEvalNumexprPandas, cls).setUpClass() - skip_if_no_ne() + tm.skip_if_no_ne() import numexpr as ne cls.ne = ne cls.engine = 'numexpr' @@ -426,7 +422,7 @@ def check_single_invert_op(self, lhs, cmp1, rhs): assert_array_equal(expected, result) for engine in self.current_engines: - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) assert_array_equal(result, pd.eval('~elb', engine=engine, parser=self.parser)) @@ -457,7 +453,7 @@ def check_compound_invert_op(self, lhs, cmp1, rhs): # make sure the other engines work the same as this one for engine in self.current_engines: - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) ev = pd.eval(ex, engine=self.engine, parser=self.parser) assert_array_equal(ev, result) @@ -709,7 +705,7 @@ class TestEvalNumexprPython(TestEvalNumexprPandas): @classmethod def setUpClass(cls): super(TestEvalNumexprPython, cls).setUpClass() - skip_if_no_ne() + tm.skip_if_no_ne() import numexpr as ne cls.ne = ne cls.engine = 'numexpr' @@ -788,7 +784,7 @@ class TestAlignment(object): lhs_index_types = index_types + ('s',) # 'p' def check_align_nested_unary_op(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) s = 'df * ~2' df = mkdf(5, 3, data_gen_f=f) res = pd.eval(s, engine=engine, parser=parser) @@ -799,7 +795,7 @@ def test_align_nested_unary_op(self): yield self.check_align_nested_unary_op, engine, parser def check_basic_frame_alignment(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) args = product(self.lhs_index_types, self.index_types, self.index_types) for lr_idx_type, rr_idx_type, c_idx_type in args: @@ -815,7 +811,7 @@ def test_basic_frame_alignment(self): yield self.check_basic_frame_alignment, engine, parser def check_frame_comparison(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) args = product(self.lhs_index_types, repeat=2) for r_idx_type, c_idx_type in args: df = mkdf(10, 10, data_gen_f=f, r_idx_type=r_idx_type, @@ -833,7 +829,7 @@ def test_frame_comparison(self): yield self.check_frame_comparison, engine, parser def check_medium_complex_frame_alignment(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) args = product(self.lhs_index_types, self.index_types, self.index_types, self.index_types) @@ -850,7 +846,7 @@ def test_medium_complex_frame_alignment(self): yield self.check_medium_complex_frame_alignment, engine, parser def check_basic_frame_series_alignment(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) def testit(r_idx_type, c_idx_type, index_name): df = mkdf(10, 10, data_gen_f=f, r_idx_type=r_idx_type, @@ -878,7 +874,7 @@ def test_basic_frame_series_alignment(self): yield self.check_basic_frame_series_alignment, engine, parser def check_basic_series_frame_alignment(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) def testit(r_idx_type, c_idx_type, index_name): df = mkdf(10, 7, data_gen_f=f, r_idx_type=r_idx_type, @@ -911,7 +907,7 @@ def test_basic_series_frame_alignment(self): yield self.check_basic_series_frame_alignment, engine, parser def check_series_frame_commutativity(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) args = product(self.lhs_index_types, self.index_types, ('+', '*'), ('index', 'columns')) for r_idx_type, c_idx_type, op, index_name in args: @@ -934,7 +930,7 @@ def test_series_frame_commutativity(self): yield self.check_series_frame_commutativity, engine, parser def check_complex_series_frame_alignment(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) import random args = product(self.lhs_index_types, self.index_types, @@ -978,7 +974,7 @@ def test_complex_series_frame_alignment(self): yield self.check_complex_series_frame_alignment, engine, parser def check_performance_warning_for_poor_alignment(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) df = DataFrame(randn(1000, 10)) s = Series(randn(10000)) if engine == 'numexpr': @@ -1034,7 +1030,7 @@ class TestOperationsNumExprPandas(tm.TestCase): @classmethod def setUpClass(cls): super(TestOperationsNumExprPandas, cls).setUpClass() - skip_if_no_ne() + tm.skip_if_no_ne() cls.engine = 'numexpr' cls.parser = 'pandas' cls.arith_ops = expr._arith_ops_syms + expr._cmp_ops_syms @@ -1194,7 +1190,7 @@ def test_assignment_fails(self): local_dict={'df': df, 'df2': df2}) def test_assignment_column(self): - skip_if_no_ne('numexpr') + tm.skip_if_no_ne('numexpr') df = DataFrame(np.random.randn(5, 2), columns=list('ab')) orig_df = df.copy() @@ -1345,10 +1341,9 @@ class TestOperationsNumExprPython(TestOperationsNumExprPandas): @classmethod def setUpClass(cls): super(TestOperationsNumExprPython, cls).setUpClass() - if not _USE_NUMEXPR: - raise nose.SkipTest("numexpr engine not installed") cls.engine = 'numexpr' cls.parser = 'python' + tm.skip_if_no_ne(cls.engine) cls.arith_ops = expr._arith_ops_syms + expr._cmp_ops_syms cls.arith_ops = filter(lambda x: x not in ('in', 'not in'), cls.arith_ops) @@ -1435,7 +1430,7 @@ def setUpClass(cls): class TestScope(object): def check_global_scope(self, e, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) assert_array_equal(_var_s * 2, pd.eval(e, engine=engine, parser=parser)) @@ -1445,7 +1440,7 @@ def test_global_scope(self): yield self.check_global_scope, e, engine, parser def check_no_new_locals(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) x = 1 lcls = locals().copy() pd.eval('x + 1', local_dict=lcls, engine=engine, parser=parser) @@ -1458,7 +1453,7 @@ def test_no_new_locals(self): yield self.check_no_new_locals, engine, parser def check_no_new_globals(self, engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) x = 1 gbls = globals().copy() pd.eval('x + 1', engine=engine, parser=parser) @@ -1471,21 +1466,21 @@ def test_no_new_globals(self): def test_invalid_engine(): - skip_if_no_ne() + tm.skip_if_no_ne() assertRaisesRegexp(KeyError, 'Invalid engine \'asdf\' passed', pd.eval, 'x + y', local_dict={'x': 1, 'y': 2}, engine='asdf') def test_invalid_parser(): - skip_if_no_ne() + tm.skip_if_no_ne() assertRaisesRegexp(KeyError, 'Invalid parser \'asdf\' passed', pd.eval, 'x + y', local_dict={'x': 1, 'y': 2}, parser='asdf') def check_is_expr_syntax(engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) s = 1 valid1 = 's + 1' valid2 = '__y + _xx' @@ -1494,7 +1489,7 @@ def check_is_expr_syntax(engine): def check_is_expr_names(engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) r, s = 1, 2 valid = 's + r' invalid = '__y + __x' @@ -1517,7 +1512,7 @@ def test_is_expr_names(): def check_disallowed_nodes(engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) VisitorClass = _parsers[parser] uns_ops = VisitorClass.unsupported_nodes inst = VisitorClass('x + 1', engine, parser) @@ -1532,7 +1527,7 @@ def test_disallowed_nodes(): def check_syntax_error_exprs(engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) e = 's +' assert_raises(SyntaxError, pd.eval, e, engine=engine, parser=parser) @@ -1543,7 +1538,7 @@ def test_syntax_error_exprs(): def check_name_error_exprs(engine, parser): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) e = 's + t' assert_raises(NameError, pd.eval, e, engine=engine, parser=parser) @@ -1553,6 +1548,33 @@ def test_name_error_exprs(): yield check_name_error_exprs, engine, parser +def check_invalid_numexpr_version(engine, parser): + def testit(): + a, b = 1, 2 + res = pd.eval('a + b', engine=engine, parser=parser) + tm.assert_equal(res, 3) + + if engine == 'numexpr': + try: + import numexpr as ne + except ImportError: + raise nose.SkipTest("no numexpr") + else: + if ne.__version__ < LooseVersion('2.0'): + with tm.assertRaisesRegexp(ImportError, "'numexpr' version is " + ".+, must be >= 2.0"): + testit() + else: + testit() + else: + testit() + + +def test_invalid_numexpr_version(): + for engine, parser in ENGINES_PARSERS: + yield check_invalid_numexpr_version, engine, parser + + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 0e30b6eda7192..2233f2749d3a8 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -11,6 +11,7 @@ import functools import itertools from itertools import product +from distutils.version import LooseVersion from pandas.compat import( map, zip, range, long, lrange, lmap, lzip, @@ -12014,14 +12015,6 @@ def test_concat_empty_dataframe_dtypes(self): self.assertEqual(result['c'].dtype, np.float64) -def skip_if_no_ne(engine='numexpr'): - if engine == 'numexpr': - try: - import numexpr as ne - except ImportError: - raise nose.SkipTest("cannot query engine numexpr when numexpr not " - "installed") - def skip_if_no_pandas_parser(parser): if parser != 'pandas': @@ -12030,7 +12023,7 @@ def skip_if_no_pandas_parser(parser): class TestDataFrameQueryWithMultiIndex(object): def check_query_with_named_multiindex(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) a = tm.choice(['red', 'green'], size=10) b = tm.choice(['eggs', 'ham'], size=10) index = MultiIndex.from_arrays([a, b], names=['color', 'food']) @@ -12084,7 +12077,7 @@ def test_query_with_named_multiindex(self): yield self.check_query_with_named_multiindex, parser, engine def check_query_with_unnamed_multiindex(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) a = tm.choice(['red', 'green'], size=10) b = tm.choice(['eggs', 'ham'], size=10) index = MultiIndex.from_arrays([a, b]) @@ -12176,7 +12169,7 @@ def test_query_with_unnamed_multiindex(self): yield self.check_query_with_unnamed_multiindex, parser, engine def check_query_with_partially_named_multiindex(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) a = tm.choice(['red', 'green'], size=10) b = np.arange(10) index = MultiIndex.from_arrays([a, b]) @@ -12242,7 +12235,7 @@ def test_raise_on_panel_with_multiindex(self): yield self.check_raise_on_panel_with_multiindex, parser, engine def check_raise_on_panel_with_multiindex(self, parser, engine): - skip_if_no_ne() + tm.skip_if_no_ne() p = tm.makePanel(7) p.items = tm.makeCustomIndex(len(p.items), nlevels=2) with tm.assertRaises(NotImplementedError): @@ -12253,7 +12246,7 @@ def test_raise_on_panel4d_with_multiindex(self): yield self.check_raise_on_panel4d_with_multiindex, parser, engine def check_raise_on_panel4d_with_multiindex(self, parser, engine): - skip_if_no_ne() + tm.skip_if_no_ne() p4d = tm.makePanel4D(7) p4d.items = tm.makeCustomIndex(len(p4d.items), nlevels=2) with tm.assertRaises(NotImplementedError): @@ -12267,7 +12260,7 @@ def setUpClass(cls): super(TestDataFrameQueryNumExprPandas, cls).setUpClass() cls.engine = 'numexpr' cls.parser = 'pandas' - skip_if_no_ne() + tm.skip_if_no_ne() @classmethod def tearDownClass(cls): @@ -12496,7 +12489,7 @@ def setUpClass(cls): super(TestDataFrameQueryNumExprPython, cls).setUpClass() cls.engine = 'numexpr' cls.parser = 'python' - skip_if_no_ne(cls.engine) + tm.skip_if_no_ne(cls.engine) cls.frame = _frame.copy() def test_date_query_method(self): @@ -12615,7 +12608,7 @@ def setUpClass(cls): class TestDataFrameQueryStrings(object): def check_str_query_method(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) df = DataFrame(randn(10, 1), columns=['b']) df['strings'] = Series(list('aabbccddee')) expect = df[df.strings == 'a'] @@ -12659,7 +12652,7 @@ def test_str_list_query_method(self): yield self.check_str_list_query_method, parser, engine def check_str_list_query_method(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) df = DataFrame(randn(10, 1), columns=['b']) df['strings'] = Series(list('aabbccddee')) expect = df[df.strings.isin(['a', 'b'])] @@ -12698,7 +12691,7 @@ def check_str_list_query_method(self, parser, engine): assert_frame_equal(res, expect) def check_query_with_string_columns(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) df = DataFrame({'a': list('aaaabbbbcccc'), 'b': list('aabbccddeeff'), 'c': np.random.randint(5, size=12), @@ -12723,7 +12716,7 @@ def test_query_with_string_columns(self): yield self.check_query_with_string_columns, parser, engine def check_object_array_eq_ne(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) df = DataFrame({'a': list('aaaabbbbcccc'), 'b': list('aabbccddeeff'), 'c': np.random.randint(5, size=12), @@ -12741,7 +12734,7 @@ def test_object_array_eq_ne(self): yield self.check_object_array_eq_ne, parser, engine def check_query_with_nested_strings(self, parser, engine): - skip_if_no_ne(engine) + tm.skip_if_no_ne(engine) skip_if_no_pandas_parser(parser) from pandas.compat import StringIO raw = """id event timestamp @@ -12776,7 +12769,7 @@ def setUpClass(cls): super(TestDataFrameEvalNumExprPandas, cls).setUpClass() cls.engine = 'numexpr' cls.parser = 'pandas' - skip_if_no_ne() + tm.skip_if_no_ne() def setUp(self): self.frame = DataFrame(randn(10, 3), columns=list('abc')) @@ -12803,7 +12796,7 @@ def setUpClass(cls): super(TestDataFrameEvalNumExprPython, cls).setUpClass() cls.engine = 'numexpr' cls.parser = 'python' - skip_if_no_ne() + tm.skip_if_no_ne(cls.engine) class TestDataFrameEvalPythonPandas(TestDataFrameEvalNumExprPandas): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 80e33eb1717da..a3bd88ed2ab4a 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -22,7 +22,7 @@ import numpy as np import pandas as pd -from pandas.core.common import isnull, _is_sequence +from pandas.core.common import _is_sequence import pandas.core.index as index import pandas.core.series as series import pandas.core.frame as frame @@ -1391,3 +1391,21 @@ def assert_produces_warning(expected_warning=Warning, filter_level="always"): % expected_warning.__name__) assert not extra_warnings, ("Caused unexpected warning(s): %r." % extra_warnings) + + +def skip_if_no_ne(engine='numexpr'): + import nose + _USE_NUMEXPR = pd.computation.expressions._USE_NUMEXPR + + if engine == 'numexpr': + try: + import numexpr as ne + except ImportError: + raise nose.SkipTest("numexpr not installed") + + if not _USE_NUMEXPR: + raise nose.SkipTest("numexpr disabled") + + if ne.__version__ < LooseVersion('2.0'): + raise nose.SkipTest("numexpr version too low: " + "%s" % ne.__version__)
closes #5857 closes #5855 closes #5845
https://api.github.com/repos/pandas-dev/pandas/pulls/6109
2014-01-26T19:13:45Z
2014-01-26T22:58:21Z
2014-01-26T22:58:21Z
2014-07-04T13:23:08Z
API: Series.str wont' raise and now returns None (GH6106)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2c03d16fc5cbe..25770a0cddf52 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -79,7 +79,7 @@ class NDFrame(PandasObject): copy : boolean, default False """ _internal_names = ['_data', '_cacher', '_item_cache', '_cache', - 'is_copy', '_subtyp', '_index', '_default_kind', + 'is_copy', 'str', '_subtyp', '_index', '_default_kind', '_default_fill_value','__array_struct__','__array_interface__'] _internal_names_set = set(_internal_names) _metadata = [] @@ -616,7 +616,7 @@ def equals(self, other): if not isinstance(other, self._constructor): return False return self._data.equals(other._data) - + #---------------------------------------------------------------------- # Iteration diff --git a/pandas/src/properties.pyx b/pandas/src/properties.pyx index a8b39d13db2f6..e619a3b6edd9a 100644 --- a/pandas/src/properties.pyx +++ b/pandas/src/properties.pyx @@ -22,7 +22,10 @@ cdef class cache_readonly(object): cache = getattr(obj, '_cache', None) if cache is None: - cache = obj._cache = {} + try: + cache = obj._cache = {} + except (AttributeError): + return if PyDict_Contains(cache, self.name): # not necessary to Py_INCREF @@ -40,10 +43,13 @@ cdef class cache_readonly(object): # Get the cache or set a default one if needed cache = getattr(obj, '_cache', None) if cache is None: - cache = obj._cache = {} + try: + cache = obj._cache = {} + except (AttributeError): + return PyDict_SetItem(cache, self.name, value) - + cdef class AxisProperty(object): cdef: Py_ssize_t axis diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index b8033abf0a6dc..797e415ab9c31 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -29,6 +29,11 @@ class TestStringMethods(tm.TestCase): _multiprocess_can_split_ = True + def test_api(self): + + # GH 6106 + self.assert_(Series.str is None) + def test_iter(self): # GH3638 strs = 'google', 'wikimedia', 'wikipedia', 'wikitravel'
closes #6106
https://api.github.com/repos/pandas-dev/pandas/pulls/6108
2014-01-26T18:25:01Z
2014-01-26T18:25:09Z
2014-01-26T18:25:09Z
2014-06-23T13:10:25Z
TST: add a test for nested strings
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 487bc49c64e7d..d654a7a205c49 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -12603,6 +12603,7 @@ def setUpClass(cls): cls.parser = 'pandas' cls.frame = _frame.copy() + class TestDataFrameQueryPythonPython(TestDataFrameQueryNumExprPython): @classmethod @@ -12611,6 +12612,7 @@ def setUpClass(cls): cls.engine = cls.parser = 'python' cls.frame = _frame.copy() + PARSERS = 'python', 'pandas' ENGINES = 'python', 'numexpr' @@ -12742,6 +12744,34 @@ def test_object_array_eq_ne(self): for parser, engine in product(PARSERS, ENGINES): yield self.check_object_array_eq_ne, parser, engine + def check_query_with_nested_strings(self, parser, engine): + skip_if_no_ne(engine) + skip_if_no_pandas_parser(parser) + from pandas.compat import StringIO + raw = """id event timestamp + 1 "page 1 load" 1/1/2014 0:00:01 + 1 "page 1 exit" 1/1/2014 0:00:31 + 2 "page 2 load" 1/1/2014 0:01:01 + 2 "page 2 exit" 1/1/2014 0:01:31 + 3 "page 3 load" 1/1/2014 0:02:01 + 3 "page 3 exit" 1/1/2014 0:02:31 + 4 "page 1 load" 2/1/2014 1:00:01 + 4 "page 1 exit" 2/1/2014 1:00:31 + 5 "page 2 load" 2/1/2014 1:01:01 + 5 "page 2 exit" 2/1/2014 1:01:31 + 6 "page 3 load" 2/1/2014 1:02:01 + 6 "page 3 exit" 2/1/2014 1:02:31 + """ + df = pd.read_csv(StringIO(raw), sep=r'\s{2,}', + parse_dates=['timestamp']) + expected = df[df.event == '"page 1 load"'] + res = df.query("""'"page 1 load"' in event""", parser=parser, + engine=engine) + tm.assert_frame_equal(expected, res) + + def test_query_with_nested_string(self): + for parser, engine in product(PARSERS, ENGINES): + yield self.check_query_with_nested_strings, parser, engine class TestDataFrameEvalNumExprPandas(tm.TestCase): @@ -12779,6 +12809,7 @@ def setUpClass(cls): cls.parser = 'python' skip_if_no_ne() + class TestDataFrameEvalPythonPandas(TestDataFrameEvalNumExprPandas): @classmethod @@ -12787,6 +12818,7 @@ def setUpClass(cls): cls.engine = 'python' cls.parser = 'pandas' + class TestDataFrameEvalPythonPython(TestDataFrameEvalNumExprPython): @classmethod @@ -12794,6 +12826,7 @@ def setUpClass(cls): super(TestDataFrameEvalPythonPython, cls).tearDownClass() cls.engine = cls.parser = 'python' + if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
null
https://api.github.com/repos/pandas-dev/pandas/pulls/6107
2014-01-26T18:21:51Z
2014-01-26T19:14:54Z
2014-01-26T19:14:54Z
2014-06-15T21:49:21Z
COMPAT: provide compat tests and better error messages for multiple file opening on PyTables >= 3.1 (GH6047)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b49c1b94b32ac..b08be80dcb16a 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -211,11 +211,12 @@ class DuplicateWarning(Warning): # oh the troubles to reduce import time _table_mod = None _table_supports_index = False - +_table_file_open_policy_is_strict = False def _tables(): global _table_mod global _table_supports_index + global _table_file_open_policy_is_strict if _table_mod is None: import tables from distutils.version import LooseVersion @@ -225,8 +226,15 @@ def _tables(): ver = tables.__version__ _table_supports_index = LooseVersion(ver) >= '2.3' - return _table_mod + # set the file open policy + # return the file open policy; this changes as of pytables 3.1 + # depending on the HDF5 version + try: + _table_file_open_policy_is_strict = tables.file._FILE_OPEN_POLICY == 'strict' + except: + pass + return _table_mod @contextmanager def get_store(path, **kwargs): @@ -524,6 +532,22 @@ def open(self, mode='a', **kwargs): self._handle = tables.openFile(self._path, 'r', **kwargs) else: raise + + except (ValueError) as e: + + # trap PyTables >= 3.1 FILE_OPEN_POLICY exception + # to provide an updated message + if 'FILE_OPEN_POLICY' in str(e): + + e = ValueError("PyTables [{version}] no longer supports opening multiple files\n" + "even in read-only mode on this HDF5 version [{hdf_version}]. You can accept this\n" + "and not open the same file multiple times at once,\n" + "upgrade the HDF5 version, or downgrade to PyTables 3.0.0 which allows\n" + "files to be opened multiple times at once\n".format(version=tables.__version__, + hdf_version=tables.getHDF5Version())) + + raise e + except (Exception) as e: # trying to read from a non-existant file causes an error which diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 4478cbc6a655b..b22eea2ef86ea 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -15,6 +15,7 @@ IncompatibilityWarning, PerformanceWarning, AttributeConflictWarning, DuplicateWarning, PossibleDataLossError, ClosedFileError) +from pandas.io import pytables as pytables import pandas.util.testing as tm from pandas.util.testing import (assert_panel4d_equal, assert_panel_equal, @@ -3683,53 +3684,66 @@ def test_multiple_open_close(self): self.assert_('CLOSED' in str(store)) self.assert_(not store.is_open) - # multiples - store1 = HDFStore(path) - store2 = HDFStore(path) - - self.assert_('CLOSED' not in str(store1)) - self.assert_('CLOSED' not in str(store2)) - self.assert_(store1.is_open) - self.assert_(store2.is_open) - - store1.close() - self.assert_('CLOSED' in str(store1)) - self.assert_(not store1.is_open) - self.assert_('CLOSED' not in str(store2)) - self.assert_(store2.is_open) - - store2.close() - self.assert_('CLOSED' in str(store1)) - self.assert_('CLOSED' in str(store2)) - self.assert_(not store1.is_open) - self.assert_(not store2.is_open) - - # nested close - store = HDFStore(path,mode='w') - store.append('df',df) + with ensure_clean_path(self.path) as path: - store2 = HDFStore(path) - store2.append('df2',df) - store2.close() - self.assert_('CLOSED' in str(store2)) - self.assert_(not store2.is_open) + if pytables._table_file_open_policy_is_strict: - store.close() - self.assert_('CLOSED' in str(store)) - self.assert_(not store.is_open) + # multiples + store1 = HDFStore(path) + def f(): + HDFStore(path) + self.assertRaises(ValueError, f) + store1.close() - # double closing - store = HDFStore(path,mode='w') - store.append('df', df) + else: - store2 = HDFStore(path) - store.close() - self.assert_('CLOSED' in str(store)) - self.assert_(not store.is_open) + # multiples + store1 = HDFStore(path) + store2 = HDFStore(path) + + self.assert_('CLOSED' not in str(store1)) + self.assert_('CLOSED' not in str(store2)) + self.assert_(store1.is_open) + self.assert_(store2.is_open) + + store1.close() + self.assert_('CLOSED' in str(store1)) + self.assert_(not store1.is_open) + self.assert_('CLOSED' not in str(store2)) + self.assert_(store2.is_open) + + store2.close() + self.assert_('CLOSED' in str(store1)) + self.assert_('CLOSED' in str(store2)) + self.assert_(not store1.is_open) + self.assert_(not store2.is_open) + + # nested close + store = HDFStore(path,mode='w') + store.append('df',df) + + store2 = HDFStore(path) + store2.append('df2',df) + store2.close() + self.assert_('CLOSED' in str(store2)) + self.assert_(not store2.is_open) + + store.close() + self.assert_('CLOSED' in str(store)) + self.assert_(not store.is_open) + + # double closing + store = HDFStore(path,mode='w') + store.append('df', df) + + store2 = HDFStore(path) + store.close() + self.assert_('CLOSED' in str(store)) + self.assert_(not store.is_open) - store2.close() - self.assert_('CLOSED' in str(store2)) - self.assert_(not store2.is_open) + store2.close() + self.assert_('CLOSED' in str(store2)) + self.assert_(not store2.is_open) # ops on a closed store with ensure_clean_path(self.path) as path:
close #6047
https://api.github.com/repos/pandas-dev/pandas/pulls/6104
2014-01-26T15:09:30Z
2014-01-26T16:11:50Z
2014-01-26T16:11:50Z
2014-07-16T08:49:12Z
TST: json test file, make encoding explicit
diff --git a/pandas/io/tests/test_json/test_ujson.py b/pandas/io/tests/test_json/test_ujson.py index 06ff5abf7cd13..4e9310d2d81ba 100644 --- a/pandas/io/tests/test_json/test_ujson.py +++ b/pandas/io/tests/test_json/test_ujson.py @@ -1,4 +1,6 @@ -from unittest import TestCase +# -*- coding: utf-8 -*- + +from unittest import TestCase try: import json
Replace hidden BOM with explicit utf-8 encoding. closes #6067
https://api.github.com/repos/pandas-dev/pandas/pulls/6101
2014-01-26T02:48:59Z
2014-01-26T03:33:33Z
2014-01-26T03:33:33Z
2014-07-16T08:49:11Z
BUG: in HTMLFormatter._write_header(), str() fails on column names in unicode
diff --git a/doc/source/release.rst b/doc/source/release.rst index 0db9023301dab..7ff6951ee7fa9 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -149,6 +149,7 @@ Bug Fixes - Regression in ``.get(None)`` indexing from 0.12 (:issue:`5652`) - Subtle ``iloc`` indexing bug, surfaced in (:issue:`6059`) - Bug with insert of strings into DatetimeIndex (:issue:`5818`) + - Bug in ``HTMLFormatter._write_header`` for column names in unicode (:issue:`6098`) pandas 0.13.0 ------------- diff --git a/pandas/core/format.py b/pandas/core/format.py index fce0ef6a27889..fa2b464c6bfec 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -767,7 +767,7 @@ def _column_header(): levels)): name = self.columns.names[lnum] row = [''] * (row_levels - 1) + ['' if name is None - else str(name)] + else name] tags = {} j = len(row)
Issue #6098
https://api.github.com/repos/pandas-dev/pandas/pulls/6099
2014-01-25T21:31:53Z
2014-01-27T03:13:14Z
null
2014-06-24T23:13:28Z
TST: don't compare inferred index freq on some tests as it may not be preserved (which is correct)
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index 219281ac00840..4478cbc6a655b 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -1295,14 +1295,14 @@ def check_col(key,name,size): 'string2=foo'), Term('A>0'), Term('B<0')]) expected = df_new[(df_new.string == 'foo') & ( df_new.string2 == 'foo') & (df_new.A > 0) & (df_new.B < 0)] - tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected, check_index_type=False) # yield an empty frame result = store.select('df', [Term('string=foo'), Term( 'string2=cool')]) expected = df_new[(df_new.string == 'foo') & ( df_new.string2 == 'cool')] - tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected, check_index_type=False) with ensure_clean_store(self.path) as store: # doc example @@ -1321,13 +1321,13 @@ def check_col(key,name,size): result = store.select('df_dc', [Term('B>0')]) expected = df_dc[df_dc.B > 0] - tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected, check_index_type=False) result = store.select( 'df_dc', ['B > 0', 'C > 0', 'string == foo']) expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & ( df_dc.string == 'foo')] - tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected, check_index_type=False) with ensure_clean_store(self.path) as store: # doc example part 2
closes #6093
https://api.github.com/repos/pandas-dev/pandas/pulls/6097
2014-01-25T17:29:33Z
2014-01-25T18:03:52Z
2014-01-25T18:03:52Z
2014-06-16T23:53:26Z
DOC: beef up tutorial section. GH5837
diff --git a/doc/source/tutorials.rst b/doc/source/tutorials.rst index 6a1b288e10d38..caa6f0bb58aa2 100644 --- a/doc/source/tutorials.rst +++ b/doc/source/tutorials.rst @@ -108,3 +108,20 @@ For more resources, please visit the main `repository <https://bitbucket.org/hro * | `11 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/11%20-%20Lesson.ipynb>`_ * Combining data from various sources + + +Excel charts with pandas, vincent and xlsxwriter +------------------------------------------------ + +* `Using Pandas and XlsxWriter to create Excel charts <http://pandas-xlsxwriter-charts.readthedocs.org/>`_ + +Various Tutorials +----------------- + +* `Wes McKinney's (Pandas BDFL) blog <http://blog.wesmckinney.com/>`_ +* `Statistical analysis made easy in Python with SciPy and pandas DataFrames, by Randal Olson <http://www.randalolson.com/2012/08/06/statistical-analysis-made-easy-in-python/>`_ +* `Statistical Data Analysis in Python, tutorial videos, by Christopher Fonnesbeck from SciPy 2013 <http://conference.scipy.org/scipy2013/tutorial_detail.php?id=109>`_ +* `Financial analysis in python, by Thomas Wiecki <http://nbviewer.ipython.org/github/twiecki/financial-analysis-python-tutorial/blob/master/1.%20Pandas%20Basics.ipynb>`_ +* `Intro to pandas data structures, by Greg Reda <http://www.gregreda.com/2013/10/26/intro-to-pandas-data-structures/>`_ +* `Pandas and Python: Top 10, by Manish Amde <http://manishamde.github.io/blog/2013/03/07/pandas-and-python-top-10/>`_ +* `Pandas Tutorial, by Mikhail Semeniuk <www.bearrelroll.com/2013/05/python-pandas-tutorial>`_
closes #5837. For the record, I'm somewhat skeptical of this google search results type documentation, but then I said the same thing about the cookbook at the time.
https://api.github.com/repos/pandas-dev/pandas/pulls/6095
2014-01-25T17:13:27Z
2014-01-25T17:13:33Z
2014-01-25T17:13:33Z
2014-07-16T08:49:07Z
BUG: ensure plt is imported before it's used in hist_frame
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 9984c3fd76f81..5162e75540ee2 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1994,7 +1994,7 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, **kwds): """ - Draw Histogram the DataFrame's series using matplotlib / pylab. + Draw histogram of the DataFrame's series using matplotlib / pylab. Parameters ---------- @@ -2022,6 +2022,8 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, kwds : other plotting keyword arguments To be passed to hist function """ + import matplotlib.pyplot as plt + if column is not None: if not isinstance(column, (list, np.ndarray)): column = [column] @@ -2044,7 +2046,6 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, return axes - import matplotlib.pyplot as plt n = len(data.columns) if layout is not None:
If the `by` argument to `hist_frame` isn't `None`, then `plt.setp` can be called be called before `plt` is imported. This moves the import to the start of the function to avoid this.
https://api.github.com/repos/pandas-dev/pandas/pulls/6094
2014-01-25T16:00:31Z
2014-01-25T16:51:38Z
2014-01-25T16:51:38Z
2014-07-16T08:49:06Z
DOC: remove warnings in panel.apply docs (GH6087)
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index 9521bae373060..638c8451bf8db 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -287,7 +287,7 @@ fact, this expression is False: (df+df == df*2).all() Notice that the boolean DataFrame ``df+df == df*2`` contains some False values! -That is because NaNs do not compare as equals: +That is because NaNs do not compare as equals: .. ipython:: python @@ -727,7 +727,7 @@ Apply can also accept multiple axes in the ``axis`` argument. This will pass a .. ipython:: python - f = lambda x: (x-x.mean(1)/x.std(1)) + f = lambda x: ((x.T-x.mean(1))/x.std(1)).T result = panel.apply(f, axis = ['items','major_axis']) result diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt index 7ae80c8d36979..ded0e3b495be2 100644 --- a/doc/source/v0.13.1.txt +++ b/doc/source/v0.13.1.txt @@ -134,7 +134,7 @@ Enhancements .. ipython:: python - f = lambda x: (x-x.mean(1)/x.std(1)) + f = lambda x: ((x.T-x.mean(1))/x.std(1)).T result = panel.apply(f, axis = ['items','major_axis']) result diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index e6a96382cf4fd..bb442519805d4 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -150,12 +150,16 @@ def test_get_quote_stringlist(self): @network def test_get_components_dow_jones(self): + raise nose.SkipTest('unreliable test, receive partial components back for dow_jones') + df = web.get_components_yahoo('^DJI') #Dow Jones assert isinstance(df, pd.DataFrame) self.assertEqual(len(df), 30) @network def test_get_components_dax(self): + raise nose.SkipTest('unreliable test, receive partial components back for dax') + df = web.get_components_yahoo('^GDAXI') #DAX assert isinstance(df, pd.DataFrame) self.assertEqual(len(df), 30) @@ -166,6 +170,8 @@ def test_get_components_dax(self): def test_get_components_nasdaq_100(self): """as of 7/12/13 the conditional will test false because the link is invalid""" + raise nose.SkipTest('unreliable test, receive partial components back for nasdaq_100') + df = web.get_components_yahoo('^NDX') #NASDAQ-100 assert isinstance(df, pd.DataFrame) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 16a43f2f9e767..170eedd3754b3 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1146,11 +1146,13 @@ def test_apply_slabs(self): assert_frame_equal(result,expected) # transforms - f = lambda x: (x-x.mean(1)/x.std(1)) + f = lambda x: ((x.T-x.mean(1))/x.std(1)).T - result = self.panel.apply(f, axis = ['items','major_axis']) - expected = Panel(dict([ (ax,f(self.panel.loc[:,:,ax])) for ax in self.panel.minor_axis ])) - assert_panel_equal(result,expected) + # make sure that we don't trigger any warnings + with tm.assert_produces_warning(False): + result = self.panel.apply(f, axis = ['items','major_axis']) + expected = Panel(dict([ (ax,f(self.panel.loc[:,:,ax])) for ax in self.panel.minor_axis ])) + assert_panel_equal(result,expected) result = self.panel.apply(f, axis = ['major_axis','minor_axis']) expected = Panel(dict([ (ax,f(self.panel.loc[ax])) for ax in self.panel.items ]))
closes #6087
https://api.github.com/repos/pandas-dev/pandas/pulls/6089
2014-01-25T13:57:53Z
2014-01-25T17:36:09Z
2014-01-25T17:36:09Z
2014-07-16T08:49:03Z
BUG: array_equivalent was not passing its own doctest.
diff --git a/pandas/core/common.py b/pandas/core/common.py index c3c038fa0945c..3cedc37533e0c 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -287,8 +287,7 @@ def array_equivalent(left, right): Parameters ---------- - left, right : array_like - Input arrays. + left, right : ndarrays Returns ------- @@ -297,20 +296,15 @@ def array_equivalent(left, right): Examples -------- - >>> array_equivalent([1, 2, nan], np.array([1, 2, nan])) + >>> array_equivalent(np.array([1, 2, nan]), np.array([1, 2, nan])) True - >>> array_equivalent([1, nan, 2], [1, 2, nan]) + >>> array_equivalent(np.array([1, nan, 2]), np.array([1, 2, nan])) False """ if left.shape != right.shape: return False # NaNs occur only in object arrays, float or complex arrays. - if left.dtype == np.object_: - # If object array, we need to use pd.isnull - return ((left == right) | pd.isnull(left) & pd.isnull(right)).all() - elif not issubclass(left.dtype.type, (np.floating, np.complexfloating)): - # if not a float or complex array, then there are no NaNs + if not issubclass(left.dtype.type, (np.floating, np.complexfloating)): return np.array_equal(left, right) - # For float or complex arrays, using np.isnan is faster than pd.isnull return ((left == right) | (np.isnan(left) & np.isnan(right))).all() def _iterable_not_string(x): diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 45c9bf5d8c374..1ea3b32713ca4 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -168,15 +168,18 @@ def test_downcast_conv(): def test_array_equivalent(): - assert array_equivalent(np.array([np.nan, np.nan]), np.array([np.nan, np.nan])) - assert array_equivalent(np.array([np.nan, 1, np.nan]), np.array([np.nan, 1, np.nan])) + assert array_equivalent(np.array([np.nan, np.nan]), + np.array([np.nan, np.nan])) + assert array_equivalent(np.array([np.nan, 1, np.nan]), + np.array([np.nan, 1, np.nan])) assert array_equivalent(np.array([np.nan, None], dtype='object'), np.array([np.nan, None], dtype='object')) assert array_equivalent(np.array([np.nan, 1+1j], dtype='complex'), np.array([np.nan, 1+1j], dtype='complex')) assert not array_equivalent(np.array([np.nan, 1+1j], dtype='complex'), np.array([np.nan, 1+2j], dtype='complex')) - assert not array_equivalent(np.array([np.nan, 1, np.nan]), np.array([np.nan, 2, np.nan])) + assert not array_equivalent(np.array([np.nan, 1, np.nan]), + np.array([np.nan, 2, np.nan])) assert not array_equivalent(np.array(['a', 'b', 'c', 'd']), np.array(['e', 'e'])) def test_datetimeindex_from_empty_datetime64_array():
The examples in the docstring showed lists being passed to array_equivalent. `array_equivalent` expects `ndarrays` only. (It raises an `AttributeError` when passed a list.) Also, the use of `pd.isnull` can be removed from `array_equivalent`. My thinking here was muddled. `pd.isnull` is only needed if `array_equivalent` were to accept objects other than ndarrays. `np.array_equal` works as desired for all `ndarrays` except those of float or complex dtype.
https://api.github.com/repos/pandas-dev/pandas/pulls/6088
2014-01-25T13:16:31Z
2014-01-25T13:30:57Z
2014-01-25T13:30:57Z
2014-07-16T08:49:02Z