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
Add SparseSeries.to_coo method, a single test and one example.
diff --git a/doc/source/api.rst b/doc/source/api.rst index 149421bde28c8..7fbb432f0be6b 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -634,6 +634,14 @@ Serialization / IO / Conversion Series.to_string Series.to_clipboard +Sparse methods +~~~~~~~~~~~~~~ +.. autosummary:: + :toctree: generated/ + + SparseSeries.to_coo + SparseSeries.from_coo + .. _api.dataframe: DataFrame diff --git a/doc/source/sparse.rst b/doc/source/sparse.rst index 391aae1cd9105..e72ee6b709282 100644 --- a/doc/source/sparse.rst +++ b/doc/source/sparse.rst @@ -109,10 +109,9 @@ accept scalar values or any 1-dimensional sequence: .. ipython:: python :suppress: - from numpy import nan - .. ipython:: python + from numpy import nan spl.append(np.array([1., nan, nan, 2., 3.])) spl.append(5) spl.append(sparr) @@ -135,3 +134,92 @@ recommend using ``block`` as it's more memory efficient. The ``integer`` format keeps an arrays of all of the locations where the data are not equal to the fill value. The ``block`` format tracks only the locations and sizes of blocks of data. + +.. _sparse.scipysparse: + +Interaction with scipy.sparse +----------------------------- + +Experimental api to transform between sparse pandas and scipy.sparse structures. + +A :meth:`SparseSeries.to_coo` method is implemented for transforming a ``SparseSeries`` indexed by a ``MultiIndex`` to a ``scipy.sparse.coo_matrix``. + +The method requires a ``MultiIndex`` with two or more levels. + +.. ipython:: python + :suppress: + + +.. ipython:: python + + from numpy import nan + s = Series([3.0, nan, 1.0, 3.0, nan, nan]) + s.index = MultiIndex.from_tuples([(1, 2, 'a', 0), + (1, 2, 'a', 1), + (1, 1, 'b', 0), + (1, 1, 'b', 1), + (2, 1, 'b', 0), + (2, 1, 'b', 1)], + names=['A', 'B', 'C', 'D']) + + s + # SparseSeries + ss = s.to_sparse() + ss + +In the example below, we transform the ``SparseSeries`` to a sparse representation of a 2-d array by specifying that the first and second ``MultiIndex`` levels define labels for the rows and the third and fourth levels define labels for the columns. We also specify that the column and row labels should be sorted in the final sparse representation. + +.. ipython:: python + + A, rows, columns = ss.to_coo(row_levels=['A', 'B'], + column_levels=['C', 'D'], + sort_labels=True) + + A + A.todense() + rows + columns + +Specifying different row and column labels (and not sorting them) yields a different sparse matrix: + +.. ipython:: python + + A, rows, columns = ss.to_coo(row_levels=['A', 'B', 'C'], + column_levels=['D'], + sort_labels=False) + + A + A.todense() + rows + columns + +A convenience method :meth:`SparseSeries.from_coo` is implemented for creating a ``SparseSeries`` from a ``scipy.sparse.coo_matrix``. + +.. ipython:: python + :suppress: + +.. ipython:: python + + from scipy import sparse + A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), + shape=(3, 4)) + A + A.todense() + +The default behaviour (with ``dense_index=False``) simply returns a ``SparseSeries`` containing +only the non-null entries. + +.. ipython:: python + + ss = SparseSeries.from_coo(A) + ss + +Specifying ``dense_index=True`` will result in an index that is the Cartesian product of the +row and columns coordinates of the matrix. Note that this will consume a significant amount of memory +(relative to ``dense_index=False``) if the sparse matrix is large (and sparse) enough. + +.. ipython:: python + + ss_dense = SparseSeries.from_coo(A, dense_index=True) + ss_dense + diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index bbc006b41a433..ded4040010683 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -194,6 +194,55 @@ Enhancements - ``StringMethods.pad()`` and ``center()`` now accept ``fillchar`` option to specify filling character (:issue:`9352`) - Added ``StringMethods.zfill()`` which behave as the same as standard ``str`` (:issue:`9387`) +Interaction with scipy.sparse +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Added :meth:`SparseSeries.to_coo` and :meth:`SparseSeries.from_coo` methods + (:issue:`8048`) for converting to and from ``scipy.sparse.coo_matrix`` + instances (see :ref:`here <sparse.scipysparse>`). + For example, given a SparseSeries with MultiIndex we can convert to a + `scipy.sparse.coo_matrix` by specifying the row and column labels as + index levels: + + .. ipython:: python + + from numpy import nan + s = Series([3.0, nan, 1.0, 3.0, nan, nan]) + s.index = MultiIndex.from_tuples([(1, 2, 'a', 0), + (1, 2, 'a', 1), + (1, 1, 'b', 0), + (1, 1, 'b', 1), + (2, 1, 'b', 0), + (2, 1, 'b', 1)], + names=['A', 'B', 'C', 'D']) + + s + # SparseSeries + ss = s.to_sparse() + ss + + A, rows, columns = ss.to_coo(row_levels=['A', 'B'], + column_levels=['C', 'D'], + sort_labels=False) + + A + A.todense() + rows + columns + + The from_coo method is a convenience method for creating a ``SparseSeries`` + from a ``scipy.sparse.coo_matrix``: + + .. ipython:: python + + from scipy import sparse + A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), + shape=(3, 4)) + A + A.todense() + + ss = SparseSeries.from_coo(A) + ss + Performance ~~~~~~~~~~~ diff --git a/pandas/sparse/scipy_sparse.py b/pandas/sparse/scipy_sparse.py new file mode 100644 index 0000000000000..91ec26396b3ec --- /dev/null +++ b/pandas/sparse/scipy_sparse.py @@ -0,0 +1,133 @@ +""" +Interaction with scipy.sparse matrices. + +Currently only includes SparseSeries.to_coo helpers. +""" +from pandas.core.frame import DataFrame +from pandas.core.index import MultiIndex, Index +from pandas.core.series import Series +import itertools +import numpy as np +from pandas.compat import OrderedDict +from pandas.tools.util import cartesian_product + + +def _check_is_partition(parts, whole): + whole = set(whole) + parts = [set(x) for x in parts] + if set.intersection(*parts) != set(): + raise ValueError( + 'Is not a partition because intersection is not null.') + if set.union(*parts) != whole: + raise ValueError('Is not a partition becuase union is not the whole.') + + +def _to_ijv(ss, row_levels=(0,), column_levels=(1,), sort_labels=False): + """ For arbitrary (MultiIndexed) SparseSeries return + (v, i, j, ilabels, jlabels) where (v, (i, j)) is suitable for + passing to scipy.sparse.coo constructor. """ + # index and column levels must be a partition of the index + _check_is_partition([row_levels, column_levels], range(ss.index.nlevels)) + + # from the SparseSeries: get the labels and data for non-null entries + values = ss._data.values._valid_sp_values + + nonnull_labels = ss.dropna() + + def get_indexers(levels): + """ Return sparse coords and dense labels for subset levels """ + + # TODO: how to do this better? cleanly slice nonnull_labels given the + # coord + values_ilabels = [tuple(x[i] for i in levels) + for x in nonnull_labels.index] + if len(levels) == 1: + values_ilabels = [x[0] for x in values_ilabels] + + ####################################################################### + # # performance issues with groupby ################################### + # TODO: these two lines can rejplace the code below but + # groupby is too slow (in some cases at least) + # labels_to_i = ss.groupby(level=levels, sort=sort_labels).first() + # labels_to_i[:] = np.arange(labels_to_i.shape[0]) + + def _get_label_to_i_dict(labels, sort_labels=False): + """ Return OrderedDict of unique labels to number. + Optionally sort by label. """ + labels = Index(map(tuple, labels)).unique().tolist() # squish + if sort_labels: + labels = sorted(list(labels)) + d = OrderedDict((k, i) for i, k in enumerate(labels)) + return(d) + + def _get_index_subset_to_coord_dict(index, subset, sort_labels=False): + def robust_get_level_values(i): + # if index has labels (that are not None) use those, + # else use the level location + try: + return(index.get_level_values(index.names[i])) + except KeyError: + return(index.get_level_values(i)) + ilabels = list( + zip(*[robust_get_level_values(i) for i in subset])) + labels_to_i = _get_label_to_i_dict( + ilabels, sort_labels=sort_labels) + labels_to_i = Series(labels_to_i) + labels_to_i.index = MultiIndex.from_tuples(labels_to_i.index) + labels_to_i.index.names = [index.names[i] for i in subset] + labels_to_i.name = 'value' + return(labels_to_i) + + labels_to_i = _get_index_subset_to_coord_dict( + ss.index, levels, sort_labels=sort_labels) + ####################################################################### + ####################################################################### + + i_coord = labels_to_i[values_ilabels].tolist() + i_labels = labels_to_i.index.tolist() + + return i_coord, i_labels + + i_coord, i_labels = get_indexers(row_levels) + j_coord, j_labels = get_indexers(column_levels) + + return values, i_coord, j_coord, i_labels, j_labels + + +def _sparse_series_to_coo(ss, row_levels=(0,), column_levels=(1,), sort_labels=False): + """ Convert a SparseSeries to a scipy.sparse.coo_matrix using index + levels row_levels, column_levels as the row and column + labels respectively. Returns the sparse_matrix, row and column labels. """ + + import scipy.sparse + + if ss.index.nlevels < 2: + raise ValueError('to_coo requires MultiIndex with nlevels > 2') + if not ss.index.is_unique: + raise ValueError( + 'Duplicate index entries are not allowed in to_coo transformation.') + + # to keep things simple, only rely on integer indexing (not labels) + row_levels = [ss.index._get_level_number(x) for x in row_levels] + column_levels = [ss.index._get_level_number(x) for x in column_levels] + + v, i, j, rows, columns = _to_ijv( + ss, row_levels=row_levels, column_levels=column_levels, sort_labels=sort_labels) + sparse_matrix = scipy.sparse.coo_matrix( + (v, (i, j)), shape=(len(rows), len(columns))) + return sparse_matrix, rows, columns + + +def _coo_to_sparse_series(A, dense_index=False): + """ Convert a scipy.sparse.coo_matrix to a SparseSeries. + Use the defaults given in the SparseSeries constructor. """ + s = Series(A.data, MultiIndex.from_arrays((A.row, A.col))) + s = s.sort_index() + s = s.to_sparse() # TODO: specify kind? + if dense_index: + # is there a better constructor method to use here? + i = range(A.shape[0]) + j = range(A.shape[1]) + ind = MultiIndex.from_product([i, j]) + s = s.reindex_axis(ind) + return s diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py index bcf9606c3748f..2c328e51b5090 100644 --- a/pandas/sparse/series.py +++ b/pandas/sparse/series.py @@ -29,12 +29,14 @@ from pandas.util.decorators import Appender +from pandas.sparse.scipy_sparse import _sparse_series_to_coo, _coo_to_sparse_series + #------------------------------------------------------------------------------ # Wrapper function for Series arithmetic methods def _arith_method(op, name, str_rep=None, default_axis=None, fill_zeros=None, - **eval_kwargs): + **eval_kwargs): """ Wrapper function for Series arithmetic operations, to avoid code duplication. @@ -115,7 +117,7 @@ def __init__(self, data=None, index=None, sparse_index=None, kind='block', if copy: data = data.copy() else: - + if data is None: data = [] @@ -657,6 +659,98 @@ def combine_first(self, other): dense_combined = self.to_dense().combine_first(other) return dense_combined.to_sparse(fill_value=self.fill_value) + def to_coo(self, row_levels=(0,), column_levels=(1,), sort_labels=False): + """ + Create a scipy.sparse.coo_matrix from a SparseSeries with MultiIndex. + + Use row_levels and column_levels to determine the row and column coordinates respectively. + row_levels and column_levels are the names (labels) or numbers of the levels. + {row_levels, column_levels} must be a partition of the MultiIndex level names (or numbers). + + Parameters + ---------- + row_levels : tuple/list + column_levels : tuple/list + sort_labels : bool, default False + Sort the row and column labels before forming the sparse matrix. + + Returns + ------- + y : scipy.sparse.coo_matrix + rows : list (row labels) + columns : list (column labels) + + Examples + -------- + >>> from numpy import nan + >>> s = Series([3.0, nan, 1.0, 3.0, nan, nan]) + >>> s.index = MultiIndex.from_tuples([(1, 2, 'a', 0), + (1, 2, 'a', 1), + (1, 1, 'b', 0), + (1, 1, 'b', 1), + (2, 1, 'b', 0), + (2, 1, 'b', 1)], + names=['A', 'B', 'C', 'D']) + >>> ss = s.to_sparse() + >>> A, rows, columns = ss.to_coo(row_levels=['A', 'B'], + column_levels=['C', 'D'], + sort_labels=True) + >>> A + <3x4 sparse matrix of type '<class 'numpy.float64'>' + with 3 stored elements in COOrdinate format> + >>> A.todense() + matrix([[ 0., 0., 1., 3.], + [ 3., 0., 0., 0.], + [ 0., 0., 0., 0.]]) + >>> rows + [(1, 1), (1, 2), (2, 1)] + >>> columns + [('a', 0), ('a', 1), ('b', 0), ('b', 1)] + """ + A, rows, columns = _sparse_series_to_coo( + self, row_levels, column_levels, sort_labels=sort_labels) + return A, rows, columns + + @classmethod + def from_coo(cls, A, dense_index=False): + """ + Create a SparseSeries from a scipy.sparse.coo_matrix. + + Parameters + ---------- + A : scipy.sparse.coo_matrix + dense_index : bool, default False + If False (default), the SparseSeries index consists of only the coords of the non-null entries of the original coo_matrix. + If True, the SparseSeries index consists of the full sorted (row, col) coordinates of the coo_matrix. + + Returns + ------- + s : SparseSeries + + Examples + --------- + >>> from scipy import sparse + >>> A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), + shape=(3, 4)) + >>> A + <3x4 sparse matrix of type '<class 'numpy.float64'>' + with 3 stored elements in COOrdinate format> + >>> A.todense() + matrix([[ 0., 0., 1., 2.], + [ 3., 0., 0., 0.], + [ 0., 0., 0., 0.]]) + >>> ss = SparseSeries.from_coo(A) + >>> ss + 0 2 1 + 3 2 + 1 0 3 + dtype: float64 + BlockIndex + Block locations: array([0], dtype=int32) + Block lengths: array([3], dtype=int32) + """ + return _coo_to_sparse_series(A, dense_index=dense_index) + # overwrite series methods with unaccelerated versions ops.add_special_arithmetic_methods(SparseSeries, use_numexpr=False, **ops.series_special_funcs) diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index eebe822ae74c0..b0cd81ce4d111 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -2,6 +2,7 @@ import operator from datetime import datetime +import functools import nose @@ -11,10 +12,10 @@ dec = np.testing.dec from pandas.util.testing import (assert_almost_equal, assert_series_equal, - assert_frame_equal, assert_panel_equal, assertRaisesRegexp) + assert_frame_equal, assert_panel_equal, assertRaisesRegexp, assert_array_equal) from numpy.testing import assert_equal -from pandas import Series, DataFrame, bdate_range, Panel +from pandas import Series, DataFrame, bdate_range, Panel, MultiIndex from pandas.core.datetools import BDay from pandas.core.index import Index from pandas.tseries.index import DatetimeIndex @@ -23,6 +24,7 @@ import pandas.util.testing as tm from pandas.compat import range, lrange, StringIO, lrange from pandas import compat +from pandas.tools.util import cartesian_product import pandas.sparse.frame as spf @@ -30,7 +32,6 @@ from pandas.sparse.api import (SparseSeries, SparseTimeSeries, SparseDataFrame, SparsePanel, SparseArray) - import pandas.tests.test_frame as test_frame import pandas.tests.test_panel as test_panel import pandas.tests.test_series as test_series @@ -168,7 +169,7 @@ def test_construct_DataFrame_with_sp_series(self): assert_sp_series_equal(df['col'], self.bseries) - result = df.iloc[:,0] + result = df.iloc[:, 0] assert_sp_series_equal(result, self.bseries) # blocking @@ -748,6 +749,126 @@ def test_combine_first(self): assert_sp_series_equal(result, expected) +class TestSparseSeriesScipyInteraction(tm.TestCase): + # Issue 8048: add SparseSeries coo methods + + def setUp(self): + tm._skip_if_no_scipy() + import scipy.sparse + # SparseSeries inputs used in tests, the tests rely on the order + self.sparse_series = [] + s = pd.Series([3.0, nan, 1.0, 2.0, nan, nan]) + s.index = pd.MultiIndex.from_tuples([(1, 2, 'a', 0), + (1, 2, 'a', 1), + (1, 1, 'b', 0), + (1, 1, 'b', 1), + (2, 1, 'b', 0), + (2, 1, 'b', 1)], + names=['A', 'B', 'C', 'D']) + self.sparse_series.append(s.to_sparse()) + + ss = self.sparse_series[0].copy() + ss.index.names = [3, 0, 1, 2] + self.sparse_series.append(ss) + + ss = pd.Series( + [nan] * 12, index=cartesian_product((range(3), range(4)))).to_sparse() + for k, v in zip([(0, 0), (1, 2), (1, 3)], [3.0, 1.0, 2.0]): + ss[k] = v + self.sparse_series.append(ss) + + # results used in tests + self.coo_matrices = [] + self.coo_matrices.append(scipy.sparse.coo_matrix( + ([3.0, 1.0, 2.0], ([0, 1, 1], [0, 2, 3])), shape=(3, 4))) + self.coo_matrices.append(scipy.sparse.coo_matrix( + ([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(3, 4))) + self.ils = [[(1, 2), (1, 1), (2, 1)], [(1, 1), (1, 2), (2, 1)]] + self.jls = [[('a', 0), ('a', 1), ('b', 0), ('b', 1)]] + + def test_to_coo_text_names_integer_row_levels_nosort(self): + ss = self.sparse_series[0] + kwargs = {'row_levels': [0, 1], 'column_levels': [2, 3]} + result = (self.coo_matrices[0], self.ils[0], self.jls[0]) + self._run_test(ss, kwargs, result) + + def test_to_coo_text_names_integer_row_levels_sort(self): + ss = self.sparse_series[0] + kwargs = {'row_levels': [0, 1], + 'column_levels': [2, 3], 'sort_labels': True} + result = (self.coo_matrices[1], self.ils[1], self.jls[0]) + self._run_test(ss, kwargs, result) + + def test_to_coo_integer_names_integer_row_levels_nosort(self): + ss = self.sparse_series[1] + kwargs = {'row_levels': [3, 0], 'column_levels': [1, 2]} + result = (self.coo_matrices[0], self.ils[0], self.jls[0]) + self._run_test(ss, kwargs, result) + + def test_to_coo_text_names_text_row_levels_nosort(self): + ss = self.sparse_series[0] + kwargs = {'row_levels': ['A', 'B'], 'column_levels': ['C', 'D']} + result = (self.coo_matrices[0], self.ils[0], self.jls[0]) + self._run_test(ss, kwargs, result) + + def test_to_coo_bad_partition_nonnull_intersection(self): + ss = self.sparse_series[0] + self.assertRaises(ValueError, ss.to_coo, ['A', 'B', 'C'], ['C', 'D']) + + def test_to_coo_bad_partition_small_union(self): + ss = self.sparse_series[0] + self.assertRaises(ValueError, ss.to_coo, ['A'], ['C', 'D']) + + def test_to_coo_nlevels_less_than_two(self): + ss = self.sparse_series[0] + ss.index = np.arange(len(ss.index)) + self.assertRaises(ValueError, ss.to_coo) + + def test_to_coo_bad_ilevel(self): + ss = self.sparse_series[0] + self.assertRaises(KeyError, ss.to_coo, ['A', 'B'], ['C', 'D', 'E']) + + def test_to_coo_duplicate_index_entries(self): + ss = pd.concat( + [self.sparse_series[0], self.sparse_series[0]]).to_sparse() + self.assertRaises(ValueError, ss.to_coo, ['A', 'B'], ['C', 'D']) + + def test_from_coo_dense_index(self): + ss = SparseSeries.from_coo(self.coo_matrices[0], dense_index=True) + check = self.sparse_series[2] + assert_sp_series_equal(ss, check) + + def test_from_coo_nodense_index(self): + ss = SparseSeries.from_coo(self.coo_matrices[0], dense_index=False) + check = self.sparse_series[2] + check = check.dropna().to_sparse() + assert_sp_series_equal(ss, check) + + def _run_test(self, ss, kwargs, check): + results = ss.to_coo(**kwargs) + self._check_results_to_coo(results, check) + # for every test, also test symmetry property (transpose), switch + # row_levels and column_levels + d = kwargs.copy() + d['row_levels'] = kwargs['column_levels'] + d['column_levels'] = kwargs['row_levels'] + results = ss.to_coo(**d) + results = (results[0].T, results[2], results[1]) + self._check_results_to_coo(results, check) + + @staticmethod + def _check_results_to_coo(results, check): + (A, il, jl) = results + (A_result, il_result, jl_result) = check + # convert to dense and compare + assert_array_equal(A.todense(), A_result.todense()) + # or compare directly as difference of sparse + # assert(abs(A - A_result).max() < 1e-12) # max is failing in python + # 2.6 + assert_equal(il, il_result) + assert_equal(jl, jl_result) + + class TestSparseTimeSeries(tm.TestCase): pass @@ -888,9 +1009,9 @@ def test_constructor_from_series(self): # GH 2873 x = Series(np.random.randn(10000), name='a') x = x.to_sparse(fill_value=0) - tm.assert_isinstance(x,SparseSeries) + tm.assert_isinstance(x, SparseSeries) df = SparseDataFrame(x) - tm.assert_isinstance(df,SparseDataFrame) + tm.assert_isinstance(df, SparseDataFrame) x = Series(np.random.randn(10000), name='a') y = Series(np.random.randn(10000), name='b') @@ -1090,7 +1211,7 @@ def test_icol(self): data = {'A': [0, 1]} iframe = SparseDataFrame(data, default_kind='integer') self.assertEqual(type(iframe['A'].sp_index), - type(iframe.icol(0).sp_index)) + type(iframe.icol(0).sp_index)) def test_set_value(self): diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py index 334534ed466f2..77e9044e2a40c 100644 --- a/vb_suite/frame_methods.py +++ b/vb_suite/frame_methods.py @@ -500,9 +500,9 @@ def get_data(n=100000): frame_from_records_generator = Benchmark('df = DataFrame.from_records(get_data())', setup, name='frame_from_records_generator', - start_date=datetime(2013,10,04)) # issue-4911 + start_date=datetime(2013,10,4)) # issue-4911 frame_from_records_generator_nrows = Benchmark('df = DataFrame.from_records(get_data(), nrows=1000)', setup, name='frame_from_records_generator_nrows', - start_date=datetime(2013,10,04)) # issue-4911 + start_date=datetime(2013,10,4)) # issue-4911 diff --git a/vb_suite/sparse.py b/vb_suite/sparse.py index 1cb0f9233f7e9..e591b197d3384 100644 --- a/vb_suite/sparse.py +++ b/vb_suite/sparse.py @@ -37,3 +37,29 @@ sparse_constructor = Benchmark(stmt, setup, name="sparse_frame_constructor", start_date=datetime(2012, 6, 1)) + + +setup = common_setup + """ +s = pd.Series([nan] * 10000) +s[0] = 3.0 +s[100] = -1.0 +s[999] = 12.1 +s.index = pd.MultiIndex.from_product((range(10), range(10), range(10), range(10))) +ss = s.to_sparse() +""" + +stmt = "ss.to_coo(row_levels=[0, 1], column_levels=[2, 3], sort_labels=True)" + +sparse_series_to_coo = Benchmark(stmt, setup, name="sparse_series_to_coo", + start_date=datetime(2015, 1, 3)) + +setup = common_setup + """ +import scipy.sparse +import pandas.sparse.series +A = scipy.sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(100, 100)) +""" + +stmt = "ss = pandas.sparse.series.from_coo(A)" + +sparse_series_from_coo = Benchmark(stmt, setup, name="sparse_series_from_coo", + start_date=datetime(2015, 1, 3)) diff --git a/vb_suite/stat_ops.py b/vb_suite/stat_ops.py index f4ea6706c193c..544ad6d00ed37 100644 --- a/vb_suite/stat_ops.py +++ b/vb_suite/stat_ops.py @@ -86,9 +86,9 @@ start_date=datetime(2011, 12, 12)) stats_rank_pct_average = Benchmark('s.rank(pct=True)', setup, - start_date=datetime(2014, 01, 16)) + start_date=datetime(2014, 1, 16)) stats_rank_pct_average_old = Benchmark('s.rank() / len(s)', setup, - start_date=datetime(2014, 01, 16)) + start_date=datetime(2014, 1, 16)) setup = common_setup + """ values = np.random.randint(0, 100000, size=200000) s = Series(values)
xref #4343 closes #8048 This passes locally run nosetests but is failing on Travis. I think the latest Travis CI changes might have caused failures. I was able to get master to pass on Travis last week but now it is failing.
https://api.github.com/repos/pandas-dev/pandas/pulls/9076
2014-12-14T21:58:32Z
2015-03-03T01:04:51Z
null
2015-03-04T21:13:49Z
fixing highly confusing typo.
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst index f30d6c9d5d4c0..7f8d0e529fc8b 100644 --- a/doc/source/visualization.rst +++ b/doc/source/visualization.rst @@ -727,7 +727,7 @@ You can use the ``labels`` and ``colors`` keywords to specify the labels and col .. warning:: - Most pandas plots use the the ``label`` and ``color`` arguments (not the lack of "s" on those). + Most pandas plots use the the ``label`` and ``color`` arguments (note the lack of "s" on those). To be consistent with :func:`matplotlib.pyplot.pie` you must use ``labels`` and ``colors``. If you want to hide wedge labels, specify ``labels=None``.
The power of an 'e'.
https://api.github.com/repos/pandas-dev/pandas/pulls/9074
2014-12-14T06:05:46Z
2014-12-14T21:50:02Z
2014-12-14T21:50:02Z
2014-12-14T22:14:09Z
ENH: add interval kwarg to get_data_yahoo issue #9071
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 21b1ddea0e9da..8e67b3c067367 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -57,6 +57,7 @@ Enhancements .. _whatsnew_0160.enhancements: - Paths beginning with ~ will now be expanded to begin with the user's home directory (:issue:`9066`) +- Added time interval selection in get_data_yahoo (:issue:`9071`) Performance ~~~~~~~~~~~ diff --git a/pandas/io/data.py b/pandas/io/data.py index 3d92d383badf8..b5cf5f9d9be19 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -180,7 +180,7 @@ def _retry_read_url(url, retry_count, pause, name): _HISTORICAL_YAHOO_URL = 'http://ichart.finance.yahoo.com/table.csv?' -def _get_hist_yahoo(sym, start, end, retry_count, pause): +def _get_hist_yahoo(sym, start, end, interval, retry_count, pause): """ Get historical data for the given name from yahoo. Date format is datetime @@ -195,7 +195,7 @@ def _get_hist_yahoo(sym, start, end, retry_count, pause): '&d=%s' % (end.month - 1) + '&e=%s' % end.day + '&f=%s' % end.year + - '&g=d' + + '&g=%s' % interval + '&ignore=.csv') return _retry_read_url(url, retry_count, pause, 'Yahoo!') @@ -203,7 +203,7 @@ def _get_hist_yahoo(sym, start, end, retry_count, pause): _HISTORICAL_GOOGLE_URL = 'http://www.google.com/finance/historical?' -def _get_hist_google(sym, start, end, retry_count, pause): +def _get_hist_google(sym, start, end, interval, retry_count, pause): """ Get historical data for the given name from google. Date format is datetime @@ -314,14 +314,14 @@ def get_components_yahoo(idx_sym): return idx_df -def _dl_mult_symbols(symbols, start, end, chunksize, retry_count, pause, +def _dl_mult_symbols(symbols, start, end, interval, chunksize, retry_count, pause, method): stocks = {} failed = [] for sym_group in _in_chunks(symbols, chunksize): for sym in sym_group: try: - stocks[sym] = method(sym, start, end, retry_count, pause) + stocks[sym] = method(sym, start, end, interval, retry_count, pause) except IOError: warnings.warn('Failed to read symbol: {0!r}, replacing with ' 'NaN.'.format(sym), SymbolWarning) @@ -343,20 +343,20 @@ def _dl_mult_symbols(symbols, start, end, chunksize, retry_count, pause, _source_functions = {'google': _get_hist_google, 'yahoo': _get_hist_yahoo} -def _get_data_from(symbols, start, end, retry_count, pause, adjust_price, +def _get_data_from(symbols, start, end, interval, retry_count, pause, adjust_price, ret_index, chunksize, source): src_fn = _source_functions[source] # If a single symbol, (e.g., 'GOOG') if isinstance(symbols, (compat.string_types, int)): - hist_data = src_fn(symbols, start, end, retry_count, pause) + hist_data = src_fn(symbols, start, end, interval, retry_count, pause) # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT']) elif isinstance(symbols, DataFrame): - hist_data = _dl_mult_symbols(symbols.index, start, end, chunksize, + hist_data = _dl_mult_symbols(symbols.index, start, end, interval, chunksize, retry_count, pause, src_fn) else: - hist_data = _dl_mult_symbols(symbols, start, end, chunksize, + hist_data = _dl_mult_symbols(symbols, start, end, interval, chunksize, retry_count, pause, src_fn) if source.lower() == 'yahoo': if ret_index: @@ -369,7 +369,7 @@ def _get_data_from(symbols, start, end, retry_count, pause, adjust_price, def get_data_yahoo(symbols=None, start=None, end=None, retry_count=3, pause=0.001, adjust_price=False, ret_index=False, - chunksize=25): + chunksize=25, interval='d'): """ Returns DataFrame/Panel of historical stock prices from symbols, over date range, start to end. To avoid being penalized by Yahoo! Finance servers, @@ -398,12 +398,17 @@ def get_data_yahoo(symbols=None, start=None, end=None, retry_count=3, If True, includes a simple return index 'Ret_Index' in hist_data. chunksize : int, default 25 Number of symbols to download consecutively before intiating pause. + interval : string, default 'd' + Time interval code, valid values are 'd' for daily, 'w' for weekly, + 'm' for monthly and 'v' for dividend. Returns ------- hist_data : DataFrame (str) or Panel (array-like object, DataFrame) """ - return _get_data_from(symbols, start, end, retry_count, pause, + if interval not in ['d', 'w', 'm', 'v']: + raise ValueError("Invalid interval: valid values are 'd', 'w', 'm' and 'v'") + return _get_data_from(symbols, start, end, interval, retry_count, pause, adjust_price, ret_index, chunksize, 'yahoo') @@ -437,7 +442,7 @@ def get_data_google(symbols=None, start=None, end=None, retry_count=3, ------- hist_data : DataFrame (str) or Panel (array-like object, DataFrame) """ - return _get_data_from(symbols, start, end, retry_count, pause, + return _get_data_from(symbols, start, end, None, retry_count, pause, adjust_price, ret_index, chunksize, 'google') diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index a65722dc76556..2d6f14c79633a 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -213,6 +213,27 @@ def test_get_data_single_symbol(self): # just test that we succeed web.get_data_yahoo('GOOG') + @network + def test_get_data_interval(self): + # daily interval data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='d') + self.assertEqual(len(pan), 252) + + # weekly interval data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='w') + self.assertEqual(len(pan), 53) + + # montly interval data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='m') + self.assertEqual(len(pan), 12) + + # dividend data + pan = web.get_data_yahoo('XOM', '2013-01-01', '2013-12-31', interval='v') + self.assertEqual(len(pan), 4) + + # test fail on invalid interval + self.assertRaises(ValueError, web.get_data_yahoo, 'XOM', interval='NOT VALID') + @network def test_get_data_multiple_symbols(self): # just test that we succeed
PR for the issue #9071
https://api.github.com/repos/pandas-dev/pandas/pulls/9072
2014-12-13T19:30:10Z
2015-01-05T23:49:33Z
2015-01-05T23:49:33Z
2015-01-05T23:50:25Z
ENH: Open Document Format ODS support in read_excel()
diff --git a/doc/source/install.rst b/doc/source/install.rst index 36a6c4038f8be..37263899c0521 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -250,7 +250,8 @@ Optional Dependencies * `matplotlib <http://matplotlib.sourceforge.net/>`__: for plotting * `statsmodels <http://statsmodels.sourceforge.net/>`__ * Needed for parts of :mod:`pandas.stats` -* `openpyxl <http://packages.python.org/openpyxl/>`__, `xlrd/xlwt <http://www.python-excel.org/>`__ +* `openpyxl <http://packages.python.org/openpyxl/>`__, `xlrd/xlwt <http://www.python-excel.org/>`__, `ezodf <https://pypi.python.org/pypi/ezodf/>`__ + * ezodf supports Open Document Format spreadsheets (ods) * Needed for Excel I/O * `XlsxWriter <https://pypi.python.org/pypi/XlsxWriter>`__ * Alternative Excel writer diff --git a/pandas/io/excel.py b/pandas/io/excel.py index d5258cb32e6e0..8f1d423800565 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -4,7 +4,10 @@ #---------------------------------------------------------------------- # ExcelFile class +from __future__ import print_function + import os +import re import datetime import abc import numpy as np @@ -28,6 +31,8 @@ _writer_extensions = ["xlsx", "xls", "xlsm"] _writers = {} +_readers = {} +_reader_extensions = {} def register_writer(klass): @@ -68,12 +73,176 @@ def get_writer(engine_name): raise ValueError("No Excel writer '%s'" % engine_name) +class BaseFile(object): + """Base class for excel readers + + A file class can be initialized even if the engine is not installed. + If the engine is not installed, io_class and workbook_factory are None. + When attempting to use open_workbook while workbook_factory is None, the + relevant ImportError is raised. + """ + + def __init__(self): + """Set the engine name, and extension. If the engine is not installed, + io_class and workbook_factory are both None. + """ + self.io_class = None + self.workbook_factory = None + + def open_workbook(self, *args, **kwargs): + """Explicitely load the engine again (and trigger an ImportError in the + process) if workbook_factory is set to None. + """ + # try to load the engine again and raise import error if required + if self.workbook_factory is None: + self.load_engine() + # just in case the user passes an already opened workbook of io_class + if len(args) > 0 and isinstance(args[0], self.io_class): + self.book = args[0] + else: + self.book = self.workbook_factory(*args, **kwargs) + return self.book + + def create_reader(self, io, engine=None): + """Create the appropriate reader object based on io and optionally + engine. + + Paratemeters + ------------ + io : string, file-like object or xlrd/ezodf workbook + If a string, expected to be a path to xls, xlsx, or ods file. + File-like objects or buffers are only supported for xlrd types. + + engine: string, default None + If io is not a buffer or path, this must be set to identify io. + Acceptable values are None, xlrd, or ezodf + + Returns + ------- + engine : string + Engine used for reading the io + + book : object + The spreadsheet book class created by the engine. + """ + + if engine is not None: + try: + reader = _readers[engine] + except KeyError: + msg = 'Excel reader engine "%s" is not implemented' % engine + raise NotImplementedError(msg) + # load_engine throws the relevant import error if not installed + reader.load_engine() + reader.open_workbook(io) + return reader + + if isinstance(io, compat.string_types): + ext = io.split('.')[-1] + try: + reader = _reader_extensions[ext] + except KeyError: + msg = 'No reader implemented for extension "%s"' % ext + raise NotImplementedError(msg) + reader.load_engine() + if _is_url(io): + data = _urlopen(io).read() + reader.read_buffer(data) + else: + reader.open_workbook(io) + return reader + + # try to determine the reader type based on properties of installed + # reader modules. + for engine, reader in compat.iteritems(_readers): + # only try to import readers that have not been imported before + if reader.io_class is None: + try: + reader.load_engine() + # if the reader is not installed, the user could not have + # passed the corresponding reader.io_class, so it is safe + # to assume that io is not the current reader + except ImportError: + continue + # Does the io type match the currently selected reader? + if isinstance(io, reader.io_class): + reader.engine = engine + reader.book = io + return reader + # xlrd has some additional/alternative reading mechanisms: + elif engine=='xlrd' and hasattr(io, "read"): + # N.B. xlrd.Book has a read attribute too + reader.read_buffer(io.read()) + return reader + + raise ValueError('Must explicitly set engine if not passing in buffer ' + 'or path for io.') + + +class XLRDFile(BaseFile): + """File reader class for MS Excel spreadsheets (depends on xlrd) + """ + extensions = ['xls', 'xlsx', 'xlsm'] + engine = 'xlrd' + + def load_engine(self): + import xlrd # throw an ImportError if we need to + ver = tuple(map(int, xlrd.__VERSION__.split(".")[:2])) + if ver < (0, 9): # pragma: no cover + raise ImportError("pandas requires xlrd >= 0.9.0 for excel " + "support, current version " + xlrd.__VERSION__) + else: + self.workbook_factory = xlrd.open_workbook + self.io_class = xlrd.Book + + def read_buffer(self, data): + """Read from a buffer + """ + return self.open_workbook(file_contents=data) + + +class EZODFFile(BaseFile): + """File reader class for ODF spreadsheets (depends on ezodf) + """ + extensions = ['ods'] + engine = 'ezodf' + + def load_engine(self): + import ezodf # throw an ImportError if we need to + self.workbook_factory = ezodf.opendoc + self.io_class = ezodf.document.PackagedDocument + + def read_buffer(self, *args, **kwargs): + """ + """ + msg = 'Can not read ODF spreadsheet from a buffer or URL.' + raise NotImplementedError(msg) + + +# register all supported readers +def register_readers(): + """ + Establish which readers are supported and/or installed. + """ + + def populate(reader): + _readers[reader.engine] = reader + for ext in reader.extensions: + _reader_extensions[ext] = reader + + populate(XLRDFile()) + populate(EZODFFile()) + +register_readers() + + def read_excel(io, sheetname=0, **kwds): - """Read an Excel table into a pandas DataFrame + """Read an Excel/ods table into a pandas DataFrame Parameters ---------- - io : string, file-like object, or xlrd workbook. + io : string, file-like object, or xlrd workbook for MS Excel files. For an + ods file (Open Document Formant), string or ezodf workbook is required. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file://localhost/path/to/workbook.xlsx @@ -106,7 +275,7 @@ def read_excel(io, sheetname=0, **kwds): converters : dict, default None Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one - input argument, the Excel cell content, and return the transformed + input argument, the Excel/ods cell content, and return the transformed content. index_col : int, default None Column to use as the row labels of the DataFrame. Pass None if @@ -126,10 +295,10 @@ def read_excel(io, sheetname=0, **kwds): Indicate number of NA values placed in non-numeric columns engine: string, default None If io is not a buffer or path, this must be set to identify io. - Acceptable values are None or xlrd + Acceptable values are None, xlrd, or ezodf convert_float : boolean, default True convert integral floats to int (i.e., 1.0 --> 1). If False, all numeric - data will be read in as floats: Excel stores all numbers as floats + data will be read in as floats: Excel/ods stores all numbers as floats internally has_index_names : boolean, default False True if the cols defined in index_col have an index name and are @@ -151,47 +320,21 @@ def read_excel(io, sheetname=0, **kwds): class ExcelFile(object): """ Class for parsing tabular excel sheets into DataFrame objects. - Uses xlrd. See ExcelFile.parse for more documentation + Uses xlrd and/or ezodf. See ExcelFile.parse for more documentation Parameters ---------- - io : string, file-like object or xlrd workbook - If a string, expected to be a path to xls or xlsx file + io : string, file-like object or xlrd/ezodf workbook + If a string, expected to be a path to xls, xlsx, or ods file engine: string, default None If io is not a buffer or path, this must be set to identify io. - Acceptable values are None or xlrd + Acceptable values are None, xlrd, or ezodf """ def __init__(self, io, **kwds): - - import xlrd # throw an ImportError if we need to - - ver = tuple(map(int, xlrd.__VERSION__.split(".")[:2])) - if ver < (0, 9): # pragma: no cover - raise ImportError("pandas requires xlrd >= 0.9.0 for excel " - "support, current version " + xlrd.__VERSION__) - self.io = io engine = kwds.pop('engine', None) - - if engine is not None and engine != 'xlrd': - raise ValueError("Unknown engine: %s" % engine) - - if isinstance(io, compat.string_types): - if _is_url(io): - data = _urlopen(io).read() - self.book = xlrd.open_workbook(file_contents=data) - else: - self.book = xlrd.open_workbook(io) - elif engine == 'xlrd' and isinstance(io, xlrd.Book): - self.book = io - elif not isinstance(io, xlrd.Book) and hasattr(io, "read"): - # N.B. xlrd.Book has a read attribute too - data = io.read() - self.book = xlrd.open_workbook(file_contents=data) - else: - raise ValueError('Must explicitly set engine if not passing in' - ' buffer or path for io.') + self.reader = BaseFile().create_reader(io, engine=engine) def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0, index_col=None, parse_cols=None, parse_dates=False, @@ -270,18 +413,25 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0, if skipfooter is not None: skip_footer = skipfooter - return self._parse_excel(sheetname=sheetname, header=header, - skiprows=skiprows, - index_col=index_col, - has_index_names=has_index_names, - parse_cols=parse_cols, - parse_dates=parse_dates, - date_parser=date_parser, na_values=na_values, - thousands=thousands, chunksize=chunksize, - skip_footer=skip_footer, - convert_float=convert_float, - converters=converters, - **kwds) + if self.reader.engine == 'ezodf': + parser = self._parse_ods + elif self.reader.engine == 'xlrd': + parser = self._parse_excel + else: + raise ValueError('Engine is not specified.') + + return parser(sheetname=sheetname, header=header, + skiprows=skiprows, + index_col=index_col, + has_index_names=has_index_names, + parse_cols=parse_cols, + parse_dates=parse_dates, + date_parser=date_parser, na_values=na_values, + thousands=thousands, chunksize=chunksize, + skip_footer=skip_footer, + convert_float=convert_float, + converters=converters, + **kwds) def _should_parse(self, i, parse_cols): @@ -326,9 +476,9 @@ def _parse_excel(self, sheetname=0, header=0, skiprows=None, skip_footer=0, XL_CELL_ERROR, XL_CELL_BOOLEAN, XL_CELL_NUMBER) - epoch1904 = self.book.datemode + epoch1904 = self.reader.book.datemode - def _parse_cell(cell_contents,cell_typ): + def _parse_cell(cell_contents, cell_typ): """converts the contents of the cell into a pandas appropriate object""" @@ -377,7 +527,7 @@ def _parse_cell(cell_contents,cell_typ): ret_dict = False - #Keep sheetname to maintain backwards compatibility. + # Keep sheetname to maintain backwards compatibility. if isinstance(sheetname, list): sheets = sheetname ret_dict = True @@ -387,7 +537,7 @@ def _parse_cell(cell_contents,cell_typ): else: sheets = [sheetname] - #handle same-type duplicates. + # handle same-type duplicates. sheets = list(set(sheets)) output = {} @@ -397,9 +547,9 @@ def _parse_cell(cell_contents,cell_typ): print("Reading sheet %s" % asheetname) if isinstance(asheetname, compat.string_types): - sheet = self.book.sheet_by_name(asheetname) + sheet = self.reader.book.sheet_by_name(asheetname) else: # assume an integer if not a string - sheet = self.book.sheet_by_index(asheetname) + sheet = self.reader.book.sheet_by_index(asheetname) data = [] should_parse = {} @@ -412,7 +562,7 @@ def _parse_cell(cell_contents,cell_typ): should_parse[j] = self._should_parse(j, parse_cols) if parse_cols is None or should_parse[j]: - row.append(_parse_cell(value,typ)) + row.append(_parse_cell(value, typ)) data.append(row) if sheet.nrows == 0: @@ -439,10 +589,195 @@ def _parse_cell(cell_contents,cell_typ): else: return output[asheetname] + def _parse_ods(self, sheetname=0, header=0, skiprows=None, skip_footer=0, + index_col=None, has_index_names=None, parse_cols=None, + parse_dates=False, date_parser=None, na_values=None, + thousands=None, chunksize=None, convert_float=True, + verbose=False, **kwds): + # adds support for parsing ODS files, see PR #9070 + + def _parse_cell(cell): + """converts the contents of the cell into a pandas + appropriate object""" + if isinstance(cell.value, float): + value = cell.value + if convert_float: + # GH5394 - Excel and ODS 'numbers' are always floats + # it's a minimal perf hit and less suprising + # FIXME: this goes wrong when int(cell.value) returns + # a long (>1e18) + val = int(cell.value) + if val == cell.value: + value = val + elif isinstance(cell.value, compat.string_types): + typ = cell.value_type + if typ == 'date' or typ == 'time': + value = self._parse_datetime(cell) + else: + value = cell.value + elif isinstance(cell.value, bool): + value = cell.value + # empty cells have None as value, type, currency, formula. + # xlrd assigns empty string to empty cells, ezodf assigns None + # test_excel.ExcelReaderTests.test_reader_converters expects empty + # cells to be an empty string + elif isinstance(cell.value, type(None)): + value = '' + else: + value = np.nan + return value + + ret_dict = False + # find numbers for the date/time object conversion + self.regex = re.compile('[[0-9]*[\\.[0-9]+]*]*') + + # Keep sheetname to maintain backwards compatibility. + if isinstance(sheetname, list): + sheets = sheetname + ret_dict = True + elif sheetname is None: + sheets = self.sheet_names + ret_dict = True + else: + sheets = [sheetname] + + # handle same-type duplicates. + sheets = list(set(sheets)) + + output = {} + + for asheetname in sheets: + if verbose: + print("Reading sheet %s" % asheetname) + + # sheetname can be index or string + sheet = self.reader.book.sheets[asheetname] + + data = [] + should_parse = {} + for i in range(sheet.nrows()): + row = [] + for j, cell in enumerate(sheet.row(i)): + + if parse_cols is not None and j not in should_parse: + should_parse[j] = self._should_parse(j, parse_cols) + + if parse_cols is None or should_parse[j]: + row.append(_parse_cell(cell)) + + data.append(row) + + parser = TextParser(data, header=header, index_col=index_col, + has_index_names=has_index_names, + na_values=na_values, + thousands=thousands, + parse_dates=parse_dates, + date_parser=date_parser, + skiprows=skiprows, + skip_footer=skip_footer, + chunksize=chunksize, + **kwds) + output[asheetname] = parser.read() + + if ret_dict: + return output + else: + return output[asheetname] + + def _parse_datetime(self, cell): + """Parse the date or time from on ods cell to a datetime object. + Formats returned by ezodf are documented here: + https://pythonhosted.org/ezodf/tableobjects.html#cell-class + + Because time cells can also be timedeltas, all time fields that exceed + 23 hours are converted to a timedelta object. + + Date string value formats: 'yyyy-mm-dd' or 'yyyy-mm-ddThh:mm:ss' + + Time string value format: 'PThhHmmMss,ffffS' + """ + + def _sec_split_micro(seconds): + """Split a floatingpoint second value into an integer second value + and an integer microsecond value. + """ + sec = float(seconds) + sec_i = int(sec) + microsec = int(round((sec - sec_i)*1e6, 0)) + return sec_i, microsec + + def _timedelta(items): + """ + Possible formats for formulas are: + 'of:=TIME(%H;%M;%S)' + 'of:=TIME(%H;%M;%S.%fS)' + Possible formats for values are: + 'PT%HH%MM%S.%fS' + 'PT%HH%MM%SS' + """ + hours, minutes, seconds = items + return datetime.timedelta(hours=int(hours), minutes=int(minutes), + seconds=float(seconds)) + + def _time(items): + hours, minutes, seconds = items + sec_i, microsec = _sec_split_micro(seconds) + return datetime.time(int(hours), int(minutes), sec_i, microsec) + + def _datetime(items): + """ + Possible formats for values are: + '%Y-%m-%d' + '%Y-%m-%dT%H:%M:%S' + '%Y-%m-%dT%H:%M:%S.%f' + """ + + if len(items) == 3: + year, month, day = [int(k) for k in items] + return datetime.datetime(year, month, day) + else: + year, month, day, hours, minutes = [int(k) for k in items[:-1]] + # seconds can be a float, convert to microseconds + sec_i, microsec = _sec_split_micro(items[-1]) + return datetime.datetime(year, month, day, hours, minutes, + sec_i, microsec) + + # Only consider the value fields, formula's can contain just cell refs. + # Note that cell formatting determines if a value type is time, date or + # just a number. By using the cell value, cell type is consistent with + # what the user will see/format in LibreOffice + items = self.regex.findall(cell.value) + if cell.value_type == 'date': + value = _datetime(items) + else: + try: + # will fail when hours > 23, which is possible in LibreOffice + value = _time(items) + except ValueError: + value = _timedelta(items) + + return value + + def _print_ods_cellinfo(self, cell): + """Convienent for debugging purposes: print all ods cell data. + Cell attributes are documented here: + https://pythonhosted.org/ezodf/tableobjects.html#id2 + """ + print(' plaintext:', cell.plaintext()) # no formatting + # formatted, but what is difference with value? + print('display_form:', cell.display_form) # format, ?=plaintext + print(' value:', cell.value) # data handled + print(' value_type:', cell.value_type) # data type + print(' formula:', cell.formula) + print(' currency:', cell.currency) @property def sheet_names(self): - return self.book.sheet_names() + if self.reader.engine == 'ezodf': + # book.sheet.names() is a generator for ezodf + return [sheetname for sheetname in self.reader.book.sheets.names()] + else: + return self.reader.book.sheet_names() def close(self): """close io if necessary""" @@ -1174,7 +1509,7 @@ class _XlwtWriter(ExcelWriter): def __init__(self, path, engine=None, encoding=None, **engine_kwargs): # Use the xlwt module as the Excel writer. import xlwt - engine_kwargs['engine'] = engine + super(_XlwtWriter, self).__init__(path, **engine_kwargs) if encoding is None: diff --git a/pandas/io/tests/data/test1.ods b/pandas/io/tests/data/test1.ods new file mode 100644 index 0000000000000..d07a979deb576 Binary files /dev/null and b/pandas/io/tests/data/test1.ods differ diff --git a/pandas/io/tests/data/test.xls b/pandas/io/tests/data/test1.xls similarity index 100% rename from pandas/io/tests/data/test.xls rename to pandas/io/tests/data/test1.xls diff --git a/pandas/io/tests/data/test.xlsm b/pandas/io/tests/data/test1.xlsm similarity index 100% rename from pandas/io/tests/data/test.xlsm rename to pandas/io/tests/data/test1.xlsm diff --git a/pandas/io/tests/data/test.xlsx b/pandas/io/tests/data/test1.xlsx similarity index 100% rename from pandas/io/tests/data/test.xlsx rename to pandas/io/tests/data/test1.xlsx diff --git a/pandas/io/tests/data/test2.ods b/pandas/io/tests/data/test2.ods new file mode 100644 index 0000000000000..35bfff5220245 Binary files /dev/null and b/pandas/io/tests/data/test2.ods differ diff --git a/pandas/io/tests/data/test2.xlsm b/pandas/io/tests/data/test2.xlsm new file mode 100644 index 0000000000000..31cfba7ede082 Binary files /dev/null and b/pandas/io/tests/data/test2.xlsm differ diff --git a/pandas/io/tests/data/test2.xlsx b/pandas/io/tests/data/test2.xlsx index 441db5e55e666..94dd951e0bb84 100644 Binary files a/pandas/io/tests/data/test2.xlsx and b/pandas/io/tests/data/test2.xlsx differ diff --git a/pandas/io/tests/data/test3.ods b/pandas/io/tests/data/test3.ods new file mode 100644 index 0000000000000..4e072a231bccf Binary files /dev/null and b/pandas/io/tests/data/test3.ods differ diff --git a/pandas/io/tests/data/test3.xlsm b/pandas/io/tests/data/test3.xlsm new file mode 100644 index 0000000000000..54b7ef456a9ea Binary files /dev/null and b/pandas/io/tests/data/test3.xlsm differ diff --git a/pandas/io/tests/data/test3.xlsx b/pandas/io/tests/data/test3.xlsx new file mode 100644 index 0000000000000..c16755c25fabd Binary files /dev/null and b/pandas/io/tests/data/test3.xlsx differ diff --git a/pandas/io/tests/data/test4.ods b/pandas/io/tests/data/test4.ods new file mode 100644 index 0000000000000..71a12f04674e9 Binary files /dev/null and b/pandas/io/tests/data/test4.ods differ diff --git a/pandas/io/tests/data/test4.xls b/pandas/io/tests/data/test4.xls new file mode 100644 index 0000000000000..0e6f4331e2547 Binary files /dev/null and b/pandas/io/tests/data/test4.xls differ diff --git a/pandas/io/tests/data/test4.xlsm b/pandas/io/tests/data/test4.xlsm new file mode 100644 index 0000000000000..52328c7b28be9 Binary files /dev/null and b/pandas/io/tests/data/test4.xlsm differ diff --git a/pandas/io/tests/data/test4.xlsx b/pandas/io/tests/data/test4.xlsx new file mode 100644 index 0000000000000..441db5e55e666 Binary files /dev/null and b/pandas/io/tests/data/test4.xlsx differ diff --git a/pandas/io/tests/data/test_converters.ods b/pandas/io/tests/data/test_converters.ods new file mode 100644 index 0000000000000..3ebb8423daa89 Binary files /dev/null and b/pandas/io/tests/data/test_converters.ods differ diff --git a/pandas/io/tests/data/test_converters.xlsm b/pandas/io/tests/data/test_converters.xlsm new file mode 100644 index 0000000000000..eaf0b1d0219c5 Binary files /dev/null and b/pandas/io/tests/data/test_converters.xlsm differ diff --git a/pandas/io/tests/data/test_datetime.ods b/pandas/io/tests/data/test_datetime.ods new file mode 100644 index 0000000000000..165202a3fb731 Binary files /dev/null and b/pandas/io/tests/data/test_datetime.ods differ diff --git a/pandas/io/tests/data/test_multisheet.ods b/pandas/io/tests/data/test_multisheet.ods new file mode 100644 index 0000000000000..275f5350fe853 Binary files /dev/null and b/pandas/io/tests/data/test_multisheet.ods differ diff --git a/pandas/io/tests/data/test_multisheet.xls b/pandas/io/tests/data/test_multisheet.xls new file mode 100644 index 0000000000000..fa37723fcdefb Binary files /dev/null and b/pandas/io/tests/data/test_multisheet.xls differ diff --git a/pandas/io/tests/data/test_multisheet.xlsm b/pandas/io/tests/data/test_multisheet.xlsm new file mode 100644 index 0000000000000..694f8e07d5e29 Binary files /dev/null and b/pandas/io/tests/data/test_multisheet.xlsm differ diff --git a/pandas/io/tests/data/test_types.ods b/pandas/io/tests/data/test_types.ods new file mode 100644 index 0000000000000..bcf5433102f78 Binary files /dev/null and b/pandas/io/tests/data/test_types.ods differ diff --git a/pandas/io/tests/data/test_types.xlsm b/pandas/io/tests/data/test_types.xlsm new file mode 100644 index 0000000000000..c66fdc82dfb67 Binary files /dev/null and b/pandas/io/tests/data/test_types.xlsm differ diff --git a/pandas/io/tests/data/test_types_datetime.ods b/pandas/io/tests/data/test_types_datetime.ods new file mode 100644 index 0000000000000..b010d02fb9949 Binary files /dev/null and b/pandas/io/tests/data/test_types_datetime.ods differ diff --git a/pandas/io/tests/data/times_1900.xlsm b/pandas/io/tests/data/times_1900.xlsm new file mode 100644 index 0000000000000..1ffdbe223453b Binary files /dev/null and b/pandas/io/tests/data/times_1900.xlsm differ diff --git a/pandas/io/tests/data/times_1900.xlsx b/pandas/io/tests/data/times_1900.xlsx new file mode 100644 index 0000000000000..3702289b256fd Binary files /dev/null and b/pandas/io/tests/data/times_1900.xlsx differ diff --git a/pandas/io/tests/data/times_1904.xlsm b/pandas/io/tests/data/times_1904.xlsm new file mode 100644 index 0000000000000..e884eca1e7c74 Binary files /dev/null and b/pandas/io/tests/data/times_1904.xlsm differ diff --git a/pandas/io/tests/data/times_1904.xlsx b/pandas/io/tests/data/times_1904.xlsx new file mode 100644 index 0000000000000..1a13468e59d1c Binary files /dev/null and b/pandas/io/tests/data/times_1904.xlsx differ diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py index 83db59f9d9029..4a3d6d18616c0 100644 --- a/pandas/io/tests/test_excel.py +++ b/pandas/io/tests/test_excel.py @@ -1,7 +1,8 @@ # pylint: disable=E1101 from pandas.compat import u, range, map, openpyxl_compat, BytesIO, iteritems -from datetime import datetime, date, time +from pandas import compat +from datetime import datetime, date, time, timedelta import sys import os from distutils.version import LooseVersion @@ -58,6 +59,13 @@ def _skip_if_no_xlsxwriter(): raise nose.SkipTest('xlsxwriter not installed, skipping') +def _skip_if_no_ezodf(): + try: + import ezodf # NOQA + except ImportError: + raise nose.SkipTest('ezodf not installed, skipping') + + def _skip_if_no_excelsuite(): _skip_if_no_xlrd() _skip_if_no_xlwt() @@ -76,11 +84,6 @@ def _skip_if_no_excelsuite(): class SharedItems(object): def setUp(self): self.dirpath = tm.get_data_path() - self.csv1 = os.path.join(self.dirpath, 'test1.csv') - self.csv2 = os.path.join(self.dirpath, 'test2.csv') - self.xls1 = os.path.join(self.dirpath, 'test.xls') - self.xlsx1 = os.path.join(self.dirpath, 'test.xlsx') - self.multisheet = os.path.join(self.dirpath, 'test_multisheet.xlsx') self.frame = _frame.copy() self.frame2 = _frame2.copy() self.tsframe = _tsframe.copy() @@ -91,266 +94,176 @@ def read_csv(self, *args, **kwds): kwds['engine'] = 'python' return read_csv(*args, **kwds) + def get_data(self, basename, csv=True): + """ + Return a DataFrame as read by the Python csv engine and a DataFrame + as read by the ExcelFile engine. Test data path is defined by + pandas.util.testing.get_data_path() + + Parameters + ---------- + + basename : str + File base name, excluding file extension. + + csv : boolean, default=True + When True, basename.csv is returned + """ + + excel = ExcelFile(os.path.join(self.dirpath, basename + self.ext)) + if csv: + # the reference is obtained form read_csv with Python engine + pref = os.path.join(self.dirpath, basename + '.csv') + dfref = self.read_csv(pref, index_col=0, parse_dates=True) + return dfref, excel + else: + return excel + + +class ReadingTestsBase(SharedItems): + # This is based on ExcelWriterBase + # + # Base class for test cases to run with different Excel readers. + # To add a reader test, define the following: + # 1. A check_skip function that skips your tests if your reader isn't + # installed. + # 2. Add a property ext, which is the file extension that your reader + # reades from. (needs to start with '.' so it's a valid path) + # 3. Add a property engine_name, which is the name of the reader class. + # For the reader this is not used for anything at the moment. + + def setUp(self): + self.check_skip() + super(ReadingTestsBase, self).setUp() -class ExcelReaderTests(SharedItems, tm.TestCase): def test_parse_cols_int(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - suffix = ['xls', 'xlsx', 'xlsm'] - - for s in suffix: - 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) - df2 = self.read_csv(self.csv1, index_col=0, parse_dates=True) - df2 = df2.reindex(columns=['A', 'B', 'C']) - df3 = xls.parse('Sheet2', skiprows=[1], index_col=0, - parse_dates=True, parse_cols=3) - # TODO add index to xls file) - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) + dfref, excel = self.get_data('test1') + dfref = dfref.reindex(columns=['A', 'B', 'C']) + df1 = excel.parse('Sheet1', index_col=0, parse_dates=True, + parse_cols=3) + df2 = excel.parse('Sheet2', skiprows=[1], index_col=0, + parse_dates=True, parse_cols=3) + # TODO add index to xls file) + tm.assert_frame_equal(df1, dfref, check_names=False) + tm.assert_frame_equal(df2, dfref, check_names=False) def test_parse_cols_list(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - suffix = ['xls', 'xlsx', 'xlsm'] - - for s in suffix: - 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]) - df2 = self.read_csv(self.csv1, index_col=0, parse_dates=True) - df2 = df2.reindex(columns=['B', 'C']) - df3 = xls.parse('Sheet2', skiprows=[1], index_col=0, - parse_dates=True, - parse_cols=[0, 2, 3]) - # TODO add index to xls file) - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) + dfref, excel = self.get_data('test1') + dfref = dfref.reindex(columns=['B', 'C']) + df1 = excel.parse('Sheet1', index_col=0, parse_dates=True, + parse_cols=[0, 2, 3]) + df2 = excel.parse('Sheet2', skiprows=[1], index_col=0, + parse_dates=True, + parse_cols=[0, 2, 3]) + # TODO add index to xls file) + tm.assert_frame_equal(df1, dfref, check_names=False) + tm.assert_frame_equal(df2, dfref, check_names=False) def test_parse_cols_str(self): - _skip_if_no_openpyxl() - _skip_if_no_xlrd() - suffix = ['xls', 'xlsx', 'xlsm'] - - for s in suffix: - - pth = os.path.join(self.dirpath, 'test.%s' % s) - xls = ExcelFile(pth) - - df = xls.parse('Sheet1', index_col=0, parse_dates=True, - parse_cols='A:D') - df2 = read_csv(self.csv1, index_col=0, parse_dates=True) - df2 = df2.reindex(columns=['A', 'B', 'C']) - df3 = xls.parse('Sheet2', skiprows=[1], index_col=0, - parse_dates=True, parse_cols='A:D') - # TODO add index to xls, read xls ignores index name ? - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) - del df, df2, df3 - - df = xls.parse('Sheet1', index_col=0, parse_dates=True, - parse_cols='A,C,D') - df2 = read_csv(self.csv1, index_col=0, parse_dates=True) - df2 = df2.reindex(columns=['B', 'C']) - df3 = xls.parse('Sheet2', skiprows=[1], index_col=0, - parse_dates=True, - parse_cols='A,C,D') - # TODO add index to xls file - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) - del df, df2, df3 - - df = xls.parse('Sheet1', index_col=0, parse_dates=True, - parse_cols='A,C:D') - df2 = read_csv(self.csv1, index_col=0, parse_dates=True) - df2 = df2.reindex(columns=['B', 'C']) - df3 = xls.parse('Sheet2', skiprows=[1], index_col=0, - parse_dates=True, - parse_cols='A,C:D') - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) + dfref, excel = self.get_data('test1') + + df1 = dfref.reindex(columns=['A', 'B', 'C']) + df2 = excel.parse('Sheet1', index_col=0, parse_dates=True, + parse_cols='A:D') + df3 = excel.parse('Sheet2', skiprows=[1], index_col=0, + parse_dates=True, parse_cols='A:D') + # TODO add index to xls, read xls ignores index name ? + tm.assert_frame_equal(df2, df1, check_names=False) + tm.assert_frame_equal(df3, df1, check_names=False) + + df1 = dfref.reindex(columns=['B', 'C']) + df2 = excel.parse('Sheet1', index_col=0, parse_dates=True, + parse_cols='A,C,D') + df3 = excel.parse('Sheet2', skiprows=[1], index_col=0, + parse_dates=True, + parse_cols='A,C,D') + # TODO add index to xls file + tm.assert_frame_equal(df2, df1, check_names=False) + tm.assert_frame_equal(df3, df1, check_names=False) + + df1 = dfref.reindex(columns=['B', 'C']) + df2 = excel.parse('Sheet1', index_col=0, parse_dates=True, + parse_cols='A,C:D') + df3 = excel.parse('Sheet2', skiprows=[1], index_col=0, + parse_dates=True, + parse_cols='A,C:D') + tm.assert_frame_equal(df2, df1, check_names=False) + tm.assert_frame_equal(df3, df1, check_names=False) def test_excel_stop_iterator(self): - _skip_if_no_xlrd() - excel_data = ExcelFile(os.path.join(self.dirpath, 'test2.xls')) - parsed = excel_data.parse('Sheet1') + excel = self.get_data('test2', csv=False) + + parsed = excel.parse('Sheet1') expected = DataFrame([['aaaa', 'bbbbb']], columns=['Test', 'Test1']) tm.assert_frame_equal(parsed, expected) def test_excel_cell_error_na(self): - _skip_if_no_xlrd() - excel_data = ExcelFile(os.path.join(self.dirpath, 'test3.xls')) - parsed = excel_data.parse('Sheet1') + excel = self.get_data('test3', csv=False) + + parsed = excel.parse('Sheet1') expected = DataFrame([[np.nan]], columns=['Test']) tm.assert_frame_equal(parsed, expected) def test_excel_passes_na(self): - _skip_if_no_xlrd() - excel_data = ExcelFile(os.path.join(self.dirpath, 'test2.xlsx')) - parsed = excel_data.parse('Sheet1', keep_default_na=False, - na_values=['apple']) + excel = self.get_data('test4', csv=False) + + parsed = excel.parse('Sheet1', keep_default_na=False, + na_values=['apple']) expected = DataFrame([['NA'], [1], ['NA'], [np.nan], ['rabbit']], columns=['Test']) tm.assert_frame_equal(parsed, expected) - parsed = excel_data.parse('Sheet1', keep_default_na=True, - na_values=['apple']) + parsed = excel.parse('Sheet1', keep_default_na=True, + na_values=['apple']) expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']], columns=['Test']) tm.assert_frame_equal(parsed, expected) - def check_excel_table_sheet_by_index(self, filename, csvfile): - import xlrd - - pth = os.path.join(self.dirpath, filename) - xls = ExcelFile(pth) - df = xls.parse(0, index_col=0, parse_dates=True) - df2 = self.read_csv(csvfile, index_col=0, parse_dates=True) - df3 = xls.parse(1, skiprows=[1], index_col=0, parse_dates=True) - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) - - df4 = xls.parse(0, index_col=0, parse_dates=True, skipfooter=1) - df5 = xls.parse(0, index_col=0, parse_dates=True, skip_footer=1) - tm.assert_frame_equal(df4, df.ix[:-1]) - tm.assert_frame_equal(df4, df5) - - self.assertRaises(xlrd.XLRDError, xls.parse, 'asdf') - def test_excel_table_sheet_by_index(self): - _skip_if_no_xlrd() - for filename, csvfile in [(self.xls1, self.csv1), - (self.xlsx1, self.csv1)]: - self.check_excel_table_sheet_by_index(filename, csvfile) - - def test_excel_table(self): - _skip_if_no_xlrd() - - pth = os.path.join(self.dirpath, 'test.xls') - xls = ExcelFile(pth) - df = xls.parse('Sheet1', index_col=0, parse_dates=True) - df2 = self.read_csv(self.csv1, index_col=0, parse_dates=True) - df3 = xls.parse('Sheet2', skiprows=[1], index_col=0, parse_dates=True) - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) - - df4 = xls.parse('Sheet1', index_col=0, parse_dates=True, - skipfooter=1) - df5 = xls.parse('Sheet1', index_col=0, parse_dates=True, - skip_footer=1) - tm.assert_frame_equal(df4, df.ix[:-1]) - tm.assert_frame_equal(df4, df5) - - def test_excel_read_buffer(self): - _skip_if_no_xlrd() - _skip_if_no_openpyxl() - - pth = os.path.join(self.dirpath, 'test.xls') - f = open(pth, 'rb') - xls = ExcelFile(f) - # it works - xls.parse('Sheet1', index_col=0, parse_dates=True) - - pth = os.path.join(self.dirpath, 'test.xlsx') - f = open(pth, 'rb') - xl = ExcelFile(f) - xl.parse('Sheet1', index_col=0, parse_dates=True) - - def test_read_xlrd_Book(self): - _skip_if_no_xlrd() - _skip_if_no_xlwt() - - import xlrd - - df = self.frame - - with ensure_clean('.xls') as pth: - df.to_excel(pth, "SheetA") - book = xlrd.open_workbook(pth) - - with ExcelFile(book, engine="xlrd") as xl: - result = xl.parse("SheetA") - tm.assert_frame_equal(df, result) - result = read_excel(book, sheetname="SheetA", engine="xlrd") - tm.assert_frame_equal(df, result) + dfref, excel = self.get_data('test1') - @tm.network - def test_read_from_http_url(self): - _skip_if_no_xlrd() + df1 = excel.parse(0, index_col=0, parse_dates=True) + df2 = excel.parse(1, skiprows=[1], index_col=0, parse_dates=True) + tm.assert_frame_equal(df1, dfref, check_names=False) + tm.assert_frame_equal(df2, dfref, check_names=False) - url = ('https://raw.github.com/pydata/pandas/master/' - 'pandas/io/tests/data/test.xlsx') - url_table = read_excel(url) - dirpath = tm.get_data_path() - localtable = os.path.join(dirpath, 'test.xlsx') - local_table = read_excel(localtable) - tm.assert_frame_equal(url_table, local_table) - - @slow - def test_read_from_file_url(self): - _skip_if_no_xlrd() + df3 = excel.parse(0, index_col=0, parse_dates=True, skipfooter=1) + df4 = excel.parse(0, index_col=0, parse_dates=True, skip_footer=1) + tm.assert_frame_equal(df3, df1.ix[:-1]) + tm.assert_frame_equal(df3, df4) - # FILE - if sys.version_info[:2] < (2, 6): - raise nose.SkipTest("file:// not supported with Python < 2.6") - dirpath = tm.get_data_path() - localtable = os.path.join(dirpath, 'test.xlsx') - local_table = read_excel(localtable) - - try: - url_table = read_excel('file://localhost/' + localtable) - except URLError: - # fails on some systems - raise nose.SkipTest("failing on %s" % - ' '.join(platform.uname()).strip()) - - tm.assert_frame_equal(url_table, local_table) - - def test_xlsx_table(self): - _skip_if_no_xlrd() - _skip_if_no_openpyxl() - - pth = os.path.join(self.dirpath, 'test.xlsx') - xlsx = ExcelFile(pth) - df = xlsx.parse('Sheet1', index_col=0, parse_dates=True) - df2 = self.read_csv(self.csv1, index_col=0, parse_dates=True) - df3 = xlsx.parse('Sheet2', skiprows=[1], index_col=0, parse_dates=True) - - # TODO add index to xlsx file - tm.assert_frame_equal(df, df2, check_names=False) - tm.assert_frame_equal(df3, df2, check_names=False) + if self.ext == '.ods': + self.assertRaises(KeyError, excel.parse, 'asdf') + else: + import xlrd + self.assertRaises(xlrd.XLRDError, excel.parse, 'asdf') - df4 = xlsx.parse('Sheet1', index_col=0, parse_dates=True, - skipfooter=1) - df5 = xlsx.parse('Sheet1', index_col=0, parse_dates=True, - skip_footer=1) - tm.assert_frame_equal(df4, df.ix[:-1]) - tm.assert_frame_equal(df4, df5) + def test_excel_table(self): - def test_reader_closes_file(self): - _skip_if_no_xlrd() - _skip_if_no_openpyxl() + dfref, excel = self.get_data('test1') - pth = os.path.join(self.dirpath, 'test.xlsx') - f = open(pth, 'rb') - with ExcelFile(f) as xlsx: - # parses okay - xlsx.parse('Sheet1', index_col=0) + df1 = excel.parse('Sheet1', index_col=0, parse_dates=True) + df2 = excel.parse('Sheet2', skiprows=[1], index_col=0, + parse_dates=True) + # TODO add index to file + tm.assert_frame_equal(df1, dfref, check_names=False) + tm.assert_frame_equal(df2, dfref, check_names=False) - self.assertTrue(f.closed) + df3 = excel.parse('Sheet1', index_col=0, parse_dates=True, + skipfooter=1) + df4 = excel.parse('Sheet1', index_col=0, parse_dates=True, + skip_footer=1) + tm.assert_frame_equal(df3, df1.ix[:-1]) + tm.assert_frame_equal(df3, df4) def test_reader_special_dtypes(self): - _skip_if_no_xlrd() expected = DataFrame.from_items([ ("IntCol", [1, 2, -3, 4, 0]), @@ -364,44 +277,40 @@ def test_reader_special_dtypes(self): datetime(2015, 3, 14)]) ]) - xlsx_path = os.path.join(self.dirpath, 'test_types.xlsx') - xls_path = os.path.join(self.dirpath, 'test_types.xls') + pth = os.path.join(self.dirpath, 'test_types' + self.ext) # should read in correctly and infer types - for path in (xls_path, xlsx_path): - actual = read_excel(path, 'Sheet1') - tm.assert_frame_equal(actual, expected) + actual = read_excel(pth, 'Sheet1') + tm.assert_frame_equal(actual, expected) # if not coercing number, then int comes in as float float_expected = expected.copy() float_expected["IntCol"] = float_expected["IntCol"].astype(float) float_expected.loc[1, "Str2Col"] = 3.0 - for path in (xls_path, xlsx_path): - actual = read_excel(path, 'Sheet1', convert_float=False) - tm.assert_frame_equal(actual, float_expected) + actual = read_excel(pth, 'Sheet1', convert_float=False) + tm.assert_frame_equal(actual, float_expected) # check setting Index (assuming xls and xlsx are the same here) for icol, name in enumerate(expected.columns): - actual = read_excel(xlsx_path, 'Sheet1', index_col=icol) - actual2 = read_excel(xlsx_path, 'Sheet1', index_col=name) + actual = read_excel(pth, 'Sheet1', index_col=icol) exp = expected.set_index(name) tm.assert_frame_equal(actual, exp) - tm.assert_frame_equal(actual2, exp) # convert_float and converters should be different but both accepted expected["StrCol"] = expected["StrCol"].apply(str) - actual = read_excel(xlsx_path, 'Sheet1', converters={"StrCol": str}) + actual = read_excel(pth, 'Sheet1', converters={"StrCol": str}) tm.assert_frame_equal(actual, expected) no_convert_float = float_expected.copy() no_convert_float["StrCol"] = no_convert_float["StrCol"].apply(str) - actual = read_excel(xlsx_path, 'Sheet1', converters={"StrCol": str}, + actual = read_excel(pth, 'Sheet1', converters={"StrCol": str}, convert_float=False) tm.assert_frame_equal(actual, no_convert_float) # GH8212 - support for converters and missing values def test_reader_converters(self): - _skip_if_no_xlrd() + + pth = os.path.join(self.dirpath, 'test_converters' + self.ext) expected = DataFrame.from_items([ ("IntCol", [1, 2, -3, -1000, 0]), @@ -416,48 +325,166 @@ def test_reader_converters(self): 3: lambda x: str(x) if x else '', } - xlsx_path = os.path.join(self.dirpath, 'test_converters.xlsx') - xls_path = os.path.join(self.dirpath, 'test_converters.xls') - # should read in correctly and set types of single cells (not array dtypes) - for path in (xls_path, xlsx_path): - actual = read_excel(path, 'Sheet1', converters=converters) - tm.assert_frame_equal(actual, expected) + actual = read_excel(pth, 'Sheet1', converters=converters) + tm.assert_frame_equal(actual, expected) def test_reading_all_sheets(self): # Test reading all sheetnames by setting sheetname to None, # Ensure a dict is returned. # See PR #9450 - - _skip_if_no_xlrd() - - dfs = read_excel(self.multisheet,sheetname=None) - expected_keys = ['Alpha','Beta','Charlie'] - tm.assert_contains_all(expected_keys,dfs.keys()) + pth = os.path.join(self.dirpath, 'test_multisheet' + self.ext) + dfs = read_excel(pth, sheetname=None) + expected_keys = ['Alpha', 'Beta', 'Charlie'] + tm.assert_contains_all(expected_keys, dfs.keys()) def test_reading_multiple_specific_sheets(self): # Test reading specific sheetnames by specifying a mixed list # of integers and strings, and confirm that duplicated sheet # references (positions/names) are removed properly. - # Ensure a dict is returned # See PR #9450 - _skip_if_no_xlrd() - - #Explicitly request duplicates. Only the set should be returned. - expected_keys = [2,'Charlie','Charlie'] - dfs = read_excel(self.multisheet,sheetname=expected_keys) + pth = os.path.join(self.dirpath, 'test_multisheet' + self.ext) + # Explicitly request duplicates. Only the set should be returned. + expected_keys = [2, 'Charlie', 'Charlie'] + dfs = read_excel(pth, sheetname=expected_keys) expected_keys = list(set(expected_keys)) - tm.assert_contains_all(expected_keys,dfs.keys()) + tm.assert_contains_all(expected_keys, dfs.keys()) assert len(expected_keys) == len(dfs.keys()) + +class OdsReaderTests(ReadingTestsBase, tm.TestCase): + ext = '.ods' + engine_name = 'ezodf' + check_skip = staticmethod(_skip_if_no_ezodf) + + def test_read_ezodf_book(self): + + import ezodf + pth = os.path.join(self.dirpath, 'test1' + self.ext) + book = ezodf.opendoc(pth) + result1 = ExcelFile(book).parse() + result2 = read_excel(book) + + df = read_excel(pth) + tm.assert_frame_equal(df, result1) + tm.assert_frame_equal(df, result2) + + def test_types_datetime(self): + + expected = DataFrame.from_items([ + ("UnicodeCol", ['øø', 'ææ', 'åå', 'oø', '€£$¥', '£@$', 'ÅøØæÆ@']), + ("ExpCol", [8.50E-010, 8.50E+012, 9.00E-055, 8.50E+011, 8.5E-10, + 5E-10, 5E-10]), + ("BoolCol", [True, False, True, True, False, False, False]), + ("TimeCol", [time(hour=23, microsecond=1), + time(hour=2), + time(hour=1, minute=1, second=1), + timedelta(days=1, hours=2, minutes=1, seconds=1, + microseconds=1), + timedelta(hours=866, minutes=1, seconds=1, + microseconds=1), + time(2, 59, 40, 500000), + time(23, 59, 59, 100)]), + ("DateTimeCol", [datetime(2014, 10, 10, 10), + datetime(1900, 2, 1, 2), + datetime(2014, 1, 1, 23, 15, 15), + datetime(2011, 2, 3, 4, 5, 6), + datetime(1900, 7, 8, 9, 0, 1), + datetime(2015, 5, 7, 9, 33, 23), + datetime(2015, 5, 7, 2, 33, 23, 300000)]), + ("DateCol", [datetime(2014,3,2), datetime(1900,2,1), + datetime(1899,12,30), datetime(2100,12,11), + datetime(1850,11,3), datetime(2950,11,3), + datetime(2015,7,6)]), + ("TimeInDateFormat", [datetime(1899,12,30,1) for k in range(7)]) + ]) + + pth = os.path.join(self.dirpath, 'test_types_datetime' + self.ext) + dfs = read_excel(pth) + tm.assert_frame_equal(dfs, expected) + + +class XlrdTests(ReadingTestsBase): + """ + This is the base class for the xlrd tests, and 3 different file formats + are supported: xls, xlsx, xlsm + """ + + def test_excel_read_buffer(self): + + pth = os.path.join(self.dirpath, 'test1' + self.ext) + f = open(pth, 'rb') + xls = ExcelFile(f) + # it works + xls.parse('Sheet1', index_col=0, parse_dates=True) + + def test_read_xlrd_Book(self): + _skip_if_no_xlwt() + + import xlrd + df = self.frame + with ensure_clean('.xls') as pth: + df.to_excel(pth, "SheetA") + book = xlrd.open_workbook(pth) + + with ExcelFile(book, engine="xlrd") as xl: + result = xl.parse("SheetA") + tm.assert_frame_equal(df, result) + + result = read_excel(book, sheetname="SheetA", engine="xlrd") + tm.assert_frame_equal(df, result) + + @tm.network + def test_read_from_http_url(self): + # TODO: remove this when merging into master + url = ('https://raw.github.com/davidovitch/pandas/master/' + 'pandas/io/tests/data/test1' + self.ext) +# url = ('https://raw.github.com/pydata/pandas/master/' +# 'pandas/io/tests/data/test' + self.ext) + url_table = read_excel(url) + dirpath = tm.get_data_path() + localtable = os.path.join(dirpath, 'test1' + self.ext) + local_table = read_excel(localtable) + tm.assert_frame_equal(url_table, local_table) + + @slow + def test_read_from_file_url(self): + + # FILE + if sys.version_info[:2] < (2, 6): + raise nose.SkipTest("file:// not supported with Python < 2.6") + dirpath = tm.get_data_path() + localtable = os.path.join(dirpath, 'test1' + self.ext) + local_table = read_excel(localtable) + + try: + url_table = read_excel('file://localhost/' + localtable) + except URLError: + # fails on some systems + import platform + raise nose.SkipTest("failing on %s" % + ' '.join(platform.uname()).strip()) + + tm.assert_frame_equal(url_table, local_table) + + def test_reader_closes_file(self): + + pth = os.path.join(self.dirpath, 'test1' + self.ext) + f = open(pth, 'rb') + with ExcelFile(f) as xlsx: + # parses okay + xlsx.parse('Sheet1', index_col=0) + + self.assertTrue(f.closed) + def test_creating_and_reading_multiple_sheets(self): # Test reading multiple sheets, from a runtime created excel file # with multiple sheets. # See PR #9450 - _skip_if_no_xlrd() _skip_if_no_xlwt() + _skip_if_no_openpyxl() def tdf(sheetname): d, i = [11,22,33], [1,2,3] @@ -468,9 +495,9 @@ def tdf(sheetname): dfs = [tdf(s) for s in sheets] dfs = dict(zip(sheets,dfs)) - with ensure_clean('.xlsx') as pth: + with ensure_clean(self.ext) as pth: with ExcelWriter(pth) as ew: - for sheetname, df in iteritems(dfs): + for sheetname, df in compat.iteritems(dfs): df.to_excel(ew,sheetname) dfs_returned = pd.read_excel(pth,sheetname=sheets) for s in sheets: @@ -478,7 +505,6 @@ def tdf(sheetname): def test_reader_seconds(self): # Test reading times with and without milliseconds. GH5945. - _skip_if_no_xlrd() import xlrd if LooseVersion(xlrd.__VERSION__) >= LooseVersion("0.9.3"): @@ -510,8 +536,8 @@ def test_reader_seconds(self): time(16, 37, 1), time(18, 20, 54)])]) - epoch_1900 = os.path.join(self.dirpath, 'times_1900.xls') - epoch_1904 = os.path.join(self.dirpath, 'times_1904.xls') + epoch_1900 = os.path.join(self.dirpath, 'times_1900' + self.ext) + epoch_1904 = os.path.join(self.dirpath, 'times_1904' + self.ext) actual = read_excel(epoch_1900, 'Sheet1') tm.assert_frame_equal(actual, expected) @@ -543,6 +569,24 @@ def test_read_excel_blank_with_header(self): actual = read_excel(blank, 'Sheet1') tm.assert_frame_equal(actual, expected) +class XlsReaderTests(XlrdTests, tm.TestCase): + ext = '.xls' + engine_name = 'xlrd' + check_skip = staticmethod(_skip_if_no_xlrd) + + +class XlsxReaderTests(XlrdTests, tm.TestCase): + ext = '.xlsx' + engine_name = 'xlrd' + check_skip = staticmethod(_skip_if_no_xlrd) + + +class XlsmReaderTests(XlrdTests, tm.TestCase): + ext = '.xlsm' + engine_name = 'xlrd' + check_skip = staticmethod(_skip_if_no_xlrd) + + class ExcelWriterBase(SharedItems): # Base class for test cases to run with different Excel writers. # To add a writer test, define the following: @@ -1269,6 +1313,8 @@ def test_datetimes(self): # GH7074 def test_bytes_io(self): + _skip_if_no_xlrd() + bio = BytesIO() df = DataFrame(np.random.randn(10, 2)) writer = ExcelWriter(bio) @@ -1280,6 +1326,8 @@ def test_bytes_io(self): # GH8188 def test_write_lists_dict(self): + _skip_if_no_xlrd() + df = pd.DataFrame({'mixed': ['a', ['b', 'c'], {'d': 'e', 'f': 2}], 'numeric': [1, 2, 3.0], 'str': ['apple', 'banana', 'cherry']}) @@ -1291,6 +1339,7 @@ def test_write_lists_dict(self): read = read_excel(path, 'Sheet1', header=0) tm.assert_frame_equal(read, expected) + def raise_wrapper(major_ver): def versioned_raise_wrapper(orig_method): @functools.wraps(orig_method)
This work should eventually lead to a reader and writer for ods spreadsheets (LibreOffice / OpenOffice Open Document Format). I am doing this work in the master of my clone of pandas. From the wiki I understood it is fine for me to commit to my master and rebase with upstream from time to time. Please let me know if I should follow another git workflow (this is my first PR). This is what I have so far: - It seems to make sense to implement an OdsFile and OdsWriter in pandas/io/excel.py - I created ods test files identical to the other Excel test files. - Basic reading works, but does not handle all corner cases correctly yet - Tests and WritingOds are not implemented yet I am not sure how to approach the following issues: - For the tests, it would make sense to also use pandas/io/tests/test_excel.py (there would be a lot of code duplication otherwise). However, this would require some kind of a more elaborate test skipping mechanism than currently implemented. One could have ods dependencies installed, but not the Excel ones and vice versa. - When considering pandas could support more spreadsheet formats, does it make sense to rename pandas/io/excel.py to spreadsheet.py, and correspondingly, read_excel to read_spreadsheet? I guess this is not easy since it a lot of stuff out there already counts on the excel naming scheme. For the record, there is one message on the [mailing list](https://groups.google.com/forum/?fromgroups#!topic/pydata/Zv-BXJNsP2U), and this PR will fix issue #2311. ods support depends on [ezodf](https://github.com/T0ha/ezodf), and issue #2311 mentions some of the alternatives.
https://api.github.com/repos/pandas-dev/pandas/pulls/9070
2014-12-13T11:45:25Z
2015-09-01T18:52:24Z
null
2022-10-13T00:16:19Z
pivot & unstack with nan in the index
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 7433adaa4b738..66b772d35f2e2 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -67,6 +67,7 @@ Bug Fixes - Bug in ``MultiIndex.has_duplicates`` when having many levels causes an indexer overflow (:issue:`9075`) +- Bug in ``pivot`` and `unstack`` where ``nan`` values would break index alignment (:issue:`7466`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4c221cc27fdce..888dca3914b53 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -6,7 +6,7 @@ from pandas.compat import( zip, builtins, range, long, lzip, - OrderedDict, callable + OrderedDict, callable, filter, map ) from pandas import compat @@ -3510,6 +3510,61 @@ def get_group_index(label_list, shape): np.putmask(group_index, mask, -1) return group_index + +def get_flat_ids(labels, shape, retain_lex_rank): + """ + Given a list of labels at each level, returns a flat array of int64 ids + corresponding to unique tuples across the labels. If `retain_lex_rank`, + rank of returned ids preserve lexical ranks of labels. + + Parameters + ---------- + labels: sequence of arrays + Integers identifying levels at each location + shape: sequence of ints same length as labels + Number of unique levels at each location + retain_lex_rank: boolean + If the ranks of returned ids should match lexical ranks of labels + + Returns + ------- + An array of type int64 where two elements are equal if their corresponding + labels are equal at all location. + """ + def loop(labels, shape): + # how many levels can be done without overflow: + pred = lambda i: not _int64_overflow_possible(shape[:i]) + nlev = next(filter(pred, range(len(shape), 0, -1))) + + # compute flat ids for the first `nlev` levels + stride = np.prod(shape[1:nlev], dtype='i8') + out = stride * labels[0].astype('i8', subok=False, copy=False) + + for i in range(1, nlev): + stride //= shape[i] + out += labels[i] * stride + + if nlev == len(shape): # all levels done! + return out + + # compress what has been done so far in order to avoid overflow + # to retain lexical ranks, obs_ids should be sorted + comp_ids, obs_ids = _compress_group_index(out, sort=retain_lex_rank) + + labels = [comp_ids] + labels[nlev:] + shape = [len(obs_ids)] + shape[nlev:] + + return loop(labels, shape) + + def maybe_lift(lab, size): # pormote nan values + return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) + + labels = map(com._ensure_int64, labels) + labels, shape = map(list, zip(*map(maybe_lift, labels, shape))) + + return loop(labels, shape) + + _INT64_MAX = np.iinfo(np.int64).max diff --git a/pandas/core/index.py b/pandas/core/index.py index d2a3093e686a7..97890299657cf 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -3226,44 +3226,13 @@ def _has_complex_internals(self): @cache_readonly def is_unique(self): from pandas.hashtable import Int64HashTable - - def _get_group_index(labels, shape): - from pandas.core.groupby import _int64_overflow_possible, \ - _compress_group_index - - # how many levels can be done without overflow - pred = lambda i: not _int64_overflow_possible(shape[:i]) - nlev = next(filter(pred, range(len(shape), 0, -1))) - - # compute group indicies for the first `nlev` levels - group_index = labels[0].astype('i8', subok=False, copy=True) - stride = shape[0] - - for i in range(1, nlev): - group_index += labels[i] * stride - stride *= shape[i] - - if nlev == len(shape): - return group_index - - comp_ids, obs_ids = _compress_group_index(group_index, sort=False) - - labels = [comp_ids] + labels[nlev:] - shape = [len(obs_ids)] + shape[nlev:] - - return _get_group_index(labels, shape) - - def _maybe_lift(lab, size): # pormote nan values - return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) + from pandas.core.groupby import get_flat_ids shape = map(len, self.levels) - labels = map(_ensure_int64, self.labels) - - labels, shape = map(list, zip(*map(_maybe_lift, labels, shape))) - group_index = _get_group_index(labels, shape) + ids = get_flat_ids(self.labels, shape, False) + table = Int64HashTable(min(1 << 20, len(ids))) - table = Int64HashTable(min(1 << 20, len(group_index))) - return len(table.unique(group_index)) == len(self) + return len(table.unique(ids)) == len(self) def get_value(self, series, key): # somewhat broken encapsulation diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py index 5ed823d690028..19208506fdc72 100644 --- a/pandas/core/reshape.py +++ b/pandas/core/reshape.py @@ -82,18 +82,10 @@ def __init__(self, values, index, level=-1, value_columns=None): self.level = self.index._get_level_number(level) - levels = index.levels - labels = index.labels - - def _make_index(lev, lab): - values = _make_index_array_level(lev.values, lab) - i = lev._simple_new(values, lev.name, - freq=getattr(lev, 'freq', None), - tz=getattr(lev, 'tz', None)) - return i - - self.new_index_levels = [_make_index(lev, lab) - for lev, lab in zip(levels, labels)] + # when index includes `nan`, need to lift levels/strides by 1 + self.lift = 1 if -1 in self.index.labels[self.level] else 0 + + self.new_index_levels = list(index.levels) self.new_index_names = list(index.names) self.removed_name = self.new_index_names.pop(self.level) @@ -134,10 +126,10 @@ def _make_selectors(self): ngroups = len(obs_ids) comp_index = _ensure_platform_int(comp_index) - stride = self.index.levshape[self.level] + stride = self.index.levshape[self.level] + self.lift self.full_shape = ngroups, stride - selector = self.sorted_labels[-1] + stride * comp_index + selector = self.sorted_labels[-1] + stride * comp_index + self.lift mask = np.zeros(np.prod(self.full_shape), dtype=bool) mask.put(selector, True) @@ -166,20 +158,6 @@ def get_result(self): values = com.take_nd(values, inds, axis=1) columns = columns[inds] - # we might have a missing index - if len(index) != values.shape[0]: - mask = isnull(index) - if mask.any(): - l = np.arange(len(index)) - values, orig_values = (np.empty((len(index), values.shape[1])), - values) - values.fill(np.nan) - values_indexer = com._ensure_int64(l[~mask]) - for i, j in enumerate(values_indexer): - values[j] = orig_values[i] - else: - index = index.take(self.unique_groups) - # may need to coerce categoricals here if self.is_categorical is not None: values = [ Categorical.from_array(values[:,i], @@ -220,9 +198,16 @@ def get_new_values(self): def get_new_columns(self): if self.value_columns is None: - return self.removed_level + if self.lift == 0: + return self.removed_level + + lev = self.removed_level + vals = np.insert(lev.astype('object'), 0, + _get_na_value(lev.dtype.type)) + + return lev._shallow_copy(vals) - stride = len(self.removed_level) + stride = len(self.removed_level) + self.lift width = len(self.value_columns) propagator = np.repeat(np.arange(width), stride) if isinstance(self.value_columns, MultiIndex): @@ -231,59 +216,34 @@ def get_new_columns(self): new_labels = [lab.take(propagator) for lab in self.value_columns.labels] - new_labels.append(np.tile(np.arange(stride), width)) else: new_levels = [self.value_columns, self.removed_level] new_names = [self.value_columns.name, self.removed_name] + new_labels = [propagator] - new_labels = [] - - new_labels.append(propagator) - new_labels.append(np.tile(np.arange(stride), width)) - + new_labels.append(np.tile(np.arange(stride) - self.lift, width)) return MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) def get_new_index(self): - result_labels = [] - for cur in self.sorted_labels[:-1]: - labels = cur.take(self.compressor) - labels = _make_index_array_level(labels, cur) - result_labels.append(labels) + result_labels = [lab.take(self.compressor) + for lab in self.sorted_labels[:-1]] # construct the new index if len(self.new_index_levels) == 1: - new_index = self.new_index_levels[0] - new_index.name = self.new_index_names[0] - else: - new_index = MultiIndex(levels=self.new_index_levels, - labels=result_labels, - names=self.new_index_names, - verify_integrity=False) - - return new_index + lev, lab = self.new_index_levels[0], result_labels[0] + if not (lab == -1).any(): + return lev.take(lab) + vals = np.insert(lev.astype('object'), len(lev), + _get_na_value(lev.dtype.type)).take(lab) -def _make_index_array_level(lev, lab): - """ create the combined index array, preserving nans, return an array """ - mask = lab == -1 - if not mask.any(): - return lev - - l = np.arange(len(lab)) - mask_labels = np.empty(len(mask[mask]), dtype=object) - mask_labels.fill(_get_na_value(lev.dtype.type)) - mask_indexer = com._ensure_int64(l[mask]) - - labels = lev - labels_indexer = com._ensure_int64(l[~mask]) - - new_labels = np.empty(tuple([len(lab)]), dtype=object) - new_labels[labels_indexer] = labels - new_labels[mask_indexer] = mask_labels - - return new_labels + return lev._shallow_copy(vals) + return MultiIndex(levels=self.new_index_levels, + labels=result_labels, + names=self.new_index_names, + verify_integrity=False) def _unstack_multiple(data, clocs): if len(clocs) == 0: @@ -483,29 +443,10 @@ def _unstack_frame(obj, level): def get_compressed_ids(labels, sizes): - # no overflow - if com._long_prod(sizes) < 2 ** 63: - group_index = get_group_index(labels, sizes) - comp_index, obs_ids = _compress_group_index(group_index) - else: - n = len(labels[0]) - mask = np.zeros(n, dtype=bool) - for v in labels: - mask |= v < 0 - - while com._long_prod(sizes) >= 2 ** 63: - i = len(sizes) - while com._long_prod(sizes[:i]) >= 2 ** 63: - i -= 1 - - rem_index, rem_ids = get_compressed_ids(labels[:i], - sizes[:i]) - sizes = [len(rem_ids)] + sizes[i:] - labels = [rem_index] + labels[i:] - - return get_compressed_ids(labels, sizes) + from pandas.core.groupby import get_flat_ids - return comp_index, obs_ids + ids = get_flat_ids(labels, sizes, True) + return _compress_group_index(ids, sort=True) def stack(frame, level=-1, dropna=True): diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index a19a32ea793ba..fcbfb21bd20e3 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -11,7 +11,7 @@ import nose import functools import itertools -from itertools import product +from itertools import product, permutations from distutils.version import LooseVersion from pandas.compat import( @@ -12334,6 +12334,53 @@ def test_unstack_non_unique_index_names(self): with tm.assertRaises(ValueError): df.T.stack('c1') + def test_unstack_nan_index(self): # GH7466 + cast = lambda val: '{0:1}'.format('' if val != val else val) + nan = np.nan + + def verify(df): + mk_list = lambda a: list(a) if isinstance(a, tuple) else [a] + rows, cols = df.notnull().values.nonzero() + for i, j in zip(rows, cols): + left = sorted(df.iloc[i, j].split('.')) + right = mk_list(df.index[i]) + mk_list(df.columns[j]) + right = sorted(list(map(cast, right))) + self.assertEqual(left, right) + + df = DataFrame({'jim':['a', 'b', nan, 'd'], + 'joe':['w', 'x', 'y', 'z'], + 'jolie':['a.w', 'b.x', ' .y', 'd.z']}) + + left = df.set_index(['jim', 'joe']).unstack()['jolie'] + right = df.set_index(['joe', 'jim']).unstack()['jolie'].T + assert_frame_equal(left, right) + + for idx in permutations(df.columns[:2]): + mi = df.set_index(list(idx)) + for lev in range(2): + udf = mi.unstack(level=lev) + self.assertEqual(udf.notnull().values.sum(), len(df)) + verify(udf['jolie']) + + df = DataFrame({'1st':['d'] * 3 + [nan] * 5 + ['a'] * 2 + + ['c'] * 3 + ['e'] * 2 + ['b'] * 5, + '2nd':['y'] * 2 + ['w'] * 3 + [nan] * 3 + + ['z'] * 4 + [nan] * 3 + ['x'] * 3 + [nan] * 2, + '3rd':[67,39,53,72,57,80,31,18,11,30,59, + 50,62,59,76,52,14,53,60,51]}) + + df['4th'], df['5th'] = \ + df.apply(lambda r: '.'.join(map(cast, r)), axis=1), \ + df.apply(lambda r: '.'.join(map(cast, r.iloc[::-1])), axis=1) + + for idx in permutations(['1st', '2nd', '3rd']): + mi = df.set_index(list(idx)) + for lev in range(3): + udf = mi.unstack(level=lev) + self.assertEqual(udf.notnull().values.sum(), 2 * len(df)) + for col in ['4th', '5th']: + verify(udf[col]) + def test_stack_datetime_column_multiIndex(self): # GH 8039 t = datetime(2014, 1, 1) diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index 23350b203ee50..39d189b7de52b 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -173,13 +173,16 @@ def test_pivot_multi_functions(self): def test_pivot_index_with_nan(self): # GH 3588 nan = np.nan - df = DataFrame({"a":['R1', 'R2', nan, 'R4'], 'b':["C1", "C2", "C3" , "C4"], "c":[10, 15, nan , 20]}) + df = DataFrame({'a':['R1', 'R2', nan, 'R4'], + 'b':['C1', 'C2', 'C3' , 'C4'], + 'c':[10, 15, 17, 20]}) result = df.pivot('a','b','c') - expected = DataFrame([[nan,nan,nan,nan],[nan,10,nan,nan], - [nan,nan,nan,nan],[nan,nan,15,20]], - index = Index(['R1','R2',nan,'R4'],name='a'), + expected = DataFrame([[nan,nan,17,nan],[10,nan,nan,nan], + [nan,15,nan,nan],[nan,nan,nan,20]], + index = Index([nan,'R1','R2','R4'],name='a'), columns = Index(['C1','C2','C3','C4'],name='b')) tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df.pivot('b', 'a', 'c'), expected.T) def test_pivot_with_tz(self): # GH 5878 @@ -268,12 +271,12 @@ def _check_output(res, col, index=['A', 'B'], columns=['C']): # issue number #8349: pivot_table with margins and dictionary aggfunc - df=DataFrame([ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17}, - {'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23}, - {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100}, - {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110}, - {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200}, - {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80}, + df=DataFrame([ {'JOB':'Worker','NAME':'Bob' ,'YEAR':2013,'MONTH':12,'DAYS': 3,'SALARY': 17}, + {'JOB':'Employ','NAME':'Mary','YEAR':2013,'MONTH':12,'DAYS': 5,'SALARY': 23}, + {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':10,'SALARY':100}, + {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 1,'DAYS':11,'SALARY':110}, + {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 1,'DAYS':15,'SALARY':200}, + {'JOB':'Worker','NAME':'Bob' ,'YEAR':2014,'MONTH': 2,'DAYS': 8,'SALARY': 80}, {'JOB':'Employ','NAME':'Mary','YEAR':2014,'MONTH': 2,'DAYS': 5,'SALARY':190} ]) df=df.set_index(['JOB','NAME','YEAR','MONTH'],drop=False,append=False)
closes https://github.com/pydata/pandas/issues/7466 on branch: ``` >>> df a b c 0 R1 C1 10 1 R2 C2 15 2 NaN C3 17 3 R4 C4 20 >>> df.pivot('a', 'b', 'c').fillna('.') b C1 C2 C3 C4 a NaN . . 17 . R1 10 . . . R2 . 15 . . R4 . . . 20 >>> df.pivot('b', 'a', 'c').fillna('.') a NaN R1 R2 R4 b C1 . 10 . . C2 . . 15 . C3 17 . . . C4 . . . 20 ``` the `pivot` function requires the `unstack` function to work with `nan`s in the index: ``` >>> df 4th 5th 1st 2nd 3rd d y 67 d.y.67 67.y.d 39 d.y.39 39.y.d w 53 d.w.53 53.w.d NaN w 72 .w.72 72.w. 57 .w.57 57.w. NaN 80 . .80 80. . 31 . .31 31. . 18 . .18 18. . a z 11 a.z.11 11.z.a 30 a.z.30 30.z.a c z 59 c.z.59 59.z.c 50 c.z.50 50.z.c NaN 62 c. .62 62. .c e NaN 59 e. .59 59. .e 76 e. .76 76. .e b x 52 b.x.52 52.x.b 14 b.x.14 14.x.b 53 b.x.53 53.x.b NaN 60 b. .60 60. .b 51 b. .51 51. .b ``` the `4th` and `5th` column are so that it is easy to verify the frame: ``` >>> df.unstack(level=1).fillna('-') 4th 5th 2nd NaN w x y z NaN w x y z 1st 3rd NaN 18 . .18 - - - - 18. . - - - - 31 . .31 - - - - 31. . - - - - 57 - .w.57 - - - - 57.w. - - - 72 - .w.72 - - - - 72.w. - - - 80 . .80 - - - - 80. . - - - - a 11 - - - - a.z.11 - - - - 11.z.a 30 - - - - a.z.30 - - - - 30.z.a b 14 - - b.x.14 - - - - 14.x.b - - 51 b. .51 - - - - 51. .b - - - - 52 - - b.x.52 - - - - 52.x.b - - 53 - - b.x.53 - - - - 53.x.b - - 60 b. .60 - - - - 60. .b - - - - c 50 - - - - c.z.50 - - - - 50.z.c 59 - - - - c.z.59 - - - - 59.z.c 62 c. .62 - - - - 62. .c - - - - d 39 - - - d.y.39 - - - - 39.y.d - 53 - d.w.53 - - - - 53.w.d - - - 67 - - - d.y.67 - - - - 67.y.d - e 59 e. .59 - - - - 59. .e - - - - 76 e. .76 - - - - 76. .e - - - - ``` `nan` values are kept out of levels and are handled by labels: ``` >>> df.unstack(level=1).index MultiIndex(levels=[['a', 'b', 'c', 'd', 'e'], [11, 14, 18, 30, 31, 39, 50, 51, 52, 53, 57, 59, 60, 62, 67, 72, 76, 80]], labels=[[-1, -1, -1, -1, -1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4], [2, 4, 10, 15, 17, 0, 3, 1, 7, 8, 9, 12, 6, 11, 13, 5, 9, 14, 11, 16]], names=['1st', '3rd']) >>> df.unstack(level=1).columns MultiIndex(levels=[['4th', '5th'], ['w', 'x', 'y', 'z']], labels=[[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [-1, 0, 1, 2, 3, -1, 0, 1, 2, 3]], names=[None, '2nd']) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/9061
2014-12-12T02:10:36Z
2014-12-22T13:08:53Z
2014-12-22T13:08:52Z
2015-01-10T20:21:07Z
DOC: fix-up docs for 0.15.2 release
diff --git a/doc/source/io.rst b/doc/source/io.rst index 2ec61f7f00bd8..d5bbddfeb7d37 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3403,7 +3403,7 @@ writes ``data`` to the database in batches of 1000 rows at a time: data.to_sql('data_chunked', engine, chunksize=1000) SQL data types -"""""""""""""" +++++++++++++++ :func:`~pandas.DataFrame.to_sql` will try to map your data to an appropriate SQL data type based on the dtype of the data. When you have columns of dtype @@ -3801,7 +3801,7 @@ is lost when exporting. Labeled data can similarly be imported from *Stata* data files as ``Categorical`` variables using the keyword argument ``convert_categoricals`` (``True`` by default). The keyword argument ``order_categoricals`` (``True`` by default) determines - whether imported ``Categorical`` variables are ordered. +whether imported ``Categorical`` variables are ordered. .. note:: diff --git a/doc/source/release.rst b/doc/source/release.rst index 321947111574b..6d952344576e6 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -50,7 +50,9 @@ pandas 0.15.2 **Release date:** (December 12, 2014) -This is a minor release from 0.15.1 and includes a small number of API changes, several new features, enhancements, and performance improvements along with a large number of bug fixes. +This is a minor release from 0.15.1 and includes a large number of bug fixes +along with several new features, enhancements, and performance improvements. +A small number of API changes were necessary to fix existing bugs. See the :ref:`v0.15.2 Whatsnew <whatsnew_0152>` overview for an extensive list of all API changes, enhancements and bugs that have been fixed in 0.15.2. diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3a0fdbae5e297..02de919e3f83e 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -3,9 +3,10 @@ v0.15.2 (December 12, 2014) --------------------------- -This is a minor release from 0.15.1 and includes a small number of API changes, several new features, -enhancements, and performance improvements along with a large number of bug fixes. We recommend that all -users upgrade to this version. +This is a minor release from 0.15.1 and includes a large number of bug fixes +along with several new features, enhancements, and performance improvements. +A small number of API changes were necessary to fix existing bugs. +We recommend that all users upgrade to this version. - :ref:`Enhancements <whatsnew_0152.enhancements>` - :ref:`API Changes <whatsnew_0152.api>` @@ -16,6 +17,7 @@ users upgrade to this version. API changes ~~~~~~~~~~~ + - Indexing in ``MultiIndex`` beyond lex-sort depth is now supported, though a lexically sorted index will have a better performance. (:issue:`2646`) @@ -38,24 +40,30 @@ API changes df2.index.lexsort_depth df2.loc[(1,'z')] -- Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`) - - Bug in unique of Series with ``category`` dtype, which returned all categories regardless whether they were "used" or not (see :issue:`8559` for the discussion). + Previous behaviour was to return all categories: -- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions and will now raise ``TypeError``. (:issue:`8302`): + .. code-block:: python - .. ipython:: python + In [3]: cat = pd.Categorical(['a', 'b', 'a'], categories=['a', 'b', 'c']) - s = pd.Series([False, True, False], index=[0, 0, 1]) - s.any(level=0) + In [4]: cat + Out[4]: + [a, b, a] + Categories (3, object): [a < b < c] -- ``Panel`` now supports the ``all`` and ``any`` aggregation functions. (:issue:`8302`): + In [5]: cat.unique() + Out[5]: array(['a', 'b', 'c'], dtype=object) + + Now, only the categories that do effectively occur in the array are returned: .. ipython:: python - p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) - p.all() + cat = pd.Categorical(['a', 'b', 'a'], categories=['a', 'b', 'c']) + cat.unique() + +- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions and will now raise ``TypeError``. (:issue:`8302`). - Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) @@ -90,25 +98,70 @@ API changes - ``Timestamp('now')`` is now equivalent to ``Timestamp.now()`` in that it returns the local time rather than UTC. Also, ``Timestamp('today')`` is now equivalent to ``Timestamp.today()`` and both have ``tz`` as a possible argument. (:issue:`9000`) +- Fix negative step support for label-based slices (:issue:`8753`) + + Old behavior: + + .. code-block:: python + + In [1]: s = pd.Series(np.arange(3), ['a', 'b', 'c']) + Out[1]: + a 0 + b 1 + c 2 + dtype: int64 + + In [2]: s.loc['c':'a':-1] + Out[2]: + c 2 + dtype: int64 + + New behavior: + + .. ipython:: python + + s = pd.Series(np.arange(3), ['a', 'b', 'c']) + s.loc['c':'a':-1] + + .. _whatsnew_0152.enhancements: Enhancements ~~~~~~~~~~~~ +``Categorical`` enhancements: + +- Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. +- Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. +- Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. +- Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). + +Other enhancements: + - Added the ability to specify the SQL type of columns when writing a DataFrame to a database (:issue:`8778`). For example, specifying to use the sqlalchemy ``String`` type instead of the default ``Text`` type for string columns: - .. code-block:: + .. code-block:: python from sqlalchemy.types import String data.to_sql('data_dtype', engine, dtype={'Col_1': String}) -- Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. -- Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. -- Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. -- Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). +- ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters (:issue:`8302`): + + .. ipython:: python + + s = pd.Series([False, True, False], index=[0, 0, 1]) + s.any(level=0) + +- ``Panel`` now supports the ``all`` and ``any`` aggregation functions. (:issue:`8302`): + + .. ipython:: python + + p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) + p.all() + - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). - Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`. - ``Timedelta`` arithmetic returns ``NotImplemented`` in unknown cases, allowing extensions by custom classes (:issue:`8813`). @@ -122,19 +175,22 @@ Enhancements - Added ability to read table footers to read_html (:issue:`8552`) - ``to_sql`` now infers datatypes of non-NA values for columns that contain NA values and have dtype ``object`` (:issue:`8778`). + .. _whatsnew_0152.performance: Performance ~~~~~~~~~~~ -- Reduce memory usage when skiprows is an integer in read_csv (:issue:`8681`) +- Reduce memory usage when skiprows is an integer in read_csv (:issue:`8681`) - Performance boost for ``to_datetime`` conversions with a passed ``format=``, and the ``exact=False`` (:issue:`8904`) + .. _whatsnew_0152.bug_fixes: Bug Fixes ~~~~~~~~~ +- Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`) - Bug in Timestamp-Timestamp not returning a Timedelta type and datelike-datelike ops with timezones (:issue:`8865`) - Made consistent a timezone mismatch exception (either tz operated with None or incompatible timezone), will now return ``TypeError`` rather than ``ValueError`` (a couple of edge cases only), (:issue:`8865`) - Bug in using a ``pd.Grouper(key=...)`` with no level/axis or level only (:issue:`8795`, :issue:`8866`) @@ -154,95 +210,32 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Bug in ``MultiIndex.reindex`` where reindexing at level would not reorder labels (:issue:`4088`) - Bug in certain operations with dateutil timezones, manifesting with dateutil 2.3 (:issue:`8639`) - -- Fix negative step support for label-based slices (:issue:`8753`) - - Old behavior: - - .. code-block:: python - - In [1]: s = pd.Series(np.arange(3), ['a', 'b', 'c']) - Out[1]: - a 0 - b 1 - c 2 - dtype: int64 - - In [2]: s.loc['c':'a':-1] - Out[2]: - c 2 - dtype: int64 - - New behavior: - - .. ipython:: python - - s = pd.Series(np.arange(3), ['a', 'b', 'c']) - s.loc['c':'a':-1] - - Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (:issue:`8890`) - Bug in ``to_datetime`` when parsing a nanoseconds using the ``%f`` format (:issue:`8989`) - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo and when it receives no data from Yahoo (:issue:`8761`), (:issue:`8783`). - Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) - Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) - Bug in outputing a Multindex with ``to_html,index=False`` which would add an extra column (:issue:`8452`) - - - - - - - - Imported categorical variables from Stata files retain the ordinal information in the underlying data (:issue:`8836`). - - - - Defined ``.size`` attribute across ``NDFrame`` objects to provide compat with numpy >= 1.9.1; buggy with ``np.array_split`` (:issue:`8846`) - - - Skip testing of histogram plots for matplotlib <= 1.2 (:issue:`8648`). - - - - - - - Bug where ``get_data_google`` returned object dtypes (:issue:`3995`) - - Bug in ``DataFrame.stack(..., dropna=False)`` when the DataFrame's ``columns`` is a ``MultiIndex`` whose ``labels`` do not reference all its ``levels``. (:issue:`8844`) - - - Bug in that Option context applied on ``__enter__`` (:issue:`8514`) - - - Bug in resample that causes a ValueError when resampling across multiple days and the last offset is not calculated from the start of the range (:issue:`8683`) - - - - Bug where ``DataFrame.plot(kind='scatter')`` fails when checking if an np.array is in the DataFrame (:issue:`8852`) - - - - Bug in ``pd.infer_freq/DataFrame.inferred_freq`` that prevented proper sub-daily frequency inference when the index contained DST days (:issue:`8772`). - Bug where index name was still used when plotting a series with ``use_index=False`` (:issue:`8558`). - Bugs when trying to stack multiple columns, when some (or all) of the level names are numbers (:issue:`8584`). - Bug in ``MultiIndex`` where ``__contains__`` returns wrong result if index is not lexically sorted or unique (:issue:`7724`) - BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`), (:issue:`8983`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) - - - - - - - Bug in `StataWriter` the produces writes strings with 244 characters irrespective of actual size (:issue:`8969`) - - - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) - Bug in Datareader returns object dtype if there are missing values (:issue:`8980`) - Bug in plotting if sharex was enabled and index was a timeseries, would show labels on multiple axes (:issue:`3964`). - - Bug where passing a unit to the TimedeltaIndex constructor applied the to nano-second conversion twice. (:issue:`9011`). - Bug in plotting of a period-like array (:issue:`9012`) +
@jreback some more clean-up of whatsnew - some small fixes so now everything builds ok, ready for release I also reworded a little bit the intro of the minor release (I thought was a bit more appropriate for minor release vs major release)
https://api.github.com/repos/pandas-dev/pandas/pulls/9058
2014-12-11T13:32:05Z
2014-12-11T13:41:59Z
2014-12-11T13:41:59Z
2014-12-11T13:41:59Z
TST: start tests for PeriodConverter
diff --git a/pandas/tseries/converter.py b/pandas/tseries/converter.py index 03a3d450827b9..a9fee1d5c3ee6 100644 --- a/pandas/tseries/converter.py +++ b/pandas/tseries/converter.py @@ -109,7 +109,7 @@ class PeriodConverter(dates.DateConverter): def convert(values, units, axis): if not hasattr(axis, 'freq'): raise TypeError('Axis must have `freq` set to convert to Periods') - valid_types = (str, datetime, Period, pydt.date, pydt.time) + valid_types = (compat.string_types, datetime, Period, pydt.date, pydt.time) if (isinstance(values, valid_types) or com.is_integer(values) or com.is_float(values)): return get_datevalue(values, axis.freq) @@ -127,7 +127,7 @@ def convert(values, units, axis): def get_datevalue(date, freq): if isinstance(date, Period): return date.asfreq(freq).ordinal - elif isinstance(date, (str, datetime, pydt.date, pydt.time)): + elif isinstance(date, (compat.string_types, datetime, pydt.date, pydt.time)): return Period(date, freq).ordinal elif (com.is_integer(date) or com.is_float(date) or (isinstance(date, (np.ndarray, Index)) and (date.size == 1))): diff --git a/pandas/tseries/tests/test_converter.py b/pandas/tseries/tests/test_converter.py index b5a284d5f50ea..95c0b4466da26 100644 --- a/pandas/tseries/tests/test_converter.py +++ b/pandas/tseries/tests/test_converter.py @@ -6,7 +6,7 @@ import numpy as np from numpy.testing import assert_almost_equal as np_assert_almost_equal -from pandas import Timestamp +from pandas import Timestamp, Period from pandas.compat import u import pandas.util.testing as tm from pandas.tseries.offsets import Second, Milli, Micro @@ -103,6 +103,60 @@ def _assert_less(ts1, ts2): _assert_less(ts, ts + Micro(50)) +class TestPeriodConverter(tm.TestCase): + + def setUp(self): + self.pc = converter.PeriodConverter() + + class Axis(object): + pass + + self.axis = Axis() + self.axis.freq = 'D' + + def test_convert_accepts_unicode(self): + r1 = self.pc.convert("2012-1-1", None, self.axis) + r2 = self.pc.convert(u("2012-1-1"), None, self.axis) + self.assert_equal(r1, r2, "PeriodConverter.convert should accept unicode") + + def test_conversion(self): + rs = self.pc.convert(['2012-1-1'], None, self.axis)[0] + xp = Period('2012-1-1').ordinal + self.assertEqual(rs, xp) + + rs = self.pc.convert('2012-1-1', None, self.axis) + self.assertEqual(rs, xp) + + rs = self.pc.convert([date(2012, 1, 1)], None, self.axis)[0] + self.assertEqual(rs, xp) + + rs = self.pc.convert(date(2012, 1, 1), None, self.axis) + self.assertEqual(rs, xp) + + rs = self.pc.convert([Timestamp('2012-1-1')], None, self.axis)[0] + self.assertEqual(rs, xp) + + rs = self.pc.convert(Timestamp('2012-1-1'), None, self.axis) + self.assertEqual(rs, xp) + + # FIXME + # rs = self.pc.convert(np.datetime64('2012-01-01'), None, self.axis) + # self.assertEqual(rs, xp) + # + # rs = self.pc.convert(np.datetime64('2012-01-01 00:00:00+00:00'), None, self.axis) + # self.assertEqual(rs, xp) + # + # rs = self.pc.convert(np.array([np.datetime64('2012-01-01 00:00:00+00:00'), + # np.datetime64('2012-01-02 00:00:00+00:00')]), None, self.axis) + # self.assertEqual(rs[0], xp) + + def test_integer_passthrough(self): + # GH9012 + rs = self.pc.convert([0, 1], None, self.axis) + xp = [0, 1] + self.assertEqual(rs, xp) + + if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
@jreback The tests I started related to PR #9050
https://api.github.com/repos/pandas-dev/pandas/pulls/9055
2014-12-11T10:29:35Z
2014-12-12T15:25:07Z
2014-12-12T15:25:07Z
2014-12-12T15:25:07Z
BUG: fix PeriodConverter issue when given a list of integers (GH9012)
diff --git a/pandas/tseries/converter.py b/pandas/tseries/converter.py index 4b3fdfd5e3303..03a3d450827b9 100644 --- a/pandas/tseries/converter.py +++ b/pandas/tseries/converter.py @@ -117,8 +117,10 @@ def convert(values, units, axis): return values.asfreq(axis.freq).values if isinstance(values, Index): return values.map(lambda x: get_datevalue(x, axis.freq)) - if isinstance(values, (list, tuple, np.ndarray, Index)): + if com.is_period_arraylike(values): return PeriodIndex(values, freq=axis.freq).values + if isinstance(values, (list, tuple, np.ndarray, Index)): + return [get_datevalue(x, axis.freq) for x in values] return values
For example coming up when [0, 1] is passed by axhline Closes #9012 test and whatsnew are coming
https://api.github.com/repos/pandas-dev/pandas/pulls/9050
2014-12-10T12:38:24Z
2014-12-11T01:34:14Z
null
2014-12-11T01:34:14Z
TST: dateutil fixes (GH8639)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index f034e0e223e6b..6936e40da6fbe 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -163,6 +163,7 @@ Bug Fixes - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Bug in ``MultiIndex.reindex`` where reindexing at level would not reorder labels (:issue:`4088`) +- Bug in certain operations with dateutil timezones, manifesting with dateutil 2.3 (:issue:`8639`) - Fix negative step support for label-based slices (:issue:`8753`) diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py index 500e19d36fff6..d568a75f6874d 100644 --- a/pandas/tseries/tests/test_daterange.py +++ b/pandas/tseries/tests/test_daterange.py @@ -371,31 +371,31 @@ def test_range_tz_pytz(self): self.assertEqual(dr.tz.zone, tz.zone) self.assertEqual(dr[0], start) self.assertEqual(dr[2], end) - + def test_range_tz_dst_straddle_pytz(self): - + tm._skip_if_no_pytz() from pytz import timezone tz = timezone('US/Eastern') - dates = [(tz.localize(datetime(2014, 3, 6)), + dates = [(tz.localize(datetime(2014, 3, 6)), tz.localize(datetime(2014, 3, 12))), - (tz.localize(datetime(2013, 11, 1)), + (tz.localize(datetime(2013, 11, 1)), tz.localize(datetime(2013, 11, 6)))] for (start, end) in dates: dr = date_range(start, end, freq='D') self.assertEqual(dr[0], start) self.assertEqual(dr[-1], end) self.assertEqual(np.all(dr.hour==0), True) - + dr = date_range(start, end, freq='D', tz='US/Eastern') self.assertEqual(dr[0], start) self.assertEqual(dr[-1], end) - self.assertEqual(np.all(dr.hour==0), True) - + self.assertEqual(np.all(dr.hour==0), True) + dr = date_range(start.replace(tzinfo=None), end.replace(tzinfo=None), freq='D', tz='US/Eastern') self.assertEqual(dr[0], start) self.assertEqual(dr[-1], end) - self.assertEqual(np.all(dr.hour==0), True) + self.assertEqual(np.all(dr.hour==0), True) def test_range_tz_dateutil(self): # GH 2906 @@ -441,7 +441,7 @@ def test_month_range_union_tz_pytz(self): def test_month_range_union_tz_dateutil(self): _skip_if_windows_python_3() tm._skip_if_no_dateutil() - from dateutil.tz import gettz as timezone + from dateutil.zoneinfo import gettz as timezone tz = timezone('US/Eastern') early_start = datetime(2011, 1, 1) diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 7a428fd629125..9b8200e266e5a 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -419,7 +419,7 @@ def test_timestamp_to_datetime_explicit_dateutil(self): tm._skip_if_no_dateutil() import dateutil rng = date_range('20090415', '20090519', - tz=dateutil.tz.gettz('US/Eastern')) + tz=dateutil.zoneinfo.gettz('US/Eastern')) stamp = rng[0] dtval = stamp.to_pydatetime() @@ -1797,7 +1797,7 @@ def test_append_concat_tz_explicit_pytz(self): def test_append_concat_tz_dateutil(self): # GH 2938 tm._skip_if_no_dateutil() - from dateutil.tz import gettz as timezone + from dateutil.zoneinfo import gettz as timezone rng = date_range('5/8/2012 1:45', periods=10, freq='5T', tz='dateutil/US/Eastern') diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py index 9fbdb714d8cfa..752d12743a5d3 100644 --- a/pandas/tseries/tests/test_timezones.py +++ b/pandas/tseries/tests/test_timezones.py @@ -443,7 +443,7 @@ def test_ambiguous_infer(self): localized_old = di.tz_localize(tz, infer_dst=True) self.assert_numpy_array_equal(dr, localized_old) self.assert_numpy_array_equal(dr, DatetimeIndex(times, tz=tz, ambiguous='infer')) - + # When there is no dst transition, nothing special happens dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=datetools.Hour()) @@ -463,31 +463,31 @@ def test_ambiguous_flags(self): times = ['11/06/2011 00:00', '11/06/2011 01:00', '11/06/2011 01:00', '11/06/2011 02:00', '11/06/2011 03:00'] - + # Test tz_localize di = DatetimeIndex(times) is_dst = [1, 1, 0, 0, 0] localized = di.tz_localize(tz, ambiguous=is_dst) self.assert_numpy_array_equal(dr, localized) self.assert_numpy_array_equal(dr, DatetimeIndex(times, tz=tz, ambiguous=is_dst)) - + localized = di.tz_localize(tz, ambiguous=np.array(is_dst)) self.assert_numpy_array_equal(dr, localized) - + localized = di.tz_localize(tz, ambiguous=np.array(is_dst).astype('bool')) self.assert_numpy_array_equal(dr, localized) - + # Test constructor localized = DatetimeIndex(times, tz=tz, ambiguous=is_dst) self.assert_numpy_array_equal(dr, localized) - + # Test duplicate times where infer_dst fails times += times di = DatetimeIndex(times) - + # When the sizes are incompatible, make sure error is raised self.assertRaises(Exception, di.tz_localize, tz, ambiguous=is_dst) - + # When sizes are compatible and there are repeats ('infer' won't work) is_dst = np.hstack((is_dst, is_dst)) localized = di.tz_localize(tz, ambiguous=is_dst) @@ -501,7 +501,7 @@ def test_ambiguous_flags(self): localized = dr.tz_localize(tz) localized_is_dst = dr.tz_localize(tz, ambiguous=is_dst) self.assert_numpy_array_equal(localized, localized_is_dst) - + def test_ambiguous_nat(self): tz = self.tz('US/Eastern') times = ['11/06/2011 00:00', '11/06/2011 01:00', @@ -509,7 +509,7 @@ def test_ambiguous_nat(self): '11/06/2011 03:00'] di = DatetimeIndex(times) localized = di.tz_localize(tz, ambiguous='NaT') - + times = ['11/06/2011 00:00', np.NaN, np.NaN, '11/06/2011 02:00', '11/06/2011 03:00'] diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index ad0ef67b5aca2..679fd2992855c 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -1,5 +1,5 @@ import nose - +from distutils.version import LooseVersion import numpy as np from pandas import tslib @@ -137,13 +137,24 @@ def test_constructor_with_stringoffset(self): self.assertEqual(result, eval(repr(result))) def test_repr(self): + tm._skip_if_no_pytz() + tm._skip_if_no_dateutil() + dates = ['2014-03-07', '2014-01-01 09:00', '2014-01-01 00:00:00.000000001'] - timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/America/Los_Angeles'] + + # dateutil zone change (only matters for repr) + import dateutil + if dateutil.__version__ >= LooseVersion('2.3'): + timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific'] + else: + timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/America/Los_Angeles'] + freqs = ['D', 'M', 'S', 'N'] for date in dates: for tz in timezones: for freq in freqs: + # avoid to match with timezone name freq_repr = "'{0}'".format(freq) if tz.startswith('dateutil'): @@ -306,10 +317,10 @@ def test_now(self): ts_from_string = Timestamp('now') ts_from_method = Timestamp.now() ts_datetime = datetime.datetime.now() - + ts_from_string_tz = Timestamp('now', tz='US/Eastern') ts_from_method_tz = Timestamp.now(tz='US/Eastern') - + # Check that the delta between the times is less than 1s (arbitrarily small) delta = Timedelta(seconds=1) self.assertTrue((ts_from_method - ts_from_string) < delta) @@ -321,10 +332,10 @@ def test_today(self): ts_from_string = Timestamp('today') ts_from_method = Timestamp.today() ts_datetime = datetime.datetime.today() - + ts_from_string_tz = Timestamp('today', tz='US/Eastern') ts_from_method_tz = Timestamp.today(tz='US/Eastern') - + # Check that the delta between the times is less than 1s (arbitrarily small) delta = Timedelta(seconds=1) self.assertTrue((ts_from_method - ts_from_string) < delta) @@ -737,7 +748,7 @@ def test_resolution(self): for freq, expected in zip(['A', 'Q', 'M', 'D', 'H', 'T', 'S', 'L', 'U'], [tslib.D_RESO, tslib.D_RESO, tslib.D_RESO, tslib.D_RESO, tslib.H_RESO, tslib.T_RESO,tslib.S_RESO, tslib.MS_RESO, tslib.US_RESO]): - for tz in [None, 'Asia/Tokyo', 'US/Eastern']: + for tz in [None, 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Eastern']: idx = date_range(start='2013-04-01', periods=30, freq=freq, tz=tz) result = tslib.resolution(idx.asi8, idx.tz) self.assertEqual(result, expected) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 1976eee96296c..e3e18b912132d 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -133,8 +133,8 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, offset=None, box=False): dt = dt + tz.utcoffset(dt) result[i] = dt else: - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + for i in range(n): value = arr[i] @@ -223,10 +223,10 @@ class Timestamp(_Timestamp): @classmethod def now(cls, tz=None): - """ + """ Return the current time in the local timezone. Equivalent to datetime.now([tz]) - + Parameters ---------- tz : string / timezone object, default None @@ -242,7 +242,7 @@ class Timestamp(_Timestamp): Return the current time in the local timezone. This differs from datetime.today() in that it can be localized to a passed timezone. - + Parameters ---------- tz : string / timezone object, default None @@ -1045,12 +1045,12 @@ cdef convert_to_tsobject(object ts, object tz, object unit): if util.is_string_object(ts): if ts in _nat_strings: ts = NaT - elif ts == 'now': - # Issue 9000, we short-circuit rather than going + elif ts == 'now': + # Issue 9000, we short-circuit rather than going # into np_datetime_strings which returns utc ts = Timestamp.now(tz) - elif ts == 'today': - # Issue 9000, we short-circuit rather than going + elif ts == 'today': + # Issue 9000, we short-circuit rather than going # into np_datetime_strings which returns a normalized datetime ts = Timestamp.today(tz) else: @@ -1174,8 +1174,8 @@ cdef inline void _localize_tso(_TSObject obj, object tz): obj.tzinfo = tz else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + pos = trans.searchsorted(obj.value, side='right') - 1 @@ -2566,8 +2566,8 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): * 1000000000) utc_dates[i] = v - delta else: - deltas = _get_deltas(tz1) - trans = _get_transitions(tz1) + trans, deltas, typ = _get_dst_info(tz1) + trans_len = len(trans) pos = trans.searchsorted(vals[0]) - 1 if pos < 0: @@ -2598,9 +2598,9 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): return result # Convert UTC to other timezone - trans = _get_transitions(tz2) + trans, deltas, typ = _get_dst_info(tz2) trans_len = len(trans) - deltas = _get_deltas(tz2) + pos = trans.searchsorted(utc_dates[0]) - 1 if pos < 0: raise ValueError('First time before start of DST info') @@ -2639,8 +2639,7 @@ def tz_convert_single(int64_t val, object tz1, object tz2): delta = int(total_seconds(_get_utcoffset(tz1, dt))) * 1000000000 utc_date = val - delta elif _get_zone(tz1) != 'UTC': - deltas = _get_deltas(tz1) - trans = _get_transitions(tz1) + trans, deltas, typ = _get_dst_info(tz1) pos = trans.searchsorted(val, side='right') - 1 if pos < 0: raise ValueError('First time before start of DST info') @@ -2658,8 +2657,8 @@ def tz_convert_single(int64_t val, object tz1, object tz2): delta = int(total_seconds(_get_utcoffset(tz2, dt))) * 1000000000 return utc_date + delta # Convert UTC to other timezone - trans = _get_transitions(tz2) - deltas = _get_deltas(tz2) + trans, deltas, typ = _get_dst_info(tz2) + pos = trans.searchsorted(utc_date, side='right') - 1 if pos < 0: raise ValueError('First time before start of DST info') @@ -2668,8 +2667,7 @@ def tz_convert_single(int64_t val, object tz1, object tz2): return utc_date + offset # Timezone data caches, key is the pytz string or dateutil file name. -trans_cache = {} -utc_offset_cache = {} +dst_cache = {} cdef inline bint _treat_tz_as_pytz(object tz): return hasattr(tz, '_utc_transition_times') and hasattr(tz, '_transition_info') @@ -2708,40 +2706,67 @@ cdef inline object _tz_cache_key(object tz): return None -cdef object _get_transitions(object tz): +cdef object _get_dst_info(object tz): """ - Get UTC times of DST transitions + return a tuple of : + (UTC times of DST transitions, + UTC offsets in microseconds corresponding to DST transitions, + string of type of transitions) + """ cache_key = _tz_cache_key(tz) if cache_key is None: - return np.array([NPY_NAT + 1], dtype=np.int64) + num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 + return (np.array([NPY_NAT + 1], dtype=np.int64), + np.array([num], dtype=np.int64), + None) - if cache_key not in trans_cache: + if cache_key not in dst_cache: if _treat_tz_as_pytz(tz): - arr = np.array(tz._utc_transition_times, dtype='M8[ns]') - arr = arr.view('i8') + trans = np.array(tz._utc_transition_times, dtype='M8[ns]') + trans = trans.view('i8') try: if tz._utc_transition_times[0].year == 1: - arr[0] = NPY_NAT + 1 + trans[0] = NPY_NAT + 1 except Exception: pass + deltas = _unbox_utcoffsets(tz._transition_info) + typ = 'pytz' + elif _treat_tz_as_dateutil(tz): if len(tz._trans_list): # get utc trans times trans_list = _get_utc_trans_times_from_dateutil_tz(tz) - arr = np.hstack([np.array([0], dtype='M8[s]'), # place holder for first item - np.array(trans_list, dtype='M8[s]')]).astype('M8[ns]') # all trans listed - arr = arr.view('i8') - arr[0] = NPY_NAT + 1 + trans = np.hstack([np.array([0], dtype='M8[s]'), # place holder for first item + np.array(trans_list, dtype='M8[s]')]).astype('M8[ns]') # all trans listed + trans = trans.view('i8') + trans[0] = NPY_NAT + 1 + + # deltas + deltas = np.array([v.offset for v in (tz._ttinfo_before,) + tz._trans_idx], dtype='i8') # + (tz._ttinfo_std,) + deltas *= 1000000000 + typ = 'dateutil' + elif _is_fixed_offset(tz): - arr = np.array([NPY_NAT + 1], dtype=np.int64) + trans = np.array([NPY_NAT + 1], dtype=np.int64) + deltas = np.array([tz._ttinfo_std.offset], dtype='i8') * 1000000000 + typ = 'fixed' else: - arr = np.array([], dtype='M8[ns]') + trans = np.array([], dtype='M8[ns]') + deltas = np.array([], dtype='i8') + typ = None + + else: - arr = np.array([NPY_NAT + 1], dtype=np.int64) - trans_cache[cache_key] = arr - return trans_cache[cache_key] + # static tzinfo + trans = np.array([NPY_NAT + 1], dtype=np.int64) + num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 + deltas = np.array([num], dtype=np.int64) + typ = 'static' + + dst_cache[cache_key] = (trans, deltas, typ) + return dst_cache[cache_key] cdef object _get_utc_trans_times_from_dateutil_tz(object tz): ''' @@ -2756,35 +2781,6 @@ cdef object _get_utc_trans_times_from_dateutil_tz(object tz): new_trans[i] = trans - last_std_offset return new_trans - -cdef object _get_deltas(object tz): - """ - Get UTC offsets in microseconds corresponding to DST transitions - """ - cache_key = _tz_cache_key(tz) - if cache_key is None: - num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 - return np.array([num], dtype=np.int64) - - if cache_key not in utc_offset_cache: - if _treat_tz_as_pytz(tz): - utc_offset_cache[cache_key] = _unbox_utcoffsets(tz._transition_info) - elif _treat_tz_as_dateutil(tz): - if len(tz._trans_list): - arr = np.array([v.offset for v in (tz._ttinfo_before,) + tz._trans_idx], dtype='i8') # + (tz._ttinfo_std,) - arr *= 1000000000 - utc_offset_cache[cache_key] = arr - elif _is_fixed_offset(tz): - utc_offset_cache[cache_key] = np.array([tz._ttinfo_std.offset], dtype='i8') * 1000000000 - else: - utc_offset_cache[cache_key] = np.array([], dtype='i8') - else: - # static tzinfo - num = int(total_seconds(_get_utcoffset(tz, None))) * 1000000000 - utc_offset_cache[cache_key] = np.array([num], dtype=np.int64) - - return utc_offset_cache[cache_key] - def tot_seconds(td): return total_seconds(td) @@ -2852,8 +2848,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None): if len(ambiguous) != len(vals): raise ValueError("Length of ambiguous bool-array must be the same size as vals") - trans = _get_transitions(tz) # transition dates - deltas = _get_deltas(tz) # utc offsets + trans, deltas, typ = _get_dst_info(tz) tdata = <int64_t*> trans.data ntrans = len(trans) @@ -3464,15 +3459,15 @@ cdef _normalize_local(ndarray[int64_t] stamps, object tz): result[i] = _normalized_stamp(&dts) else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + _pos = trans.searchsorted(stamps, side='right') - 1 if _pos.dtype != np.int64: _pos = _pos.astype(np.int64) pos = _pos # statictzinfo - if not hasattr(tz, '_transition_info'): + if typ not in ['pytz','dateutil']: for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT @@ -3521,8 +3516,8 @@ def dates_normalized(ndarray[int64_t] stamps, tz=None): if dt.hour > 0: return False else: - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + for i in range(n): # Adjust datetime64 timestamp, recompute datetimestruct pos = trans.searchsorted(stamps[i]) - 1 @@ -3609,15 +3604,15 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps, dts.hour, dts.min, dts.sec, dts.us, dts.ps, freq) else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + _pos = trans.searchsorted(stamps, side='right') - 1 if _pos.dtype != np.int64: _pos = _pos.astype(np.int64) pos = _pos # statictzinfo - if not hasattr(tz, '_transition_info'): + if typ not in ['pytz','dateutil']: for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT @@ -4111,15 +4106,15 @@ cdef _reso_local(ndarray[int64_t] stamps, object tz): reso = curr_reso else: # Adjust datetime64 timestamp, recompute datetimestruct - trans = _get_transitions(tz) - deltas = _get_deltas(tz) + trans, deltas, typ = _get_dst_info(tz) + _pos = trans.searchsorted(stamps, side='right') - 1 if _pos.dtype != np.int64: _pos = _pos.astype(np.int64) pos = _pos # statictzinfo - if not hasattr(tz, '_transition_info'): + if typ not in ['pytz','dateutil']: for i in range(n): if stamps[i] == NPY_NAT: continue
xref #8639
https://api.github.com/repos/pandas-dev/pandas/pulls/9047
2014-12-09T01:21:31Z
2014-12-10T11:11:03Z
2014-12-10T11:11:03Z
2014-12-10T11:11:03Z
Fix timedelta json on windows
diff --git a/pandas/src/datetime_helper.h b/pandas/src/datetime_helper.h index 8e188a431a086..c8c54dd5fc947 100644 --- a/pandas/src/datetime_helper.h +++ b/pandas/src/datetime_helper.h @@ -1,4 +1,7 @@ #include "datetime.h" +#include "numpy/arrayobject.h" +#include "numpy/arrayscalars.h" +#include <stdio.h> #if PY_MAJOR_VERSION >= 3 #define PyInt_AS_LONG PyLong_AsLong @@ -9,15 +12,16 @@ void mangle_nat(PyObject *val) { PyDateTime_GET_DAY(val) = -1; } -long get_long_attr(PyObject *o, const char *attr) { - return PyInt_AS_LONG(PyObject_GetAttrString(o, attr)); +npy_int64 get_long_attr(PyObject *o, const char *attr) { + PyObject *value = PyObject_GetAttrString(o, attr); + return PyLong_Check(value) ? PyLong_AsLongLong(value) : PyInt_AS_LONG(value); } -double total_seconds(PyObject *td) { +npy_float64 total_seconds(PyObject *td) { // Python 2.6 compat - long microseconds = get_long_attr(td, "microseconds"); - long seconds = get_long_attr(td, "seconds"); - long days = get_long_attr(td, "days"); - long days_in_seconds = days * 24 * 3600; + npy_int64 microseconds = get_long_attr(td, "microseconds"); + npy_int64 seconds = get_long_attr(td, "seconds"); + npy_int64 days = get_long_attr(td, "days"); + npy_int64 days_in_seconds = days * 24LL * 3600LL; return (microseconds + (seconds + days_in_seconds) * 1000000.0) / 1000000.0; } diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c index 00ba8975d58c8..25fbb71482f9e 100644 --- a/pandas/src/ujson/python/objToJSON.c +++ b/pandas/src/ujson/python/objToJSON.c @@ -1452,12 +1452,12 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) else if (PyDelta_Check(obj)) { - long value; + npy_int64 value; - if (PyObject_HasAttrString(obj, "value")) + if (PyObject_HasAttrString(obj, "value")) { value = get_long_attr(obj, "value"); - else - value = total_seconds(obj) * 1000000000; // nanoseconds per second + } else + value = total_seconds(obj) * 1000000000LL; // nanoseconds per second exc = PyErr_Occurred();
some fixes for different int sizes on windows
https://api.github.com/repos/pandas-dev/pandas/pulls/9044
2014-12-08T15:29:40Z
2014-12-08T16:32:56Z
2014-12-08T16:32:56Z
2014-12-09T00:51:22Z
BUG: series.fillna() fails with quoted numbers
diff --git a/pandas/core/internals.py b/pandas/core/internals.py index ef33e27d861fd..7a84f2c399671 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -4009,7 +4009,7 @@ def _putmask_smart(v, m, n): nv = v.copy() nv[m] = nn_at return nv - except (ValueError, IndexError, TypeError): + except (ValueError, IndexError, TypeError, AttributeError): pass # change the dtype
Here's a simple example: ``` python import pandas as pd import numpy as np x = pd.Series(range(5)) x.iloc[1] = np.nan x.fillna(0) # works x.fillna('foo') # works x.fillna('0') # crash ``` in the function `_putmask_smart()`, two numpy arrays are compared to determine if they have compatible dtypes. However if one array contains quoted numbers, then the test does NOT resolve as element wise compare, but rather as a "normal" python comparison. This means the result is `False`, rather than an array, and the attempt to get `False.all()` obviously fails. Not sure exactly why the arrays don't compare as expected -- perhaps there are other criteria that would trigger it -- but an easy fix is to add `AttributeError` to the try/except clause as a "valid" error.
https://api.github.com/repos/pandas-dev/pandas/pulls/9043
2014-12-08T14:44:13Z
2015-05-09T16:05:40Z
null
2022-10-13T00:16:19Z
ENH: Store in SQL using double precision
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index b3ac58a9fb84a..999f0cd0be8e7 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -202,3 +202,4 @@ Bug Fixes - Fixed issue in the ``xlsxwriter`` engine where it added a default 'General' format to cells if no other format wass applied. This prevented other row or column formatting being applied. (:issue:`9167`) - Fixes issue with ``index_col=False`` when ``usecols`` is also specified in ``read_csv``. (:issue:`9082`) - Bug where ``wide_to_long`` would modify the input stubnames list (:issue:`9204`) +- Bug in to_sql not storing float64 values using double precision. (:issue:`9009`) diff --git a/pandas/io/sql.py b/pandas/io/sql.py index b4318bdc2a3bf..cd1c40b7b075a 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -908,7 +908,7 @@ def _sqlalchemy_type(self, col): col_type = self._get_notnull_col_dtype(col) - from sqlalchemy.types import (BigInteger, Float, Text, Boolean, + from sqlalchemy.types import (BigInteger, Integer, Float, Text, Boolean, DateTime, Date, Time) if col_type == 'datetime64' or col_type == 'datetime': @@ -923,10 +923,15 @@ def _sqlalchemy_type(self, col): "database.", UserWarning) return BigInteger elif col_type == 'floating': - return Float + if col.dtype == 'float32': + return Float(precision=23) + else: + return Float(precision=53) elif col_type == 'integer': - # TODO: Refine integer size. - return BigInteger + if col.dtype == 'int32': + return Integer + else: + return BigInteger elif col_type == 'boolean': return Boolean elif col_type == 'date': @@ -1187,9 +1192,17 @@ def has_table(self, name, schema=None): def get_table(self, table_name, schema=None): schema = schema or self.meta.schema if schema: - return self.meta.tables.get('.'.join([schema, table_name])) + tbl = self.meta.tables.get('.'.join([schema, table_name])) else: - return self.meta.tables.get(table_name) + tbl = self.meta.tables.get(table_name) + + # Avoid casting double-precision floats into decimals + from sqlalchemy import Numeric + for column in tbl.columns: + if isinstance(column.type, Numeric): + column.type.asdecimal = False + + return tbl def drop_table(self, table_name, schema=None): schema = schema or self.meta.schema @@ -1198,8 +1211,9 @@ def drop_table(self, table_name, schema=None): self.get_table(table_name, schema).drop() self.meta.clear() - def _create_sql_schema(self, frame, table_name, keys=None): - table = SQLTable(table_name, self, frame=frame, index=False, keys=keys) + def _create_sql_schema(self, frame, table_name, keys=None, dtype=None): + table = SQLTable(table_name, self, frame=frame, index=False, keys=keys, + dtype=dtype) return str(table.sql_schema()) @@ -1213,7 +1227,7 @@ def _create_sql_schema(self, frame, table_name, keys=None): 'sqlite': 'TEXT', }, 'floating': { - 'mysql': 'FLOAT', + 'mysql': 'DOUBLE', 'sqlite': 'REAL', }, 'integer': { @@ -1520,13 +1534,13 @@ def drop_table(self, name, schema=None): drop_sql = "DROP TABLE %s" % name self.execute(drop_sql) - def _create_sql_schema(self, frame, table_name, keys=None): + def _create_sql_schema(self, frame, table_name, keys=None, dtype=None): table = SQLiteTable(table_name, self, frame=frame, index=False, - keys=keys) + keys=keys, dtype=dtype) return str(table.sql_schema()) -def get_schema(frame, name, flavor='sqlite', keys=None, con=None): +def get_schema(frame, name, flavor='sqlite', keys=None, con=None, dtype=None): """ Get the SQL db table schema for the given frame. @@ -1545,11 +1559,14 @@ def get_schema(frame, name, flavor='sqlite', keys=None, con=None): Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type, or a string for sqlite3 fallback connection. """ pandas_sql = pandasSQL_builder(con=con, flavor=flavor) - return pandas_sql._create_sql_schema(frame, name, keys=keys) + return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype) # legacy names, with depreciation warnings and copied docs diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index b185d530e056c..1d581b00e4b3c 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -651,6 +651,14 @@ def test_get_schema(self): con=self.conn) self.assertTrue('CREATE' in create_sql) + def test_get_schema_dtypes(self): + float_frame = DataFrame({'a':[1.1,1.2], 'b':[2.1,2.2]}) + dtype = sqlalchemy.Integer if self.mode == 'sqlalchemy' else 'INTEGER' + create_sql = sql.get_schema(float_frame, 'test', 'sqlite', + con=self.conn, dtype={'b':dtype}) + self.assertTrue('CREATE' in create_sql) + self.assertTrue('INTEGER' in create_sql) + def test_chunksize_read(self): df = DataFrame(np.random.randn(22, 5), columns=list('abcde')) df.to_sql('test_chunksize', self.conn, index=False) @@ -1233,7 +1241,6 @@ def test_dtype(self): df.to_sql('dtype_test3', self.conn, dtype={'B': sqlalchemy.String(10)}) meta.reflect() sqltype = meta.tables['dtype_test3'].columns['B'].type - print(sqltype) self.assertTrue(isinstance(sqltype, sqlalchemy.String)) self.assertEqual(sqltype.length, 10) @@ -1262,6 +1269,36 @@ def test_notnull_dtype(self): self.assertTrue(isinstance(col_dict['Int'].type, sqltypes.Integer)) self.assertTrue(isinstance(col_dict['Float'].type, sqltypes.Float)) + def test_double_precision(self): + V = 1.23456789101112131415 + + df = DataFrame({'f32':Series([V,], dtype='float32'), + 'f64':Series([V,], dtype='float64'), + 'f64_as_f32':Series([V,], dtype='float64'), + 'i32':Series([5,], dtype='int32'), + 'i64':Series([5,], dtype='int64'), + }) + + df.to_sql('test_dtypes', self.conn, index=False, if_exists='replace', + dtype={'f64_as_f32':sqlalchemy.Float(precision=23)}) + res = sql.read_sql_table('test_dtypes', self.conn) + + # check precision of float64 + self.assertEqual(np.round(df['f64'].iloc[0],14), + np.round(res['f64'].iloc[0],14)) + + # check sql types + meta = sqlalchemy.schema.MetaData(bind=self.conn) + meta.reflect() + col_dict = meta.tables['test_dtypes'].columns + self.assertEqual(str(col_dict['f32'].type), + str(col_dict['f64_as_f32'].type)) + self.assertTrue(isinstance(col_dict['f32'].type, sqltypes.Float)) + self.assertTrue(isinstance(col_dict['f64'].type, sqltypes.Float)) + self.assertTrue(isinstance(col_dict['i32'].type, sqltypes.Integer)) + self.assertTrue(isinstance(col_dict['i64'].type, sqltypes.BigInteger)) + + class TestSQLiteAlchemy(_TestSQLAlchemy): """
Closes #9009 . @jorisvandenbossche -- do you think this should test/use single precision ? We could test for float32 perhaps? My own feeling is that this is the safer default.
https://api.github.com/repos/pandas-dev/pandas/pulls/9041
2014-12-08T08:17:20Z
2015-01-25T18:01:04Z
2015-01-25T18:01:04Z
2015-01-25T18:01:21Z
Return from to_timedelta is forced to dtype timedelta64[ns].
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index f034e0e223e6b..a2728c2d82d61 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -268,3 +268,5 @@ Bug Fixes - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) - Bug in Datareader returns object dtype if there are missing values (:issue:`8980`) - Bug in plotting if sharex was enabled and index was a timeseries, would show labels on multiple axes (:issue:`3964`). + +- Bug where passing a unit to the TimedeltaIndex constructor applied the to nano-second conversion twice. (:issue:`9011`). diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index 494a9cc95dc49..de23ddcc397d9 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -525,6 +525,22 @@ def conv(v): expected = TimedeltaIndex([ np.timedelta64(1,'D') ]*5) tm.assert_index_equal(result, expected) + # Test with lists as input when box=false + expected = np.array(np.arange(3)*1000000000, dtype='timedelta64[ns]') + result = to_timedelta(range(3), unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + + result = to_timedelta(np.arange(3), unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + + result = to_timedelta([0, 1, 2], unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + + # Tests with fractional seconds as input: + expected = np.array([0, 500000000, 800000000, 1200000000], dtype='timedelta64[ns]') + result = to_timedelta([0., 0.5, 0.8, 1.2], unit='s', box=False) + tm.assert_numpy_array_equal(expected, result) + def testit(unit, transform): # array @@ -852,6 +868,13 @@ def test_constructor(self): pd.offsets.Second(3)]) tm.assert_index_equal(result,expected) + expected = TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02']) + tm.assert_index_equal(TimedeltaIndex(range(3), unit='s'), expected) + expected = TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:05', '0 days 00:00:09']) + tm.assert_index_equal(TimedeltaIndex([0, 5, 9], unit='s'), expected) + expected = TimedeltaIndex(['0 days 00:00:00.400', '0 days 00:00:00.450', '0 days 00:00:01.200']) + tm.assert_index_equal(TimedeltaIndex([400, 450, 1200], unit='ms'), expected) + def test_constructor_coverage(self): rng = timedelta_range('1 days', periods=10.5) exp = timedelta_range('1 days', periods=10) diff --git a/pandas/tseries/timedeltas.py b/pandas/tseries/timedeltas.py index dc60f5024c9ed..91e75da1b551c 100644 --- a/pandas/tseries/timedeltas.py +++ b/pandas/tseries/timedeltas.py @@ -52,6 +52,7 @@ def _convert_listlike(arg, box, unit): value = np.array([ _get_string_converter(r, unit=unit)() for r in arg ],dtype='m8[ns]') except: value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit, coerce=coerce) for r in arg ]) + value = value.astype('timedelta64[ns]', copy=False) if box: from pandas import TimedeltaIndex
This is a revised change, fixing the issue I experienced (issue #9011). The proper change seems to be setting the dtype to `'timedelta64[ns]'`, as was already done for the other cases in the `to_timedelta` routine. I have also added more tests, and moved them to the `test_timedeltas` function (next to the other tests of the functionality of the constructor method). I have not looked too much at #8886, it is difficult for me to understand the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/9040
2014-12-08T07:38:36Z
2014-12-09T21:23:19Z
2014-12-09T21:23:19Z
2014-12-12T14:37:30Z
DOC: expand docs on sql type conversion
diff --git a/doc/source/io.rst b/doc/source/io.rst index f2d5924edac77..2ec61f7f00bd8 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3393,12 +3393,34 @@ the database using :func:`~pandas.DataFrame.to_sql`. data.to_sql('data', engine) -With some databases, writing large DataFrames can result in errors due to packet size limitations being exceeded. This can be avoided by setting the ``chunksize`` parameter when calling ``to_sql``. For example, the following writes ``data`` to the database in batches of 1000 rows at a time: +With some databases, writing large DataFrames can result in errors due to +packet size limitations being exceeded. This can be avoided by setting the +``chunksize`` parameter when calling ``to_sql``. For example, the following +writes ``data`` to the database in batches of 1000 rows at a time: .. ipython:: python data.to_sql('data_chunked', engine, chunksize=1000) +SQL data types +"""""""""""""" + +:func:`~pandas.DataFrame.to_sql` will try to map your data to an appropriate +SQL data type based on the dtype of the data. When you have columns of dtype +``object``, pandas will try to infer the data type. + +You can always override the default type by specifying the desired SQL type of +any of the columns by using the ``dtype`` argument. This argument needs a +dictionary mapping column names to SQLAlchemy types (or strings for the sqlite3 +fallback mode). +For example, specifying to use the sqlalchemy ``String`` type instead of the +default ``Text`` type for string columns: + +.. ipython:: python + + from sqlalchemy.types import String + data.to_sql('data_dtype', engine, dtype={'Col_1': String}) + .. note:: Due to the limited support for timedelta's in the different database @@ -3413,15 +3435,6 @@ With some databases, writing large DataFrames can result in errors due to packet Because of this, reading the database table back in does **not** generate a categorical. -.. note:: - - You can specify the SQL type of any of the columns by using the dtypes - parameter (a dictionary mapping column names to SQLAlchemy types). This - can be useful in cases where columns with NULL values are inferred by - Pandas to an excessively general datatype (e.g. a boolean column is is - inferred to be object because it has NULLs). - - Reading Tables ~~~~~~~~~~~~~~ @@ -3782,11 +3795,11 @@ is lost when exporting. *Stata* only supports string value labels, and so ``str`` is called on the categories when exporting data. Exporting ``Categorical`` variables with - non-string categories produces a warning, and can result a loss of + non-string categories produces a warning, and can result a loss of information if the ``str`` representations of the categories are not unique. Labeled data can similarly be imported from *Stata* data files as ``Categorical`` -variables using the keyword argument ``convert_categoricals`` (``True`` by default). +variables using the keyword argument ``convert_categoricals`` (``True`` by default). The keyword argument ``order_categoricals`` (``True`` by default) determines whether imported ``Categorical`` variables are ordered. diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 419885ad4159b..8e2c7a862362a 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -96,7 +96,16 @@ API changes Enhancements ~~~~~~~~~~~~ -- Added the ability to specify the SQL type of columns when writing a DataFrame to a database (:issue:`8778`). +- Added the ability to specify the SQL type of columns when writing a DataFrame + to a database (:issue:`8778`). + For example, specifying to use the sqlalchemy ``String`` type instead of the + default ``Text`` type for string columns: + + .. code-block:: + + from sqlalchemy.types import String + data.to_sql('data_dtype', engine, dtype={'Col_1': String}) + - Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. - Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. - Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d63643c53e6f4..0fc7171410152 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -954,8 +954,9 @@ def to_sql(self, name, con, flavor='sqlite', schema=None, if_exists='fail', chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : Dictionary of column name to SQLAlchemy type, default None - Optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type, or a string for sqlite3 fallback connection. """ from pandas.io import sql @@ -4128,7 +4129,7 @@ def func(self, axis=None, dtype=None, out=None, skipna=True, y = _values_from_object(self).copy() - if skipna and issubclass(y.dtype.type, + if skipna and issubclass(y.dtype.type, (np.datetime64, np.timedelta64)): result = accum_func(y, axis) mask = isnull(self) diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 77527f867fad8..ea6239f080caa 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -518,8 +518,9 @@ def to_sql(frame, name, con, flavor='sqlite', schema=None, if_exists='fail', chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : dictionary of column name to SQLAchemy type, default None - optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type, or a string for sqlite3 fallback connection. """ if if_exists not in ('fail', 'replace', 'append'): @@ -1133,8 +1134,9 @@ def to_sql(self, frame, name, if_exists='fail', index=True, chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : dictionary of column name to SQLAlchemy type, default None - Optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a SQLAlchemy type. """ if dtype is not None: @@ -1468,8 +1470,9 @@ def to_sql(self, frame, name, if_exists='fail', index=True, chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - dtype : dictionary of column_name to SQLite string type, default None - optional datatypes for SQL columns. + dtype : dict of column name to SQL type, default None + Optional specifying the datatype for columns. The SQL type should + be a string. """ if dtype is not None:
Some doc changes related to #8926 and #8973
https://api.github.com/repos/pandas-dev/pandas/pulls/9038
2014-12-07T21:21:55Z
2014-12-08T11:59:49Z
2014-12-08T11:59:49Z
2014-12-08T11:59:49Z
COMPAT: dateutil fixups for 2.3 (GH9021, GH8639)
diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index 1fd2d7b8fa8e5..cf82733c6629d 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -104,12 +104,12 @@ def test_timestamp_tz_arg_dateutil(self): import dateutil from pandas.tslib import maybe_get_tz p = Period('1/1/2005', freq='M').to_timestamp(tz=maybe_get_tz('dateutil/Europe/Brussels')) - self.assertEqual(p.tz, dateutil.tz.gettz('Europe/Brussels')) + self.assertEqual(p.tz, dateutil.zoneinfo.gettz('Europe/Brussels')) def test_timestamp_tz_arg_dateutil_from_string(self): import dateutil p = Period('1/1/2005', freq='M').to_timestamp(tz='dateutil/Europe/Brussels') - self.assertEqual(p.tz, dateutil.tz.gettz('Europe/Brussels')) + self.assertEqual(p.tz, dateutil.zoneinfo.gettz('Europe/Brussels')) def test_timestamp_nat_tz(self): t = Period('NaT', freq='M').to_timestamp() diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index b9ccb76b59c59..1976eee96296c 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -37,8 +37,12 @@ cimport cython from datetime import timedelta, datetime from datetime import time as datetime_time + +# dateutil compat from dateutil.tz import (tzoffset, tzlocal as _dateutil_tzlocal, tzfile as _dateutil_tzfile, - tzutc as _dateutil_tzutc, gettz as _dateutil_gettz) + tzutc as _dateutil_tzutc) +from dateutil.zoneinfo import gettz as _dateutil_gettz + from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo from pandas.compat import parse_date, string_types, PY3, iteritems @@ -1258,7 +1262,7 @@ cpdef inline object maybe_get_tz(object tz): if isinstance(tz, string_types): if tz.startswith('dateutil/'): zone = tz[9:] - tz = _dateutil_gettz(tz[9:]) + tz = _dateutil_gettz(zone) # On Python 3 on Windows, the filename is not always set correctly. if isinstance(tz, _dateutil_tzfile) and '.tar.gz' in tz._filename: tz._filename = zone
fixes #9021 but going to reopen #8639
https://api.github.com/repos/pandas-dev/pandas/pulls/9036
2014-12-07T20:51:49Z
2014-12-07T22:26:13Z
2014-12-07T22:26:13Z
2014-12-08T14:46:53Z
DOC: fix categorical comparison example (GH8946)
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index d10524e5d392f..91cfa77bc618c 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -356,9 +356,9 @@ Comparisons Comparing categorical data with other objects is possible in three cases: * comparing equality (``==`` and ``!=``) to a list-like object (list, Series, array, - ...) of the same length as the categorical data or + ...) of the same length as the categorical data. * all comparisons (``==``, ``!=``, ``>``, ``>=``, ``<``, and ``<=``) of categorical data to - another categorical Series, when ``ordered==True`` and the `categories` are the same or + another categorical Series, when ``ordered==True`` and the `categories` are the same. * all comparisons of a categorical data to a scalar. All other comparisons, especially "non-equality" comparisons of two categoricals with different @@ -392,7 +392,8 @@ Equality comparisons work with any list-like object of same length and scalars: .. ipython:: python - cat == cat_base2 + cat == cat_base + cat == np.array([1,2,3]) cat == 2 This doesn't work because the categories are not the same:
See discussion https://github.com/pydata/pandas/pull/8946/files#r21376839
https://api.github.com/repos/pandas-dev/pandas/pulls/9035
2014-12-07T20:38:08Z
2014-12-07T21:42:53Z
2014-12-07T21:42:53Z
2014-12-07T21:42:53Z
Calling qcut with too many duplicates now gives an informative error
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 58dc1da214c05..5bd78ec6b439a 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -164,7 +164,7 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) - Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) - +- Fixed an unclear error message in ``qcut`` when repeated values result in duplicate bin edges. diff --git a/pandas/tools/tests/test_tile.py b/pandas/tools/tests/test_tile.py index 4a0218bef6001..c099ee787d2c9 100644 --- a/pandas/tools/tests/test_tile.py +++ b/pandas/tools/tests/test_tile.py @@ -153,7 +153,7 @@ def test_qcut_specify_quantiles(self): self.assertTrue(factor.equals(expected)) def test_qcut_all_bins_same(self): - assertRaisesRegexp(ValueError, "edges.*unique", qcut, [0,0,0,0,0,0,0,0,0,0], 3) + assertRaisesRegexp(ValueError, "quantiles.*repeated", qcut, [0,0,0,0,0,0,0,0,0,0], 3) def test_cut_out_of_bounds(self): arr = np.random.randn(100) diff --git a/pandas/tools/tile.py b/pandas/tools/tile.py index 6830919d9c09f..2f98f314c3afe 100644 --- a/pandas/tools/tile.py +++ b/pandas/tools/tile.py @@ -165,6 +165,10 @@ def qcut(x, q, labels=None, retbins=False, precision=3): else: quantiles = q bins = algos.quantile(x, quantiles) + if len(algos.unique(bins)) < len(bins): + bins_sorted = np.sort(bins, axis=None) + bins_dup = algos.unique(bins_sorted[bins_sorted[1:] == bins_sorted[:-1]]) + raise ValueError('One or more quantiles consists entirely of a repeated value: %s' % repr(bins_dup)) return _bins_to_cuts(x, bins, labels=labels, retbins=retbins,precision=precision, include_lowest=True)
Closes #7751.
https://api.github.com/repos/pandas-dev/pandas/pulls/9030
2014-12-06T23:27:06Z
2015-05-09T16:05:51Z
null
2022-10-13T00:16:18Z
BUG: Fixed maximum columns limit when using usecols for csv. #8985
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 58dc1da214c05..409ef8bee3662 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -164,6 +164,7 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) - Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) +- When using usecols csv reader only requires the minimum amount of columns instead of all (:issue:`8985`) diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index b23aa017138e1..e858b4bf0ced4 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1918,9 +1918,17 @@ def _rows_to_cols(self, content): # Loop through rows to verify lengths are correct. if col_len != zip_len and self.index_col is not False: i = 0 + incorrect_row = False + if self.usecols: + col_len = max(self.usecols) + 1 + for (i, l) in enumerate(content): if len(l) != col_len: - break + if self.usecols and len(l) > col_len: + continue + else: + incorrect_row = True + break footers = 0 if self.skip_footer: @@ -1930,7 +1938,8 @@ def _rows_to_cols(self, content): msg = ('Expected %d fields in line %d, saw %d' % (col_len, row_num + 1, zip_len)) - raise ValueError(msg) + if incorrect_row: + raise ValueError(msg) if self.usecols: if self._implicit_index: diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 2f211ab0381a2..e510b95bb094e 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -2090,6 +2090,23 @@ def test_parse_integers_above_fp_precision(self): self.assertTrue(np.array_equal(result['Numbers'], expected['Numbers'])) + def test_use_cols_minumum_fields_in_line(self): + # issue #8985 + data = """ +19,29,39 +19,29,39 +10,20,30,40""" + df = pd.read_csv(StringIO(data), engine='python', + header=None, usecols=list(range(3))) + self.assertEqual(len(df.columns), 3) + + df = pd.read_csv(StringIO(data), engine='python', + header=None, usecols=list(range(2))) + self.assertEqual(len(df.columns), 2) + + self.assertRaises(ValueError, self.read_csv, StringIO(data), + engine='python', usecols=list(range(4)), header=None) + def test_usecols_index_col_conflict(self): # Issue 4201 Test that index_col as integer reflects usecols data = """SecId,Time,Price,P2,P3
fixes #8985
https://api.github.com/repos/pandas-dev/pandas/pulls/9029
2014-12-06T22:47:34Z
2014-12-07T12:33:36Z
null
2014-12-07T12:33:36Z
Implement timedeltas for to_json
diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py index 5732bc90573fd..75a6f22488b41 100644 --- a/pandas/io/tests/test_json/test_pandas.py +++ b/pandas/io/tests/test_json/test_pandas.py @@ -4,8 +4,8 @@ import os import numpy as np -import nose from pandas import Series, DataFrame, DatetimeIndex, Timestamp +from datetime import timedelta import pandas as pd read_json = pd.read_json @@ -601,7 +601,6 @@ def test_url(self): self.assertEqual(result[c].dtype, 'datetime64[ns]') def test_timedelta(self): - from datetime import timedelta converter = lambda x: pd.to_timedelta(x,unit='ms') s = Series([timedelta(23), timedelta(seconds=5)]) @@ -613,17 +612,32 @@ def test_timedelta(self): assert_frame_equal( frame, pd.read_json(frame.to_json()).apply(converter)) - def test_default_handler(self): - from datetime import timedelta - - frame = DataFrame([timedelta(23), timedelta(seconds=5), 42]) - self.assertRaises(OverflowError, frame.to_json) + frame = DataFrame({'a': [timedelta(23), timedelta(seconds=5)], + 'b': [1, 2], + 'c': pd.date_range(start='20130101', periods=2)}) + result = pd.read_json(frame.to_json(date_unit='ns')) + result['a'] = pd.to_timedelta(result.a, unit='ns') + result['c'] = pd.to_datetime(result.c) + assert_frame_equal(frame, result) + + def test_mixed_timedelta_datetime(self): + frame = DataFrame({'a': [timedelta(23), pd.Timestamp('20130101')]}, + dtype=object) + expected = pd.read_json(frame.to_json(date_unit='ns'), + dtype={'a': 'int64'}) + assert_frame_equal(DataFrame({'a': [pd.Timedelta(frame.a[0]).value, + pd.Timestamp(frame.a[1]).value]}), + expected) - expected = DataFrame([str(timedelta(23)), str(timedelta(seconds=5)), 42]) - assert_frame_equal( - expected, pd.read_json(frame.to_json(default_handler=str))) + def test_default_handler(self): + value = object() + frame = DataFrame({'a': ['a', value]}) + expected = frame.applymap(str) + result = pd.read_json(frame.to_json(default_handler=str)) + assert_frame_equal(expected, result) + def test_default_handler_raises(self): def my_handler_raises(obj): raise TypeError("raisin") - self.assertRaises(TypeError, frame.to_json, + self.assertRaises(TypeError, DataFrame({'a': [1, 2, object()]}).to_json, default_handler=my_handler_raises) diff --git a/pandas/src/datetime_helper.h b/pandas/src/datetime_helper.h index 8be5f59728bb3..8e188a431a086 100644 --- a/pandas/src/datetime_helper.h +++ b/pandas/src/datetime_helper.h @@ -1,6 +1,23 @@ #include "datetime.h" +#if PY_MAJOR_VERSION >= 3 +#define PyInt_AS_LONG PyLong_AsLong +#endif + void mangle_nat(PyObject *val) { PyDateTime_GET_MONTH(val) = -1; PyDateTime_GET_DAY(val) = -1; } + +long get_long_attr(PyObject *o, const char *attr) { + return PyInt_AS_LONG(PyObject_GetAttrString(o, attr)); +} + +double total_seconds(PyObject *td) { + // Python 2.6 compat + long microseconds = get_long_attr(td, "microseconds"); + long seconds = get_long_attr(td, "seconds"); + long days = get_long_attr(td, "days"); + long days_in_seconds = days * 24 * 3600; + return (microseconds + (seconds + days_in_seconds) * 1000000.0) / 1000000.0; +} diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c index c1e9f8edcf423..00ba8975d58c8 100644 --- a/pandas/src/ujson/python/objToJSON.c +++ b/pandas/src/ujson/python/objToJSON.c @@ -41,11 +41,11 @@ Numeric decoder derived from from TCL library #include <numpy/arrayscalars.h> #include <np_datetime.h> #include <np_datetime_strings.h> +#include <datetime_helper.h> #include <numpy_helper.h> #include <numpy/npy_math.h> #include <math.h> #include <stdio.h> -#include <datetime.h> #include <ultrajson.h> static PyObject* type_decimal; @@ -154,6 +154,7 @@ enum PANDAS_FORMAT // import_array() compat #if (PY_VERSION_HEX >= 0x03000000) void *initObjToJSON(void) + #else void initObjToJSON(void) #endif @@ -1445,14 +1446,38 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc) PRINTMARK(); pc->PyTypeToJSON = NpyDateTimeToJSON; - if (enc->datetimeIso) - { - tc->type = JT_UTF8; - } + tc->type = enc->datetimeIso ? JT_UTF8 : JT_LONG; + return; + } + else + if (PyDelta_Check(obj)) + { + long value; + + if (PyObject_HasAttrString(obj, "value")) + value = get_long_attr(obj, "value"); else + value = total_seconds(obj) * 1000000000; // nanoseconds per second + + exc = PyErr_Occurred(); + + if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { - tc->type = JT_LONG; + PRINTMARK(); + goto INVALID; } + + if (value == get_nat()) { + PRINTMARK(); + tc->type = JT_NULL; + return; + } + + GET_TC(tc)->longValue = value; + + PRINTMARK(); + pc->PyTypeToJSON = PyLongToINT64; + tc->type = JT_LONG; return; } else diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 4cb6c93bdf3d0..3a3c14ac0cc58 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -20,6 +20,9 @@ cdef extern from "Python.h": cdef PyTypeObject *Py_TYPE(object) int PySlice_Check(object) +cdef extern from "datetime_helper.h": + double total_seconds(object) + # this is our datetime.pxd from datetime cimport * from util cimport is_integer_object, is_float_object, is_datetime64_object, is_timedelta64_object @@ -2753,10 +2756,6 @@ cdef object _get_deltas(object tz): return utc_offset_cache[cache_key] -cdef double total_seconds(object td): # Python 2.6 compat - return ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) // - 10**6) - def tot_seconds(td): return total_seconds(td)
Closes #9027
https://api.github.com/repos/pandas-dev/pandas/pulls/9028
2014-12-06T22:27:31Z
2014-12-07T20:25:34Z
2014-12-07T20:25:34Z
2014-12-07T20:25:39Z
BUG: Datareader index name shows unicode characters
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 02de919e3f83e..22a89b465ad7d 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -239,3 +239,4 @@ Bug Fixes - Bug where passing a unit to the TimedeltaIndex constructor applied the to nano-second conversion twice. (:issue:`9011`). - Bug in plotting of a period-like array (:issue:`9012`) + diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index b3ac58a9fb84a..931b8009d8cf0 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -202,3 +202,5 @@ Bug Fixes - Fixed issue in the ``xlsxwriter`` engine where it added a default 'General' format to cells if no other format wass applied. This prevented other row or column formatting being applied. (:issue:`9167`) - Fixes issue with ``index_col=False`` when ``usecols`` is also specified in ``read_csv``. (:issue:`9082`) - Bug where ``wide_to_long`` would modify the input stubnames list (:issue:`9204`) +- Bug in Datareader index name shows unicode characters (:issue:`8967`) + diff --git a/pandas/io/data.py b/pandas/io/data.py index b5cf5f9d9be19..72729d7a189f6 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -171,6 +171,14 @@ def _retry_read_url(url, retry_count, pause, name): # return 2 rows for the most recent business day if len(rs) > 2 and rs.index[-1] == rs.index[-2]: # pragma: no cover rs = rs[:-1] + + #Get rid of unicode characters in index name. + try: + rs.index.name = rs.index.name.decode('unicode_escape').encode('ascii', 'ignore') + except AttributeError: + #Python 3 string has no decode method. + rs.index.name = rs.index.name.encode('ascii', 'ignore').decode() + return rs raise IOError("after %d tries, %s did not " diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 2d6f14c79633a..df6a8fe2005be 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -126,6 +126,12 @@ def test_dtypes(self): assert np.issubdtype(data.High.dtype, np.number) assert np.issubdtype(data.Volume.dtype, np.number) + def test_unicode_date(self): + #GH8967 + data = web.get_data_google('F', start='JAN-01-10', end='JAN-27-13') + self.assertEquals(data.index.name, 'Date') + + class TestYahoo(tm.TestCase): @classmethod def setUpClass(cls):
Fixes #8967
https://api.github.com/repos/pandas-dev/pandas/pulls/9026
2014-12-06T20:45:54Z
2015-03-07T21:11:28Z
null
2015-03-07T21:17:28Z
BUG: Fix Datareader dtypes if there are missing values from Google.
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 58dc1da214c05..7d54bc73e9ae6 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -222,3 +222,4 @@ Bug Fixes - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) +- Bug in Datareader returns object dtype if there are missing values (:issue:`8980`) diff --git a/pandas/io/data.py b/pandas/io/data.py index 0827d74191842..3d92d383badf8 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -166,7 +166,7 @@ def _retry_read_url(url, retry_count, pause, name): pass else: rs = read_csv(StringIO(bytes_to_str(lines)), index_col=0, - parse_dates=True)[::-1] + parse_dates=True, na_values='-')[::-1] # Yahoo! Finance sometimes does this awesome thing where they # return 2 rows for the most recent business day if len(rs) > 2 and rs.index[-1] == rs.index[-2]: # pragma: no cover diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 3fca0393339fc..a65722dc76556 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -118,8 +118,8 @@ def test_get_multi2(self): assert_n_failed_equals_n_null_columns(w, result) def test_dtypes(self): - #GH3995 - data = web.get_data_google('MSFT', 'JAN-01-12', 'JAN-31-12') + #GH3995, #GH8980 + data = web.get_data_google('F', start='JAN-01-10', end='JAN-27-13') assert np.issubdtype(data.Open.dtype, np.number) assert np.issubdtype(data.Close.dtype, np.number) assert np.issubdtype(data.Low.dtype, np.number)
Fixes #8980
https://api.github.com/repos/pandas-dev/pandas/pulls/9025
2014-12-06T20:34:01Z
2014-12-07T00:07:23Z
2014-12-07T00:07:23Z
2014-12-07T00:07:27Z
Gh9010 yahoo options parsing bug
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d64dbf6e14345..73c72ae963f60 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -221,3 +221,5 @@ Bug Fixes - Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) + +- Bug in ``Options`` where parsing the underlying price returns a ValueError when the price has a thousands separator in the HTML text. (:issue:`9010`) diff --git a/pandas/io/data.py b/pandas/io/data.py index 0827d74191842..8216b41014320 100644 --- a/pandas/io/data.py +++ b/pandas/io/data.py @@ -698,8 +698,19 @@ def _option_frames_from_url(self, url): def _get_underlying_price(self, url): root = self._parse_url(url) - underlying_price = float(root.xpath('.//*[@class="time_rtq_ticker Fz-30 Fw-b"]')[0]\ - .getchildren()[0].text) + + underlying_price = root.xpath('.//*[@class="time_rtq_ticker Fz-30 Fw-b"]')[0]\ + .getchildren()[0].text + try: + underlying_price = float(underlying_price) + except ValueError: + # see if there is a comma thousands separator in here that needs to be filtered out + # filtering via join works in both Python 2.7 and Python 3 + underlying_price = ''.join(c for c in underlying_price if c != ',') + try: + underlying_price = float(underlying_price) + except ValueError: + underlying_price = np.nan #Gets the time of the quote, note this is actually the time of the underlying price. try: @@ -1192,6 +1203,7 @@ def _process_data(self, frame, type): frame["Quote_Time"] = np.nan frame.rename(columns={'Open Int': 'Open_Int'}, inplace=True) frame['Type'] = type + frame.set_index(['Strike', 'Expiry', 'Type', 'Symbol'], inplace=True) return frame diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py index 3fca0393339fc..b23873eecd918 100644 --- a/pandas/io/tests/test_data.py +++ b/pandas/io/tests/test_data.py @@ -320,6 +320,17 @@ def test_get_expiry_dates(self): raise nose.SkipTest(e) self.assertTrue(len(dates) > 1) + @network + def test_get_underlying_price(self): + try: + options_object = web.Options('^spxpm', 'yahoo') + expiry_dates, urls = options_object._get_expiry_dates_and_links() + url = options_object._FINANCE_BASE_URL + urls.values()[0] + quote_price, quote_time = options_object._get_underlying_price( url ) + except RemoteDataError as e: + raise nose.SkipTest(e) + self.assertIsInstance( quote_price, float ) + @network def test_get_all_data(self): try:
closes #9010. Fix for Yahoo Options parse error for underlying prices of 1,000.00 or larger.
https://api.github.com/repos/pandas-dev/pandas/pulls/9024
2014-12-06T19:52:43Z
2015-01-05T23:51:07Z
null
2015-01-05T23:51:07Z
ENH/API: DataFrame.stack() support for level=None, sequentially=True/False, and NaN level values.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e92de770ac4bd..e950df9c633af 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3718,7 +3718,7 @@ def pivot(self, index=None, columns=None, values=None): from pandas.core.reshape import pivot return pivot(self, index=index, columns=columns, values=values) - def stack(self, level=-1, dropna=True): + def stack(self, level=-1, dropna=True, sequentially=True): """ Pivot a level of the (possibly hierarchical) column labels, returning a DataFrame (or Series in the case of an object with a single level of @@ -3728,11 +3728,15 @@ def stack(self, level=-1, dropna=True): Parameters ---------- - level : int, string, or list of these, default last level - Level(s) to stack, can pass level name + level : int, string, list of these, or None; default -1 (last level) + Level(s) to stack, can pass level name(s). + None specifies all column levels, i.e. list(range(columns.nlevels)). dropna : boolean, default True Whether to drop rows in the resulting Frame/Series with no valid values + sequentially : boolean, default True + When level is a list (or None), whether the multiple column levels + should be stacked sequentially (if True) or simultaneously (if False). Examples ---------- @@ -3751,14 +3755,20 @@ def stack(self, level=-1, dropna=True): ------- stacked : DataFrame or Series """ - from pandas.core.reshape import stack, stack_multiple + from pandas.core.reshape import stack_levels_sequentially, stack_multi_levels_simultaneously - if isinstance(level, (tuple, list)): - return stack_multiple(self, level, dropna=dropna) + level_nums = self.columns._get_level_numbers(level, allow_mixed_names_and_numbers=False) + if level_nums == []: + if dropna: + return self.dropna(axis=0, how='all') + else: + return self + elif (not sequentially) and isinstance(self.columns, MultiIndex): + return stack_multi_levels_simultaneously(self, level_nums, dropna=dropna) else: - return stack(self, level, dropna=dropna) + return stack_levels_sequentially(self, level_nums, dropna=dropna) - def unstack(self, level=-1): + def unstack(self, level=-1, dropna=False, sequentially=False): """ Pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level @@ -3769,8 +3779,15 @@ def unstack(self, level=-1): Parameters ---------- - level : int, string, or list of these, default -1 (last level) - Level(s) of index to unstack, can pass level name + level : int, string, list of these, or None; default -1 (last level) + Level(s) of index to unstack, can pass level name(s). + None specifies all index levels, i.e. list(range(index.nlevels)). + dropna : boolean, default False + Whether to drop columns in the resulting Frame/Series with no valid + values + sequentially : boolean, default True + When level is a list (or None), whether the multiple index levels + should be stacked sequentially (if True) or simultaneously (if False). See also -------- @@ -3812,7 +3829,44 @@ def unstack(self, level=-1): unstacked : DataFrame or Series """ from pandas.core.reshape import unstack - return unstack(self, level) + + level_nums = self.index._get_level_numbers(level, allow_mixed_names_and_numbers=False) + if level_nums == []: + if dropna: + return self.dropna(axis=1, how='all') + else: + return self + if sequentially and isinstance(level_nums, list) and (len(level_nums) > 1): + result = self + # Adjust level_nums to account for the fact that levels move "up" + # as a result of stacking of earlier levels. + adjusted_level_nums = [x - sum((y < x) for y in level_nums[:i]) + for i, x in enumerate(level_nums)] + for level_num in adjusted_level_nums: + result = unstack(result, level_num) + else: + result = unstack(self, level_nums) + + if isinstance(result, DataFrame): + # fix dtypes, if necessary + desired_dtypes = self.dtypes.values.repeat(len(result.columns) // len(self.columns)) + result_dtypes = result.dtypes.values + for i, c in enumerate(result.columns): + if result_dtypes[i] != desired_dtypes[i]: + if result_dtypes[i] == np.object: + # use default Series constructor to set type + result[c] = Series(result[c].values.tolist(), index=result.index) + else: + # try to convert type directly + result[c] = result[c].astype(desired_dtypes[i], raise_on_error=False) + # drop empty columns, if necessary + if dropna: + result = result.dropna(axis=1, how='all') + else: + if dropna: + result = result.dropna() + + return result #---------------------------------------------------------------------- # Time series-related diff --git a/pandas/core/index.py b/pandas/core/index.py index b4c690fe8973b..86afc922fb8db 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1033,7 +1033,7 @@ def _validate_index_level(self, level): verification must be done like in MultiIndex. """ - if isinstance(level, int): + if com.is_integer(level): if level < 0 and level != -1: raise IndexError("Too many levels: Index has only 1 level," " %d is not a valid level number" % (level,)) @@ -1045,10 +1045,44 @@ def _validate_index_level(self, level): raise KeyError('Level %s must be same as name (%s)' % (level, self.name)) - def _get_level_number(self, level): + def _get_level_number(self, level, ignore_names=False): + """ + Returns level number corresponding to level. + If level is a level name and ignore_names is False, + the level number corresponding to such level name is returned. + Otherwise level must be a number. + If level is a positive number, it is returned. + If level is a negative number, its sum with self.nlevels is returned. + """ + if ignore_names and (not com.is_integer(level)): + raise KeyError('Level %s not found' % str(level)) self._validate_index_level(level) return 0 + def _get_level_numbers(self, levels, allow_mixed_names_and_numbers=False): + """ + Returns level numbers corresponding to levels. + If levels is None, a list of all level numbers is returned. + If levels is a single number or level name, + then a single number is returned (using _get_level_number()). + If levels is a list of numbers or level names, + then a list of numbers is returned (each using _get_level_number()). + If allow_mixed_names_and_numbers is False, then levels must be + either all level numbers or all level names. + """ + if levels is None: + return list(range(self.nlevels)) + elif isinstance(levels, (list, tuple, set)): + if (not allow_mixed_names_and_numbers) and (not all(lev in self.names for lev in levels)): + if all(isinstance(lev, int) for lev in levels): + return type(levels)(self._get_level_number(level, ignore_names=True) for level in levels) + else: + raise ValueError("level should contain all level names or all level numbers, " + "not a mixture of the two.") + return type(levels)(self._get_level_number(level) for level in levels) + else: + return self._get_level_number(levels) + @cache_readonly def inferred_type(self): """ return a string of the type inferred from the values """ @@ -4294,28 +4328,38 @@ def _from_elements(values, labels=None, levels=None, names=None, sortorder=None): return MultiIndex(levels, labels, names, sortorder=sortorder) - def _get_level_number(self, level): - try: + def _get_level_number(self, level, ignore_names=False): + """ + Returns level number corresponding to level. + If level is a level name and ignore_names is False, + the level number corresponding to such level name is returned. + Otherwise level must be a number. + If level is a positive number, it is returned. + If level is a negative number, its sum with self.nlevels is returned. + """ + if not ignore_names: count = self.names.count(level) if count > 1: raise ValueError('The name %s occurs multiple times, use a ' 'level number' % level) - level = self.names.index(level) - except ValueError: - if not isinstance(level, int): - raise KeyError('Level %s not found' % str(level)) - elif level < 0: - level += self.nlevels - if level < 0: - orig_level = level - self.nlevels - raise IndexError( - 'Too many levels: Index has only %d levels, ' - '%d is not a valid level number' % (self.nlevels, orig_level) - ) - # Note: levels are zero-based - elif level >= self.nlevels: - raise IndexError('Too many levels: Index has only %d levels, ' - 'not %d' % (self.nlevels, level + 1)) + try: + return self.names.index(level) + except ValueError: + pass + if not com.is_integer(level): + raise KeyError('Level %s not found' % str(level)) + elif level < 0: + level += self.nlevels + if level < 0: + orig_level = level - self.nlevels + raise IndexError( + 'Too many levels: Index has only %d levels, ' + '%d is not a valid level number' % (self.nlevels, orig_level) + ) + # Note: levels are zero-based + elif level >= self.nlevels: + raise IndexError('Too many levels: Index has only %d levels, ' + 'not %d' % (self.nlevels, level + 1)) return level _tuples = None @@ -4891,7 +4935,7 @@ def _drop_from_level(self, labels, level): return self[mask] - def droplevel(self, level=0): + def droplevel(self, level=0, ignore_names=False): """ Return Index with requested level removed. If MultiIndex has only 2 levels, the result will be of Index type not MultiIndex. @@ -4899,6 +4943,8 @@ def droplevel(self, level=0): Parameters ---------- level : int/level name or list thereof + ignore_names : boolean, default True + If True, level must be an int or list thereof Notes ----- @@ -4916,7 +4962,7 @@ def droplevel(self, level=0): new_labels = list(self.labels) new_names = list(self.names) - levnums = sorted(self._get_level_number(lev) for lev in levels)[::-1] + levnums = sorted((self._get_level_number(lev, ignore_names) for lev in levels), reverse=True) for i in levnums: new_levels.pop(i) @@ -4929,6 +4975,9 @@ def droplevel(self, level=0): mask = new_labels[0] == -1 result = new_levels[0].take(new_labels[0]) if mask.any(): + if result.is_integer(): + # cannot store NaNs in an integer index, so promote to Float64Index + result = Float64Index(result.values, name=result.name) result = result.putmask(mask, np.nan) result.name = new_names[0] @@ -5539,7 +5588,7 @@ def convert_indexer(start, stop, step, indexer=indexer, labels=labels): else: - loc = level_index.get_loc(key) + loc = -1 if com.is_float(key) and np.isnan(key) else level_index.get_loc(key) if level > 0 or self.lexsort_depth == 0: return np.array(labels == loc,dtype=bool) else: @@ -6050,7 +6099,7 @@ def _trim_front(strings): def _sanitize_and_check(indexes): - kinds = list(set([type(index) for index in indexes])) + kinds = list(set(type(index) for index in indexes)) if list in kinds: if len(kinds) > 1: @@ -6071,11 +6120,11 @@ def _get_consensus_names(indexes): # find the non-none names, need to tupleify to make # the set hashable, then reverse on return - consensus_names = set([ + consensus_names = set( tuple(i.names) for i in indexes if all(n is not None for n in i.names) - ]) + ) if len(consensus_names) == 1: - return list(list(consensus_names)[0]) + return list(consensus_names.pop()) return [None] * indexes[0].nlevels diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py index fecfe5cd82c6d..6940e36b23f4a 100644 --- a/pandas/core/reshape.py +++ b/pandas/core/reshape.py @@ -21,6 +21,8 @@ import pandas.algos as algos from pandas.core.index import MultiIndex, _get_na_value +from pandas.core.algorithms import factorize, unique +from pandas.tslib import NaTType class _Unstacker(object): @@ -61,8 +63,25 @@ class _Unstacker(object): unstacked : DataFrame """ - def __init__(self, values, index, level=-1, value_columns=None): - + def __init__(self, values, index, level_num, value_columns=None): + """ + Initializes _Unstacker object. + + Parameters + ---------- + values : ndarray + Values to use for populating new frame's values + index : ndarray + Labels to use to make new frame's index + level_num : int + Level to unstack, must be an integer in the range [0, len(index)) + value_columns : ndarray + Labels to use to make new frame's columns + + Notes + ----- + Obviously, values, index, and values_columns must have the same length + """ self.is_categorical = None if values.ndim == 1: if isinstance(values, Categorical): @@ -77,13 +96,7 @@ def __init__(self, values, index, level=-1, value_columns=None): self.index = index - if isinstance(self.index, MultiIndex): - if index._reference_duplicate_name(level): - msg = ("Ambiguous reference to {0}. The index " - "names are not unique.".format(level)) - raise ValueError(msg) - - self.level = self.index._get_level_number(level) + self.level = level_num # when index includes `nan`, need to lift levels/strides by 1 self.lift = 1 if -1 in self.index.labels[self.level] else 0 @@ -239,6 +252,26 @@ def get_new_index(self): verify_integrity=False) +def _make_new_index(lev, lab): + from pandas.core.index import Index, _get_na_value + + nan = _get_na_value(lev.dtype.type) + vals = lev.values.astype('object') + vals = np.insert(vals, 0, nan) if lab is None else \ + np.insert(vals, len(vals), nan).take(lab) + + if com.is_datetime_or_timedelta_dtype(lev.dtype): + nan_indices = [0] if lab is None else (np.array(lab) == -1) + vals[nan_indices] = None + + try: + vals = vals.astype(lev.dtype, subok=False, copy=False) + except ValueError: + return Index(vals, **lev._get_attributes_dict()) + + return lev._shallow_copy(vals) + + def _unstack_multiple(data, clocs): from pandas.core.groupby import decons_obs_group_ids @@ -249,8 +282,6 @@ def _unstack_multiple(data, clocs): index = data.index - clocs = [index._get_level_number(i) for i in clocs] - rlocs = [i for i in range(index.nlevels) if i not in clocs] clevels = [index.levels[i] for i in clocs] @@ -395,26 +426,30 @@ def _slow_pivot(index, columns, values): return DataFrame(tree) -def unstack(obj, level): - if isinstance(level, (tuple, list)): - return _unstack_multiple(obj, level) +def unstack(obj, level_num): + if isinstance(level_num, (tuple, list)): + if len(level_num) == 1: + level_num = level_num[0] + else: + return _unstack_multiple(obj, level_num) if isinstance(obj, DataFrame): if isinstance(obj.index, MultiIndex): - return _unstack_frame(obj, level) + return _unstack_frame(obj, level_num) else: - return obj.T.stack(dropna=False) + #return obj.T.stack(dropna=False) + return stack_single_level(obj.T, 0, dropna=False) else: - unstacker = _Unstacker(obj.values, obj.index, level=level) + unstacker = _Unstacker(obj.values, obj.index, level_num=level_num) return unstacker.get_result() -def _unstack_frame(obj, level): +def _unstack_frame(obj, level_num): from pandas.core.internals import BlockManager, make_block if obj._is_mixed_type: unstacker = _Unstacker(np.empty(obj.shape, dtype=bool), # dummy - obj.index, level=level, + obj.index, level_num=level_num, value_columns=obj.columns) new_columns = unstacker.get_new_columns() new_index = unstacker.get_new_index() @@ -424,7 +459,7 @@ def _unstack_frame(obj, level): mask_blocks = [] for blk in obj._data.blocks: blk_items = obj._data.items[blk.mgr_locs.indexer] - bunstacker = _Unstacker(blk.values.T, obj.index, level=level, + bunstacker = _Unstacker(blk.values.T, obj.index, level_num=level_num, value_columns=blk_items) new_items = bunstacker.get_new_columns() new_placement = new_columns.get_indexer(new_items) @@ -440,7 +475,7 @@ def _unstack_frame(obj, level): mask_frame = DataFrame(BlockManager(mask_blocks, new_axes)) return result.ix[:, mask_frame.sum(0) > 0] else: - unstacker = _Unstacker(obj.values, obj.index, level=level, + unstacker = _Unstacker(obj.values, obj.index, level_num=level_num, value_columns=obj.columns) return unstacker.get_result() @@ -452,54 +487,45 @@ def get_compressed_ids(labels, sizes): return _compress_group_index(ids, sort=True) -def stack(frame, level=-1, dropna=True): +def stack_single_level(frame, level_num, dropna=True): """ - Convert DataFrame to Series with multi-level Index. Columns become the - second level of the resulting hierarchical index + Convert DataFrame to DataFrame or Series with multi-level Index. + Columns become the second level of the resulting hierarchical index + + Parameters + ---------- + frame : DataFrame + DataFrame to be unstacked + level_num : int + Column level to unstack, must be an integer in the range [0, len(index)) + dropna : boolean, default True + Whether to drop rows in the resulting Frame/Series with no valid + values Returns ------- - stacked : Series + stacked : DataFrame or Series """ - def factorize(index): - if index.is_unique: - return index, np.arange(len(index)) - cat = Categorical(index, ordered=True) - return cat.categories, cat.codes - - N, K = frame.shape if isinstance(frame.columns, MultiIndex): - if frame.columns._reference_duplicate_name(level): - msg = ("Ambiguous reference to {0}. The column " - "names are not unique.".format(level)) - raise ValueError(msg) + return stack_multi_levels_simultaneously(frame, level_nums=[level_num], dropna=dropna) - # Will also convert negative level numbers and check if out of bounds. - level_num = frame.columns._get_level_number(level) - - if isinstance(frame.columns, MultiIndex): - return _stack_multi_columns(frame, level_num=level_num, dropna=dropna) - elif isinstance(frame.index, MultiIndex): + # frame.columns is a simple Index (not a MultiIndex) + N, K = frame.shape + if isinstance(frame.index, MultiIndex): new_levels = list(frame.index.levels) new_labels = [lab.repeat(K) for lab in frame.index.labels] - - clev, clab = factorize(frame.columns) - new_levels.append(clev) - new_labels.append(np.tile(clab, N).ravel()) - new_names = list(frame.index.names) - new_names.append(frame.columns.name) - new_index = MultiIndex(levels=new_levels, labels=new_labels, - names=new_names, verify_integrity=False) else: - levels, (ilab, clab) = \ - zip(*map(factorize, (frame.index, frame.columns))) - labels = ilab.repeat(K), np.tile(clab, N).ravel() - new_index = MultiIndex(levels=levels, - labels=labels, - names=[frame.index.name, frame.columns.name], - verify_integrity=False) - + idx_labels, new_levels = factorize(frame.index) + new_levels = [new_levels] + new_labels = [idx_labels.repeat(K)] + new_names = [frame.index.name] + col_labels, col_levels = factorize(frame.columns) + new_levels.append(col_levels) + new_labels.append(np.tile(col_labels, N).ravel()) + new_names.append(frame.columns.name) + new_index = MultiIndex(levels=new_levels, labels=new_labels, + names=new_names, verify_integrity=False) new_values = frame.values.ravel() if dropna: mask = notnull(new_values) @@ -508,46 +534,29 @@ def factorize(index): return Series(new_values, index=new_index) -def stack_multiple(frame, level, dropna=True): - # If all passed levels match up to column names, no - # ambiguity about what to do - if all(lev in frame.columns.names for lev in level): - result = frame - for lev in level: - result = stack(result, lev, dropna=dropna) - - # Otherwise, level numbers may change as each successive level is stacked - elif all(isinstance(lev, int) for lev in level): - # As each stack is done, the level numbers decrease, so we need - # to account for that when level is a sequence of ints - result = frame - # _get_level_number() checks level numbers are in range and converts - # negative numbers to positive - level = [frame.columns._get_level_number(lev) for lev in level] - - # Can't iterate directly through level as we might need to change - # values as we go - for index in range(len(level)): - lev = level[index] - result = stack(result, lev, dropna=dropna) - # Decrement all level numbers greater than current, as these - # have now shifted down by one - updated_level = [] - for other in level: - if other > lev: - updated_level.append(other - 1) - else: - updated_level.append(other) - level = updated_level +def stack_levels_sequentially(frame, level_nums, dropna=True): + """ + Stack multiple levels of frame.columns -- which may be a MultiIndex or a simple Index -- sequentially. + """ + if isinstance(level_nums, int): + return stack_single_level(frame, level_nums, dropna=dropna) - else: - raise ValueError("level should contain all level names or all level numbers, " - "not a mixture of the two.") + result = frame + # Adjust level_nums to account for the fact that levels move "up" + # as a result of stacking of earlier levels. + adjusted_level_nums = [x - sum((y < x) for y in level_nums[:i]) + for i, x in enumerate(level_nums)] + for level_num in adjusted_level_nums: + result = stack_single_level(result, level_num, dropna=dropna) return result -def _stack_multi_columns(frame, level_num=-1, dropna=True): +def stack_multi_levels_simultaneously(frame, level_nums, dropna=True): + """ + Stack multiple levels of frame.columns -- which must be a MultiIndex -- simultaneously. + """ + def _convert_level_number(level_num, columns): """ Logic for converting the level number to something @@ -565,70 +574,39 @@ def _convert_level_number(level_num, columns): else: return columns.names[level_num] + if isinstance(level_nums, int): + level_nums = [level_nums] + this = frame.copy() # this makes life much simpler - if level_num != frame.columns.nlevels - 1: - # roll levels to put selected level at end - roll_columns = this.columns - for i in range(level_num, frame.columns.nlevels - 1): + # roll levels to put selected level(s) at end + roll_columns = this.columns + for j, level_num in enumerate(reversed(level_nums)): + for i in range(level_num, frame.columns.nlevels - (j + 1)): # Need to check if the ints conflict with level names lev1 = _convert_level_number(i, roll_columns) lev2 = _convert_level_number(i + 1, roll_columns) roll_columns = roll_columns.swaplevel(lev1, lev2) - this.columns = roll_columns + this.columns = roll_columns if not this.columns.is_lexsorted(): # Workaround the edge case where 0 is one of the column names, - # which interferes with trying to sort based on the first - # level + # which interferes with trying to sort based on the first level level_to_sort = _convert_level_number(0, this.columns) this = this.sortlevel(level_to_sort, axis=1) - # tuple list excluding level for grouping columns - if len(frame.columns.levels) > 2: - tuples = list(zip(*[ - lev.take(lab) for lev, lab in - zip(this.columns.levels[:-1], this.columns.labels[:-1]) - ])) - unique_groups = [key for key, _ in itertools.groupby(tuples)] - new_names = this.columns.names[:-1] - new_columns = MultiIndex.from_tuples(unique_groups, names=new_names) - else: - new_columns = unique_groups = this.columns.levels[0] - - # time to ravel the values - new_data = {} - level_vals = this.columns.levels[-1] - level_labels = sorted(set(this.columns.labels[-1])) - level_vals_used = level_vals[level_labels] + num_levels_to_stack = len(level_nums) + level_vals = this.columns.levels[-num_levels_to_stack:] + level_labels = sorted(set(zip(*this.columns.labels[-num_levels_to_stack:]))) + level_vals_used = MultiIndex.from_tuples([tuple(np.nan if lab == -1 else level_vals[i][lab] + for i, lab in enumerate(label)) + for label in level_labels], + names=this.columns.names[-num_levels_to_stack:]) levsize = len(level_labels) - drop_cols = [] - for key in unique_groups: - loc = this.columns.get_loc(key) - slice_len = loc.stop - loc.start - # can make more efficient? - - if slice_len == 0: - drop_cols.append(key) - continue - elif slice_len != levsize: - chunk = this.ix[:, this.columns[loc]] - chunk.columns = level_vals.take(chunk.columns.labels[-1]) - value_slice = chunk.reindex(columns=level_vals_used).values - else: - if frame._is_mixed_type: - value_slice = this.ix[:, this.columns[loc]].values - else: - value_slice = this.values[:, loc] - - new_data[key] = value_slice.ravel() - - if len(drop_cols) > 0: - new_columns = new_columns.difference(drop_cols) + # construct new_index N = len(this) - if isinstance(this.index, MultiIndex): new_levels = list(this.index.levels) new_names = list(this.index.names) @@ -637,15 +615,55 @@ def _convert_level_number(level_num, columns): new_levels = [this.index] new_labels = [np.arange(N).repeat(levsize)] new_names = [this.index.name] # something better? - - new_levels.append(frame.columns.levels[level_num]) - new_labels.append(np.tile(level_labels, N)) - new_names.append(frame.columns.names[level_num]) - + new_levels += level_vals + new_labels += [np.tile(labels, N) for labels in zip(*level_labels)] + new_names += level_vals_used.names new_index = MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) - result = DataFrame(new_data, index=new_index, columns=new_columns) + # if stacking all levels in columns, result will be a Series + if len(this.columns.levels) == num_levels_to_stack: + new_data = this.values.ravel() + if dropna: + mask = notnull(new_data) + new_data = new_data[mask] + new_index = new_index[mask] + return Series(new_data, index=new_index) + + # result will be a DataFrame + + # construct new_columns + new_columns = this.columns.droplevel(list(range(this.columns.nlevels - num_levels_to_stack, + this.columns.nlevels)), True).drop_duplicates() + + # construct new_data + new_data = {} + unique_group_levels = this.columns.nlevels - num_levels_to_stack + unique_label_groups = unique(zip(*this.columns.labels[:unique_group_levels])) + + for i, unique_label_group in enumerate(unique_label_groups): + loc = np.array([True] * len(this.columns)) + for level_num in range(unique_group_levels): + loc &= (this.columns.labels[level_num] == unique_label_group[level_num]) + slice_len = loc.sum() + if slice_len != levsize: + chunk = this.iloc[:, loc] + chunk.columns = MultiIndex.from_arrays([_make_new_index(vals, labels) for vals, labels + in zip(level_vals, chunk.columns.labels[-num_levels_to_stack:])], + names=chunk.columns.names[-num_levels_to_stack:]) + value_slice = chunk.reindex(columns=level_vals_used).values + else: + if frame._is_mixed_type: + value_slice = this.iloc[:, loc].values + else: + value_slice = this.values[:, loc] + + new_data[i] = value_slice.ravel() + + # construct DataFrame with dummy columns, since construction from a dict + # doesn't handle NaNs correctly + result = DataFrame(new_data, index=new_index, columns=list(range(len(new_columns)))) + result.columns = new_columns # more efficient way to go about this? can do the whole masking biz but # will only save a small amount of time... diff --git a/pandas/core/series.py b/pandas/core/series.py index f4e3374626011..865ecce5d1fd8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1983,7 +1983,9 @@ def unstack(self, level=-1): unstacked : DataFrame """ from pandas.core.reshape import unstack - return unstack(self, level) + + level_nums = self.index._get_level_numbers(level, allow_mixed_names_and_numbers=False) + return unstack(self, level_nums) #---------------------------------------------------------------------- # function application diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 6667d389bd6c5..222646c6db832 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -234,9 +234,9 @@ def test_setitem_mulit_index(self): ['left', 'center', 'right'] cols = MultiIndex.from_product(it) - index = pd.date_range('20141006',periods=20) + index = date_range('20141006',periods=20) vals = np.random.randint(1, 1000, (len(index), len(cols))) - df = pd.DataFrame(vals, columns=cols, index=index) + df = DataFrame(vals, columns=cols, index=index) i, j = df.index.values.copy(), it[-1][:] @@ -1996,7 +1996,7 @@ def verify(df, level, idx, indexer): right = df.iloc[indexer].set_index(icol) assert_frame_equal(left, right) - df = pd.DataFrame({'jim':list('B' * 4 + 'A' * 2 + 'C' * 3), + df = DataFrame({'jim':list('B' * 4 + 'A' * 2 + 'C' * 3), 'joe':list('abcdeabcd')[::-1], 'jolie':[10, 20, 30] * 3, 'joline': np.random.randint(0, 1000, 9)}) @@ -2045,7 +2045,7 @@ def verify(df, level, idx, indexer): verify(df, 'joe', ['3rd', '1st'], i) def test_getitem_ix_float_duplicates(self): - df = pd.DataFrame(np.random.randn(3, 3), + df = DataFrame(np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list('abc')) expect = df.iloc[1:] tm.assert_frame_equal(df.loc[0.2], expect) @@ -2062,7 +2062,7 @@ def test_getitem_ix_float_duplicates(self): expect = df.iloc[1:, 0] tm.assert_series_equal(df.loc[0.2, 'a'], expect) - df = pd.DataFrame(np.random.randn(4, 3), + df = DataFrame(np.random.randn(4, 3), index=[1, 0.2, 0.2, 1], columns=list('abc')) expect = df.iloc[1:-1] tm.assert_frame_equal(df.loc[0.2], expect) @@ -2081,14 +2081,14 @@ def test_getitem_ix_float_duplicates(self): def test_setitem_with_sparse_value(self): # GH8131 - df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_1': [1., 2., 3.]}) - sp_series = pd.Series([0, 0, 1]).to_sparse(fill_value=0) + df = DataFrame({'c_1':['a', 'b', 'c'], 'n_1': [1., 2., 3.]}) + sp_series = Series([0, 0, 1]).to_sparse(fill_value=0) df['new_column'] = sp_series tm.assert_series_equal(df['new_column'], sp_series, check_names=False) def test_setitem_with_unaligned_sparse_value(self): - df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_1': [1., 2., 3.]}) - sp_series = (pd.Series([0, 0, 1], index=[2, 1, 0]) + df = DataFrame({'c_1':['a', 'b', 'c'], 'n_1': [1., 2., 3.]}) + sp_series = (Series([0, 0, 1], index=[2, 1, 0]) .to_sparse(fill_value=0)) df['new_column'] = sp_series exp = pd.Series([1, 0, 0], name='new_column') @@ -2488,7 +2488,7 @@ def test_set_index_cast_datetimeindex(self): # don't cast a DatetimeIndex WITH a tz, leave as object # GH 6032 - i = pd.DatetimeIndex(pd.tseries.tools.to_datetime(['2013-1-1 13:00','2013-1-2 14:00'], errors="raise")).tz_localize('US/Pacific') + i = DatetimeIndex(pd.tseries.tools.to_datetime(['2013-1-1 13:00','2013-1-2 14:00'], errors="raise")).tz_localize('US/Pacific') df = DataFrame(np.random.randn(2,1),columns=['A']) expected = Series(np.array([pd.Timestamp('2013-01-01 13:00:00-0800', tz='US/Pacific'), @@ -2533,10 +2533,10 @@ def test_set_index_cast_datetimeindex(self): # GH 3950 # reset_index with single level for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern']: - idx = pd.date_range('1/1/2011', periods=5, freq='D', tz=tz, name='idx') - df = pd.DataFrame({'a': range(5), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) + idx = date_range('1/1/2011', periods=5, freq='D', tz=tz, name='idx') + df = DataFrame({'a': range(5), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) - expected = pd.DataFrame({'idx': [datetime(2011, 1, 1), datetime(2011, 1, 2), + expected = DataFrame({'idx': [datetime(2011, 1, 1), datetime(2011, 1, 2), datetime(2011, 1, 3), datetime(2011, 1, 4), datetime(2011, 1, 5)], 'a': range(5), 'b': ['A', 'B', 'C', 'D', 'E']}, @@ -2619,7 +2619,7 @@ def test_constructor_dtype_copy(self): 'col2': [2.], 'col3': [3.]}) - new_df = pd.DataFrame(orig_df, dtype=float, copy=True) + new_df = DataFrame(orig_df, dtype=float, copy=True) new_df['col1'] = 200. self.assertEqual(orig_df['col1'][0], 1.) @@ -3883,9 +3883,9 @@ def check(result, expected=None): # check column dups with index equal and not equal to df's index df = DataFrame(np.random.randn(5, 3), index=['a', 'b', 'c', 'd', 'e'], columns=['A', 'B', 'A']) - for index in [df.index, pd.Index(list('edcba'))]: + for index in [df.index, Index(list('edcba'))]: this_df = df.copy() - expected_ser = pd.Series(index.values, index=this_df.index) + expected_ser = Series(index.values, index=this_df.index) expected_df = DataFrame.from_items([('A', expected_ser), ('B', this_df['B']), ('A', expected_ser)]) @@ -4397,7 +4397,7 @@ def test_constructor_for_list_with_dtypes(self): assert_series_equal(result, expected) def test_not_hashable(self): - df = pd.DataFrame([1]) + df = DataFrame([1]) self.assertRaises(TypeError, hash, df) self.assertRaises(TypeError, hash, self.empty) @@ -7521,7 +7521,7 @@ def test_info_memory_usage(self): # excluded column with object dtype, so estimate is accurate self.assertFalse(re.match(r"memory usage: [^+]+\+", res[-1])) - df_with_object_index = pd.DataFrame({'a': [1]}, index=['foo']) + df_with_object_index = DataFrame({'a': [1]}, index=['foo']) df_with_object_index.info(buf=buf, memory_usage=True) res = buf.getvalue().splitlines() self.assertTrue(re.match(r"memory usage: [^+]+\+", res[-1])) @@ -7545,11 +7545,11 @@ def test_info_memory_usage(self): # test for validity DataFrame(1,index=['a'],columns=['A']).memory_usage(index=True) DataFrame(1,index=['a'],columns=['A']).index.nbytes - DataFrame(1,index=pd.MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.nbytes - DataFrame(1,index=pd.MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.values.nbytes - DataFrame(1,index=pd.MultiIndex.from_product([['a'],range(1000)]),columns=['A']).memory_usage(index=True) - DataFrame(1,index=pd.MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.nbytes - DataFrame(1,index=pd.MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.values.nbytes + DataFrame(1,index=MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.nbytes + DataFrame(1,index=MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.values.nbytes + DataFrame(1,index=MultiIndex.from_product([['a'],range(1000)]),columns=['A']).memory_usage(index=True) + DataFrame(1,index=MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.nbytes + DataFrame(1,index=MultiIndex.from_product([['a'],range(1000)]),columns=['A']).index.values.nbytes def test_dtypes(self): self.mixed_frame['bool'] = self.mixed_frame['A'] > 0 @@ -8706,14 +8706,14 @@ def test_drop(self): assert_frame_equal(nu_df.drop('a', axis=1), nu_df[['b']]) assert_frame_equal(nu_df.drop('b', axis='columns'), nu_df['a']) - nu_df = nu_df.set_index(pd.Index(['X', 'Y', 'X'])) + nu_df = nu_df.set_index(Index(['X', 'Y', 'X'])) nu_df.columns = list('abc') assert_frame_equal(nu_df.drop('X', axis='rows'), nu_df.ix[["Y"], :]) assert_frame_equal(nu_df.drop(['X', 'Y'], axis=0), nu_df.ix[[], :]) # inplace cache issue # GH 5628 - df = pd.DataFrame(np.random.randn(10,3), columns=list('abc')) + df = DataFrame(np.random.randn(10,3), columns=list('abc')) expected = df[~(df.b>0)] df.drop(labels=df[df.b>0].index, inplace=True) assert_frame_equal(df,expected) @@ -9404,7 +9404,7 @@ def test_regex_replace_dict_nested(self): assert_frame_equal(res4, expec) def test_regex_replace_dict_nested_gh4115(self): - df = pd.DataFrame({'Type':['Q','T','Q','Q','T'], 'tmp':2}) + df = DataFrame({'Type':['Q','T','Q','Q','T'], 'tmp':2}) expected = DataFrame({'Type': [0,1,0,0,1], 'tmp': 2}) assert_frame_equal(df.replace({'Type': {'Q':0,'T':1}}), expected) @@ -9845,14 +9845,14 @@ def test_replace_str_to_str_chain(self): df.replace({'a': dict(zip(astr, bstr))}) def test_replace_swapping_bug(self): - df = pd.DataFrame({'a': [True, False, True]}) + df = DataFrame({'a': [True, False, True]}) res = df.replace({'a': {True: 'Y', False: 'N'}}) - expect = pd.DataFrame({'a': ['Y', 'N', 'Y']}) + expect = DataFrame({'a': ['Y', 'N', 'Y']}) tm.assert_frame_equal(res, expect) - df = pd.DataFrame({'a': [0, 1, 0]}) + df = DataFrame({'a': [0, 1, 0]}) res = df.replace({'a': {0: 'Y', 1: 'N'}}) - expect = pd.DataFrame({'a': ['Y', 'N', 'Y']}) + expect = DataFrame({'a': ['Y', 'N', 'Y']}) tm.assert_frame_equal(res, expect) def test_replace_period(self): @@ -9865,7 +9865,7 @@ def test_replace_period(self): 'out_augmented_MAY_2011.json': pd.Period(year=2011, month=5, freq='M'), 'out_augmented_SEP_2013.json': pd.Period(year=2013, month=9, freq='M')}} - df = pd.DataFrame(['out_augmented_AUG_2012.json', + df = DataFrame(['out_augmented_AUG_2012.json', 'out_augmented_SEP_2013.json', 'out_augmented_SUBSIDY_WEEK.json', 'out_augmented_MAY_2012.json', @@ -9888,7 +9888,7 @@ def test_replace_datetime(self): 'out_augmented_MAY_2011.json': pd.Timestamp('2011-05'), 'out_augmented_SEP_2013.json': pd.Timestamp('2013-09')}} - df = pd.DataFrame(['out_augmented_AUG_2012.json', + df = DataFrame(['out_augmented_AUG_2012.json', 'out_augmented_SEP_2013.json', 'out_augmented_SUBSIDY_WEEK.json', 'out_augmented_MAY_2012.json', @@ -11562,7 +11562,7 @@ def test_apply_bug(self): # GH 6125 import datetime - positions = pd.DataFrame([[1, 'ABC0', 50], [1, 'YUM0', 20], + positions = DataFrame([[1, 'ABC0', 50], [1, 'YUM0', 20], [1, 'DEF0', 20], [2, 'ABC1', 50], [2, 'YUM1', 20], [2, 'DEF1', 20]], columns=['a', 'market', 'position']) @@ -13055,7 +13055,7 @@ def wrapper(x): self.assertTrue(np.isnan(r1).all()) def test_mode(self): - df = pd.DataFrame({"A": [12, 12, 11, 12, 19, 11], + df = DataFrame({"A": [12, 12, 11, 12, 19, 11], "B": [10, 10, 10, np.nan, 3, 4], "C": [8, 8, 8, 9, 9, 9], "D": np.arange(6,dtype='int64'), @@ -13067,9 +13067,9 @@ def test_mode(self): expected = pd.Series([1, 3, 8], dtype='int64', name='E').to_frame() assert_frame_equal(df[["E"]].mode(), expected) assert_frame_equal(df[["A", "B"]].mode(), - pd.DataFrame({"A": [12], "B": [10.]})) + DataFrame({"A": [12], "B": [10.]})) assert_frame_equal(df.mode(), - pd.DataFrame({"A": [12, np.nan, np.nan], + DataFrame({"A": [12, np.nan, np.nan], "B": [10, np.nan, np.nan], "C": [8, 9, np.nan], "D": [np.nan, np.nan, np.nan], @@ -13080,7 +13080,7 @@ def test_mode(self): com.pprint_thing(df["C"]) com.pprint_thing(df["C"].mode()) a, b = (df[["A", "B", "C"]].mode(), - pd.DataFrame({"A": [12, np.nan], + DataFrame({"A": [12, np.nan], "B": [10, np.nan], "C": [8, 9]})) com.pprint_thing(a) @@ -13090,18 +13090,18 @@ def test_mode(self): df = pd.DataFrame({"A": np.arange(6,dtype='int64'), "B": pd.date_range('2011', periods=6), "C": list('abcdef')}) - exp = pd.DataFrame({"A": pd.Series([], dtype=df["A"].dtype), - "B": pd.Series([], dtype=df["B"].dtype), - "C": pd.Series([], dtype=df["C"].dtype)}) + exp = DataFrame({"A": Series([], dtype=df["A"].dtype), + "B": Series([], dtype=df["B"].dtype), + "C": Series([], dtype=df["C"].dtype)}) assert_frame_equal(df.mode(), exp) # and also when not empty df.loc[1, "A"] = 0 df.loc[4, "B"] = df.loc[3, "B"] df.loc[5, "C"] = 'e' - exp = pd.DataFrame({"A": pd.Series([0], dtype=df["A"].dtype), - "B": pd.Series([df.loc[3, "B"]], dtype=df["B"].dtype), - "C": pd.Series(['e'], dtype=df["C"].dtype)}) + exp = DataFrame({"A": Series([0], dtype=df["A"].dtype), + "B": Series([df.loc[3, "B"]], dtype=df["B"].dtype), + "C": Series(['e'], dtype=df["C"].dtype)}) assert_frame_equal(df.mode(), exp) @@ -13668,6 +13668,13 @@ def test_stack_ints(self): list(itertools.product(range(3), repeat=3)) ) ) + + for level in (2, 1, 0, [0, 1], [0, 2], [1, 2], [1, 0], [2, 0], [2, 1]): + np.testing.assert_equal(df.stack(level=level).size, + df.size) + np.testing.assert_almost_equal(df.stack(level=level).sum().sum(), + df.sum().sum()) + assert_frame_equal( df.stack(level=[1, 2]), df.stack(level=1).stack(level=1) @@ -13811,7 +13818,6 @@ def test_unstack_to_series(self): assert_frame_equal(old_data, data) def test_unstack_dtypes(self): - # GH 2929 rows = [[1, 1, 3, 4], [1, 2, 3, 4], @@ -13849,7 +13855,7 @@ def test_unstack_dtypes(self): (np.arange(5, dtype='f8'), np.arange(5, 10, dtype='f8')): df = DataFrame({'A': ['a']*5, 'C':c, 'D':d, - 'B':pd.date_range('2012-01-01', periods=5)}) + 'B':date_range('2012-01-01', periods=5)}) right = df.iloc[:3].copy(deep=True) @@ -13873,7 +13879,8 @@ def test_unstack_non_unique_index_names(self): with tm.assertRaises(ValueError): df.T.stack('c1') - def test_unstack_nan_index(self): # GH7466 + def test_unstack_nan_index(self): + # GH7466 cast = lambda val: '{0:1}'.format('' if val != val else val) nan = np.nan @@ -13881,7 +13888,7 @@ def verify(df): mk_list = lambda a: list(a) if isinstance(a, tuple) else [a] rows, cols = df.notnull().values.nonzero() for i, j in zip(rows, cols): - left = sorted(df.iloc[i, j].split('.')) + left = sorted(df.iloc[i, :].iloc[j].split('.')) right = mk_list(df.index[i]) + mk_list(df.columns[j]) right = sorted(list(map(cast, right))) self.assertEqual(left, right) @@ -13921,7 +13928,7 @@ def verify(df): verify(udf[col]) # GH7403 - df = pd.DataFrame({'A': list('aaaabbbb'),'B':range(8), 'C':range(8)}) + df = DataFrame({'A': list('aaaabbbb'),'B':range(8), 'C':range(8)}) df.iloc[3, 1] = np.NaN left = df.set_index(['A', 'B']).unstack(0) @@ -13949,7 +13956,7 @@ def verify(df): right = DataFrame(vals, columns=cols, index=idx) assert_frame_equal(left, right) - df = pd.DataFrame({'A': list('aaaabbbb'),'B':list(range(4))*2, + df = DataFrame({'A': list('aaaabbbb'),'B':list(range(4))*2, 'C':range(8)}) df.iloc[3,1] = np.NaN left = df.set_index(['A', 'B']).unstack(0) @@ -13963,7 +13970,7 @@ def verify(df): assert_frame_equal(left, right) # GH7401 - df = pd.DataFrame({'A': list('aaaaabbbbb'), 'C':np.arange(10), + df = DataFrame({'A': list('aaaaabbbbb'), 'C':np.arange(10), 'B':date_range('2012-01-01', periods=5).tolist()*2 }) df.iloc[3,1] = np.NaN @@ -13976,6 +13983,8 @@ def verify(df): names=[None, 'B']) right = DataFrame(vals, columns=cols, index=idx) + for i in [1, 2, 3, 5]: + right.iloc[:, i] = right.iloc[:, i].astype(df.dtypes['C']) assert_frame_equal(left, right) # GH4862 @@ -14086,6 +14095,403 @@ def _test_stack_with_multiindex(multiindex): dtype=df.dtypes[0]) assert_frame_equal(result, expected) + def test_stack_multi(self): + # GH 8851 + + df_nonan = DataFrame(np.arange(2*6).reshape(2,6), + columns=MultiIndex.from_tuples([('A','a','X'), ('A','a','Y'), + ('A','b','X'), ('B','a','Z'), + ('B','b','Y'), ('B','b','X')], + names=['ABC','abc','XYZ']), + dtype=np.float64) + # ABC A B + # abc a b a b + # XYZ X Y X Z Y X + # 0 0 1 2 3 4 5 + # 1 6 7 8 9 10 11 + + df_nan = df_nonan.copy() + df_nan.iloc[0, 1] = nan + df_nan.iloc[0, 4] = nan + # ABC A B + # abc a b a b + # XYZ X Y X Z Y X + # 0 0 NaN 2 3 NaN 5 + # 1 6 7 8 9 10 11 + + # check consistency of the following calls for any single level n + # stack(level=n, sequentially=True) + # stack(level=n, sequentially=False) + # stack(level=[n], sequentially=True) + # stack(level=[n], sequentially=False) + for df in (df_nonan, df_nan): + for lev in (-1, 0, 1, 2, 'ABC', 'abc', 'XYZ'): + for dropna in (True, False): + expected = None + for level in (lev, [lev]): + for sequentially in (True, False): + result = df.stack(level=level, dropna=dropna, sequentially=sequentially) + if expected is None: + expected = result + else: + assert_frame_equal(result, expected) + + # check that result of stacking a single level is as expected + result = df_nonan.stack(level=0, dropna=False) + expected = DataFrame([[0, 1, None, 2, None], + [None, None, 3, 5, 4], + [6, 7, None, 8, None], + [None, None, 9, 11, 10]], + index=MultiIndex.from_tuples([(0,'A'), (0,'B'), + (1,'A'), (1,'B')], + names=[None, 'ABC']), + columns=MultiIndex.from_tuples([('a','X'), ('a','Y'), ('a','Z'), + ('b','X'), ('b','Y')], + names=['abc', 'XYZ']), + dtype=np.float64) + # abc a b + # XYZ X Y Z X Y + # ABC + # 0 A 0 1 NaN 2 NaN + # B NaN NaN 3 5 4 + # 1 A 6 7 NaN 8 NaN + # B NaN NaN 9 11 10 + assert_frame_equal(result, expected) + + # when dropna=False, missing values should not affect shape of result + result = df_nan.stack(level=0, dropna=False) + expected = expected.replace(1, nan).replace(4, nan) + assert_frame_equal(result, expected) + + # dropna=True has the effect of dropping all empty rows in the result + result = df_nan.stack(level=0, dropna=True) + expected.dropna(axis=0, how='all', inplace=True) + assert_frame_equal(result, expected) + + # check that result of stacking two levels simultaneously is as expected + result = df_nonan.stack(level=[0, 2], dropna=False, sequentially=False) + expected = DataFrame([[0, 2], + [1, None], + [None, 5], + [None, 4], + [3, None], + [6, 8], + [7, None], + [None, 11], + [None, 10], + [9, None]], + index=MultiIndex.from_tuples([(0,'A','X'), (0,'A','Y'), + (0,'B','X'), (0,'B','Y'), (0,'B','Z'), + (1,'A','X'), (1,'A','Y'), + (1,'B','X'), (1,'B','Y'), (1,'B','Z')], + names=[None, 'ABC', 'XYZ']), + columns=Index(['a', 'b'], name='abc'), + dtype=np.float64) + # abc a b + # ABC XYZ + # 0 A X 0 2 + # Y 1 NaN + # B X NaN 5 + # Y NaN 4 + # Z 3 NaN + # 1 A X 6 8 + # Y 7 NaN + # B X NaN 11 + # Y NaN 10 + # Z 9 NaN + assert_frame_equal(result, expected) + + # when sequentially=False and the DataFrame has no missing values, the value of dropna shouldn't matter + result = df_nonan.stack(level=[0, 2], dropna=True, sequentially=False) + assert_frame_equal(result, expected) + + # when dropna=True, the value of sequentially shouldn't matter + result = df_nonan.stack(level=[0, 2], dropna=True, sequentially=True) + assert_frame_equal(result, expected) + + # when dropna=False and sequentially=False, missing values don't affect the shape of the result + result = df_nan.stack(level=[0, 2], dropna=False, sequentially=False) + expected = expected.replace(1, nan).replace(4, nan) + assert_frame_equal(result, expected) + + # dropna=True has the effect of dropping all empty rows in the result + result = df_nan.stack(level=[0, 2], dropna=True, sequentially=False) + expected.dropna(axis=0, how='all', inplace=True) + assert_frame_equal(result, expected) + + # when dropna=True, the value of sequentially shouldn't matter + result = df_nan.stack(level=[0, 2], dropna=True, sequentially=True) + assert_frame_equal(result, expected) + + def test_stack_and_unstack_all_product_levels(self): + # GH 8851 + + for index in (Index([0, 1]), + MultiIndex.from_tuples([(0, 100), (1, 101)], + names=[None, 'Hundred'])): + pass + + df = DataFrame(np.arange(2 * 3).reshape((2, 3)), + columns=Index(['x', 'y', 'z'], name='Lower'), + dtype=np.float64) + # Lower x y z + # 0 0 1 2 + # 1 3 4 5 + + # stacking with any parameters should produce the following: + expected = Series(np.arange(2 * 3), + index=MultiIndex.from_product([[0, 1], ['x', 'y', 'z']], + names=[None, 'Lower']), + dtype=np.float64) + # Lower + # 0 x 0 + # y 1 + # z 2 + # 1 x 3 + # y 4 + # z 5 + for level in (-1, 0, [0], None): + for dropna in (True, False): + for sequentially in (True, False): + result = df.stack(level=level, dropna=dropna, sequentially=sequentially) + assert_series_equal(result, expected) + result = df.T.unstack(level=level, dropna=dropna, sequentially=sequentially) + assert_series_equal(result, expected) + + df = DataFrame(np.arange(2 * 4).reshape((2, 4)), + columns=MultiIndex.from_product([['A', 'B'], ['x', 'y']], + names=['Upper', 'Lower']), + dtype=np.float64) + # Upper A B + # Lower x y x y + # 0 0 1 2 3 + # 1 4 5 6 7 + + # stacking all column levels in order should produce the following: + expected = Series(np.arange(2 * 4), + index=MultiIndex.from_product([[0, 1], ['A', 'B'], ['x', 'y']], + names=[None, 'Upper', 'Lower']), + dtype=np.float64) + # Upper Lower + # 0 A x 0 + # y 1 + # B x 2 + # y 3 + # 1 A x 4 + # y 5 + # B x 6 + # y 7 + # dtype: float64 + for level in ([0, 1], None): + for dropna in (True, False): + for sequentially in (True, False): + result = df.stack(level=level, dropna=dropna, sequentially=sequentially) + assert_series_equal(result, expected) + result = df.T.unstack(level=level, dropna=dropna, sequentially=sequentially) + assert_series_equal(result, expected) + + # stacking all column levels in reverse order should produce the following: + expected = Series([0, 2, 1, 3, 4, 6, 5, 7], + index=MultiIndex.from_product([[0, 1], ['x', 'y'], ['A', 'B']], + names=[None, 'Lower', 'Upper']), + dtype=np.float64) + # Lower Upper + # 0 x A 0 + # B 2 + # y A 1 + # B 3 + # 1 x A 4 + # B 6 + # y A 5 + # B 7 + # dtype: float64 + for dropna in (True, False): + for sequentially in (True, False): + result = df.stack(level=[1, 0], dropna=dropna, sequentially=sequentially) + assert_series_equal(result, expected) + if sequentially: + # DataFrame.unstack() does not properly sort list levels; see GH 9514 + result = df.T.unstack(level=[1, 0], dropna=dropna, sequentially=sequentially) + assert_series_equal(result, expected) + + def test_stack_all_levels_multiindex_columns(self): + # GH 8851 + + df = DataFrame(np.arange(2 * 3).reshape((2, 3)), + columns=MultiIndex.from_tuples([('A','x'), ('A','y'), ('B','z')], + names=['Upper', 'Lower']), + dtype=np.float64) + # Upper A B + # Lower x y z + # 0 0 1 2 + # 1 3 4 5 + + # stacking all column levels with sequentially=False should produce the following: + expected = Series(np.arange(2 * 3), + index=MultiIndex.from_tuples([(0,'A','x'), (0,'A','y'), (0,'B','z'), + (1,'A','x'), (1,'A','y'), (1,'B','z')], + names=[None, 'Upper', 'Lower']), + dtype=np.float64) + # Upper Lower + # 0 A x 0 + # y 1 + # B z 2 + # 1 A x 3 + # y 4 + # B z 5 + + # switching order of levels should correspond to swapping levels of result + expected_swapped = expected.copy() + expected_swapped.index = expected.index.swaplevel(1, 2) + + for dropna in (True, False): + for level in ([0, 1], [0, -1], None): + result = df.stack(level=level, dropna=dropna, sequentially=False) + assert_series_equal(result, expected) + + for level in ([1, 0], [-1, 0]): + result = df.stack(level=level, dropna=dropna, sequentially=False) + assert_series_equal(result, expected_swapped) + + # since df has no missing values, should get same result with dropna=True and sequentially=True + result = df.stack(level=[0, 1], dropna=True, sequentially=True) + assert_series_equal(result, expected) + + # stacking all column levels with dropna=False and sequentially=True + expected = Series([0, 1, None, None, None, 2, + 3, 4, None, None, None, 5], + index=MultiIndex.from_tuples([(0,'A','x'), (0,'A','y'), (0,'A','z'), + (0,'B','x'), (0,'B','y'), (0,'B','z'), + (1,'A','x'), (1,'A','y'), (1,'A','z'), + (1,'B','x'), (1,'B','y'), (1,'B','z')], + names=[None, 'Upper', 'Lower']), + dtype=np.float64) + # Upper Lower + # 0 A x 0 + # y 1 + # z NaN + # B x NaN + # y NaN + # z 2 + # 1 A x 3 + # y 4 + # z NaN + # B x NaN + # y NaN + # z 5 + + for level in ([0, 1], [0, -1], None): + result = df.stack(level=level, dropna=False, sequentially=True) + assert_series_equal(result, expected) + + # check that this is indeed the result of stacking levels sequentially + result = df.stack(level=0, dropna=False).stack(level=0, dropna=False) + assert_series_equal(result, expected) + + def test_stack_nan_index(self): + # GH 9406 + df = DataFrame({'A': list('aaaabbbb'),'B':range(8), 'C':range(8)}) + df.iloc[3, 1] = np.NaN + dfs = df.set_index(['A', 'B']).T + + result = dfs.stack(0) + data0 = [[3, 0, 1, 2, nan, nan, nan, nan], + [nan, nan, nan, nan, 4, 5, 6, 7]] + cols = Index([nan, 0, 1, 2, 4, 5, 6, 7], name='B') + idx = MultiIndex(levels=[['C'], ['a', 'b']], + labels=[[0, 0], [0, 1]], + names=[None, 'A']) + expected = DataFrame(data0, index=idx, columns=cols) + assert_frame_equal(result, expected) + + result = dfs.stack([0, 1], dropna=False, sequentially=True) + data = [x for y in data0 for x in y] + idx = MultiIndex(levels=[['C'], ['a', 'b'], [0., 1., 2., 4., 5., 6., 7.]], + labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], + [-1, 0, 1, 2, 3, 4, 5, 6, -1, 0, 1, 2, 3, 4, 5, 6]], + names=[None, 'A', 'B']) + expected = Series(data, index=idx) + assert_series_equal(result, expected) + + result = dfs.stack([0, 1], dropna=False, sequentially=False) + data = [3, 0, 1, 2, 4, 5, 6, 7] + idx = MultiIndex(levels=[['C'], ['a', 'b'], [0, 1, 2, 4, 5, 6, 7]], + labels=[[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 1], + [-1, 0, 1, 2, 3, 4, 5, 6]], + names=[None, 'A', 'B']) + expected = Series(data, index=idx, dtype=dfs.dtypes[0]) + assert_series_equal(result, expected) + + result = dfs.stack(1, dropna=False) + data1 = [list(tuple) for tuple in zip(*data0)] # transpose + cols = Index(['a', 'b'], name='A') + idx = MultiIndex(levels=[['C'], [0, 1, 2, 4, 5, 6, 7]], + labels=[[0, 0, 0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4, 5, 6]], + names=[None, 'B']) + expected = DataFrame(data1, index=idx, columns=cols) + assert_frame_equal(result, expected) + + result = dfs.stack([1, 0], dropna=False, sequentially=True) + data = [x for y in data1 for x in y] + idx = MultiIndex(levels=[['C'], [0, 1, 2, 4, 5, 6, 7], ['a', 'b']], + labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [-1, -1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6], + [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]], + names=[None, 'B', 'A']) + expected = Series(data, index=idx) + assert_series_equal(result, expected) + + result = dfs.stack([1, 0], dropna=False, sequentially=False) + idx = MultiIndex(levels=[['C'], [0, 1, 2, 4, 5, 6, 7], ['a', 'b']], + labels=[[0, 0, 0, 0, 0, 0, 0, 0], + [-1, 0, 1, 2, 3, 4, 5, 6], + [0, 0, 0, 0, 1, 1, 1, 1]], + names=[None, 'B', 'A']) + data = [3, 0, 1, 2, 4, 5, 6, 7] + expected = Series(data, index=idx, dtype=dfs.dtypes[0]) + assert_series_equal(result, expected) + + df_nan = DataFrame(np.arange(4).reshape(2, 2), + columns=MultiIndex.from_tuples([('A', np.nan), ('B', 'b')], + names=['Upper', 'Lower']), + index=Index([0, 1], name='Num'), + dtype=np.float64) + df_nonan = DataFrame(np.arange(4).reshape(2, 2), + columns=MultiIndex.from_tuples([('A', 'a'), ('B', 'b')], + names=['Upper', 'Lower']), + index=Index([0, 1], name='Num'), + dtype=np.float64) + for level in (0, 1, None, [1, 0]): + for dropna in (True, False): + for sequentially in (True, False): + result_nan = df_nan.stack(level, dropna=dropna, sequentially=sequentially) + result_nonan = df_nonan.stack(level, dropna=dropna, sequentially=sequentially) + assert_almost_equal(result_nan.values, result_nonan.values) + if level == 1: + tm.assert_index_equal(result_nan.columns, result_nonan.columns) + elif level == 0: + tm.assert_index_equal(result_nan.index, result_nonan.index) + + df = DataFrame([[11, 22], [33, 44]], + columns=MultiIndex.from_tuples([(1, 'a'), (None, 'b')], + names=['ints', 'letters'])) + + result = df.stack(0) + expected = DataFrame([[None, 22], [11, None], [None, 44], [33, None]], + columns=Index(['a', 'b'], name='letters'), + index=MultiIndex.from_product([[0, 1], [None, 1]], + names=[None, 'ints'])) + tm.assert_frame_equal(result, expected) + + result = df.stack(1) + expected = DataFrame([[None, 11], [22, None], [None, 33], [44, None]], + columns=Index([nan, 1], name='ints'), + index=MultiIndex.from_product([[0, 1], ['a', 'b']], + names=[None, 'letters'])) + tm.assert_frame_equal(result, expected) + def test_repr_with_mi_nat(self): df = DataFrame({'X': [1, 2]}, index=[[pd.NaT, pd.Timestamp('20130101')], ['a', 'b']]) @@ -14224,12 +14630,12 @@ def test_reset_index_multiindex_col(self): def test_reset_index_with_datetimeindex_cols(self): # GH5818 # - df = pd.DataFrame([[1, 2], [3, 4]], - columns=pd.date_range('1/1/2013', '1/2/2013'), + df = DataFrame([[1, 2], [3, 4]], + columns=date_range('1/1/2013', '1/2/2013'), index=['A', 'B']) result = df.reset_index() - expected = pd.DataFrame([['A', 1, 2], ['B', 3, 4]], + expected = DataFrame([['A', 1, 2], ['B', 3, 4]], columns=['index', datetime(2013, 1, 1), datetime(2013, 1, 2)]) assert_frame_equal(result, expected) @@ -14909,8 +15315,8 @@ def test_consolidate_datetime64(self): df.starting = ser_starting.index df.ending = ser_ending.index - tm.assert_index_equal(pd.DatetimeIndex(df.starting), ser_starting.index) - tm.assert_index_equal(pd.DatetimeIndex(df.ending), ser_ending.index) + tm.assert_index_equal(DatetimeIndex(df.starting), ser_starting.index) + tm.assert_index_equal(DatetimeIndex(df.ending), ser_ending.index) def _check_bool_op(self, name, alternative, frame=None, has_skipna=True, has_bool_only=False): @@ -15090,7 +15496,7 @@ def test_isin(self): def test_isin_empty(self): df = DataFrame({'A': ['a', 'b', 'c'], 'B': ['a', 'e', 'f']}) result = df.isin([]) - expected = pd.DataFrame(False, df.index, df.columns) + expected = DataFrame(False, df.index, df.columns) assert_frame_equal(result, expected) def test_isin_dict(self): @@ -15166,9 +15572,9 @@ def test_isin_dupe_self(self): assert_frame_equal(result, expected) def test_isin_against_series(self): - df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [2, np.nan, 4, 4]}, + df = DataFrame({'A': [1, 2, 3, 4], 'B': [2, np.nan, 4, 4]}, index=['a', 'b', 'c', 'd']) - s = pd.Series([1, 3, 11, 4], index=['a', 'b', 'c', 'd']) + s = Series([1, 3, 11, 4], index=['a', 'b', 'c', 'd']) expected = DataFrame(False, index=df.index, columns=df.columns) expected['A'].loc['a'] = True expected.loc['d'] = True @@ -15272,50 +15678,50 @@ def test_concat_empty_dataframe_dtypes(self): self.assertEqual(result['c'].dtype, np.float64) def test_empty_frame_dtypes_ftypes(self): - empty_df = pd.DataFrame() - assert_series_equal(empty_df.dtypes, pd.Series(dtype=np.object)) - assert_series_equal(empty_df.ftypes, pd.Series(dtype=np.object)) + empty_df = DataFrame() + assert_series_equal(empty_df.dtypes, Series(dtype=np.object)) + assert_series_equal(empty_df.ftypes, Series(dtype=np.object)) - nocols_df = pd.DataFrame(index=[1,2,3]) - assert_series_equal(nocols_df.dtypes, pd.Series(dtype=np.object)) - assert_series_equal(nocols_df.ftypes, pd.Series(dtype=np.object)) + nocols_df = DataFrame(index=[1,2,3]) + assert_series_equal(nocols_df.dtypes, Series(dtype=np.object)) + assert_series_equal(nocols_df.ftypes, Series(dtype=np.object)) - norows_df = pd.DataFrame(columns=list("abc")) - assert_series_equal(norows_df.dtypes, pd.Series(np.object, index=list("abc"))) - assert_series_equal(norows_df.ftypes, pd.Series('object:dense', index=list("abc"))) + norows_df = DataFrame(columns=list("abc")) + assert_series_equal(norows_df.dtypes, Series(np.object, index=list("abc"))) + assert_series_equal(norows_df.ftypes, Series('object:dense', index=list("abc"))) - norows_int_df = pd.DataFrame(columns=list("abc")).astype(np.int32) - assert_series_equal(norows_int_df.dtypes, pd.Series(np.dtype('int32'), index=list("abc"))) - assert_series_equal(norows_int_df.ftypes, pd.Series('int32:dense', index=list("abc"))) + norows_int_df = DataFrame(columns=list("abc")).astype(np.int32) + assert_series_equal(norows_int_df.dtypes, Series(np.dtype('int32'), index=list("abc"))) + assert_series_equal(norows_int_df.ftypes, Series('int32:dense', index=list("abc"))) odict = OrderedDict - df = pd.DataFrame(odict([('a', 1), ('b', True), ('c', 1.0)]), index=[1, 2, 3]) - assert_series_equal(df.dtypes, pd.Series(odict([('a', np.int64), + df = DataFrame(odict([('a', 1), ('b', True), ('c', 1.0)]), index=[1, 2, 3]) + assert_series_equal(df.dtypes, Series(odict([('a', np.int64), ('b', np.bool), ('c', np.float64)]))) - assert_series_equal(df.ftypes, pd.Series(odict([('a', 'int64:dense'), + assert_series_equal(df.ftypes, Series(odict([('a', 'int64:dense'), ('b', 'bool:dense'), ('c', 'float64:dense')]))) # same but for empty slice of df - assert_series_equal(df[:0].dtypes, pd.Series(odict([('a', np.int64), + assert_series_equal(df[:0].dtypes, Series(odict([('a', np.int64), ('b', np.bool), ('c', np.float64)]))) - assert_series_equal(df[:0].ftypes, pd.Series(odict([('a', 'int64:dense'), + assert_series_equal(df[:0].ftypes, Series(odict([('a', 'int64:dense'), ('b', 'bool:dense'), ('c', 'float64:dense')]))) def test_dtypes_are_correct_after_column_slice(self): # GH6525 - df = pd.DataFrame(index=range(5), columns=list("abc"), dtype=np.float_) + df = DataFrame(index=range(5), columns=list("abc"), dtype=np.float_) odict = OrderedDict assert_series_equal(df.dtypes, - pd.Series(odict([('a', np.float_), ('b', np.float_), + Series(odict([('a', np.float_), ('b', np.float_), ('c', np.float_),]))) assert_series_equal(df.iloc[:,2:].dtypes, - pd.Series(odict([('c', np.float_)]))) + Series(odict([('c', np.float_)]))) assert_series_equal(df.dtypes, - pd.Series(odict([('a', np.float_), ('b', np.float_), + Series(odict([('a', np.float_), ('b', np.float_), ('c', np.float_),]))) def test_set_index_names(self): @@ -15376,7 +15782,7 @@ def test_select_dtypes_exclude_include(self): 'c': np.arange(3, 6).astype('u1'), 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], - 'f': pd.date_range('now', periods=3).values}) + 'f': date_range('now', periods=3).values}) exclude = np.datetime64, include = np.bool_, 'integer' r = df.select_dtypes(include=include, exclude=exclude) @@ -15395,7 +15801,7 @@ def test_select_dtypes_not_an_attr_but_still_valid_dtype(self): 'c': np.arange(3, 6).astype('u1'), 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], - 'f': pd.date_range('now', periods=3).values}) + 'f': date_range('now', periods=3).values}) df['g'] = df.f.diff() assert not hasattr(np, 'u8') r = df.select_dtypes(include=['i8', 'O'], exclude=['timedelta']) @@ -15427,7 +15833,7 @@ def test_select_dtypes_bad_datetime64(self): 'c': np.arange(3, 6).astype('u1'), 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], - 'f': pd.date_range('now', periods=3).values}) + 'f': date_range('now', periods=3).values}) with tm.assertRaisesRegexp(ValueError, '.+ is too specific'): df.select_dtypes(include=['datetime64[D]']) @@ -15441,7 +15847,7 @@ def test_select_dtypes_str_raises(self): 'c': np.arange(3, 6).astype('u1'), 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], - 'f': pd.date_range('now', periods=3).values}) + 'f': date_range('now', periods=3).values}) string_dtypes = set((str, 'str', np.string_, 'S1', 'unicode', np.unicode_, 'U1')) try: @@ -15463,7 +15869,7 @@ def test_select_dtypes_bad_arg_raises(self): 'c': np.arange(3, 6).astype('u1'), 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], - 'f': pd.date_range('now', periods=3).values}) + 'f': date_range('now', periods=3).values}) with tm.assertRaisesRegexp(TypeError, 'data type.*not understood'): df.select_dtypes(['blargy, blarg, blarg']) @@ -16531,7 +16937,7 @@ def test_query_single_element_booleans(self): def check_query_string_scalar_variable(self, parser, engine): tm.skip_if_no_ne(engine) - df = pd.DataFrame({'Symbol': ['BUD US', 'BUD US', 'IBM US', 'IBM US'], + df = DataFrame({'Symbol': ['BUD US', 'BUD US', 'IBM US', 'IBM US'], 'Price': [109.70, 109.72, 183.30, 183.35]}) e = df[df.Symbol == 'BUD US'] symb = 'BUD US' diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index f7d93a978a46a..c947481c8a87c 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -4257,8 +4257,11 @@ def test_changing_names(self): self.check_level_names(self.index, new_names) def test_duplicate_names(self): + # GH 9399 self.index.names = ['foo', 'foo'] - assertRaisesRegexp(KeyError, 'Level foo not found', + assertRaisesRegexp(KeyError, 'Level bar not found', + self.index._get_level_number, 'bar') + assertRaisesRegexp(ValueError, 'The name foo occurs multiple times, use a level number', self.index._get_level_number, 'foo') def test_get_level_number_integer(self): @@ -4419,7 +4422,6 @@ def test_legacy_pickle(self): assert_almost_equal(exp, exp2) def test_legacy_v2_unpickle(self): - # 0.7.3 -> 0.8.0 format manage path = tm.get_data_path('mindex_073.pickle') obj = pd.read_pickle(path) @@ -4438,7 +4440,6 @@ def test_legacy_v2_unpickle(self): assert_almost_equal(exp, exp2) def test_roundtrip_pickle_with_tz(self): - # GH 8367 # round-trip of timezone index=MultiIndex.from_product([[1,2],['a','b'],date_range('20130101',periods=3,tz='US/Eastern')],names=['one','two','three']) diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index 50ae574c03067..e2e17dcb7d115 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -431,6 +431,7 @@ def test_pivot_timegrouper(self): columns='Carl Joe Mark'.split()) expected.index.name = 'Date' expected.columns.name = 'Buyer' + expected['Carl'] = expected['Carl'].astype(df.dtypes['Quantity']) result = pivot_table(df, index=Grouper(freq='6MS'), columns='Buyer', values='Quantity', aggfunc=np.sum)
closes #8851 closes #9399 closes #9406 closes #9533
https://api.github.com/repos/pandas-dev/pandas/pulls/9023
2014-12-06T19:11:36Z
2016-01-20T14:14:44Z
null
2023-05-11T01:12:45Z
Make Timestamp('now') equivalent to Timestamp.now()
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d64dbf6e14345..4468b267e9d7f 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -62,6 +62,9 @@ API changes - Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) +- Timestamp('now') is now equivalent to Timestamp.now() in that it returns the local time rather than UTC. Also, Timestamp('today') is now + equivalent to Timestamp.today() and both have tz as a possible argument. (:issue:`9000`) + .. _whatsnew_0152.enhancements: Enhancements diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 2e59febb2c62b..ad0ef67b5aca2 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -301,6 +301,36 @@ def test_barely_oob_dts(self): def test_utc_z_designator(self): self.assertEqual(get_timezone(Timestamp('2014-11-02 01:00Z').tzinfo), 'UTC') + def test_now(self): + # #9000 + ts_from_string = Timestamp('now') + ts_from_method = Timestamp.now() + ts_datetime = datetime.datetime.now() + + ts_from_string_tz = Timestamp('now', tz='US/Eastern') + ts_from_method_tz = Timestamp.now(tz='US/Eastern') + + # Check that the delta between the times is less than 1s (arbitrarily small) + delta = Timedelta(seconds=1) + self.assertTrue((ts_from_method - ts_from_string) < delta) + self.assertTrue((ts_from_method_tz - ts_from_string_tz) < delta) + self.assertTrue((ts_from_string_tz.tz_localize(None) - ts_from_string) < delta) + + def test_today(self): + + ts_from_string = Timestamp('today') + ts_from_method = Timestamp.today() + ts_datetime = datetime.datetime.today() + + ts_from_string_tz = Timestamp('today', tz='US/Eastern') + ts_from_method_tz = Timestamp.today(tz='US/Eastern') + + # Check that the delta between the times is less than 1s (arbitrarily small) + delta = Timedelta(seconds=1) + self.assertTrue((ts_from_method - ts_from_string) < delta) + self.assertTrue((ts_datetime - ts_from_method) < delta) + self.assertTrue((ts_datetime - ts_from_method) < delta) + self.assertTrue((ts_from_string_tz.tz_localize(None) - ts_from_string) < delta) class TestDatetimeParsingWrappers(tm.TestCase): def test_does_not_convert_mixed_integer(self): diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 4cb6c93bdf3d0..ae694840d0195 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -173,9 +173,9 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): result[i] = NaT else: if box: - result[i] = Timedelta(value) + result[i] = Timedelta(value) else: - result[i] = timedelta(microseconds=int(value)/1000) + result[i] = timedelta(microseconds=int(value)/1000) return result @@ -216,15 +216,32 @@ class Timestamp(_Timestamp): @classmethod def now(cls, tz=None): - """ compat now with datetime """ + """ + Return the current time in the local timezone. Equivalent + to datetime.now([tz]) + + Parameters + ---------- + tz : string / timezone object, default None + Timezone to localize to + """ if isinstance(tz, basestring): tz = maybe_get_tz(tz) return cls(datetime.now(tz)) @classmethod - def today(cls): - """ compat today with datetime """ - return cls(datetime.today()) + def today(cls, tz=None): + """ + Return the current time in the local timezone. This differs + from datetime.today() in that it can be localized to a + passed timezone. + + Parameters + ---------- + tz : string / timezone object, default None + Timezone to localize to + """ + return cls.now(tz) @classmethod def utcnow(cls): @@ -1021,6 +1038,14 @@ cdef convert_to_tsobject(object ts, object tz, object unit): if util.is_string_object(ts): if ts in _nat_strings: ts = NaT + elif ts == 'now': + # Issue 9000, we short-circuit rather than going + # into np_datetime_strings which returns utc + ts = Timestamp.now(tz) + elif ts == 'today': + # Issue 9000, we short-circuit rather than going + # into np_datetime_strings which returns a normalized datetime + ts = Timestamp.today(tz) else: try: _string_to_dts(ts, &obj.dts, &out_local, &out_tzoffset)
closes #9000 I opted to not change np_datetime_strings but instead short-circuit in Timestamp. I don't have a strong preference one way or another.
https://api.github.com/repos/pandas-dev/pandas/pulls/9022
2014-12-06T18:27:51Z
2014-12-07T21:01:06Z
2014-12-07T21:01:06Z
2014-12-22T14:55:29Z
reindex multi-index at level with reordered labels
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d64dbf6e14345..6e065c5818616 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -119,6 +119,7 @@ Bug Fixes - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) +- Bug in ``MultiIndex.reindex`` where reindexing at level would not reorder labels (:issue:`4088`) - Fix negative step support for label-based slices (:issue:`8753`) diff --git a/pandas/core/index.py b/pandas/core/index.py index 7d9f772126483..be17c36e65675 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1828,13 +1828,41 @@ def _join_non_unique(self, other, how='left', return_indexers=False): else: return join_index - def _join_level(self, other, level, how='left', return_indexers=False): + def _join_level(self, other, level, how='left', + return_indexers=False, + keep_order=True): """ The join method *only* affects the level of the resulting MultiIndex. Otherwise it just exactly aligns the Index data to the - labels of the level in the MultiIndex. The order of the data indexed by - the MultiIndex will not be changed (currently) - """ + labels of the level in the MultiIndex. If `keep_order` == True, the + order of the data indexed by the MultiIndex will not be changed; + otherwise, it will tie out with `other`. + """ + from pandas.algos import groupsort_indexer + + def _get_leaf_sorter(labels): + ''' + returns sorter for the inner most level while preserving the + order of higher levels + ''' + if labels[0].size == 0: + return np.empty(0, dtype='int64') + + if len(labels) == 1: + lab = com._ensure_int64(labels[0]) + sorter, _ = groupsort_indexer(lab, 1 + lab.max()) + return sorter + + # find indexers of begining of each set of + # same-key labels w.r.t all but last level + tic = labels[0][:-1] != labels[0][1:] + for lab in labels[1:-1]: + tic |= lab[:-1] != lab[1:] + + starts = np.hstack(([True], tic, [True])).nonzero()[0] + lab = com._ensure_int64(labels[-1]) + return lib.get_level_sorter(lab, starts) + if isinstance(self, MultiIndex) and isinstance(other, MultiIndex): raise TypeError('Join on level between two MultiIndex objects ' 'is ambiguous') @@ -1849,33 +1877,69 @@ def _join_level(self, other, level, how='left', return_indexers=False): level = left._get_level_number(level) old_level = left.levels[level] + if not right.is_unique: + raise NotImplementedError('Index._join_level on non-unique index ' + 'is not implemented') + new_level, left_lev_indexer, right_lev_indexer = \ old_level.join(right, how=how, return_indexers=True) - if left_lev_indexer is not None: + if left_lev_indexer is None: + if keep_order or len(left) == 0: + left_indexer = None + join_index = left + else: # sort the leaves + left_indexer = _get_leaf_sorter(left.labels[:level + 1]) + join_index = left[left_indexer] + + else: left_lev_indexer = com._ensure_int64(left_lev_indexer) rev_indexer = lib.get_reverse_indexer(left_lev_indexer, len(old_level)) new_lev_labels = com.take_nd(rev_indexer, left.labels[level], allow_fill=False) - omit_mask = new_lev_labels != -1 new_labels = list(left.labels) new_labels[level] = new_lev_labels - if not omit_mask.all(): - new_labels = [lab[omit_mask] for lab in new_labels] - new_levels = list(left.levels) new_levels[level] = new_level - join_index = MultiIndex(levels=new_levels, labels=new_labels, - names=left.names, verify_integrity=False) - left_indexer = np.arange(len(left))[new_lev_labels != -1] - else: - join_index = left - left_indexer = None + if keep_order: # just drop missing values. o.w. keep order + left_indexer = np.arange(len(left)) + mask = new_lev_labels != -1 + if not mask.all(): + new_labels = [lab[mask] for lab in new_labels] + left_indexer = left_indexer[mask] + + else: # tie out the order with other + if level == 0: # outer most level, take the fast route + ngroups = 1 + new_lev_labels.max() + left_indexer, counts = groupsort_indexer(new_lev_labels, + ngroups) + # missing values are placed first; drop them! + left_indexer = left_indexer[counts[0]:] + new_labels = [lab[left_indexer] for lab in new_labels] + + else: # sort the leaves + mask = new_lev_labels != -1 + mask_all = mask.all() + if not mask_all: + new_labels = [lab[mask] for lab in new_labels] + + left_indexer = _get_leaf_sorter(new_labels[:level + 1]) + new_labels = [lab[left_indexer] for lab in new_labels] + + # left_indexers are w.r.t masked frame. + # reverse to original frame! + if not mask_all: + left_indexer = mask.nonzero()[0][left_indexer] + + join_index = MultiIndex(levels=new_levels, + labels=new_labels, + names=left.names, + verify_integrity=False) if right_lev_indexer is not None: right_indexer = com.take_nd(right_lev_indexer, @@ -3925,7 +3989,8 @@ def reindex(self, target, method=None, level=None, limit=None): else: target = _ensure_index(target) target, indexer, _ = self._join_level(target, level, how='right', - return_indexers=True) + return_indexers=True, + keep_order=False) else: if self.equals(target): indexer = None diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 2a5b93d111acc..71aeaf0895035 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -1138,6 +1138,27 @@ def row_bool_subset_object(ndarray[object, ndim=2] values, return out +@cython.boundscheck(False) +@cython.wraparound(False) +def get_level_sorter(ndarray[int64_t, ndim=1] label, + ndarray[int64_t, ndim=1] starts): + """ + argsort for a single level of a multi-index, keeping the order of higher + levels unchanged. `starts` points to starts of same-key indices w.r.t + to leading levels; equivalent to: + np.hstack([label[starts[i]:starts[i+1]].argsort(kind='mergesort') + + starts[i] for i in range(len(starts) - 1)]) + """ + cdef: + int64_t l, r + Py_ssize_t i + ndarray[int64_t, ndim=1] out = np.empty(len(label), dtype=np.int64) + + for i in range(len(starts) - 1): + l, r = starts[i], starts[i + 1] + out[l:r] = l + label[l:r].argsort(kind='mergesort') + + return out def group_count(ndarray[int64_t] values, Py_ssize_t size): cdef: diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 67f86a1c6cb7e..40823537dbc04 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -1897,6 +1897,66 @@ def test_reversed_reindex_ffill_raises(self): self.assertRaises(ValueError, df.reindex, dr[::-1], method='ffill') self.assertRaises(ValueError, df.reindex, dr[::-1], method='bfill') + def test_reindex_level(self): + from itertools import permutations + icol = ['jim', 'joe', 'jolie'] + + def verify_first_level(df, level, idx): + f = lambda val: np.nonzero(df[level] == val)[0] + i = np.concatenate(list(map(f, idx))) + left = df.set_index(icol).reindex(idx, level=level) + right = df.iloc[i].set_index(icol) + assert_frame_equal(left, right) + + def verify(df, level, idx, indexer): + left = df.set_index(icol).reindex(idx, level=level) + right = df.iloc[indexer].set_index(icol) + assert_frame_equal(left, right) + + df = pd.DataFrame({'jim':list('B' * 4 + 'A' * 2 + 'C' * 3), + 'joe':list('abcdeabcd')[::-1], + 'jolie':[10, 20, 30] * 3, + 'joline': np.random.randint(0, 1000, 9)}) + + target = [['C', 'B', 'A'], ['F', 'C', 'A', 'D'], ['A'], ['D', 'F'], + ['A', 'B', 'C'], ['C', 'A', 'B'], ['C', 'B'], ['C', 'A'], + ['A', 'B'], ['B', 'A', 'C'], ['A', 'C', 'B']] + + for idx in target: + verify_first_level(df, 'jim', idx) + + verify(df, 'joe', list('abcde'), [3, 2, 1, 0, 5, 4, 8, 7, 6]) + verify(df, 'joe', list('abcd'), [3, 2, 1, 0, 5, 8, 7, 6]) + verify(df, 'joe', list('abc'), [3, 2, 1, 8, 7, 6]) + verify(df, 'joe', list('eca'), [1, 3, 4, 6, 8]) + verify(df, 'joe', list('edc'), [0, 1, 4, 5, 6]) + verify(df, 'joe', list('eadbc'), [3, 0, 2, 1, 4, 5, 8, 7, 6]) + verify(df, 'joe', list('edwq'), [0, 4, 5]) + verify(df, 'joe', list('wq'), []) + + df = DataFrame({'jim':['mid'] * 5 + ['btm'] * 8 + ['top'] * 7, + 'joe':['3rd'] * 2 + ['1st'] * 3 + ['2nd'] * 3 + + ['1st'] * 2 + ['3rd'] * 3 + ['1st'] * 2 + + ['3rd'] * 3 + ['2nd'] * 2, + 'jolie':np.random.randint(0, 1000, 20), + 'joline': np.random.randn(20).round(3) * 10}) + + for idx in permutations(df['jim'].unique()): + for i in range(3): + verify_first_level(df, 'jim', idx[:i+1]) + + i = [2,3,4,0,1,8,9,5,6,7,10,11,12,13,14,18,19,15,16,17] + verify(df, 'joe', ['1st', '2nd', '3rd'], i) + + i = [0,1,2,3,4,10,11,12,5,6,7,8,9,15,16,17,18,19,13,14] + verify(df, 'joe', ['3rd', '2nd', '1st'], i) + + i = [0,1,5,6,7,10,11,12,18,19,15,16,17] + verify(df, 'joe', ['2nd', '3rd'], i) + + i = [0,1,2,3,4,10,11,12,8,9,15,16,17,13,14] + verify(df, 'joe', ['3rd', '1st'], i) + def test_getitem_ix_float_duplicates(self): df = pd.DataFrame(np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list('abc'))
closes https://github.com/pydata/pandas/issues/4088 on branch: ``` >>> df vals first second third mid 3rd 992 1.96 562 12.06 1st 73 -6.46 818 -15.75 658 5.90 btm 2nd 915 9.75 474 -1.47 905 -6.03 1st 717 8.01 909 -21.12 3rd 616 11.91 675 1.06 579 -4.01 top 1st 241 1.79 363 1.71 3rd 677 13.38 238 -16.77 407 17.19 2nd 728 -21.55 36 8.09 >>> df.reindex(['top', 'mid', 'btm'], level='first') vals first second third top 1st 241 1.79 363 1.71 3rd 677 13.38 238 -16.77 407 17.19 2nd 728 -21.55 36 8.09 mid 3rd 992 1.96 562 12.06 1st 73 -6.46 818 -15.75 658 5.90 btm 2nd 915 9.75 474 -1.47 905 -6.03 1st 717 8.01 909 -21.12 3rd 616 11.91 675 1.06 579 -4.01 >>> df.reindex(['1st', '2nd', '3rd'], level='second') vals first second third mid 1st 73 -6.46 818 -15.75 658 5.90 3rd 992 1.96 562 12.06 btm 1st 717 8.01 909 -21.12 2nd 915 9.75 474 -1.47 905 -6.03 3rd 616 11.91 675 1.06 579 -4.01 top 1st 241 1.79 363 1.71 2nd 728 -21.55 36 8.09 3rd 677 13.38 238 -16.77 407 17.19 >>> df.reindex(['top', 'btm'], level='first').reindex(['1st', '2nd'], level='second') vals first second third top 1st 241 1.79 363 1.71 2nd 728 -21.55 36 8.09 btm 1st 717 8.01 909 -21.12 2nd 915 9.75 474 -1.47 905 -6.03 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/9019
2014-12-06T15:51:22Z
2014-12-07T00:18:23Z
2014-12-07T00:18:23Z
2014-12-07T00:29:18Z
BUG: Prevent index header column from being added on MultiIndex when ind...
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a1a353980f7aa..596bb841f16c9 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -155,6 +155,7 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) - Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) +- Fixed Multindex to_html index=False adds an extra column (:issue:`8452`) diff --git a/pandas/core/format.py b/pandas/core/format.py index dbfe78d93bdcd..a17c45b70c74b 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -959,6 +959,10 @@ def _column_header(): name = self.columns.names[lnum] row = [''] * (row_levels - 1) + ['' if name is None else com.pprint_thing(name)] + + if row == [""] and self.fmt.index is False: + row = [] + tags = {} j = len(row) for i, v in enumerate(values): diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index ba3daf1b52045..80f1733ab4be5 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -571,6 +571,47 @@ def test_to_html_escape_disabled(self): </table>""" self.assertEqual(xp, rs) + def test_to_html_multiindex_index_false(self): + # issue 8452 + df = pd.DataFrame({ + 'a': range(2), + 'b': range(3, 5), + 'c': range(5, 7), + 'd': range(3, 5)} + ) + df.columns = pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']]) + result = df.to_html(index=False) + expected = """\ +<table border="1" class="dataframe"> + <thead> + <tr> + <th colspan="2" halign="left">a</th> + <th colspan="2" halign="left">b</th> + </tr> + <tr> + <th>c</th> + <th>d</th> + <th>c</th> + <th>d</th> + </tr> + </thead> + <tbody> + <tr> + <td> 0</td> + <td> 3</td> + <td> 5</td> + <td> 3</td> + </tr> + <tr> + <td> 1</td> + <td> 4</td> + <td> 6</td> + <td> 4</td> + </tr> + </tbody> +</table>""" + self.assertEqual(result, expected) + def test_to_html_multiindex_sparsify_false_multi_sparse(self): with option_context('display.multi_sparse', False): index = pd.MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]],
Fix for #8452 Index column was added when index=False.
https://api.github.com/repos/pandas-dev/pandas/pulls/9018
2014-12-06T01:01:08Z
2014-12-07T22:27:17Z
2014-12-07T22:27:17Z
2014-12-07T22:27:24Z
TST: better testing for test_where (GH8997)
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 4852e142d2f29..45b278dc32a0e 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -909,8 +909,8 @@ def test_searchsorted(self): exp = np.array([1]) self.assert_numpy_array_equal(res, exp) self.assert_numpy_array_equal(res, chk) - - # Searching for a value that is not present in the Categorical + + # Searching for a value that is not present in the Categorical res = c1.searchsorted(['bread', 'eggs']) chk = s1.searchsorted(['bread', 'eggs']) exp = np.array([1, 4]) @@ -927,7 +927,7 @@ def test_searchsorted(self): # As above, but with a sorter array to reorder an unsorted array res = c2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) chk = s2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) - exp = np.array([3, 5]) # eggs after donuts, after switching milk and donuts + exp = np.array([3, 5]) # eggs after donuts, after switching milk and donuts self.assert_numpy_array_equal(res, exp) self.assert_numpy_array_equal(res, chk) @@ -2477,7 +2477,7 @@ def test_to_records(self): result = df.to_records() expected = np.rec.array([(0, 'a'), (1, 'b'), (2, 'c')], dtype=[('index', '<i8'), ('0', 'O')]) - tm.assert_almost_equal(result,expected) + tm.assert_numpy_array_equal(result,expected) def test_numeric_like_ops(self):
closes #8996
https://api.github.com/repos/pandas-dev/pandas/pulls/9015
2014-12-05T20:38:36Z
2014-12-06T15:17:00Z
null
2015-05-05T08:23:02Z
ENH: Implement Series.StringMethod.slice_replace
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 839a055bf2a63..e58bb6f703b3d 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -62,6 +62,8 @@ Enhancements - Paths beginning with ~ will now be expanded to begin with the user's home directory (:issue:`9066`) - Added time interval selection in get_data_yahoo (:issue:`9071`) +- Added ``Series.str.slice_replace()``, which previously raised NotImplementedError (:issue:`8888`) + Performance ~~~~~~~~~~~ diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 2c2a98c0c5434..9d4994e0f2de9 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -687,15 +687,34 @@ def str_slice(arr, start=None, stop=None, step=None): def str_slice_replace(arr, start=None, stop=None, repl=None): """ + Replace a slice of each string with another string. Parameters ---------- + start : int or None + stop : int or None + repl : str or None Returns ------- replaced : array """ - raise NotImplementedError + if repl is None: + repl = '' + + def f(x): + if x[start:stop] == '': + local_stop = start + else: + local_stop = stop + y = '' + if start is not None: + y += x[:start] + y += repl + if stop is not None: + y += x[local_stop:] + return y + return _na_map(f, arr) def str_strip(arr, to_strip=None): @@ -998,9 +1017,10 @@ def slice(self, start=None, stop=None, step=None): result = str_slice(self.series, start, stop, step) return self._wrap_result(result) - @copy(str_slice) - def slice_replace(self, i=None, j=None): - raise NotImplementedError + @copy(str_slice_replace) + def slice_replace(self, start=None, stop=None, repl=None): + result = str_slice_replace(self.series, start, stop, repl) + return self._wrap_result(result) @copy(str_decode) def decode(self, encoding, errors="strict"): diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 06f507a50f785..50dba3bc7218a 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -963,7 +963,39 @@ def test_slice(self): tm.assert_series_equal(result, exp) def test_slice_replace(self): - pass + values = Series(['short', 'a bit longer', 'evenlongerthanthat', '', NA]) + + exp = Series(['shrt', 'a it longer', 'evnlongerthanthat', '', NA]) + result = values.str.slice_replace(2, 3) + tm.assert_series_equal(result, exp) + + exp = Series(['shzrt', 'a zit longer', 'evznlongerthanthat', 'z', NA]) + result = values.str.slice_replace(2, 3, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shzort', 'a zbit longer', 'evzenlongerthanthat', 'z', NA]) + result = values.str.slice_replace(2, 2, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shzort', 'a zbit longer', 'evzenlongerthanthat', 'z', NA]) + result = values.str.slice_replace(2, 1, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shorz', 'a bit longez', 'evenlongerthanthaz', 'z', NA]) + result = values.str.slice_replace(-1, None, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['zrt', 'zer', 'zat', 'z', NA]) + result = values.str.slice_replace(None, -2, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['shortz', 'a bit znger', 'evenlozerthanthat', 'z', NA]) + result = values.str.slice_replace(6, 8, 'z') + tm.assert_series_equal(result, exp) + + exp = Series(['zrt', 'a zit longer', 'evenlongzerthanthat', 'z', NA]) + result = values.str.slice_replace(-10, 3, 'z') + tm.assert_series_equal(result, exp) def test_strip_lstrip_rstrip(self): values = Series([' aa ', ' bb \n', NA, 'cc '])
closes #8888 This does not implement immerrr's suggestion of implementing `__setitem__`, as all `StringMethod` methods return a new `Series` (or `DataFrame`) rather than mutating.
https://api.github.com/repos/pandas-dev/pandas/pulls/9014
2014-12-05T19:57:58Z
2015-01-08T01:59:16Z
2015-01-08T01:59:16Z
2015-01-08T02:01:29Z
BUG: Bug in using a pd.Grouper(key=...) with no level/axis or level only (GH8795, GH8866)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a1a353980f7aa..10b23605cca85 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -98,6 +98,7 @@ Bug Fixes - Bug in Timestamp-Timestamp not returning a Timedelta type and datelike-datelike ops with timezones (:issue:`8865`) - Made consistent a timezone mismatch exception (either tz operated with None or incompatible timezone), will now return ``TypeError`` rather than ``ValueError`` (a couple of edge cases only), (:issue:`8865`) +- Bug in using a ``pd.Grouper(key=...)`` with no level/axis or level only (:issue:`8795`, :issue:`8866`) - Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) - Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) - Bug in ``groupby`` signatures that didn't include \*args or \*\*kwargs (:issue:`8733`). diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4b85da1b7b224..4c221cc27fdce 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -168,7 +168,7 @@ class Grouper(object): freq : string / freqency object, defaults to None This will groupby the specified frequency if the target selection (via key or level) is a datetime-like object - axis : number/name of the axis, defaults to None + axis : number/name of the axis, defaults to 0 sort : boolean, default to False whether to sort the resulting labels @@ -198,7 +198,7 @@ def __new__(cls, *args, **kwargs): cls = TimeGrouper return super(Grouper, cls).__new__(cls) - def __init__(self, key=None, level=None, freq=None, axis=None, sort=False): + def __init__(self, key=None, level=None, freq=None, axis=0, sort=False): self.key=key self.level=level self.freq=freq @@ -228,6 +228,8 @@ def _get_grouper(self, obj): """ self._set_grouper(obj) + self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key], axis=self.axis, + level=self.level, sort=self.sort) return self.binner, self.grouper, self.obj def _set_grouper(self, obj, sort=False): diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index a9ea64f54f51e..f60cf0a184832 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -373,6 +373,39 @@ def test_grouper_multilevel_freq(self): pd.Grouper(level=1, freq='W')]).sum() assert_frame_equal(result, expected) + def test_grouper_creation_bug(self): + + # GH 8795 + df = DataFrame({'A':[0,0,1,1,2,2], 'B':[1,2,3,4,5,6]}) + g = df.groupby('A') + expected = g.sum() + + g = df.groupby(pd.Grouper(key='A')) + result = g.sum() + assert_frame_equal(result, expected) + + result = g.apply(lambda x: x.sum()) + assert_frame_equal(result, expected) + + g = df.groupby(pd.Grouper(key='A',axis=0)) + result = g.sum() + assert_frame_equal(result, expected) + + # GH8866 + s = Series(np.arange(8), + index=pd.MultiIndex.from_product([list('ab'), + range(2), + date_range('20130101',periods=2)], + names=['one','two','three'])) + result = s.groupby(pd.Grouper(level='three',freq='M')).sum() + expected = Series([28],index=Index([Timestamp('2013-01-31')],freq='M',name='three')) + assert_series_equal(result, expected) + + # just specifying a level breaks + result = s.groupby(pd.Grouper(level='one')).sum() + expected = s.groupby(level='one').sum() + assert_series_equal(result, expected) + def test_grouper_iter(self): self.assertEqual(sorted(self.df.groupby('A').grouper), ['bar', 'foo'])
closes #8795 closes #8866
https://api.github.com/repos/pandas-dev/pandas/pulls/9008
2014-12-05T01:58:13Z
2014-12-05T02:34:01Z
2014-12-05T02:34:01Z
2014-12-05T02:34:01Z
Fix groupby().transform() example in cookbook.rst
diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index 8378873db9a65..81fe4aac51dd7 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -489,10 +489,10 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to .. ipython:: python def GrowUp(x): - avg_weight = sum(x[x.size == 'S'].weight * 1.5) - avg_weight += sum(x[x.size == 'M'].weight * 1.25) - avg_weight += sum(x[x.size == 'L'].weight) - avg_weight = avg_weight / len(x) + avg_weight = sum(x[x['size'] == 'S'].weight * 1.5) + avg_weight += sum(x[x['size'] == 'M'].weight * 1.25) + avg_weight += sum(x[x['size'] == 'L'].weight) + avg_weight /= len(x) return pd.Series(['L',avg_weight,True], index=['size', 'weight', 'adult']) expected_df = gb.apply(GrowUp)
@jorisvandenbossche : Fixes code in example, and makes final averaging by len(x) stylistically similar to previous adds. New pull request replacing my earlier one, which contained some other erroneous commits. closes #8944
https://api.github.com/repos/pandas-dev/pandas/pulls/9007
2014-12-05T00:24:42Z
2014-12-05T02:11:13Z
2014-12-05T02:11:13Z
2014-12-05T06:11:47Z
update NDFrame __setattr__ to match behavior of __getattr__
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a1a353980f7aa..47a82fdceb17b 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -61,6 +61,23 @@ API changes - Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) +- Bug in ``NDFrame``: conflicting attribute/column names now behave consistently between getting and setting. Previously, when both a column and attribute named ``y`` existed, ``data.y`` would return the attribute, while ``data.y = z`` would update the column (:issue:`8994`) + + .. ipython:: python + + data = pd.DataFrame({'x':[1, 2, 3]}) + data.y = 2 + data['y'] = [2, 4, 6] + data.y = 5 # this assignment was inconsistent + + print(data.y) + # prior output : 2 + # 0.15.2 output: 5 + + print(data['y'].values) + # prior output : [5, 5, 5] + # 0.15.2 output: [2, 4, 6] + .. _whatsnew_0152.enhancements: Enhancements diff --git a/pandas/core/generic.py b/pandas/core/generic.py index edea0b33e5b4f..d63643c53e6f4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1929,11 +1929,12 @@ def __finalize__(self, other, method=None, **kwargs): return self def __getattr__(self, name): - """After regular attribute access, try looking up the name of a the - info. - + """After regular attribute access, try looking up the name This allows simpler access to columns for interactive use. """ + # Note: obj.x will always call obj.__getattribute__('x') prior to + # calling obj.__getattr__('x'). + if name in self._internal_names_set: return object.__getattribute__(self, name) elif name in self._metadata: @@ -1945,12 +1946,24 @@ def __getattr__(self, name): (type(self).__name__, name)) def __setattr__(self, name, value): - """After regular attribute access, try looking up the name of the info + """After regular attribute access, try setting the name This allows simpler access to columns for interactive use.""" + # first try regular attribute access via __getattribute__, so that + # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify + # the same attribute. + + try: + object.__getattribute__(self, name) + return object.__setattr__(self, name, value) + except AttributeError: + pass + + # if this fails, go on to more involved attribute setting + # (note that this matches __getattr__, above). if name in self._internal_names_set: object.__setattr__(self, name, value) elif name in self._metadata: - return object.__setattr__(self, name, value) + object.__setattr__(self, name, value) else: try: existing = getattr(self, name) diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index 5e78e8dc44bea..40d6d2151155a 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -19,6 +19,7 @@ assert_frame_equal, assert_panel_equal, assert_almost_equal, + assert_equal, ensure_clean) import pandas.util.testing as tm @@ -1316,6 +1317,18 @@ def test_tz_convert_and_localize(self): df = DataFrame(index=l0) df = getattr(df, fn)('US/Pacific', level=1) + def test_set_attribute(self): + # Test for consistent setattr behavior when an attribute and a column + # have the same name (Issue #8994) + df = DataFrame({'x':[1, 2, 3]}) + + df.y = 2 + df['y'] = [2, 4, 6] + df.y = 5 + + assert_equal(df.y, 5) + assert_series_equal(df['y'], Series([2, 4, 6])) + class TestPanel(tm.TestCase, Generic): _typ = Panel
This addresses the issue raised in #8994. Here is the behavior before this PR: ``` python data = pd.DataFrame({'x':[1, 2, 3]}) data.y = 2 data['y'] = [2, 4, 6] data.y = 5 print(data.y) #2 print(data['y'].values) # [5, 5, 5] ``` Here is the behavior after this PR: ``` python data = pd.DataFrame({'x':[1, 2, 3]}) data.y = 2 data['y'] = [2, 4, 6] data.y = 5 print(data.y) #5 print(data['y'].values) # [2, 4, 6] ``` The fix boils down to the fact that when `data.y` is called, Python first calls `data.__getattribute__('y')` before calling `data.__getattr__('y')`, but when `data.y = 5` is called, Python goes directly to `data.__setattr__('y', 5)` without any prior search for defined attributes. I don't think there are any unintended side-effects to this change, but I'd appreciate some other folks thinking through whether this is the right solution. Thanks!
https://api.github.com/repos/pandas-dev/pandas/pulls/9004
2014-12-04T22:29:27Z
2014-12-07T15:15:07Z
null
2014-12-07T21:13:31Z
REGR: Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (GH8890)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 260e4e8a17c7d..4fbf7cbfa7c98 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -118,6 +118,7 @@ Bug Fixes s.loc['c':'a':-1] - Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) +- Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (:issue:`8890`) - Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) - Bug in ``groupby`` signatures that didn't include \*args or \*\*kwargs (:issue:`8733`). - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo and when it receives no data from Yahoo (:issue:`8761`), (:issue:`8783`). diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 436f9f3b9c9b3..12e10a71c67b2 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -2313,6 +2313,27 @@ def test_map(self): exp = [f(x) for x in rng] self.assert_numpy_array_equal(result, exp) + + def test_iteration_preserves_tz(self): + + tm._skip_if_no_dateutil() + + # GH 8890 + import dateutil + index = date_range("2012-01-01", periods=3, freq='H', tz='US/Eastern') + + for i, ts in enumerate(index): + result = ts + expected = index[i] + self.assertEqual(result, expected) + + index = date_range("2012-01-01", periods=3, freq='H', tz=dateutil.tz.tzoffset(None, -28800)) + + for i, ts in enumerate(index): + result = ts + expected = index[i] + self.assertEqual(result, expected) + def test_misc_coverage(self): rng = date_range('1/1/2000', periods=5) result = rng.groupby(rng.day) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 8efc174d6890b..02c1ae82a7fca 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -122,7 +122,9 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, offset=None, box=False): else: pandas_datetime_to_datetimestruct(value, PANDAS_FR_ns, &dts) dt = func_create(value, dts, tz, offset) - result[i] = dt + tz.utcoffset(dt) + if not box: + dt = dt + tz.utcoffset(dt) + result[i] = dt else: trans = _get_transitions(tz) deltas = _get_deltas(tz)
closes #8890
https://api.github.com/repos/pandas-dev/pandas/pulls/8990
2014-12-04T01:36:00Z
2014-12-04T02:47:31Z
2014-12-04T02:47:31Z
2014-12-04T02:47:31Z
FIX: use decorator to append read_frame/frame_query docstring (GH8315)
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index bb810b8509ef3..77527f867fad8 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -19,6 +19,7 @@ from pandas.core.common import isnull from pandas.core.base import PandasObject from pandas.tseries.tools import to_datetime +from pandas.util.decorators import Appender from contextlib import contextmanager @@ -1533,6 +1534,7 @@ def get_schema(frame, name, flavor='sqlite', keys=None, con=None): # legacy names, with depreciation warnings and copied docs +@Appender(read_sql.__doc__, join='\n') def read_frame(*args, **kwargs): """DEPRECATED - use read_sql """ @@ -1540,6 +1542,7 @@ def read_frame(*args, **kwargs): return read_sql(*args, **kwargs) +@Appender(read_sql.__doc__, join='\n') def frame_query(*args, **kwargs): """DEPRECATED - use read_sql """ @@ -1587,8 +1590,3 @@ def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs): index = kwargs.pop('index', False) return to_sql(frame, name, con, flavor=flavor, if_exists=if_exists, index=index, **kwargs) - - -# Append wrapped function docstrings -read_frame.__doc__ += read_sql.__doc__ -frame_query.__doc__ += read_sql.__doc__
Closes #8315
https://api.github.com/repos/pandas-dev/pandas/pulls/8988
2014-12-03T22:51:12Z
2014-12-04T08:27:53Z
2014-12-04T08:27:53Z
2014-12-04T10:43:27Z
User facing AssertionError in empty groupby GH5289
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4b85da1b7b224..774d9f651bae0 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2163,7 +2163,7 @@ def _convert_grouper(axis, grouper): return grouper.reindex(axis).values elif isinstance(grouper, (list, Series, Index, np.ndarray)): if len(grouper) != len(axis): - raise AssertionError('Grouper and axis must be same length') + raise ValueError('Grouper and axis must be same length') return grouper else: return grouper diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index bf24eda60b986..ef516be28431e 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -4847,6 +4847,11 @@ def test_groupby_categorical_two_columns(self): "C3":[nan,nan,nan,nan, 10,100,nan,nan, nan,nan,200,34]}, index=idx) tm.assert_frame_equal(res, exp) +def test_convert_grouper(axis, grouper): + def f(): + len(grouper) != len(axis) + self.assertRaisesRegexp(ValueError, 'Grouper and axis must be same length', f) + def assert_fp_equal(a, b): assert (np.abs(a - b) < 1e-12).all()
closes https://github.com/pydata/pandas/issues/5289 Is this all we need to do? Or am I missing something?
https://api.github.com/repos/pandas-dev/pandas/pulls/8987
2014-12-03T20:19:12Z
2015-05-09T15:59:39Z
null
2015-05-09T15:59:39Z
BUG: Dynamically created table names allow SQL injection
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index b3ac58a9fb84a..7a47cc68fb627 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -106,6 +106,7 @@ Enhancements - ``tseries.frequencies.to_offset()`` now accepts ``Timedelta`` as input (:issue:`9064`) - ``Timedelta`` will now accept nanoseconds keyword in constructor (:issue:`9273`) +- SQL code now safely escapes table and column names (:issue:`8986`) Performance ~~~~~~~~~~~ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index b4318bdc2a3bf..87c86e8ef91a8 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1239,18 +1239,58 @@ def _create_sql_schema(self, frame, table_name, keys=None): } +def _get_unicode_name(name): + try: + uname = name.encode("utf-8", "strict").decode("utf-8") + except UnicodeError: + raise ValueError("Cannot convert identifier to UTF-8: '%s'" % name) + return uname + +def _get_valid_mysql_name(name): + # Filter for unquoted identifiers + # See http://dev.mysql.com/doc/refman/5.0/en/identifiers.html + uname = _get_unicode_name(name) + if not len(uname): + raise ValueError("Empty table or column name specified") + + basere = r'[0-9,a-z,A-Z$_]' + for c in uname: + if not re.match(basere, c): + if not (0x80 < ord(c) < 0xFFFF): + raise ValueError("Invalid MySQL identifier '%s'" % uname) + if not re.match(r'[^0-9]', uname): + raise ValueError('MySQL identifier cannot be entirely numeric') + + return '`' + uname + '`' + + +def _get_valid_sqlite_name(name): + # See http://stackoverflow.com/questions/6514274/how-do-you-escape-strings-for-sqlite-table-column-names-in-python + # Ensure the string can be encoded as UTF-8. + # Ensure the string does not include any NUL characters. + # Replace all " with "". + # Wrap the entire thing in double quotes. + + uname = _get_unicode_name(name) + if not len(uname): + raise ValueError("Empty table or column name specified") + + nul_index = uname.find("\x00") + if nul_index >= 0: + raise ValueError('SQLite identifier cannot contain NULs') + return '"' + uname.replace('"', '""') + '"' + + # SQL enquote and wildcard symbols -_SQL_SYMB = { - 'mysql': { - 'br_l': '`', - 'br_r': '`', - 'wld': '%s' - }, - 'sqlite': { - 'br_l': '[', - 'br_r': ']', - 'wld': '?' - } +_SQL_WILDCARD = { + 'mysql': '%s', + 'sqlite': '?' +} + +# Validate and return escaped identifier +_SQL_GET_IDENTIFIER = { + 'mysql': _get_valid_mysql_name, + 'sqlite': _get_valid_sqlite_name, } @@ -1276,18 +1316,17 @@ def _execute_create(self): def insert_statement(self): names = list(map(str, self.frame.columns)) flv = self.pd_sql.flavor - br_l = _SQL_SYMB[flv]['br_l'] # left val quote char - br_r = _SQL_SYMB[flv]['br_r'] # right val quote char - wld = _SQL_SYMB[flv]['wld'] # wildcard char + wld = _SQL_WILDCARD[flv] # wildcard char + escape = _SQL_GET_IDENTIFIER[flv] if self.index is not None: [names.insert(0, idx) for idx in self.index[::-1]] - bracketed_names = [br_l + column + br_r for column in names] + bracketed_names = [escape(column) for column in names] col_names = ','.join(bracketed_names) wildcards = ','.join([wld] * len(names)) insert_statement = 'INSERT INTO %s (%s) VALUES (%s)' % ( - self.name, col_names, wildcards) + escape(self.name), col_names, wildcards) return insert_statement def _execute_insert(self, conn, keys, data_iter): @@ -1309,29 +1348,28 @@ def _create_table_setup(self): warnings.warn(_SAFE_NAMES_WARNING) flv = self.pd_sql.flavor + escape = _SQL_GET_IDENTIFIER[flv] - br_l = _SQL_SYMB[flv]['br_l'] # left val quote char - br_r = _SQL_SYMB[flv]['br_r'] # right val quote char + create_tbl_stmts = [escape(cname) + ' ' + ctype + for cname, ctype, _ in column_names_and_types] - create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, col_type) - for cname, col_type, _ in column_names_and_types] if self.keys is not None and len(self.keys): - cnames_br = ",".join([br_l + c + br_r for c in self.keys]) + cnames_br = ",".join([escape(c) for c in self.keys]) create_tbl_stmts.append( "CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format( tbl=self.name, cnames_br=cnames_br)) - create_stmts = ["CREATE TABLE " + self.name + " (\n" + + create_stmts = ["CREATE TABLE " + escape(self.name) + " (\n" + ',\n '.join(create_tbl_stmts) + "\n)"] ix_cols = [cname for cname, _, is_index in column_names_and_types if is_index] if len(ix_cols): cnames = "_".join(ix_cols) - cnames_br = ",".join([br_l + c + br_r for c in ix_cols]) + cnames_br = ",".join([escape(c) for c in ix_cols]) create_stmts.append( - "CREATE INDEX ix_{tbl}_{cnames} ON {tbl} ({cnames_br})".format( - tbl=self.name, cnames=cnames, cnames_br=cnames_br)) + "CREATE INDEX " + escape("ix_"+self.name+"_"+cnames) + + "ON " + escape(self.name) + " (" + cnames_br + ")") return create_stmts @@ -1505,19 +1543,23 @@ def to_sql(self, frame, name, if_exists='fail', index=True, table.insert(chunksize) def has_table(self, name, schema=None): + escape = _SQL_GET_IDENTIFIER[self.flavor] + esc_name = escape(name) + wld = _SQL_WILDCARD[self.flavor] flavor_map = { 'sqlite': ("SELECT name FROM sqlite_master " - "WHERE type='table' AND name='%s';") % name, - 'mysql': "SHOW TABLES LIKE '%s'" % name} + "WHERE type='table' AND name=%s;") % wld, + 'mysql': "SHOW TABLES LIKE %s" % wld} query = flavor_map.get(self.flavor) - return len(self.execute(query).fetchall()) > 0 + return len(self.execute(query, [name,]).fetchall()) > 0 def get_table(self, table_name, schema=None): return None # not supported in fallback mode def drop_table(self, name, schema=None): - drop_sql = "DROP TABLE %s" % name + escape = _SQL_GET_IDENTIFIER[self.flavor] + drop_sql = "DROP TABLE %s" % escape(name) self.execute(drop_sql) def _create_sql_schema(self, frame, table_name, keys=None): diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index b185d530e056c..804d925790a6e 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -865,7 +865,7 @@ def test_uquery(self): def _get_sqlite_column_type(self, schema, column): for col in schema.split('\n'): - if col.split()[0].strip('[]') == column: + if col.split()[0].strip('""') == column: return col.split()[1] raise ValueError('Column %s not found' % (column)) @@ -1630,6 +1630,24 @@ def test_notnull_dtype(self): self.assertEqual(self._get_sqlite_column_type(tbl, 'Int'), 'INTEGER') self.assertEqual(self._get_sqlite_column_type(tbl, 'Float'), 'REAL') + def test_illegal_names(self): + # For sqlite, these should work fine + df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) + + # Raise error on blank + self.assertRaises(ValueError, df.to_sql, "", self.conn, + flavor=self.flavor) + + for ndx, weird_name in enumerate(['test_weird_name]','test_weird_name[', + 'test_weird_name`','test_weird_name"', 'test_weird_name\'']): + df.to_sql(weird_name, self.conn, flavor=self.flavor) + sql.table_exists(weird_name, self.conn) + + df2 = DataFrame([[1, 2], [3, 4]], columns=['a', weird_name]) + c_tbl = 'test_weird_col_name%d'%ndx + df.to_sql(c_tbl, self.conn, flavor=self.flavor) + sql.table_exists(c_tbl, self.conn) + class TestMySQLLegacy(TestSQLiteFallback): """ @@ -1721,6 +1739,19 @@ def test_to_sql_save_index(self): def test_to_sql_save_index(self): self._to_sql_save_index() + def test_illegal_names(self): + # For MySQL, these should raise ValueError + for ndx, illegal_name in enumerate(['test_illegal_name]','test_illegal_name[', + 'test_illegal_name`','test_illegal_name"', 'test_illegal_name\'', '']): + df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) + self.assertRaises(ValueError, df.to_sql, illegal_name, self.conn, + flavor=self.flavor, index=False) + + df2 = DataFrame([[1, 2], [3, 4]], columns=['a', illegal_name]) + c_tbl = 'test_illegal_col_name%d'%ndx + self.assertRaises(ValueError, df2.to_sql, 'test_illegal_col_name', + self.conn, flavor=self.flavor, index=False) + #------------------------------------------------------------------------------ #--- Old tests from 0.13.1 (before refactor using sqlalchemy) @@ -1817,7 +1848,7 @@ def test_schema(self): frame = tm.makeTimeDataFrame() create_sql = sql.get_schema(frame, 'test', 'sqlite', keys=['A', 'B'],) lines = create_sql.splitlines() - self.assertTrue('PRIMARY KEY ([A],[B])' in create_sql) + self.assertTrue('PRIMARY KEY ("A","B")' in create_sql) cur = self.db.cursor() cur.execute(create_sql)
Working with the SQL code, I realized that the legacy code does not properly validate / escape passed in table and column names. E.g.: ``` n [116]: import pandas as pd import pandas.io.sql as sql import sqlite3 df = pd.DataFrame({'a':[1,2],'b':[2,3]}) con = sqlite3.connect(':memory:') db = sql.SQLiteDatabase(con, 'sqlite') t=sql.SQLiteTable('a; DELETE FROM contacts; INSERT INTO b', db, frame=df) print t.insert_statement() ``` results in: ``` INSERT INTO a; DELETE FROM contacts; INSERT INTO b ([index],[a],[b]) VALUES (?,?,?) ``` This fixes the issues.
https://api.github.com/repos/pandas-dev/pandas/pulls/8986
2014-12-03T19:47:26Z
2015-01-26T00:04:28Z
2015-01-26T00:04:27Z
2015-01-26T00:04:38Z
BUG in read_csv skipping rows after a row with trailing spaces, #8983
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 740263bed7970..e86b53ef745d3 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -165,7 +165,7 @@ Bug Fixes of the level names are numbers (:issue:`8584`). - Bug in ``MultiIndex`` where ``__contains__`` returns wrong result if index is not lexically sorted or unique (:issue:`7724`) -- BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`) +- BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`), (:issue:`8983`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 59647b4c781e5..05a5493d0c70c 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -3049,17 +3049,17 @@ def test_comment_skiprows(self): tm.assert_almost_equal(df.values, expected) def test_trailing_spaces(self): - data = """skip + data = """A B C random line with trailing spaces skip 1,2,3 1,2.,4. random line with trailing tabs\t\t\t -5.,NaN,10.0 +5.1,NaN,10.0 """ expected = pd.DataFrame([[1., 2., 4.], - [5., np.nan, 10.]]) + [5.1, np.nan, 10.]]) # this should ignore six lines including lines with trailing # whitespace and blank lines. issues 8661, 8679 df = self.read_csv(StringIO(data.replace(',', ' ')), @@ -3070,6 +3070,13 @@ def test_trailing_spaces(self): header=None, delim_whitespace=True, skiprows=[0,1,2,3,5,6], skip_blank_lines=True) tm.assert_frame_equal(df, expected) + # test skipping set of rows after a row with trailing spaces, issue #8983 + expected = pd.DataFrame({"A":[1., 5.1], "B":[2., np.nan], + "C":[4., 10]}) + df = self.read_table(StringIO(data.replace(',', ' ')), + delim_whitespace=True, + skiprows=[1,2,3,5,6], skip_blank_lines=True) + tm.assert_frame_equal(df, expected) def test_comment_header(self): data = """# empty diff --git a/pandas/src/parser/tokenizer.c b/pandas/src/parser/tokenizer.c index fc96cc5429775..a64235c7c9732 100644 --- a/pandas/src/parser/tokenizer.c +++ b/pandas/src/parser/tokenizer.c @@ -1324,6 +1324,7 @@ int tokenize_whitespace(parser_t *self, size_t line_limit) if (c == '\n') { END_LINE(); self->state = START_RECORD; + break; } else if (c == '\r') { self->state = EAT_CRNL; break;
Update tokenizer.c to fix a BUG in read_csv skipping rows after tokenizing a row with trailing spaces, Closes #8983
https://api.github.com/repos/pandas-dev/pandas/pulls/8984
2014-12-03T18:18:24Z
2014-12-03T21:56:45Z
2014-12-03T21:56:45Z
2014-12-03T23:55:42Z
FIX: Workaround for integer hashing
diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 45d3274088c75..6ef8de26906db 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -611,9 +611,10 @@ class StataMissingValue(StringMixin): MISSING_VALUES = {} bases = (101, 32741, 2147483621) for b in bases: - MISSING_VALUES[b] = '.' + # Conversion to long to avoid hash issues on 32 bit platforms #8968 + MISSING_VALUES[compat.long(b)] = '.' for i in range(1, 27): - MISSING_VALUES[i + b] = '.' + chr(96 + i) + MISSING_VALUES[compat.long(i + b)] = '.' + chr(96 + i) float32_base = b'\x00\x00\x00\x7f' increment = struct.unpack('<i', b'\x00\x08\x00\x00')[0] @@ -643,6 +644,8 @@ class StataMissingValue(StringMixin): def __init__(self, value): self._value = value + # Conversion to long to avoid hash issues on 32 bit platforms #8968 + value = compat.long(value) if value < 2147483648 else float(value) self._str = self.MISSING_VALUES[value] string = property(lambda self: self._str, @@ -1375,13 +1378,6 @@ def _pad_bytes(name, length): return name + "\x00" * (length - len(name)) -def _default_names(nvar): - """ - Returns default Stata names v1, v2, ... vnvar - """ - return ["v%d" % i for i in range(1, nvar+1)] - - def _convert_datetime_to_stata_type(fmt): """ Converts from one of the stata date formats to a type in TYPE_MAP
Force conversion to integer for missing values when they must be integer to avoid hash errors on 32 bit platforms. closes #8968
https://api.github.com/repos/pandas-dev/pandas/pulls/8982
2014-12-03T12:40:22Z
2014-12-06T15:10:53Z
2014-12-06T15:10:53Z
2015-01-18T22:42:16Z
BUG: Bug in Timestamp-Timestamp not returning a Timedelta type (GH8865)
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 260e4e8a17c7d..bdfa858bfb2e5 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -92,6 +92,24 @@ Experimental Bug Fixes ~~~~~~~~~ + +- Bug in Timestamp-Timestamp not returning a Timedelta type and datelike-datelike ops with timezones (:issue:`8865`) +- Made consistent a timezone mismatch exception (either tz operated with None or incompatible timezone), will now return ``TypeError`` rather than ``ValueError`` (a couple of edge cases only), (:issue:`8865`) +- Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) +- Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) +- Bug in ``groupby`` signatures that didn't include \*args or \*\*kwargs (:issue:`8733`). +- ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo and when it receives no data from Yahoo (:issue:`8761`), (:issue:`8783`). +- Unclear error message in csv parsing when passing dtype and names and the parsed data is a different data type (:issue:`8833`) +- Bug in slicing a multi-index with an empty list and at least one boolean indexer (:issue:`8781`) +- ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`). +- ``Timedelta`` kwargs may now be numpy ints and floats (:issue:`8757`). +- Fixed several outstanding bugs for ``Timedelta`` arithmetic and comparisons (:issue:`8813`, :issue:`5963`, :issue:`5436`). +- ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) +- ``slice`` string method now takes step into account (:issue:`8754`) +- Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) +- Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) +- Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) + - Fix negative step support for label-based slices (:issue:`8753`) Old behavior: diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index a91c2573cc84e..615346f34b5bf 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -285,8 +285,8 @@ def test_ops(self): expected = pd.Period(ordinal=getattr(o.values, op)(), freq=o.freq) try: self.assertEqual(result, expected) - except ValueError: - # comparing tz-aware series with np.array results in ValueError + except TypeError: + # comparing tz-aware series with np.array results in TypeError expected = expected.astype('M8[ns]').astype('int64') self.assertEqual(result.value, expected) diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py index b523fb1d56290..b223d2bfd9ebc 100644 --- a/pandas/tseries/base.py +++ b/pandas/tseries/base.py @@ -346,7 +346,7 @@ def __sub__(self, other): cls.__sub__ = __sub__ def __rsub__(self, other): - return -self + other + return -(self - other) cls.__rsub__ = __rsub__ cls.__iadd__ = __add__ diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index e7c001ac57c0a..edb6d34f65f5e 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -381,7 +381,7 @@ def _generate(cls, start, end, periods, name, offset, try: inferred_tz = tools._infer_tzinfo(start, end) except: - raise ValueError('Start and end cannot both be tz-aware with ' + raise TypeError('Start and end cannot both be tz-aware with ' 'different timezones') inferred_tz = tslib.maybe_get_tz(inferred_tz) @@ -645,6 +645,11 @@ def _sub_datelike(self, other): from pandas import TimedeltaIndex other = Timestamp(other) + + # require tz compat + if tslib.get_timezone(self.tz) != tslib.get_timezone(other.tzinfo): + raise TypeError("Timestamp subtraction must have the same timezones or no timezones") + i8 = self.asi8 result = i8 - other.value result = self._maybe_mask_results(result,fill_value=tslib.iNaT) diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py index 917e10c4b7706..d3393feb2ca33 100644 --- a/pandas/tseries/tests/test_base.py +++ b/pandas/tseries/tests/test_base.py @@ -468,6 +468,74 @@ def test_subtraction_ops(self): expected = DatetimeIndex(['20121231',pd.NaT,'20121230']) tm.assert_index_equal(result,expected) + def test_subtraction_ops_with_tz(self): + + # check that dt/dti subtraction ops with tz are validated + dti = date_range('20130101',periods=3) + ts = Timestamp('20130101') + dt = ts.to_datetime() + dti_tz = date_range('20130101',periods=3).tz_localize('US/Eastern') + ts_tz = Timestamp('20130101').tz_localize('US/Eastern') + ts_tz2 = Timestamp('20130101').tz_localize('CET') + dt_tz = ts_tz.to_datetime() + td = Timedelta('1 days') + + def _check(result, expected): + self.assertEqual(result,expected) + self.assertIsInstance(result, Timedelta) + + # scalars + result = ts - ts + expected = Timedelta('0 days') + _check(result, expected) + + result = dt_tz - ts_tz + expected = Timedelta('0 days') + _check(result, expected) + + result = ts_tz - dt_tz + expected = Timedelta('0 days') + _check(result, expected) + + # tz mismatches + self.assertRaises(TypeError, lambda : dt_tz - ts) + self.assertRaises(TypeError, lambda : dt_tz - dt) + self.assertRaises(TypeError, lambda : dt_tz - ts_tz2) + self.assertRaises(TypeError, lambda : dt - dt_tz) + self.assertRaises(TypeError, lambda : ts - dt_tz) + self.assertRaises(TypeError, lambda : ts_tz2 - ts) + self.assertRaises(TypeError, lambda : ts_tz2 - dt) + self.assertRaises(TypeError, lambda : ts_tz - ts_tz2) + + # with dti + self.assertRaises(TypeError, lambda : dti - ts_tz) + self.assertRaises(TypeError, lambda : dti_tz - ts) + self.assertRaises(TypeError, lambda : dti_tz - ts_tz2) + + result = dti_tz-dt_tz + expected = TimedeltaIndex(['0 days','1 days','2 days']) + tm.assert_index_equal(result,expected) + + result = dt_tz-dti_tz + expected = TimedeltaIndex(['0 days','-1 days','-2 days']) + tm.assert_index_equal(result,expected) + + result = dti_tz-ts_tz + expected = TimedeltaIndex(['0 days','1 days','2 days']) + tm.assert_index_equal(result,expected) + + result = ts_tz-dti_tz + expected = TimedeltaIndex(['0 days','-1 days','-2 days']) + tm.assert_index_equal(result,expected) + + result = td - td + expected = Timedelta('0 days') + _check(result, expected) + + result = dti_tz - td + expected = DatetimeIndex(['20121231','20130101','20130102'],tz='US/Eastern') + tm.assert_index_equal(result,expected) + def test_dti_tdi_numeric_ops(self): # These are normally union/diff set-like ops diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 6c358bd99e620..2e59febb2c62b 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -5,7 +5,7 @@ from pandas import tslib import datetime -from pandas.core.api import Timestamp, Series +from pandas.core.api import Timestamp, Series, Timedelta from pandas.tslib import period_asfreq, period_ordinal, get_timezone from pandas.tseries.index import date_range from pandas.tseries.frequencies import get_freq @@ -232,13 +232,13 @@ def test_tz(self): conv = local.tz_convert('US/Eastern') self.assertEqual(conv.nanosecond, 5) self.assertEqual(conv.hour, 19) - + def test_tz_localize_ambiguous(self): - + ts = Timestamp('2014-11-02 01:00') ts_dst = ts.tz_localize('US/Eastern', ambiguous=True) ts_no_dst = ts.tz_localize('US/Eastern', ambiguous=False) - + rng = date_range('2014-11-02', periods=3, freq='H', tz='US/Eastern') self.assertEqual(rng[1], ts_dst) self.assertEqual(rng[2], ts_no_dst) @@ -679,8 +679,8 @@ def test_addition_subtraction_types(self): self.assertEqual(type(timestamp_instance - 1), Timestamp) # Timestamp + datetime not supported, though subtraction is supported and yields timedelta - self.assertEqual(type(timestamp_instance - datetime_instance), datetime.timedelta) - + # more tests in tseries/base/tests/test_base.py + self.assertEqual(type(timestamp_instance - datetime_instance), Timedelta) self.assertEqual(type(timestamp_instance + timedelta_instance), Timestamp) self.assertEqual(type(timestamp_instance - timedelta_instance), Timestamp) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 8efc174d6890b..30245d4de2f8d 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -810,10 +810,10 @@ cdef class _Timestamp(datetime): object other) except -1: if self.tzinfo is None: if other.tzinfo is not None: - raise ValueError('Cannot compare tz-naive and tz-aware ' + raise TypeError('Cannot compare tz-naive and tz-aware ' 'timestamps') elif other.tzinfo is None: - raise ValueError('Cannot compare tz-naive and tz-aware timestamps') + raise TypeError('Cannot compare tz-naive and tz-aware timestamps') cpdef datetime to_datetime(_Timestamp self): cdef: @@ -863,6 +863,11 @@ cdef class _Timestamp(datetime): # a Timestamp-DatetimeIndex -> yields a negative TimedeltaIndex elif getattr(other,'_typ',None) == 'datetimeindex': + + # we may be passed reverse ops + if get_timezone(getattr(self,'tzinfo',None)) != get_timezone(other.tz): + raise TypeError("Timestamp subtraction must have the same timezones or no timezones") + return -other.__sub__(self) # a Timestamp-TimedeltaIndex -> yields a negative TimedeltaIndex @@ -871,6 +876,23 @@ cdef class _Timestamp(datetime): elif other is NaT: return NaT + + # coerce if necessary if we are a Timestamp-like + if isinstance(self, datetime) and (isinstance(other, datetime) or is_datetime64_object(other)): + self = Timestamp(self) + other = Timestamp(other) + + # validate tz's + if get_timezone(self.tzinfo) != get_timezone(other.tzinfo): + raise TypeError("Timestamp subtraction must have the same timezones or no timezones") + + # scalar Timestamp/datetime - Timestamp/datetime -> yields a Timedelta + try: + return Timedelta(self.value-other.value) + except (OverflowError, OutOfBoundsDatetime): + pass + + # scalar Timestamp/datetime - Timedelta -> yields a Timestamp (with same timezone if specified) return datetime.__sub__(self, other) cpdef _get_field(self, field):
closes #8865
https://api.github.com/repos/pandas-dev/pandas/pulls/8981
2014-12-03T12:40:22Z
2014-12-04T02:48:19Z
2014-12-04T02:48:19Z
2014-12-04T02:48:20Z
TST/COMPAT: tests and compat for unicode for lib.max_len_string_array
diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 82408cd460fcd..2a5b93d111acc 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -898,17 +898,17 @@ def clean_index_list(list obj): @cython.boundscheck(False) @cython.wraparound(False) -def max_len_string_array(ndarray[object, ndim=1] arr): +def max_len_string_array(ndarray arr): """ return the maximum size of elements in a 1-dim string array """ cdef: int i, m, l - length = arr.shape[0] + int length = arr.shape[0] object v m = 0 for i from 0 <= i < length: v = arr[i] - if PyString_Check(v) or PyBytes_Check(v): + if PyString_Check(v) or PyBytes_Check(v) or PyUnicode_Check(v): l = len(v) if l > m: diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 2873cd81d4744..1276a7fc96a46 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -3,10 +3,21 @@ import numpy as np import pandas as pd -from pandas.lib import isscalar, item_from_zerodim +from pandas.lib import isscalar, item_from_zerodim, max_len_string_array import pandas.util.testing as tm from pandas.compat import u +class TestMisc(tm.TestCase): + + def test_max_len_string_array(self): + + arr = np.array(['foo','b',np.nan],dtype='object') + self.assertTrue(max_len_string_array(arr),3) + + # unicode + arr = arr.astype('U') + self.assertTrue(max_len_string_array(arr),3) + class TestIsscalar(tm.TestCase): def test_isscalar_builtin_scalars(self): self.assertTrue(isscalar(None))
https://api.github.com/repos/pandas-dev/pandas/pulls/8978
2014-12-03T03:26:28Z
2014-12-03T07:04:47Z
2014-12-03T07:04:47Z
2014-12-03T07:04:47Z
BUG: StataWriter uses incorrect string length
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 929471acb3105..aca1320980720 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -166,3 +166,10 @@ Bug Fixes not lexically sorted or unique (:issue:`7724`) - BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) + + + + + +- Bug in `StataWriter` the produces writes strings with 244 characters irrespective of actual size (:issue:`8969`) + diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 45d3274088c75..cd37efd8e0991 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1409,7 +1409,7 @@ def _maybe_convert_to_int_keys(convert_dates, varlist): return new_dict -def _dtype_to_stata_type(dtype): +def _dtype_to_stata_type(dtype, column): """ Converts dtype types to stata types. Returns the byte of the given ordinal. See TYPE_MAP and comments for an explanation. This is also explained in @@ -1425,13 +1425,14 @@ def _dtype_to_stata_type(dtype): If there are dates to convert, then dtype will already have the correct type inserted. """ - #TODO: expand to handle datetime to integer conversion + # TODO: expand to handle datetime to integer conversion if dtype.type == np.string_: return chr(dtype.itemsize) elif dtype.type == np.object_: # try to coerce it to the biggest string # not memory efficient, what else could we # do? - return chr(244) + itemsize = max_len_string_array(column.values) + return chr(max(itemsize, 1)) elif dtype == np.float64: return chr(255) elif dtype == np.float32: @@ -1461,6 +1462,7 @@ def _dtype_to_default_stata_fmt(dtype, column): int16 -> "%8.0g" int8 -> "%8.0g" """ + # TODO: Refactor to combine type with format # TODO: expand this to handle a default datetime format? if dtype.type == np.object_: inferred_dtype = infer_dtype(column.dropna()) @@ -1470,8 +1472,7 @@ def _dtype_to_default_stata_fmt(dtype, column): itemsize = max_len_string_array(column.values) if itemsize > 244: raise ValueError(excessive_string_length_error % column.name) - - return "%" + str(itemsize) + "s" + return "%" + str(max(itemsize, 1)) + "s" elif dtype == np.float64: return "%10.0g" elif dtype == np.float32: @@ -1718,10 +1719,11 @@ def _prepare_pandas(self, data): self._convert_dates[key] ) dtypes[key] = np.dtype(new_type) - self.typlist = [_dtype_to_stata_type(dt) for dt in dtypes] + self.typlist = [] self.fmtlist = [] for col, dtype in dtypes.iteritems(): self.fmtlist.append(_dtype_to_default_stata_fmt(dtype, data[col])) + self.typlist.append(_dtype_to_stata_type(dtype, data[col])) # set the given format for the datetime cols if self._convert_dates is not None: diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py index a99bcf741792f..6a3c16655745e 100644 --- a/pandas/io/tests/test_stata.py +++ b/pandas/io/tests/test_stata.py @@ -593,10 +593,12 @@ def test_minimal_size_col(self): with tm.ensure_clean() as path: original.to_stata(path, write_index=False) sr = StataReader(path) + typlist = sr.typlist variables = sr.varlist formats = sr.fmtlist - for variable, fmt in zip(variables, formats): + for variable, fmt, typ in zip(variables, formats, typlist): self.assertTrue(int(variable[1:]) == int(fmt[1:-1])) + self.assertTrue(int(variable[1:]) == typ) def test_excessively_long_string(self): str_lens = (1, 244, 500) @@ -850,7 +852,6 @@ def test_categorical_order(self): # Check identity of codes for col in expected: if is_categorical_dtype(expected[col]): - print(col) tm.assert_series_equal(expected[col].cat.codes, parsed_115[col].cat.codes) tm.assert_index_equal(expected[col].cat.categories, diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 82408cd460fcd..2a5b93d111acc 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -898,17 +898,17 @@ def clean_index_list(list obj): @cython.boundscheck(False) @cython.wraparound(False) -def max_len_string_array(ndarray[object, ndim=1] arr): +def max_len_string_array(ndarray arr): """ return the maximum size of elements in a 1-dim string array """ cdef: int i, m, l - length = arr.shape[0] + int length = arr.shape[0] object v m = 0 for i from 0 <= i < length: v = arr[i] - if PyString_Check(v) or PyBytes_Check(v): + if PyString_Check(v) or PyBytes_Check(v) or PyUnicode_Check(v): l = len(v) if l > m:
Fixes bug where StataWriter always writes strings with a size of 244. closes #8969
https://api.github.com/repos/pandas-dev/pandas/pulls/8977
2014-12-03T03:07:24Z
2014-12-03T14:24:58Z
2014-12-03T14:24:58Z
2015-01-18T22:42:19Z
COMPAT: infer_dtype not handling categoricals (GH8974)
diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx index e754f3c21de3c..dbe6f2f1f8351 100644 --- a/pandas/src/inference.pyx +++ b/pandas/src/inference.pyx @@ -21,6 +21,8 @@ def is_period(object val): return util.is_period_object(val) _TYPE_MAP = { + 'categorical' : 'categorical', + 'category' : 'categorical', 'int8': 'integer', 'int16': 'integer', 'int32': 'integer', @@ -65,7 +67,23 @@ try: except AttributeError: pass +cdef _try_infer_map(v): + """ if its in our map, just return the dtype """ + cdef: + object val_name, val_kind + val_name = v.dtype.name + if val_name in _TYPE_MAP: + return _TYPE_MAP[val_name] + val_kind = v.dtype.kind + if val_kind in _TYPE_MAP: + return _TYPE_MAP[val_kind] + return None + def infer_dtype(object _values): + """ + we are coercing to an ndarray here + """ + cdef: Py_ssize_t i, n object val @@ -73,21 +91,29 @@ def infer_dtype(object _values): if isinstance(_values, np.ndarray): values = _values - elif hasattr(_values,'values'): - values = _values.values + elif hasattr(_values,'dtype'): + + # this will handle ndarray-like + # e.g. categoricals + try: + values = getattr(_values, 'values', _values) + except: + val = _try_infer_map(_values) + if val is not None: + return val + + # its ndarray like but we can't handle + raise ValueError("cannot infer type for {0}".format(type(_values))) + else: if not isinstance(_values, list): _values = list(_values) values = list_to_object_array(_values) values = getattr(values, 'values', values) - - val_name = values.dtype.name - if val_name in _TYPE_MAP: - return _TYPE_MAP[val_name] - val_kind = values.dtype.kind - if val_kind in _TYPE_MAP: - return _TYPE_MAP[val_kind] + val = _try_infer_map(values) + if val is not None: + return val if values.dtype != np.object_: values = values.astype('O') diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index 5c26fce2b111e..04092346a70e8 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -660,6 +660,24 @@ def test_object(self): result = lib.infer_dtype(arr) self.assertEqual(result, 'mixed') + def test_categorical(self): + + # GH 8974 + from pandas import Categorical, Series + arr = Categorical(list('abc')) + result = lib.infer_dtype(arr) + self.assertEqual(result, 'categorical') + + result = lib.infer_dtype(Series(arr)) + self.assertEqual(result, 'categorical') + + arr = Categorical(list('abc'),categories=['cegfab'],ordered=True) + result = lib.infer_dtype(arr) + self.assertEqual(result, 'categorical') + + result = lib.infer_dtype(Series(arr)) + self.assertEqual(result, 'categorical') + class TestMoments(tm.TestCase): pass
closes #8974
https://api.github.com/repos/pandas-dev/pandas/pulls/8975
2014-12-03T02:14:19Z
2014-12-03T02:53:18Z
2014-12-03T02:53:18Z
2014-12-03T02:53:18Z
ENH: Infer dtype from non-nulls when pushing to SQL
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index a329cb25173cf..8c2fbc059ce5b 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -115,6 +115,7 @@ Enhancements - ``to_datetime`` gains an ``exact`` keyword to allow for a format to not require an exact match for a provided format string (if its ``False). ``exact`` defaults to ``True`` (meaning that exact matching is still the default) (:issue:`8904`) - Added ``axvlines`` boolean option to parallel_coordinates plot function, determines whether vertical lines will be printed, default is True - Added ability to read table footers to read_html (:issue:`8552`) +- ``to_sql`` now infers datatypes of non-NA values for columns that contain NA values and have dtype ``object`` (:issue:`8778`). .. _whatsnew_0152.performance: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 77527f867fad8..a1b3180e721fc 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -885,37 +885,56 @@ def _harmonize_columns(self, parse_dates=None): except KeyError: pass # this column not in results + def _get_notnull_col_dtype(self, col): + """ + Infer datatype of the Series col. In case the dtype of col is 'object' + and it contains NA values, this infers the datatype of the not-NA + values. Needed for inserting typed data containing NULLs, GH8778. + """ + col_for_inference = col + if col.dtype == 'object': + notnulldata = col[~isnull(col)] + if len(notnulldata): + col_for_inference = notnulldata + + return lib.infer_dtype(col_for_inference) + def _sqlalchemy_type(self, col): - from sqlalchemy.types import (BigInteger, Float, Text, Boolean, - DateTime, Date, Time) dtype = self.dtype or {} if col.name in dtype: return self.dtype[col.name] - if com.is_datetime64_dtype(col): + col_type = self._get_notnull_col_dtype(col) + + from sqlalchemy.types import (BigInteger, Float, Text, Boolean, + DateTime, Date, Time) + + if col_type == 'datetime64': try: tz = col.tzinfo return DateTime(timezone=True) except: return DateTime - if com.is_timedelta64_dtype(col): + if col_type == 'timedelta64': warnings.warn("the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the " "database.", UserWarning) return BigInteger - elif com.is_float_dtype(col): + elif col_type == 'floating': return Float - elif com.is_integer_dtype(col): + elif col_type == 'integer': # TODO: Refine integer size. return BigInteger - elif com.is_bool_dtype(col): + elif col_type == 'boolean': return Boolean - inferred = lib.infer_dtype(com._ensure_object(col)) - if inferred == 'date': + elif col_type == 'date': return Date - if inferred == 'time': + elif col_type == 'time': return Time + elif col_type == 'complex': + raise ValueError('Complex datatypes not supported') + return Text def _numpy_type(self, sqltype): @@ -1187,15 +1206,15 @@ def _create_sql_schema(self, frame, table_name, keys=None): # SQLAlchemy installed # SQL type convertions for each DB _SQL_TYPES = { - 'text': { + 'string': { 'mysql': 'VARCHAR (63)', 'sqlite': 'TEXT', }, - 'float': { + 'floating': { 'mysql': 'FLOAT', 'sqlite': 'REAL', }, - 'int': { + 'integer': { 'mysql': 'BIGINT', 'sqlite': 'INTEGER', }, @@ -1211,12 +1230,13 @@ def _create_sql_schema(self, frame, table_name, keys=None): 'mysql': 'TIME', 'sqlite': 'TIME', }, - 'bool': { + 'boolean': { 'mysql': 'BOOLEAN', 'sqlite': 'INTEGER', } } + # SQL enquote and wildcard symbols _SQL_SYMB = { 'mysql': { @@ -1291,8 +1311,8 @@ def _create_table_setup(self): br_l = _SQL_SYMB[flv]['br_l'] # left val quote char br_r = _SQL_SYMB[flv]['br_r'] # right val quote char - create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, ctype) - for cname, ctype, _ in column_names_and_types] + create_tbl_stmts = [(br_l + '%s' + br_r + ' %s') % (cname, col_type) + for cname, col_type, _ in column_names_and_types] if self.keys is not None and len(self.keys): cnames_br = ",".join([br_l + c + br_r for c in self.keys]) create_tbl_stmts.append( @@ -1317,30 +1337,27 @@ def _sql_type_name(self, col): dtype = self.dtype or {} if col.name in dtype: return dtype[col.name] - pytype = col.dtype.type - pytype_name = "text" - if issubclass(pytype, np.floating): - pytype_name = "float" - elif com.is_timedelta64_dtype(pytype): + + col_type = self._get_notnull_col_dtype(col) + if col_type == 'timedelta64': warnings.warn("the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the " "database.", UserWarning) - pytype_name = "int" - elif issubclass(pytype, np.integer): - pytype_name = "int" - elif issubclass(pytype, np.datetime64) or pytype is datetime: - # Caution: np.datetime64 is also a subclass of np.number. - pytype_name = "datetime" - elif issubclass(pytype, np.bool_): - pytype_name = "bool" - elif issubclass(pytype, np.object): - pytype = lib.infer_dtype(com._ensure_object(col)) - if pytype == "date": - pytype_name = "date" - elif pytype == "time": - pytype_name = "time" - - return _SQL_TYPES[pytype_name][self.pd_sql.flavor] + col_type = "integer" + + elif col_type == "datetime64": + col_type = "datetime" + + elif col_type == "empty": + col_type = "string" + + elif col_type == "complex": + raise ValueError('Complex datatypes not supported') + + if col_type not in _SQL_TYPES: + col_type = "string" + + return _SQL_TYPES[col_type][self.pd_sql.flavor] class SQLiteDatabase(PandasSQL): diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index eb46df7686d18..c7b6b77ae7aea 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -560,6 +560,11 @@ def test_timedelta(self): result = sql.read_sql_query('SELECT * FROM test_timedelta', self.conn) tm.assert_series_equal(result['foo'], df['foo'].astype('int64')) + def test_complex(self): + df = DataFrame({'a':[1+1j, 2j]}) + # Complex data type should raise error + self.assertRaises(ValueError, df.to_sql, 'test_complex', self.conn) + def test_to_sql_index_label(self): temp_frame = DataFrame({'col1': range(4)}) @@ -1175,19 +1180,38 @@ def test_dtype(self): (0.9, None)] df = DataFrame(data, columns=cols) df.to_sql('dtype_test', self.conn) - df.to_sql('dtype_test2', self.conn, dtype={'B': sqlalchemy.Boolean}) + df.to_sql('dtype_test2', self.conn, dtype={'B': sqlalchemy.TEXT}) + meta = sqlalchemy.schema.MetaData(bind=self.conn) + meta.reflect() + sqltype = meta.tables['dtype_test2'].columns['B'].type + self.assertTrue(isinstance(sqltype, sqlalchemy.TEXT)) + self.assertRaises(ValueError, df.to_sql, + 'error', self.conn, dtype={'B': str}) + + def test_notnull_dtype(self): + cols = {'Bool': Series([True,None]), + 'Date': Series([datetime(2012, 5, 1), None]), + 'Int' : Series([1, None], dtype='object'), + 'Float': Series([1.1, None]) + } + df = DataFrame(cols) + + tbl = 'notnull_dtype_test' + df.to_sql(tbl, self.conn) + returned_df = sql.read_sql_table(tbl, self.conn) meta = sqlalchemy.schema.MetaData(bind=self.conn) meta.reflect() - self.assertTrue(isinstance(meta.tables['dtype_test'].columns['B'].type, - sqltypes.TEXT)) if self.flavor == 'mysql': my_type = sqltypes.Integer else: my_type = sqltypes.Boolean - self.assertTrue(isinstance(meta.tables['dtype_test2'].columns['B'].type, - my_type)) - self.assertRaises(ValueError, df.to_sql, - 'error', self.conn, dtype={'B': bool}) + + col_dict = meta.tables[tbl].columns + + self.assertTrue(isinstance(col_dict['Bool'].type, my_type)) + self.assertTrue(isinstance(col_dict['Date'].type, sqltypes.DateTime)) + self.assertTrue(isinstance(col_dict['Int'].type, sqltypes.Integer)) + self.assertTrue(isinstance(col_dict['Float'].type, sqltypes.Float)) class TestSQLiteAlchemy(_TestSQLAlchemy): @@ -1507,6 +1531,13 @@ def test_to_sql_save_index(self): def test_transactions(self): self._transaction_test() + def _get_sqlite_column_type(self, table, column): + recs = self.conn.execute('PRAGMA table_info(%s)' % table) + for cid, name, ctype, not_null, default, pk in recs: + if name == column: + return ctype + raise ValueError('Table %s, column %s not found' % (table, column)) + def test_dtype(self): if self.flavor == 'mysql': raise nose.SkipTest('Not applicable to MySQL legacy') @@ -1515,20 +1546,35 @@ def test_dtype(self): (0.9, None)] df = DataFrame(data, columns=cols) df.to_sql('dtype_test', self.conn) - df.to_sql('dtype_test2', self.conn, dtype={'B': 'bool'}) + df.to_sql('dtype_test2', self.conn, dtype={'B': 'STRING'}) - def get_column_type(table, column): - recs = self.conn.execute('PRAGMA table_info(%s)' % table) - for cid, name, ctype, not_null, default, pk in recs: - if name == column: - return ctype - raise ValueError('Table %s, column %s not found' % (table, column)) - - self.assertEqual(get_column_type('dtype_test', 'B'), 'TEXT') - self.assertEqual(get_column_type('dtype_test2', 'B'), 'bool') + # sqlite stores Boolean values as INTEGER + self.assertEqual(self._get_sqlite_column_type('dtype_test', 'B'), 'INTEGER') + + self.assertEqual(self._get_sqlite_column_type('dtype_test2', 'B'), 'STRING') self.assertRaises(ValueError, df.to_sql, 'error', self.conn, dtype={'B': bool}) + def test_notnull_dtype(self): + if self.flavor == 'mysql': + raise nose.SkipTest('Not applicable to MySQL legacy') + + cols = {'Bool': Series([True,None]), + 'Date': Series([datetime(2012, 5, 1), None]), + 'Int' : Series([1, None], dtype='object'), + 'Float': Series([1.1, None]) + } + df = DataFrame(cols) + + tbl = 'notnull_dtype_test' + df.to_sql(tbl, self.conn) + + self.assertEqual(self._get_sqlite_column_type(tbl, 'Bool'), 'INTEGER') + self.assertEqual(self._get_sqlite_column_type(tbl, 'Date'), 'TIMESTAMP') + self.assertEqual(self._get_sqlite_column_type(tbl, 'Int'), 'INTEGER') + self.assertEqual(self._get_sqlite_column_type(tbl, 'Float'), 'REAL') + + class TestMySQLLegacy(TestSQLiteFallback): """ Test the legacy mode against a MySQL database.
Closes #8778 This infers dtype from non-null values for insertion into SQL database. See #8778 . I had to alter @tiagoantao test a bit. Like @tiagoantao, I skipped writing tests for legacy MySQL. Support for this will be removed soon, right? As a side note, `lib.infer_dtype` throws an exception for categorical data -- probably shouldn't happen, right? @jorisvandenbossche @jahfet @tiagoantao
https://api.github.com/repos/pandas-dev/pandas/pulls/8973
2014-12-03T01:21:26Z
2014-12-08T07:42:33Z
2014-12-08T07:42:33Z
2014-12-08T07:42:42Z
Implement Categorical.searchsorted(v, side, sorter) #8420
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 11cf2450d2f28..1a6234625ab93 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -66,6 +66,7 @@ Enhancements - Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. - Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. +- Added support for ``searchsorted()`` on `Categorical` class (:issue:`8420`). - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). - Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`. - Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 5b3e9e8a22b12..b91b46283e2fe 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -776,7 +776,61 @@ def nbytes(self): return self._codes.nbytes + self._categories.values.nbytes def searchsorted(self, v, side='left', sorter=None): - raise NotImplementedError("See https://github.com/pydata/pandas/issues/8420") + """Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted Categorical `self` such that, if the + corresponding elements in `v` were inserted before the indices, the + order of `self` would be preserved. + + Parameters + ---------- + v : array_like + Array-like values or a scalar value, to insert/search for in `self`. + side : {'left', 'right'}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `a`). + sorter : 1-D array_like, optional + Optional array of integer indices that sort `self` into ascending + order. They are typically the result of ``np.argsort``. + + Returns + ------- + indices : array of ints + Array of insertion points with the same shape as `v`. + + See Also + -------- + Series.searchsorted + numpy.searchsorted + + Notes + ----- + Binary search is used to find the required insertion points. + + Examples + -------- + >>> x = pd.Categorical(['apple', 'bread', 'bread', 'cheese', 'milk' ]) + [apple, bread, bread, cheese, milk] + Categories (4, object): [apple < bread < cheese < milk] + >>> x.searchsorted('bread') + array([1]) # Note: an array, not a scalar + >>> x.searchsorted(['bread']) + array([1]) + >>> x.searchsorted(['bread', 'eggs']) + array([1, 4]) + >>> x.searchsorted(['bread', 'eggs'], side='right') + array([3, 4]) # eggs before milk + >>> x = pd.Categorical(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ]) + >>> x.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + array([3, 5]) # eggs after donuts, after switching milk and donuts + """ + if not self.ordered: + raise ValueError("searchsorted requires an ordered Categorical.") + + from pandas.core.series import Series + values_as_codes = self.categories.values.searchsorted(Series(v).values, side) + return self.codes.searchsorted(values_as_codes, sorter=sorter) def isnull(self): """ diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 196ad8b7680b9..e04be787d04ee 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -888,13 +888,47 @@ def test_nbytes(self): self.assertEqual(cat.nbytes, exp) def test_searchsorted(self): + # https://github.com/pydata/pandas/issues/8420 + s1 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk' ]) + s2 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ]) + c1 = pd.Categorical(s1) + c2 = pd.Categorical(s2) + + # Single item array + res = c1.searchsorted(['bread']) + chk = s1.searchsorted(['bread']) + exp = np.array([1]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) - # See https://github.com/pydata/pandas/issues/8420 - # TODO: implement me... - cat = pd.Categorical([1,2,3]) - def f(): - cat.searchsorted(3) - self.assertRaises(NotImplementedError, f) + # Scalar version of single item array + # Categorical return np.array like pd.Series, but different from np.array.searchsorted() + res = c1.searchsorted('bread') + chk = s1.searchsorted('bread') + exp = np.array([1]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # Searching for a value that is not present in the Categorical + res = c1.searchsorted(['bread', 'eggs']) + chk = s1.searchsorted(['bread', 'eggs']) + exp = np.array([1, 4]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # Searching for a value that is not present, to the right + res = c1.searchsorted(['bread', 'eggs'], side='right') + chk = s1.searchsorted(['bread', 'eggs'], side='right') + exp = np.array([3, 4]) # eggs before milk + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # As above, but with a sorter array to reorder an unsorted array + res = c2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + chk = s2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + exp = np.array([3, 5]) # eggs after donuts, after switching milk and donuts + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) def test_deprecated_labels(self): # TODO: labels is deprecated and should be removed in 0.18 or 2017, whatever is earlier
closes #8420 Continuation of #8928
https://api.github.com/repos/pandas-dev/pandas/pulls/8972
2014-12-02T23:59:50Z
2014-12-05T13:36:25Z
null
2014-12-05T13:36:25Z
PERF: astype(str) on object dtypes GH8732
diff --git a/pandas/core/common.py b/pandas/core/common.py index f7f944bb418e9..4eef28f357930 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2585,14 +2585,15 @@ def _astype_nansafe(arr, dtype, copy=True): if np.isnan(arr).any(): raise ValueError('Cannot convert NA to integer') elif arr.dtype == np.object_ and np.issubdtype(dtype.type, np.integer): + # partially address #8732 + iterate_over = isnull(arr).any() or not is_numeric_dtype(arr.dtype) # work around NumPy brokenness, #1987 - return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape) + return lib.astype_intsafe(arr.ravel(), dtype, iterate_over).reshape(arr.shape) elif issubclass(dtype.type, compat.text_type): # in Py3 that's str, in Py2 that's unicode return lib.astype_unicode(arr.ravel()).reshape(arr.shape) elif issubclass(dtype.type, compat.string_types): return lib.astype_str(arr.ravel()).reshape(arr.shape) - if copy: return arr.astype(dtype) return arr.view(dtype) diff --git a/pandas/lib.pyx b/pandas/lib.pyx index 82408cd460fcd..20d573645059b 100644 --- a/pandas/lib.pyx +++ b/pandas/lib.pyx @@ -827,7 +827,7 @@ def vec_binop(ndarray[object] left, ndarray[object] right, object op): return maybe_convert_bool(result) -def astype_intsafe(ndarray[object] arr, new_dtype): +def astype_intsafe(ndarray[object] arr, new_dtype, iterate_over): cdef: Py_ssize_t i, n = len(arr) object v @@ -837,6 +837,9 @@ def astype_intsafe(ndarray[object] arr, new_dtype): # on 32-bit, 1.6.2 numpy M8[ns] is a subdtype of integer, which is weird is_datelike = new_dtype in ['M8[ns]','m8[ns]'] + if not is_datelike and not iterate_over: + return arr.astype(new_dtype) + result = np.empty(n, dtype=new_dtype) for i in range(n): v = arr[i] diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c4c2eebacb0e9..60b131df0db9c 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -560,11 +560,27 @@ def test_scalar_conversion(self): def test_astype(self): s = Series(np.random.randn(5),name='foo') - for dtype in ['float32','float64','int64','int32']: + for dtype in ['float32','float64','int64','int32', 'object']: astyped = s.astype(dtype) self.assertEqual(astyped.dtype, dtype) self.assertEqual(astyped.name, s.name) + def test_astype_to(self): + arr = np.random.randint(1, 10, size=100) + s = Series(arr) + for dtype in ['float32', 'float64', 'int64', 'int32', 'object']: + astyped = s.astype(dtype) + self.assertEqual(astyped.dtype, dtype) + + def test_astype_int(self): + s = Series([1, 1.01, 1.02, 1.03]) + astyped = s.astype(np.int64) + self.assertEqual(astyped.dtype, np.int64) + s = Series([1, 1.01, 1.02, 1.03, np.nan]) + self.assertRaises(ValueError, s.astype, np.int64) + s = Series(['1', '1.01', 1.02, 1.03, np.nan]) + self.assertRaises(ValueError, s.astype, np.int64) + def test_constructor(self): # Recognize TimeSeries self.assertTrue(self.ts.is_time_series) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 6a71160a08ae9..51eae209f8381 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -894,6 +894,20 @@ def getMixedTypeDict(): return index, data + +def makeMixedDataFrameWithNaN(): + index = Index(['a', 'b', 'c', 'd', 'e', 'f']) + + data = { + 'A': [0., 1., 2., 3., 4., np.nan], + 'B': [0., 1., 0., 1., 0., np.nan], + 'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5', np.nan], + 'D': bdate_range('1/1/2009', periods=6) + } + + return DataFrame(data, index=index) + + def makeMixedDataFrame(): return DataFrame(getMixedTypeDict()[1]) diff --git a/vb_suite/astype.py b/vb_suite/astype.py new file mode 100644 index 0000000000000..d1f92cbf10720 --- /dev/null +++ b/vb_suite/astype.py @@ -0,0 +1,24 @@ +from vbench.api import Benchmark + +common_setup = """from pandas_vb_common import * +from datetime import timedelta +import pandas as pd +import numpy as np + +N = 1000000 +df = pd.DataFrame({'a': 1., + 'b': 2, + 'c': 'foo', + 'float32' : np.array([1.]*N,dtype='float32'), + 'int32' : np.array([1]*N,dtype='int32'), + }, + index=np.arange(N)) + +mn = df._get_numeric_data() +mn['little_float'] = np.array(12345.,dtype='float16') +mn['big_float'] = np.array(123456789101112.,dtype='float64') +""" + +astype_test = Benchmark('s.astype(np.int64)', + common_setup, + name='astype_test') diff --git a/vb_suite/suite.py b/vb_suite/suite.py index a16d183ae62e2..ee5a49dac2e66 100644 --- a/vb_suite/suite.py +++ b/vb_suite/suite.py @@ -13,6 +13,7 @@ 'indexing', 'io_bench', 'io_sql', + 'astype', 'inference', 'hdfstore_bench', 'join_merge',
Closes #8732 In most cases it looks like, we need to iterate over array and coerce each element. This is so that the appropriate exception can be raised, or we can deal with nulls. So the original case of casting ints to strings, has to work the way it does, unless we change the underlying behaviour. So when astype(str) is called on ints. Then each element is first cast as a string then made into a numpy object. If we relied on numpy it wouldn't cast it to string, just return it as an object. This breaks existing behaviour. It is possible to bypass iterating over the array, when we are coercing to int. Assuming that there are no NaNs and the type of the array is a numeric.
https://api.github.com/repos/pandas-dev/pandas/pulls/8971
2014-12-02T20:41:29Z
2015-05-09T16:17:22Z
null
2015-05-14T15:49:37Z
docfix: add boolean array as option for indexing with .iloc
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst index 920be3672acd4..f56e0d22b25a7 100644 --- a/doc/source/indexing.rst +++ b/doc/source/indexing.rst @@ -84,14 +84,17 @@ 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`` if an indexer is requested and it - is out-of-bounds, except *slice* indexers which allow out-of-bounds indexing. - (this conforms with python/numpy *slice* semantics). Allowed inputs are: +- ``.iloc`` is primarily integer position based (from ``0`` to + ``length-1`` of the axis), but may also be used with a boolean + array. ``.iloc`` will raise ``IndexError`` if a requested + indexer is out-of-bounds, except *slice* indexers which allow + out-of-bounds indexing. (this conforms with python/numpy *slice* + semantics). Allowed inputs are: - An integer e.g. ``5`` - A list or array of integers ``[4, 3, 0]`` - A slice object with ints ``1:7`` + - A boolean array See more at :ref:`Selection by Position <indexing.integer>` @@ -368,6 +371,7 @@ The ``.iloc`` attribute is the primary access method. The following are valid in - An integer e.g. ``5`` - A list or array of integers ``[4, 3, 0]`` - A slice object with ints ``1:7`` +- A boolean array .. ipython:: python
resolves #8956 Trivial documentation addition of boolean array as option for .iloc
https://api.github.com/repos/pandas-dev/pandas/pulls/8970
2014-12-02T19:18:18Z
2014-12-04T00:08:00Z
null
2014-12-04T00:54:23Z
BUG: ValueError raised by cummin/cummax when datetime64 Series contains NaT.
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 929471acb3105..0a0bed826abba 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -166,3 +166,4 @@ Bug Fixes not lexically sorted or unique (:issue:`7724`) - BUG CSV: fix problem with trailing whitespace in skipped rows, (:issue:`8679`), (:issue:`8661`) - Regression in ``Timestamp`` does not parse 'Z' zone designator for UTC (:issue:`8771`) +- Fixed ValueError raised by cummin/cummax when datetime64 Series contains NaT. (:issue:`8965`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 52f37ee24f69a..b948ceb9b6b88 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4112,13 +4112,17 @@ def func(self, axis=None, dtype=None, out=None, skipna=True, axis = self._get_axis_number(axis) y = _values_from_object(self).copy() - if not issubclass(y.dtype.type, (np.integer, np.bool_)): + + if skipna and issubclass(y.dtype.type, + (np.datetime64, np.timedelta64)): + result = accum_func(y, axis) + mask = isnull(self) + np.putmask(result, mask, pd.tslib.iNaT) + elif skipna and not issubclass(y.dtype.type, (np.integer, np.bool_)): mask = isnull(self) - if skipna: - np.putmask(y, mask, mask_a) + np.putmask(y, mask, mask_a) result = accum_func(y, axis) - if skipna: - np.putmask(result, mask, mask_b) + np.putmask(result, mask, mask_b) else: result = accum_func(y, axis) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c4c2eebacb0e9..df48c5e62a9b6 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2309,6 +2309,62 @@ def test_cummax(self): self.assert_numpy_array_equal(result, expected) + def test_cummin_datetime64(self): + s = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-1'])) + result = s.cummin(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', '2000-1-2', '2000-1-1', '2000-1-1', '2000-1-1'])) + result = s.cummin(skipna=False) + self.assert_series_equal(expected, result) + + def test_cummax_datetime64(self): + s = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', 'NaT', '2000-1-2', 'NaT', '2000-1-3'])) + result = s.cummax(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_datetime( + ['NaT', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-3'])) + result = s.cummax(skipna=False) + self.assert_series_equal(expected, result) + + def test_cummin_timedelta64(self): + s = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min', ])) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '1 min', 'NaT', '1 min', ])) + result = s.cummin(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', '2 min', '1 min', '1 min', '1 min', ])) + result = s.cummin(skipna=False) + self.assert_series_equal(expected, result) + + def test_cummax_timedelta64(self): + s = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min', ])) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', 'NaT', '2 min', 'NaT', '3 min', ])) + result = s.cummax(skipna=True) + self.assert_series_equal(expected, result) + + expected = pd.Series(pd.to_timedelta( + ['NaT', '2 min', '2 min', '2 min', '2 min', '3 min', ])) + result = s.cummax(skipna=False) + self.assert_series_equal(expected, result) + def test_npdiff(self): raise nose.SkipTest("skipping due to Series no longer being an " "ndarray")
closes #8965
https://api.github.com/repos/pandas-dev/pandas/pulls/8966
2014-12-02T13:00:45Z
2014-12-03T14:27:36Z
2014-12-03T14:27:36Z
2014-12-03T14:27:45Z
BUG: fixes pd.Grouper for non-datetimelike groupings #8866
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 6688f106f922e..bfa38680d5e1d 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -42,6 +42,8 @@ API changes - Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`) +- Bug in pd.Grouper when specifying non-datetimelike grouping. (:issue:`8844`) + - ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions and will now raise ``TypeError``. (:issue:`8302`): .. ipython:: python diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4b85da1b7b224..170a8dc938b88 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -198,7 +198,7 @@ def __new__(cls, *args, **kwargs): cls = TimeGrouper return super(Grouper, cls).__new__(cls) - def __init__(self, key=None, level=None, freq=None, axis=None, sort=False): + def __init__(self, key=None, level=None, freq=None, axis=0, sort=False): self.key=key self.level=level self.freq=freq @@ -232,22 +232,40 @@ def _get_grouper(self, obj): def _set_grouper(self, obj, sort=False): """ - given an object and the specifcations, setup the internal grouper for this particular specification + given an object and the specifications, setup the internal grouper + for this particular specification Parameters ---------- obj : the subject object """ + if self.freq is not None: + self._set_timegrouper(obj) + return self.grouper + else: + self._set_basegrouper(obj) + + def _set_timegrouper(self, obj, sort=False): + """ + given an object and the specifications, setup the internal grouper + as a Datetime Index + + Parameters + ---------- + obj : the subject object + """ if self.key is not None and self.level is not None: - raise ValueError("The Grouper cannot specify both a key and a level!") + raise ValueError("The Grouper cannot specify both a key and \ + a level!") # the key must be a valid info item if self.key is not None: key = self.key if key not in obj._info_axis: - raise KeyError("The grouper name {0} is not found".format(key)) + raise KeyError("The grouper name {0} is not found" + .format(key)) ax = Index(obj[key], name=key) else: @@ -259,20 +277,78 @@ def _set_grouper(self, obj, sort=False): # equivalent to the axis name if isinstance(ax, MultiIndex): level = ax._get_level_number(level) - ax = Index(ax.get_level_values(level), name=ax.names[level]) + ax = Index(ax.get_level_values(level), + name=ax.names[level]) else: if level not in (0, ax.name): - raise ValueError("The level {0} is not valid".format(level)) + raise ValueError("The level {0} is not valid" + .format(level)) # possibly sort if (self.sort or sort) and not ax.is_monotonic: indexer = self.indexer = ax.argsort(kind='quicksort') ax = ax.take(indexer) - obj = obj.take(indexer, axis=self.axis, convert=False, is_copy=False) + obj = obj.take(indexer, axis=self.axis, convert=False, + is_copy=False) self.obj = obj self.grouper = ax + + def _set_basegrouper(self, obj, sort=False): + """ + given an object and the specifications, setup the internal grouper + as a BaseGrouper Class + + Parameters + ---------- + obj : the subject object + + """ + ax = obj._get_axis(self.axis) + gpr = self.key + if self.key is not None: + if self.key not in obj._info_axis: + raise KeyError("The grouper name {0} is not found" + .format(self.key)) + else: + if self.level is not None: + if not isinstance(ax, MultiIndex): + if self.level not in (0, ax.name): + raise ValueError("The level {0} is not valid" + .format(self.level)) + + def is_in_axis(key): + if not _is_label_like(key): + try: + obj._data.items.get_loc(key) + except Exception: + return False + return True + + # if the the grouper is obj[name] + def is_in_obj(gpr): + try: + return id(gpr) == id(obj[gpr.name]) + except Exception: + return False + + if is_in_obj(gpr): # df.groupby(df['name']) + in_axis, name = True, gpr.name + elif is_in_axis(gpr): # df.groupby('name') + in_axis, name, gpr = True, gpr, obj[gpr] + else: + in_axis, name = False, None + + if isinstance(self.key, Categorical) and len(gpr) != len(obj): + raise ValueError("Categorical grouper must have len(grouper) \ + == len(data)") + + grouping = [Grouping(ax, gpr, obj=obj, name=name, + level=self.level, sort=sort, in_axis=in_axis)] + grouper = BaseGrouper(ax, grouping) + self.obj = obj + self.grouper = grouper return self.grouper def _get_binner_for_grouping(self, obj): @@ -2137,7 +2213,6 @@ def is_in_obj(gpr): ping = Grouping(group_axis, gpr, obj=obj, name=name, level=level, sort=sort, in_axis=in_axis) - groupings.append(ping) if len(groupings) == 0: diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index ef3fc03fc8d22..c852b21f1e14d 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -3677,6 +3677,16 @@ def test_timegrouper_get_group(self): dt = pd.Timestamp(t) result = grouped.get_group(dt) assert_frame_equal(result, expected) + + def test_grouper_with_nondatetime(self): + # GH 8866 + s = Series(np.arange(8),index=pd.MultiIndex.from_product([list('ab'), + range(2),pd.date_range('20130101',periods=2)], + names=['one','two','three'])) + + expected = Series(data = [6,22], index=pd.Index(['a','b'], name='one')) + result = s.groupby(pd.Grouper(level='one')).sum() + assert_series_equal(result,expected) def test_cumcount(self): df = DataFrame([['a'], ['a'], ['a'], ['b'], ['a']], columns=['A'])
closes #8866 The bug was caused by a couple of things, firstly when specifying only a level, the axis default was None. This meant it failed to create the internal grouper breaking on line 254 of groupby.py: ``` python ax = obj._get_axis(self.axis) ``` Secondly, the aggregate function is set up to take a basegrouper class whereas for datetime resampling we need to pass a datetime index. I split the `_set_grouper` method to return a datetime index when a resampling frequency is specified and a `BaseGrouper` class otherwise. I opted to split that out into two functions to reduce complexity with much of the `_set_basegrouper` function being borrowed from the `_get_grouper` function. Let me know if there's a better way to fix this.
https://api.github.com/repos/pandas-dev/pandas/pulls/8964
2014-12-02T11:45:28Z
2014-12-05T01:59:06Z
null
2014-12-05T05:15:44Z
Fixes #8933 simple renaming
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 7dfdc88dddbff..5b3e9e8a22b12 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -18,7 +18,7 @@ from pandas.core.common import (CategoricalDtype, ABCSeries, isnull, notnull, is_categorical_dtype, is_integer_dtype, is_object_dtype, _possibly_infer_to_datetimelike, get_dtype_kinds, - is_list_like, _is_sequence, + is_list_like, is_sequence, _ensure_platform_int, _ensure_object, _ensure_int64, _coerce_indexer_dtype, _values_from_object, take_1d) from pandas.util.terminal import get_terminal_size @@ -1477,7 +1477,7 @@ def _convert_to_list_like(list_like): return list_like if isinstance(list_like, list): return list_like - if (_is_sequence(list_like) or isinstance(list_like, tuple) + if (is_sequence(list_like) or isinstance(list_like, tuple) or isinstance(list_like, types.GeneratorType)): return list(list_like) elif np.isscalar(list_like): diff --git a/pandas/core/common.py b/pandas/core/common.py index 6aff67412d677..f7f944bb418e9 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2504,7 +2504,7 @@ def is_list_like(arg): not isinstance(arg, compat.string_and_binary_types)) -def _is_sequence(x): +def is_sequence(x): try: iter(x) len(x) # it has a length @@ -2512,6 +2512,7 @@ def _is_sequence(x): except (TypeError, AttributeError): return False + def _get_callable_name(obj): # typical case has name if hasattr(obj, '__name__'): @@ -3093,7 +3094,7 @@ def as_escaped_unicode(thing, escape_chars=escape_chars): elif (isinstance(thing, dict) and _nest_lvl < get_option("display.pprint_nest_depth")): result = _pprint_dict(thing, _nest_lvl, quote_strings=True) - elif _is_sequence(thing) and _nest_lvl < \ + elif is_sequence(thing) and _nest_lvl < \ get_option("display.pprint_nest_depth"): result = _pprint_seq(thing, _nest_lvl, escape_chars=escape_chars, quote_strings=quote_strings) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a464b687209cb..7c7872cf7b6a5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -24,7 +24,7 @@ import numpy.ma as ma from pandas.core.common import (isnull, notnull, PandasError, _try_sort, - _default_index, _maybe_upcast, _is_sequence, + _default_index, _maybe_upcast, is_sequence, _infer_dtype_from_scalar, _values_from_object, is_list_like, _get_dtype, _maybe_box_datetimelike, is_categorical_dtype) @@ -2255,7 +2255,7 @@ def reindexer(value): elif isinstance(value, Categorical): value = value.copy() - elif (isinstance(value, Index) or _is_sequence(value)): + elif (isinstance(value, Index) or is_sequence(value)): from pandas.core.series import _sanitize_index value = _sanitize_index(value, self.index, copy=False) if not isinstance(value, (np.ndarray, Index)): @@ -2844,7 +2844,7 @@ def sort_index(self, axis=0, by=None, ascending=True, inplace=False, '(rows)') if not isinstance(by, list): by = [by] - if com._is_sequence(ascending) and len(by) != len(ascending): + if com.is_sequence(ascending) and len(by) != len(ascending): raise ValueError('Length of ascending (%d) != length of by' ' (%d)' % (len(ascending), len(by))) if len(by) > 1: @@ -3694,7 +3694,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True): com.pprint_thing(k),) raise - if len(results) > 0 and _is_sequence(results[0]): + if len(results) > 0 and is_sequence(results[0]): if not isinstance(results[0], Series): index = res_columns else: diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 048e4af20d02f..c9322a9371309 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -541,7 +541,7 @@ def _align_series(self, indexer, ser): # we have a frame, with multiple indexers on both axes; and a # series, so need to broadcast (see GH5206) if (sum_aligners == self.ndim and - all([com._is_sequence(_) for _ in indexer])): + all([com.is_sequence(_) for _ in indexer])): ser = ser.reindex(obj.axes[0][indexer[0]], copy=True).values # single indexer @@ -555,7 +555,7 @@ def _align_series(self, indexer, ser): ax = obj.axes[i] # multiple aligners (or null slices) - if com._is_sequence(idx) or isinstance(idx, slice): + if com.is_sequence(idx) or isinstance(idx, slice): if single_aligner and _is_null_slice(idx): continue new_ix = ax[idx] @@ -625,7 +625,7 @@ def _align_frame(self, indexer, df): sindexers = [] for i, ix in enumerate(indexer): ax = self.obj.axes[i] - if com._is_sequence(ix) or isinstance(ix, slice): + if com.is_sequence(ix) or isinstance(ix, slice): if idx is None: idx = ax[ix].ravel() elif cols is None: diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 0d13b6513b377..9465247056e27 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -25,7 +25,7 @@ def test_mut_exclusive(): def test_is_sequence(): - is_seq = com._is_sequence + is_seq = com.is_sequence assert(is_seq((1, 2))) assert(is_seq([1, 2])) assert(not is_seq("abcd")) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 4acf4d63d9de7..6a71160a08ae9 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -24,7 +24,7 @@ from numpy.testing import assert_array_equal import pandas as pd -from pandas.core.common import _is_sequence, array_equivalent, is_list_like +from pandas.core.common import is_sequence, array_equivalent, is_list_like import pandas.core.index as index import pandas.core.series as series import pandas.core.frame as frame @@ -945,7 +945,7 @@ def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None, if ndupe_l is None: ndupe_l = [1] * nlevels - assert (_is_sequence(ndupe_l) and len(ndupe_l) <= nlevels) + assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels) assert (names is None or names is False or names is True or len(names) is nlevels) assert idx_type is None or \
closes #8933 Refactored _is_sequence to is_sequence
https://api.github.com/repos/pandas-dev/pandas/pulls/8959
2014-12-02T09:00:48Z
2014-12-02T10:52:26Z
2014-12-02T10:52:26Z
2014-12-02T10:52:26Z
ENH: add contextmanager to HDFStore (#8791)
diff --git a/doc/source/io.rst b/doc/source/io.rst index ba19173546cb2..f2d5924edac77 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2348,7 +2348,7 @@ Closing a Store, Context Manager # Working with, and automatically closing the store with the context # manager - with get_store('store.h5') as store: + with HDFStore('store.h5') as store: store.keys() .. ipython:: python diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 260e4e8a17c7d..57534fa2e1ef0 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -75,6 +75,7 @@ Enhancements - Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`). - Added ``gbq.generate_bq_schema`` function to the gbq module (:issue:`8325`). - ``Series`` now works with map objects the same way as generators (:issue:`8909`). +- Added context manager to ``HDFStore`` (:issue:`8791`). Now with HDFStore('path') as store: should also close to store. get_store will be deprecated in the future. .. _whatsnew_0152.performance: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 56c444095ca51..05510f655f7be 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -251,33 +251,6 @@ def _tables(): return _table_mod -@contextmanager -def get_store(path, **kwargs): - """ - Creates an HDFStore instance. This function can be used in a with statement - - Parameters - ---------- - same as HDFStore - - Examples - -------- - >>> from pandas import DataFrame - >>> from numpy.random import randn - >>> bar = DataFrame(randn(10, 4)) - >>> with get_store('test.h5') as store: - ... store['foo'] = bar # write to HDF5 - ... bar = store['foo'] # retrieve - """ - store = None - try: - store = HDFStore(path, **kwargs) - yield store - finally: - if store is not None: - store.close() - - # interface to/from ### def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, @@ -289,7 +262,7 @@ def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, f = lambda store: store.put(key, value, **kwargs) if isinstance(path_or_buf, string_types): - with get_store(path_or_buf, mode=mode, complevel=complevel, + with HDFStore(path_or_buf, mode=mode, complevel=complevel, complib=complib) as store: f(store) else: @@ -493,6 +466,12 @@ def __unicode__(self): return output + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def keys(self): """ Return a (potentially unordered) list of the keys corresponding to the @@ -1288,6 +1267,12 @@ def _read_group(self, group, **kwargs): return s.read(**kwargs) +def get_store(path, **kwargs): + """ Backwards compatible alias for ``HDFStore`` + """ + return HDFStore(path, **kwargs) + + class TableIterator(object): """ define the iteration interface on a table diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index e2a99076e7607..e95d46f66f17f 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -172,6 +172,25 @@ def test_factory_fun(self): finally: safe_remove(self.path) + def test_context(self): + try: + with HDFStore(self.path) as tbl: + raise ValueError('blah') + except ValueError: + pass + finally: + safe_remove(self.path) + + try: + with HDFStore(self.path) as tbl: + tbl['a'] = tm.makeDataFrame() + + with HDFStore(self.path) as tbl: + self.assertEqual(len(tbl), 1) + self.assertEqual(type(tbl['a']), DataFrame) + finally: + safe_remove(self.path) + def test_conv_read_write(self): try: @@ -334,10 +353,10 @@ def test_api_default_format(self): pandas.set_option('io.hdf.default_format','table') df.to_hdf(path,'df3') - with get_store(path) as store: + with HDFStore(path) as store: self.assertTrue(store.get_storer('df3').is_table) df.to_hdf(path,'df4',append=True) - with get_store(path) as store: + with HDFStore(path) as store: self.assertTrue(store.get_storer('df4').is_table) pandas.set_option('io.hdf.default_format',None) @@ -463,11 +482,11 @@ def check(mode): # context if mode in ['r','r+']: def f(): - with get_store(path,mode=mode) as store: + with HDFStore(path,mode=mode) as store: pass self.assertRaises(IOError, f) else: - with get_store(path,mode=mode) as store: + with HDFStore(path,mode=mode) as store: self.assertEqual(store._handle.mode, mode) with ensure_clean_path(self.path) as path:
Added a context manager to HDFStore closes #8791
https://api.github.com/repos/pandas-dev/pandas/pulls/8958
2014-12-02T08:59:57Z
2014-12-04T11:30:36Z
2014-12-04T11:30:36Z
2014-12-04T11:30:51Z
Cookbook text fix
diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index 8378873db9a65..6e411626ca770 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -489,9 +489,9 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to .. ipython:: python def GrowUp(x): - avg_weight = sum(x[x.size == 'S'].weight * 1.5) - avg_weight += sum(x[x.size == 'M'].weight * 1.25) - avg_weight += sum(x[x.size == 'L'].weight) + avg_weight = sum(x[x['size'] == 'S'].weight * 1.5) + avg_weight += sum(x[x['size'] == 'M'].weight * 1.25) + avg_weight += sum(x[x['size'] == 'L'].weight) avg_weight = avg_weight / len(x) return pd.Series(['L',avg_weight,True], index=['size', 'weight', 'adult']) diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index eb0429ad4a0cd..0e586f22a3190 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -776,7 +776,60 @@ def nbytes(self): return self._codes.nbytes + self._categories.values.nbytes def searchsorted(self, v, side='left', sorter=None): - raise NotImplementedError("See https://github.com/pydata/pandas/issues/8420") + """Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted Categorical `self` such that, if the + corresponding elements in `v` were inserted before the indices, the + order of `self` would be preserved. + + Parameters + ---------- + v : array_like + Array-like values or a scalar value, to insert/search for in `self`. + side : {'left', 'right'}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `a`). + sorter : 1-D array_like, optional + Optional array of integer indices that sort `self` into ascending + order. They are typically the result of ``np.argsort``. + + Returns + ------- + indices : array of ints + Array of insertion points with the same shape as `v`. + + See Also + -------- + Series.searchsorted + numpy.searchsorted + + Notes + ----- + Binary search is used to find the required insertion points. + + Examples + -------- + >>> x = pd.Categorical(['apple', 'bread', 'bread', 'cheese', 'milk' ]) + [apple, bread, bread, cheese, milk] + Categories (4, object): [apple < bread < cheese < milk] + >>> x.searchsorted('bread') + 1 + >>> x.searchsorted(['bread']) + array([1]) + >>> x.searchsorted(['bread', 'eggs']) + array([1, 4]) + >>> x.searchsorted(['bread', 'eggs'], side='right') + array([3, 4]) # eggs before milk + >>> x = pd.Categorical(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ]) + >>> x.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + array([3, 5]) # eggs after donuts, after switching milk and donuts + """ + if not self.ordered: + raise ValueError("searchsorted requires an ordered Categorical.") + + values_as_codes = self.categories.values.searchsorted(np.asarray(v), side) + return self.codes.searchsorted(values_as_codes, sorter=sorter) def isnull(self): """ diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index dc82abfb40e02..05fc0c0fec39b 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -882,13 +882,57 @@ def test_nbytes(self): self.assertEqual(cat.nbytes, exp) def test_searchsorted(self): + # https://github.com/pydata/pandas/issues/8420 + s1 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk' ]) + s2 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ]) + c1 = pd.Categorical(s1) + c2 = pd.Categorical(s2) + + # Single item array + res = c1.searchsorted(['bread']) + chk = s1.searchsorted(['bread']) + exp = np.array([1]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # Scalar version of single item array + # Ambiguous what Categorical should return as np.array returns + # a scalar and pd.Series returns an array. + # We get different results depending on whether + # Categorical.searchsorted(v) passes v through np.asarray() + # or pd.Series(v).values. The former returns scalar, the + # latter an array. + # Test code here follows np.array.searchsorted(). + # Commented out lines below follow pd.Series. + res = c1.searchsorted('bread') + chk = np.array(s1).searchsorted('bread') + exp = 1 + #exp = np.array([1]) + #chk = s1.searchsorted('bread') + #exp = np.array([1]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # Searching for a value that is not present in the Categorical + res = c1.searchsorted(['bread', 'eggs']) + chk = s1.searchsorted(['bread', 'eggs']) + exp = np.array([1, 4]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) - # See https://github.com/pydata/pandas/issues/8420 - # TODO: implement me... - cat = pd.Categorical([1,2,3]) - def f(): - cat.searchsorted(3) - self.assertRaises(NotImplementedError, f) + # Searching for a value that is not present, to the right + res = c1.searchsorted(['bread', 'eggs'], side='right') + chk = s1.searchsorted(['bread', 'eggs'], side='right') + exp = np.array([3, 4]) # eggs before milk + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # As above, but with a sorter array to reorder an unsorted array + res = c2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + chk = s2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + exp = np.array([3, 5]) # eggs after donuts, after switching milk and donuts + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) def test_deprecated_labels(self): # TODO: labels is deprecated and should be removed in 0.18 or 2017, whatever is earlier
Closes #8944
https://api.github.com/repos/pandas-dev/pandas/pulls/8957
2014-12-02T00:11:05Z
2014-12-03T00:20:09Z
null
2014-12-04T00:08:00Z
Applying max_colwidth to the DataFrame index (#7856)
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 19bda851e392b..9a4e65819422b 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -543,3 +543,5 @@ Bug Fixes - Bug in ``Series.values_counts`` with excluding ``NaN`` for categorical type ``Series`` with ``dropna=True`` (:issue:`9443`) + +- Bug in ``DataFrameFormatter._get_formatted_index`` with not applying ``max_colwidth`` to the ``DataFrame`` index (:issue:`7856`) diff --git a/pandas/core/format.py b/pandas/core/format.py index 3efcfec254591..0d154a587acaf 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -746,6 +746,9 @@ def _get_formatted_index(self, frame): formatter=fmt) else: fmt_index = [index.format(name=show_index_names, formatter=fmt)] + fmt_index = [tuple(_make_fixed_width( + list(x), justify='left', minimum=(self.col_space or 0))) + for x in fmt_index] adjoined = adjoin(1, *fmt_index).split('\n') diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index b52e4f7e3947b..f8598ef4d4294 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -298,6 +298,21 @@ def mkframe(n): com.pprint_thing(df._repr_fits_horizontal_()) self.assertTrue(has_expanded_repr(df)) + def test_str_max_colwidth(self): + # GH 7856 + df = pd.DataFrame([{'a': 'foo', 'b': 'bar', + 'c': 'uncomfortably long line with lots of stuff', + 'd': 1}, + {'a': 'foo', 'b': 'bar', 'c': 'stuff', 'd': 1}]) + df.set_index(['a', 'b', 'c']) + self.assertTrue(str(df) == ' a b c d\n' + '0 foo bar uncomfortably long line with lots of stuff 1\n' + '1 foo bar stuff 1') + with option_context('max_colwidth', 20): + self.assertTrue(str(df) == ' a b c d\n' + '0 foo bar uncomfortably lo... 1\n' + '1 foo bar stuff 1') + def test_auto_detect(self): term_width, term_height = get_terminal_size() fac = 1.05 # Arbitrary large factor to exceed term widht
closes #7856 reports a problem with the application of max_colwidth to groupby. The real problem is that max_colwidth is not applied to the index. This patch solves that. I am not applying self.justify to the formatting of the index (as that would break a test). But maybe it makes more sense to change the test?
https://api.github.com/repos/pandas-dev/pandas/pulls/8954
2014-12-01T21:06:12Z
2015-04-28T12:00:07Z
null
2015-04-28T12:00:07Z
Doc for GH 8946
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index a7091d6ab38fb..2a4c78ad837d1 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -328,13 +328,23 @@ old categories must be included in the new categories and no new categories are Comparisons ----------- -Comparing `Categoricals` with other objects is possible in two cases: +Comparing categorical data with other objects is possible in three cases: - * comparing a categorical Series to another categorical Series, when `categories` and `ordered` is - the same or - * comparing a categorical Series to a scalar. + * comparing equality (``==`` and ``!=``) to a list-like object (list, Series, array, + ...) of the same length as the categorical data or + * all comparisons (``==``, ``!=``, ``>``, ``>=``, ``<``, and ``<=``) of categorical data to + another categorical Series, when ``ordered==True`` and the `categories` are the same or + * all comparisons of a categorical data to a scalar. -All other comparisons will raise a TypeError. +All other comparisons, especially "non-equality" comparisons of two categoricals with different +categories or a categorical with any list-like object, will raise a TypeError. + +.. note:: + + Any "non-equality" comparisons of categorical data with a `Series`, `np.array`, `list` or + categorical data with different categories or ordering will raise an `TypeError` because custom + categories ordering could be interpreted in two ways: one with taking in account the + ordering and one without. .. ipython:: python @@ -353,6 +363,13 @@ Comparing to a categorical with the same categories and ordering or to a scalar cat > cat_base cat > 2 +Equality comparisons work with any list-like object of same length and scalars: + +.. ipython:: python + + cat == cat_base2 + cat == 2 + This doesn't work because the categories are not the same: .. ipython:: python @@ -362,13 +379,9 @@ This doesn't work because the categories are not the same: except TypeError as e: print("TypeError: " + str(e)) -.. note:: - - Comparisons with `Series`, `np.array` or a `Categorical` with different categories or ordering - will raise an `TypeError` because custom categories ordering could be interpreted in two ways: - one with taking in account the ordering and one without. If you want to compare a categorical - series with such a type, you need to be explicit and convert the categorical data back to the - original values: +If you want to do a "non-equality" comparison of a categorical series with a list-like object +which is not categorical data, you need to be explicit and convert the categorical data back to +the original values: .. ipython:: python diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index fc560782816ff..9aa09272fb7fd 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -59,6 +59,8 @@ API changes p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) p.all() +- Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) + .. _whatsnew_0152.enhancements: Enhancements diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 7dfdc88dddbff..8dc7c3537183e 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -64,6 +64,12 @@ def f(self, other): else: return np.repeat(False, len(self)) else: + + # allow categorical vs object dtype array comparisons for equality + # these are only positional comparisons + if op in ['__eq__','__ne__']: + return getattr(np.array(self),op)(np.array(other)) + msg = "Cannot compare a Categorical for op {op} with type {typ}. If you want to \n" \ "compare values, use 'np.asarray(cat) <op> other'." raise TypeError(msg.format(op=op,typ=type(other))) diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 068cdff7fcf2d..a3154ff9df9a1 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -541,10 +541,13 @@ def _comp_method_SERIES(op, name, str_rep, masker=False): """ def na_op(x, y): - if com.is_categorical_dtype(x) != (not np.isscalar(y) and com.is_categorical_dtype(y)): - msg = "Cannot compare a Categorical for op {op} with type {typ}. If you want to \n" \ - "compare values, use 'series <op> np.asarray(cat)'." - raise TypeError(msg.format(op=op,typ=type(y))) + # dispatch to the categorical if we have a categorical + # in either operand + if com.is_categorical_dtype(x): + return op(x,y) + elif com.is_categorical_dtype(y) and not lib.isscalar(y): + return op(y,x) + if x.dtype == np.object_: if isinstance(y, list): y = lib.list_to_object_array(y) @@ -586,33 +589,33 @@ def wrapper(self, other): msg = "Cannot compare a Categorical for op {op} with Series of dtype {typ}.\n"\ "If you want to compare values, use 'series <op> np.asarray(other)'." raise TypeError(msg.format(op=op,typ=self.dtype)) - else: - mask = isnull(self) - values = self.get_values() - other = _index.convert_scalar(values,_values_from_object(other)) + mask = isnull(self) - if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): - values = values.view('i8') + values = self.get_values() + other = _index.convert_scalar(values,_values_from_object(other)) - # scalars - res = na_op(values, other) - if np.isscalar(res): - raise TypeError('Could not compare %s type with Series' - % type(other)) + if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): + values = values.view('i8') - # always return a full value series here - res = _values_from_object(res) + # scalars + res = na_op(values, other) + if np.isscalar(res): + raise TypeError('Could not compare %s type with Series' + % type(other)) - res = pd.Series(res, index=self.index, name=self.name, - dtype='bool') + # always return a full value series here + res = _values_from_object(res) - # mask out the invalids - if mask.any(): - res[mask] = masker + res = pd.Series(res, index=self.index, name=self.name, + dtype='bool') + + # mask out the invalids + if mask.any(): + res[mask] = masker - return res + return res return wrapper diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 196ad8b7680b9..4c202a525863d 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -2211,11 +2211,63 @@ def f(): tm.assert_series_equal(res, exp) # And test NaN handling... - cat = pd.Series(pd.Categorical(["a","b","c", np.nan])) + cat = Series(Categorical(["a","b","c", np.nan])) exp = Series([True, True, True, False]) res = (cat == cat) tm.assert_series_equal(res, exp) + def test_cat_equality(self): + + # GH 8938 + # allow equality comparisons + a = Series(list('abc'),dtype="category") + b = Series(list('abc'),dtype="object") + c = Series(['a','b','cc'],dtype="object") + d = Series(list('acb'),dtype="object") + e = Categorical(list('abc')) + f = Categorical(list('acb')) + + # vs scalar + self.assertFalse((a=='a').all()) + self.assertTrue(((a!='a') == ~(a=='a')).all()) + + self.assertFalse(('a'==a).all()) + self.assertTrue((a=='a')[0]) + self.assertTrue(('a'==a)[0]) + self.assertFalse(('a'!=a)[0]) + + # vs list-like + self.assertTrue((a==a).all()) + self.assertFalse((a!=a).all()) + + self.assertTrue((a==list(a)).all()) + self.assertTrue((a==b).all()) + self.assertTrue((b==a).all()) + self.assertTrue(((~(a==b))==(a!=b)).all()) + self.assertTrue(((~(b==a))==(b!=a)).all()) + + self.assertFalse((a==c).all()) + self.assertFalse((c==a).all()) + self.assertFalse((a==d).all()) + self.assertFalse((d==a).all()) + + # vs a cat-like + self.assertTrue((a==e).all()) + self.assertTrue((e==a).all()) + self.assertFalse((a==f).all()) + self.assertFalse((f==a).all()) + + self.assertTrue(((~(a==e)==(a!=e)).all())) + self.assertTrue(((~(e==a)==(e!=a)).all())) + self.assertTrue(((~(a==f)==(a!=f)).all())) + self.assertTrue(((~(f==a)==(f!=a)).all())) + + # non-equality is not comparable + self.assertRaises(TypeError, lambda: a < b) + self.assertRaises(TypeError, lambda: b < a) + self.assertRaises(TypeError, lambda: a > b) + self.assertRaises(TypeError, lambda: b > a) + def test_concat(self): cat = pd.Categorical(["a","b"], categories=["a","b"]) vals = [1,2]
For https://github.com/pydata/pandas/pull/8946
https://api.github.com/repos/pandas-dev/pandas/pulls/8952
2014-12-01T17:17:45Z
2014-12-02T12:15:59Z
null
2014-12-02T12:15:59Z
Updating generic.py error message #8618 - New branch
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 52f37ee24f69a..059cdff8996f7 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2875,10 +2875,12 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, GroupBy object """ - from pandas.core.groupby import groupby + + if level is None and by is None: + raise TypeError("You have to supply one of 'by' and 'level'") axis = self._get_axis_number(axis) - return groupby(self, by, axis=axis, level=level, as_index=as_index, + return groupby(self, by=by, axis=axis, level=level, as_index=as_index, sort=sort, group_keys=group_keys, squeeze=squeeze) def asfreq(self, freq, method=None, how=None, normalize=False): diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index ef3fc03fc8d22..bf24eda60b986 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -1961,6 +1961,9 @@ def test_groupby_level(self): # raise exception for non-MultiIndex self.assertRaises(ValueError, self.df.groupby, level=1) + + + def test_groupby_level_index_names(self): ## GH4014 this used to raise ValueError since 'exp'>1 (in py2) df = DataFrame({'exp' : ['A']*3 + ['B']*3, 'var1' : lrange(6),}).set_index('exp') @@ -1999,6 +2002,17 @@ def test_groupby_level_apply(self): result = frame['A'].groupby(level=0).count() self.assertEqual(result.index.name, 'first') + def test_groupby_args(self): + #PR8618 and issue 8015 + frame = self.mframe + def j(): + frame.groupby() + self.assertRaisesRegexp(TypeError, "You have to supply one of 'by' and 'level'", j) + + def k(): + frame.groupby(by=None, level=None) + self.assertRaisesRegexp(TypeError, "You have to supply one of 'by' and 'level'", k) + def test_groupby_level_mapper(self): frame = self.mframe deleveled = frame.reset_index() @@ -3689,8 +3703,8 @@ def test_cumcount(self): assert_series_equal(expected, sg.cumcount()) def test_cumcount_empty(self): - ge = DataFrame().groupby() - se = Series().groupby() + ge = DataFrame().groupby(level=0) + se = Series().groupby(level=0) e = Series(dtype='int64') # edge case, as this is usually considered float
closes #8015 I deleted the previous branch that was causing problems and submitted this. This is my first attempt at a PR. I just made a little change to allow an error message. Would appreciate some feedback. @jreback @jorisvandenbossche @hayd
https://api.github.com/repos/pandas-dev/pandas/pulls/8950
2014-12-01T08:24:17Z
2014-12-03T10:51:37Z
null
2014-12-03T10:52:43Z
BLD/TST: skip mpl 1.2.1 tests (GH8947)
diff --git a/.travis.yml b/.travis.yml index ea1a0d9d6752a..bf6a3f166e706 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,6 +38,13 @@ matrix: - BUILD_TYPE=conda - JOB_NAME: "27_nslow" - DOC_BUILD=true # if rst files were changed, build docs in parallel with tests + - python: 2.7 + env: + - NOSE_ARGS="slow and not network and not disabled" + - FULL_DEPS=true + - JOB_TAG=_SLOW + - BUILD_TYPE=conda + - JOB_NAME: "27_slow" - python: 3.3 env: - NOSE_ARGS="not slow and not disabled" @@ -76,6 +83,13 @@ matrix: - CLIPBOARD_GUI=qt4 - BUILD_TYPE=pydata - JOB_NAME: "32_nslow" + - python: 2.7 + env: + - NOSE_ARGS="slow and not network and not disabled" + - FULL_DEPS=true + - JOB_TAG=_SLOW + - BUILD_TYPE=conda + - JOB_NAME: "27_slow" - python: 2.7 env: - EXPERIMENTAL=true diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.txt index 036e597e5b788..6c70bfd77ff3f 100644 --- a/ci/requirements-2.7_LOCALE.txt +++ b/ci/requirements-2.7_LOCALE.txt @@ -7,7 +7,7 @@ xlrd=0.9.2 numpy=1.7.1 cython=0.19.1 bottleneck=0.8.0 -matplotlib=1.3.0 +matplotlib=1.2.1 patsy=0.1.0 sqlalchemy=0.8.1 html5lib=1.0b2 diff --git a/ci/requirements-2.7_SLOW.txt b/ci/requirements-2.7_SLOW.txt new file mode 100644 index 0000000000000..a1ecbceda40dd --- /dev/null +++ b/ci/requirements-2.7_SLOW.txt @@ -0,0 +1,25 @@ +dateutil +pytz +numpy +cython +matplotlib +scipy +patsy +statsmodels +xlwt +openpyxl +xlsxwriter +xlrd +numexpr +pytables +sqlalchemy +lxml +boto +bottleneck +psycopg2 +pymysql +html5lib +beautiful-soup +httplib2 +python-gflags +google-api-python-client diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 74ec6d22ca4cd..06902dded0da4 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -77,6 +77,9 @@ def setUp(self): else: self.bp_n_objects = 8 + self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') + self.mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1') + def tearDown(self): tm.close() @@ -443,7 +446,6 @@ def setUp(self): import matplotlib as mpl mpl.rcdefaults() - self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') self.ts = tm.makeTimeSeries() self.ts.name = 'ts' @@ -818,12 +820,13 @@ def test_hist_kwargs(self): self._check_text_labels(ax.yaxis.get_label(), 'Degree') tm.close() - ax = self.ts.plot(kind='hist', orientation='horizontal') - self._check_text_labels(ax.xaxis.get_label(), 'Degree') - tm.close() + if self.mpl_ge_1_3_1: + ax = self.ts.plot(kind='hist', orientation='horizontal') + self._check_text_labels(ax.xaxis.get_label(), 'Degree') + tm.close() - ax = self.ts.plot(kind='hist', align='left', stacked=True) - tm.close() + ax = self.ts.plot(kind='hist', align='left', stacked=True) + tm.close() @slow def test_hist_kde_color(self): @@ -961,9 +964,6 @@ def setUp(self): import matplotlib as mpl mpl.rcdefaults() - self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1') - self.mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1') - self.tdf = tm.makeTimeDataFrame() self.hexbin_df = DataFrame({"A": np.random.uniform(size=20), "B": np.random.uniform(size=20), @@ -2141,31 +2141,33 @@ def test_hist_df_coord(self): self._check_box_coord(axes[2].patches, expected_y=np.array([0, 0, 0, 0, 0]), expected_h=np.array([6, 7, 8, 9, 10])) - # horizontal - ax = df.plot(kind='hist', bins=5, orientation='horizontal') - self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([10, 9, 8, 7, 6])) - self._check_box_coord(ax.patches[5:10], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([8, 8, 8, 8, 8])) - self._check_box_coord(ax.patches[10:], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([6, 7, 8, 9, 10])) - - ax = df.plot(kind='hist', bins=5, stacked=True, orientation='horizontal') - self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([10, 9, 8, 7, 6])) - self._check_box_coord(ax.patches[5:10], expected_x=np.array([10, 9, 8, 7, 6]), - expected_w=np.array([8, 8, 8, 8, 8])) - self._check_box_coord(ax.patches[10:], expected_x=np.array([18, 17, 16, 15, 14]), - expected_w=np.array([6, 7, 8, 9, 10])) - - axes = df.plot(kind='hist', bins=5, stacked=True, - subplots=True, orientation='horizontal') - self._check_box_coord(axes[0].patches, expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([10, 9, 8, 7, 6])) - self._check_box_coord(axes[1].patches, expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([8, 8, 8, 8, 8])) - self._check_box_coord(axes[2].patches, expected_x=np.array([0, 0, 0, 0, 0]), - expected_w=np.array([6, 7, 8, 9, 10])) + if self.mpl_ge_1_3_1: + + # horizontal + ax = df.plot(kind='hist', bins=5, orientation='horizontal') + self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([10, 9, 8, 7, 6])) + self._check_box_coord(ax.patches[5:10], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([8, 8, 8, 8, 8])) + self._check_box_coord(ax.patches[10:], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([6, 7, 8, 9, 10])) + + ax = df.plot(kind='hist', bins=5, stacked=True, orientation='horizontal') + self._check_box_coord(ax.patches[:5], expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([10, 9, 8, 7, 6])) + self._check_box_coord(ax.patches[5:10], expected_x=np.array([10, 9, 8, 7, 6]), + expected_w=np.array([8, 8, 8, 8, 8])) + self._check_box_coord(ax.patches[10:], expected_x=np.array([18, 17, 16, 15, 14]), + expected_w=np.array([6, 7, 8, 9, 10])) + + axes = df.plot(kind='hist', bins=5, stacked=True, + subplots=True, orientation='horizontal') + self._check_box_coord(axes[0].patches, expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([10, 9, 8, 7, 6])) + self._check_box_coord(axes[1].patches, expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([8, 8, 8, 8, 8])) + self._check_box_coord(axes[2].patches, expected_x=np.array([0, 0, 0, 0, 0]), + expected_w=np.array([6, 7, 8, 9, 10])) @slow def test_hist_df_legacy(self):
closes #8947 add SLOW build (optional)
https://api.github.com/repos/pandas-dev/pandas/pulls/8949
2014-11-30T23:00:05Z
2014-11-30T23:37:41Z
2014-11-30T23:37:41Z
2014-11-30T23:37:41Z
BUG: preserve left frame order in left merge
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index fc560782816ff..9c585cebcbe18 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -101,6 +101,7 @@ Bug Fixes - ``slice`` string method now takes step into account (:issue:`8754`) - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) +- Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix negative step support for label-based slices (:issue:`8753`) Old behavior: diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py index 2f0920b6d4e98..e19c0de884c31 100644 --- a/pandas/tools/merge.py +++ b/pandas/tools/merge.py @@ -479,8 +479,10 @@ def _get_join_indexers(left_keys, right_keys, sort=False, how='inner'): left_group_key, right_group_key, max_groups = \ _factorize_keys(left_group_key, right_group_key, sort=sort) + # preserve left frame order if how == 'left' and sort == False + kwargs = {'sort':sort} if how == 'left' else {} join_func = _join_functions[how] - return join_func(left_group_key, right_group_key, max_groups) + return join_func(left_group_key, right_group_key, max_groups, **kwargs) class _OrderedMerge(_MergeOperation): diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index c942998d430f4..96e4b32d2ad25 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -1022,6 +1022,13 @@ def test_left_join_index_multi_match_multiindex(self): tm.assert_frame_equal(result, expected) + # GH7331 - maintain left frame order in left merge + right.reset_index(inplace=True) + right.columns = left.columns[:3].tolist() + right.columns[-1:].tolist() + result = merge(left, right, how='left', on=left.columns[:-1].tolist()) + expected.index = np.arange(len(expected)) + tm.assert_frame_equal(result, expected) + def test_left_join_index_multi_match(self): left = DataFrame([ ['c', 0], @@ -1059,6 +1066,11 @@ def test_left_join_index_multi_match(self): tm.assert_frame_equal(result, expected) + # GH7331 - maintain left frame order in left merge + result = merge(left, right.reset_index(), how='left', on='tag') + expected.index = np.arange(len(expected)) + tm.assert_frame_equal(result, expected) + def test_join_multi_dtypes(self): # test with multi dtypes in the join index
closes https://github.com/pydata/pandas/issues/7331 on master: ``` >>> left dates states 0 20140101 CA 1 20140102 NY 2 20140103 CA >>> right stateid states 0 1 CA 1 2 NY >>> pd.merge(left, right, how='left', on='states', sort=False) dates states stateid 0 20140101 CA 1 1 20140103 CA 1 2 20140102 NY 2 ``` `DataFrame.join` already works fine: ``` >>> left.join(right.set_index('states'), on='states', how='left') dates states stateid 0 20140101 CA 1 1 20140102 NY 2 2 20140103 CA 1 ``` on branch: ``` >>> pd.merge(left, right, how='left', on='states', sort=False) dates states stateid 0 20140101 CA 1 1 20140102 NY 2 2 20140103 CA 1 >>> pd.merge(left, right, how='left', on='states', sort=True) dates states stateid 0 20140101 CA 1 1 20140103 CA 1 2 20140102 NY 2 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/8948
2014-11-30T22:20:32Z
2014-12-01T00:46:44Z
2014-12-01T00:46:44Z
2014-12-01T12:54:02Z
API: Allow equality comparisons of Series with a categorical dtype and object type are allowed (GH8938)
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index a7091d6ab38fb..2a4c78ad837d1 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -328,13 +328,23 @@ old categories must be included in the new categories and no new categories are Comparisons ----------- -Comparing `Categoricals` with other objects is possible in two cases: +Comparing categorical data with other objects is possible in three cases: - * comparing a categorical Series to another categorical Series, when `categories` and `ordered` is - the same or - * comparing a categorical Series to a scalar. + * comparing equality (``==`` and ``!=``) to a list-like object (list, Series, array, + ...) of the same length as the categorical data or + * all comparisons (``==``, ``!=``, ``>``, ``>=``, ``<``, and ``<=``) of categorical data to + another categorical Series, when ``ordered==True`` and the `categories` are the same or + * all comparisons of a categorical data to a scalar. -All other comparisons will raise a TypeError. +All other comparisons, especially "non-equality" comparisons of two categoricals with different +categories or a categorical with any list-like object, will raise a TypeError. + +.. note:: + + Any "non-equality" comparisons of categorical data with a `Series`, `np.array`, `list` or + categorical data with different categories or ordering will raise an `TypeError` because custom + categories ordering could be interpreted in two ways: one with taking in account the + ordering and one without. .. ipython:: python @@ -353,6 +363,13 @@ Comparing to a categorical with the same categories and ordering or to a scalar cat > cat_base cat > 2 +Equality comparisons work with any list-like object of same length and scalars: + +.. ipython:: python + + cat == cat_base2 + cat == 2 + This doesn't work because the categories are not the same: .. ipython:: python @@ -362,13 +379,9 @@ This doesn't work because the categories are not the same: except TypeError as e: print("TypeError: " + str(e)) -.. note:: - - Comparisons with `Series`, `np.array` or a `Categorical` with different categories or ordering - will raise an `TypeError` because custom categories ordering could be interpreted in two ways: - one with taking in account the ordering and one without. If you want to compare a categorical - series with such a type, you need to be explicit and convert the categorical data back to the - original values: +If you want to do a "non-equality" comparison of a categorical series with a list-like object +which is not categorical data, you need to be explicit and convert the categorical data back to +the original values: .. ipython:: python diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 11cf2450d2f28..e61ae93ca49c0 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -59,6 +59,8 @@ API changes p = pd.Panel(np.random.rand(2, 5, 4) > 0.1) p.all() +- Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`) + .. _whatsnew_0152.enhancements: Enhancements diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 5b3e9e8a22b12..ff1051dc00a00 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -64,6 +64,12 @@ def f(self, other): else: return np.repeat(False, len(self)) else: + + # allow categorical vs object dtype array comparisons for equality + # these are only positional comparisons + if op in ['__eq__','__ne__']: + return getattr(np.array(self),op)(np.array(other)) + msg = "Cannot compare a Categorical for op {op} with type {typ}. If you want to \n" \ "compare values, use 'np.asarray(cat) <op> other'." raise TypeError(msg.format(op=op,typ=type(other))) diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 068cdff7fcf2d..a3154ff9df9a1 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -541,10 +541,13 @@ def _comp_method_SERIES(op, name, str_rep, masker=False): """ def na_op(x, y): - if com.is_categorical_dtype(x) != (not np.isscalar(y) and com.is_categorical_dtype(y)): - msg = "Cannot compare a Categorical for op {op} with type {typ}. If you want to \n" \ - "compare values, use 'series <op> np.asarray(cat)'." - raise TypeError(msg.format(op=op,typ=type(y))) + # dispatch to the categorical if we have a categorical + # in either operand + if com.is_categorical_dtype(x): + return op(x,y) + elif com.is_categorical_dtype(y) and not lib.isscalar(y): + return op(y,x) + if x.dtype == np.object_: if isinstance(y, list): y = lib.list_to_object_array(y) @@ -586,33 +589,33 @@ def wrapper(self, other): msg = "Cannot compare a Categorical for op {op} with Series of dtype {typ}.\n"\ "If you want to compare values, use 'series <op> np.asarray(other)'." raise TypeError(msg.format(op=op,typ=self.dtype)) - else: - mask = isnull(self) - values = self.get_values() - other = _index.convert_scalar(values,_values_from_object(other)) + mask = isnull(self) - if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): - values = values.view('i8') + values = self.get_values() + other = _index.convert_scalar(values,_values_from_object(other)) - # scalars - res = na_op(values, other) - if np.isscalar(res): - raise TypeError('Could not compare %s type with Series' - % type(other)) + if issubclass(values.dtype.type, (np.datetime64, np.timedelta64)): + values = values.view('i8') - # always return a full value series here - res = _values_from_object(res) + # scalars + res = na_op(values, other) + if np.isscalar(res): + raise TypeError('Could not compare %s type with Series' + % type(other)) - res = pd.Series(res, index=self.index, name=self.name, - dtype='bool') + # always return a full value series here + res = _values_from_object(res) - # mask out the invalids - if mask.any(): - res[mask] = masker + res = pd.Series(res, index=self.index, name=self.name, + dtype='bool') + + # mask out the invalids + if mask.any(): + res[mask] = masker - return res + return res return wrapper diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 196ad8b7680b9..4c202a525863d 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -2211,11 +2211,63 @@ def f(): tm.assert_series_equal(res, exp) # And test NaN handling... - cat = pd.Series(pd.Categorical(["a","b","c", np.nan])) + cat = Series(Categorical(["a","b","c", np.nan])) exp = Series([True, True, True, False]) res = (cat == cat) tm.assert_series_equal(res, exp) + def test_cat_equality(self): + + # GH 8938 + # allow equality comparisons + a = Series(list('abc'),dtype="category") + b = Series(list('abc'),dtype="object") + c = Series(['a','b','cc'],dtype="object") + d = Series(list('acb'),dtype="object") + e = Categorical(list('abc')) + f = Categorical(list('acb')) + + # vs scalar + self.assertFalse((a=='a').all()) + self.assertTrue(((a!='a') == ~(a=='a')).all()) + + self.assertFalse(('a'==a).all()) + self.assertTrue((a=='a')[0]) + self.assertTrue(('a'==a)[0]) + self.assertFalse(('a'!=a)[0]) + + # vs list-like + self.assertTrue((a==a).all()) + self.assertFalse((a!=a).all()) + + self.assertTrue((a==list(a)).all()) + self.assertTrue((a==b).all()) + self.assertTrue((b==a).all()) + self.assertTrue(((~(a==b))==(a!=b)).all()) + self.assertTrue(((~(b==a))==(b!=a)).all()) + + self.assertFalse((a==c).all()) + self.assertFalse((c==a).all()) + self.assertFalse((a==d).all()) + self.assertFalse((d==a).all()) + + # vs a cat-like + self.assertTrue((a==e).all()) + self.assertTrue((e==a).all()) + self.assertFalse((a==f).all()) + self.assertFalse((f==a).all()) + + self.assertTrue(((~(a==e)==(a!=e)).all())) + self.assertTrue(((~(e==a)==(e!=a)).all())) + self.assertTrue(((~(a==f)==(a!=f)).all())) + self.assertTrue(((~(f==a)==(f!=a)).all())) + + # non-equality is not comparable + self.assertRaises(TypeError, lambda: a < b) + self.assertRaises(TypeError, lambda: b < a) + self.assertRaises(TypeError, lambda: a > b) + self.assertRaises(TypeError, lambda: b > a) + def test_concat(self): cat = pd.Categorical(["a","b"], categories=["a","b"]) vals = [1,2]
closes #8938
https://api.github.com/repos/pandas-dev/pandas/pulls/8946
2014-11-30T16:00:05Z
2014-12-04T11:06:12Z
2014-12-04T11:06:12Z
2014-12-05T15:46:03Z
BUG: Fixed plot label shows as None. #8905
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 58dc1da214c05..9707cac00c05a 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -122,6 +122,7 @@ Bug Fixes - Bug in ``merge`` where ``how='left'`` and ``sort=False`` would not preserve left frame order (:issue:`7331`) - Fix negative step support for label-based slices (:issue:`8753`) +- Fixed given label showing as None (:issue:`#8905`) Old behavior: diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index b9a96ee262101..a2baad32e0c2d 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1589,7 +1589,9 @@ def _make_plot(self): errors = self._get_errorbars(label=label, index=i) kwds = dict(kwds, **errors) - label = com.pprint_thing(label) # .encode('utf-8') + if label is not None or self.legend: + label = com.pprint_thing(label) # .encode('utf-8') + kwds['label'] = label newlines = plotf(ax, x, y, style=style, column_num=i, **kwds) @@ -2283,7 +2285,7 @@ def _plot(data, x=None, y=None, subplots=False, if com.is_integer(y) and not data.columns.holds_integer(): y = data.columns[y] label = x if x is not None else data.index.name - label = kwds.pop('label', label) + label = kwds.get('label', label) series = data[y].copy() # Don't modify series.index.name = label diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index c4e642ffe43b0..ec8be9d66ae25 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -89,6 +89,20 @@ def test_nonnumeric_exclude(self): self.assertRaises(TypeError, df['A'].plot) + @slow + def test_legend_added(self): + df = DataFrame(np.random.rand(2, 4), columns=['a', 'b', 'c', 'd']) + a_plot = df.plot(kind='scatter', x='a', y='b', + color='DarkBlue', label='Label') + b_plot = df.plot(kind='line', x='a', y='b', + color='DarkBlue', label="foo") + c_plot = df.plot(kind='line', x='a', y='b', + color='DarkBlue', label=None, legend=False) + + self.assertEqual(a_plot.legend().texts[0].get_text(), 'Label') + self.assertEqual(b_plot.legend().texts[0].get_text(), 'foo') + self.assertEqual(c_plot.legend(), None) + @slow def test_tsplot(self): from pandas.tseries.plotting import tsplot
Fixes https://github.com/pydata/pandas/issues/8905
https://api.github.com/repos/pandas-dev/pandas/pulls/8945
2014-11-30T15:45:34Z
2015-05-01T16:08:58Z
null
2023-05-11T01:12:45Z
round function added to DatetimeIndex
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index b7a18da3924c8..29b02c195680f 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -1886,6 +1886,28 @@ def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): self.assertEqual(str(index.reindex([])[0].tz), 'US/Eastern') self.assertEqual(str(index.reindex(np.array([]))[0].tz), 'US/Eastern') + def test_round(self): + index = pd.DatetimeIndex([ pd.Timestamp('20120827 12:05:00.002'), + pd.Timestamp('20130101 12:05:01'), + pd.Timestamp('20130712 15:10:00'), + pd.Timestamp('20130712 15:10:00.000004') ]) + + result = index.round('1s') + + tm.assert_index_equal(result, pd.DatetimeIndex([ + pd.Timestamp('20120827 12:05:00'), + pd.Timestamp('20130101 12:05:01'), + pd.Timestamp('20130712 15:10:00'), + pd.Timestamp('20130712 15:10:00') ]) ) + + result = index.round('1h') + + tm.assert_index_equal(result, pd.DatetimeIndex([ + pd.Timestamp('20120827 12:00:00'), + pd.Timestamp('20130101 12:00:00'), + pd.Timestamp('20130712 15:00:00'), + pd.Timestamp('20130712 15:00:00') ]) ) + class TestPeriodIndex(Base, tm.TestCase): _holder = PeriodIndex diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 202e30cc2eb5e..128fe13a62c4a 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -592,6 +592,11 @@ def _is_dates_only(self): from pandas.core.format import _is_dates_only return _is_dates_only(self.values) + def round(self, freq): + if isinstance(freq, compat.string_types): + freq = to_offset(freq).nanos + return DatetimeIndex(((self.asi8/freq).round()*freq).astype(np.int64)) + @property def _formatter_func(self): from pandas.core.format import _get_format_datetime64
closes #4314
https://api.github.com/repos/pandas-dev/pandas/pulls/8942
2014-11-30T14:10:47Z
2015-05-09T16:06:17Z
null
2022-10-13T00:16:17Z
BUG: Resample across multiple days
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3aa50ad609064..d111dc34995d2 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -145,7 +145,8 @@ Bug Fixes - +- Bug in resample that causes a ValueError when resampling across multiple days + and the last offset is not calculated from the start of the range (:issue:`8683`) - Bug in `pd.infer_freq`/`DataFrame.inferred_freq` that prevented proper sub-daily frequency inference diff --git a/pandas/tseries/resample.py b/pandas/tseries/resample.py index b362c55b156a4..95d3ff015394a 100644 --- a/pandas/tseries/resample.py +++ b/pandas/tseries/resample.py @@ -411,15 +411,19 @@ def _get_range_edges(first, last, offset, closed='left', base=0): def _adjust_dates_anchored(first, last, offset, closed='right', base=0): from pandas.tseries.tools import normalize_date + # First and last offsets should be calculated from the start day to fix an + # error cause by resampling across multiple days when a one day period is + # not a multiple of the frequency. + # + # See https://github.com/pydata/pandas/issues/8683 + start_day_nanos = Timestamp(normalize_date(first)).value - last_day_nanos = Timestamp(normalize_date(last)).value base_nanos = (base % offset.n) * offset.nanos // offset.n start_day_nanos += base_nanos - last_day_nanos += base_nanos foffset = (first.value - start_day_nanos) % offset.nanos - loffset = (last.value - last_day_nanos) % offset.nanos + loffset = (last.value - start_day_nanos) % offset.nanos if closed == 'right': if foffset > 0: diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py index bd6c1766cfd61..42b09b699b919 100644 --- a/pandas/tseries/tests/test_resample.py +++ b/pandas/tseries/tests/test_resample.py @@ -705,6 +705,29 @@ def test_resample_anchored_monthstart(self): for freq in freqs: result = ts.resample(freq, how='mean') + def test_resample_anchored_multiday(self): + # When resampling a range spanning multiple days, ensure that the + # start date gets used to determine the offset. Fixes issue where + # a one day period is not a multiple of the frequency. + # + # See: https://github.com/pydata/pandas/issues/8683 + + s = pd.Series(np.random.randn(5), + index=pd.date_range('2014-10-14 23:06:23.206', + periods=3, freq='400L') + | pd.date_range('2014-10-15 23:00:00', + periods=2, freq='2200L')) + + # Ensure left closing works + result = s.resample('2200L', 'mean') + self.assertEqual(result.index[-1], + pd.Timestamp('2014-10-15 23:00:02.000')) + + # Ensure right closing works + result = s.resample('2200L', 'mean', label='right') + self.assertEqual(result.index[-1], + pd.Timestamp('2014-10-15 23:00:04.200')) + def test_corner_cases(self): # miscellaneous test coverage
Fixes an issue where resampling over multiple days causes a ValueError when a number of days between the normalized first and normalized last days is not a multiple of the frequency. Added test TestSeries.test_resample Closes #8683
https://api.github.com/repos/pandas-dev/pandas/pulls/8941
2014-11-30T13:33:57Z
2014-11-30T23:21:01Z
2014-11-30T23:21:01Z
2014-11-30T23:21:01Z
BUG: Fixed font size (set it on both x and y axis). #8765
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index eacccaa7cba92..f3f5cf41676da 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -99,6 +99,7 @@ Bug Fixes - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Fix negative step support for label-based slices (:issue:`8753`) +- Fix: The font size was only set on x axis if vertical or the y axis if horizontal. (:issue:`8765`) Old behavior: diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index cb669b75e5c96..4f3aa4e8e4a9e 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1051,13 +1051,15 @@ def _adorn_subplots(self): xticklabels = [labels.get(x, '') for x in ax.get_xticks()] ax.set_xticklabels(xticklabels) self._apply_axis_properties(ax.xaxis, rot=self.rot, - fontsize=self.fontsize) + fontsize=self.fontsize) + self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize) elif self.orientation == 'horizontal': if self._need_to_set_index: yticklabels = [labels.get(y, '') for y in ax.get_yticks()] ax.set_yticklabels(yticklabels) self._apply_axis_properties(ax.yaxis, rot=self.rot, - fontsize=self.fontsize) + fontsize=self.fontsize) + self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize) def _apply_axis_properties(self, axis, rot=None, fontsize=None): labels = axis.get_majorticklabels() + axis.get_minorticklabels() diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py index 4a60cdbedae4d..c4e642ffe43b0 100644 --- a/pandas/tseries/tests/test_plotting.py +++ b/pandas/tseries/tests/test_plotting.py @@ -48,6 +48,14 @@ def test_ts_plot_with_tz(self): ts = Series([188.5, 328.25], index=index) _check_plot_works(ts.plot) + def test_fontsize_set_correctly(self): + # For issue #8765 + import matplotlib.pyplot as plt + df = DataFrame(np.random.randn(10, 9), index=range(10)) + ax = df.plot(fontsize=2) + for label in (ax.get_xticklabels() + ax.get_yticklabels()): + self.assertEqual(label.get_fontsize(), 2) + @slow def test_frame_inferred(self): # inferred freq
Fix for https://github.com/pydata/pandas/issues/8765 The font size was only set on x axis if vertical or the y axis if horizontal.
https://api.github.com/repos/pandas-dev/pandas/pulls/8940
2014-11-30T12:41:40Z
2014-12-01T00:08:43Z
2014-12-01T00:08:43Z
2014-12-01T00:08:43Z
Adding encoding lines to files in tests/
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index fe070cff2e0ea..b145400afe13b 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pandas.compat import range import numpy as np diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 814da043d0319..a91c2573cc84e 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function import re from datetime import datetime, timedelta diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index dc82abfb40e02..a54c3bb84874d 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=E1101,E1103,W0232 from datetime import datetime diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 0d13b6513b377..d42306627f9ca 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime import re diff --git a/pandas/tests/test_compat.py b/pandas/tests/test_compat.py index 0d38bb23d6aa7..242b54c84d0ee 100644 --- a/pandas/tests/test_compat.py +++ b/pandas/tests/test_compat.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ Testing that functions from compat work as expected """ diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 8d012b871d8ca..86831a8485786 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function # pylint: disable-msg=W0612,E1101 diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 3e8534762ec05..ba3daf1b52045 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -1,5 +1,5 @@ -from __future__ import print_function # -*- coding: utf-8 -*- +from __future__ import print_function import re from pandas.compat import range, zip, lrange, StringIO, PY3, lzip, u diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index f4c8b9ecdbc86..5e78e8dc44bea 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index ef3fc03fc8d22..8533e85bcc309 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function import nose diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index b7a18da3924c8..da2e46166fa35 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=E1101,E1103,W0232 from datetime import datetime, timedelta diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 60c5676a99506..8e2e6e612a1a3 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101 import sys import nose diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 37b557743b731..45f089f5e0a53 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=W0102 import nose diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 2873cd81d4744..d69e224ae9933 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime, timedelta, date, time import numpy as np diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 2171b8e8428a4..a10467cf7ab4a 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101,W0141 import datetime import itertools diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 3ec00fee1d151..2a605cba8a6c0 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import division, print_function from functools import partial diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 7f902827ba5db..744dd31755c81 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=W0612,E1101 from datetime import datetime diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 6ef8c1820400a..94c6bb9e2a4aa 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime from pandas.compat import range, lrange import os diff --git a/pandas/tests/test_panelnd.py b/pandas/tests/test_panelnd.py index 92083afb38f41..67d015b940885 100644 --- a/pandas/tests/test_panelnd.py +++ b/pandas/tests/test_panelnd.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime import os import operator diff --git a/pandas/tests/test_reshape.py b/pandas/tests/test_reshape.py index 3cc2d94789a8d..f89d04f6fb2df 100644 --- a/pandas/tests/test_reshape.py +++ b/pandas/tests/test_reshape.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101 from copy import deepcopy from datetime import datetime, timedelta diff --git a/pandas/tests/test_rplot.py b/pandas/tests/test_rplot.py index ddfce477a320d..c58f17550a137 100644 --- a/pandas/tests/test_rplot.py +++ b/pandas/tests/test_rplot.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pandas.compat import range import pandas.tools.rplot as rplot import pandas.util.testing as tm diff --git a/pandas/tests/test_stats.py b/pandas/tests/test_stats.py index cb3fdcafd4056..eaaf89a52c2dc 100644 --- a/pandas/tests/test_stats.py +++ b/pandas/tests/test_stats.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pandas import compat import nose diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index a7d3c53c31e3d..06f507a50f785 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta, date diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index 5c26fce2b111e..9cc4d9e11c02e 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -1,4 +1,4 @@ - +# -*- coding: utf-8 -*- import nose from numpy import nan import numpy as np diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py index 8c56ba0e0f548..aed24f958a8f5 100644 --- a/pandas/tests/test_util.py +++ b/pandas/tests/test_util.py @@ -1,4 +1,4 @@ - +# -*- coding: utf-8 -*- import warnings import nose
https://api.github.com/repos/pandas-dev/pandas/pulls/8939
2014-11-30T12:35:49Z
2014-12-03T22:31:15Z
2014-12-03T22:31:15Z
2014-12-03T22:31:15Z
Categorical: let unique only return used categories
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d6d36fd8d14ba..377a9dea126e6 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -42,6 +42,9 @@ API changes - Bug in concat of Series with ``category`` dtype which were coercing to ``object``. (:issue:`8641`) +- Bug in unique of Series with ``category`` dtype, which returned all categories regardless + whether they were "used" or not (see :issue:`8559` for the discussion). + - ``Series.all`` and ``Series.any`` now support the ``level`` and ``skipna`` parameters. ``Series.all``, ``Series.any``, ``Index.all``, and ``Index.any`` no longer support the ``out`` and ``keepdims`` parameters, which existed for compatibility with ndarray. Various index types no longer support the ``all`` and ``any`` aggregation functions and will now raise ``TypeError``. (:issue:`8302`): .. ipython:: python diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index eb0429ad4a0cd..7dfdc88dddbff 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -1326,13 +1326,18 @@ def unique(self): """ Return the unique values. - This includes all categories, even if one or more is unused. + Unused categories are NOT returned. Returns ------- unique values : array """ - return np.asarray(self.categories) + unique_codes = np.unique(self.codes) + # for compatibility with normal unique, which has nan last + if unique_codes[0] == -1: + unique_codes[0:-1] = unique_codes[1:] + unique_codes[-1] = -1 + return take_1d(self.categories.values, unique_codes) def equals(self, other): """ diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index dc82abfb40e02..196ad8b7680b9 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -769,11 +769,17 @@ def test_min_max(self): self.assertEqual(_max, 1) def test_unique(self): - cat = Categorical(["a","b","c","d"]) - exp = np.asarray(["a","b","c","d"]) + cat = Categorical(["a","b"]) + exp = np.asarray(["a","b"]) res = cat.unique() self.assert_numpy_array_equal(res, exp) - self.assertEqual(type(res), type(exp)) + cat = Categorical(["a","b","a","a"], categories=["a","b","c"]) + res = cat.unique() + self.assert_numpy_array_equal(res, exp) + cat = Categorical(["a","b","a", np.nan], categories=["a","b","c"]) + res = cat.unique() + exp = np.asarray(["a","b", np.nan], dtype=object) + self.assert_numpy_array_equal(res, exp) def test_mode(self): s = Categorical([1,1,2,4,5,5,5], categories=[5,4,3,2,1], ordered=True)
Discussion see here: https://github.com/pydata/pandas/issues/8559#issuecomment-64189570
https://api.github.com/repos/pandas-dev/pandas/pulls/8937
2014-11-29T21:42:38Z
2014-11-30T16:09:10Z
2014-11-30T16:09:10Z
2014-11-30T16:09:14Z
ENH: Adds gcs module for IO with Google Cloud Storage
diff --git a/pandas/io/gcs.py b/pandas/io/gcs.py new file mode 100644 index 0000000000000..b2639fe6bc2db --- /dev/null +++ b/pandas/io/gcs.py @@ -0,0 +1,259 @@ +from StringIO import StringIO +import logging + +import pandas as pd + +from distutils.version import LooseVersion +from pandas import compat +from pandas.core.api import DataFrame +from pandas.tools.merge import concat +from pandas.core.common import PandasError + +_GOOGLE_API_CLIENT_INSTALLED = False +_GOOGLE_API_CLIENT_VALID_VERSION = False +_GOOGLE_FLAGS_INSTALLED = False +_GOOGLE_FLAGS_VALID_VERSION = False +_HTTPLIB2_INSTALLED = False +_SETUPTOOLS_INSTALLED = False + +if not compat.PY3: + + try: + import pkg_resources + _SETUPTOOLS_INSTALLED = True + except ImportError: + _SETUPTOOLS_INSTALLED = False + + if _SETUPTOOLS_INSTALLED: + try: + from apiclient.discovery import build + from apiclient.errors import HttpError + from apiclient.http import MediaFileUpload, MediaIoBaseUpload + + from oauth2client.client import AccessTokenRefreshError + from oauth2client.client import OAuth2WebServerFlow + from oauth2client.client import SignedJwtAssertionCredentials + from oauth2client.client import flow_from_clientsecrets + from oauth2client.file import Storage + from oauth2client.tools import run, run_flow + + _GOOGLE_API_CLIENT_INSTALLED=True + _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version + + if LooseVersion(_GOOGLE_API_CLIENT_VERSION) >= '1.2.0': + _GOOGLE_API_CLIENT_VALID_VERSION = True + + except ImportError: + _GOOGLE_API_CLIENT_INSTALLED = False + + + try: + import gflags as flags + _GOOGLE_FLAGS_INSTALLED = True + + _GOOGLE_FLAGS_VERSION = pkg_resources.get_distribution('python-gflags').version + + if LooseVersion(_GOOGLE_FLAGS_VERSION) >= '2.0': + _GOOGLE_FLAGS_VALID_VERSION = True + + except ImportError: + _GOOGLE_FLAGS_INSTALLED = False + + try: + import httplib2 + _HTTPLIB2_INSTALLED = True + except ImportError: + _HTTPLIB2_INSTALLED = False + +logger = logging.getLogger('pandas.io.gcs') +logger.setLevel(logging.DEBUG) + +def _test_imports(): + _GOOGLE_API_CLIENT_INSTALLED + _GOOGLE_API_CLIENT_VALID_VERSION + _GOOGLE_FLAGS_INSTALLED + _GOOGLE_FLAGS_VALID_VERSION + _HTTPLIB2_INSTALLED + _SETUPTOOLS_INSTALLED + + if compat.PY3: + raise NotImplementedError("Google's libraries do not support Python 3 yet") + + if not _SETUPTOOLS_INSTALLED: + raise ImportError('Could not import pkg_resources (setuptools).') + + if not _GOOGLE_API_CLIENT_INSTALLED: + raise ImportError('Could not import Google API Client.') + + if not _GOOGLE_FLAGS_INSTALLED: + raise ImportError('Could not import Google Command Line Flags Module.') + + if not _GOOGLE_API_CLIENT_VALID_VERSION: + raise ImportError("pandas requires google-api-python-client >= 1.2.0 for Google " + "BigQuery support, current version " + _GOOGLE_API_CLIENT_VERSION) + + if not _GOOGLE_FLAGS_VALID_VERSION: + raise ImportError("pandas requires python-gflags >= 2.0.0 for Google " + "BigQuery support, current version " + _GOOGLE_FLAGS_VERSION) + + if not _HTTPLIB2_INSTALLED: + raise ImportError("pandas requires httplib2 for Google BigQuery support") + +class GCSConnector(object): + + def __init__(self, project_id, service_account=None, private_key=None): + self.project_id = project_id + + #self.service_account = service_account + #self.private_key = private_key + + self.credentials = self.get_credentials(service_account, private_key) + self.service = self.get_service(self.credentials) + + def get_service(self, credentials): + + http = httplib2.Http() + http = credentials.authorize(http) + + service = build('storage', 'v1', http=http) + + return service + + def get_credentials(self, service_account=None, private_key=None): + + scope = "https://www.googleapis.com/auth/devstorage.read_write" + + #if service_account and private_key: + #flow = SignedJwtAssertionCredentials(service_account, private_key, scope) + #else: + flow = OAuth2WebServerFlow(client_id='495642085510-k0tmvj2m941jhre2nbqka17vqpjfddtd.apps.googleusercontent.com', + client_secret='kOc9wMptUtxkcIFbtZCcrEAc', + scope=scope, + redirect_uri='urn:ietf:wg:oauth:2.0:oob') + + storage = Storage("gcs_credentials.dat") + credentials = storage.get() + + #import argparse + + #parser = argparse.ArgumentParser() + #flags = parser.parse_args(None) + + if credentials is None or credentials.invalid: + #credentials = run_flow(flow, storage, flags) + credentials = run(flow, storage) + + return credentials + + def upload(self, dataframe, bucket, name, project_id, + to_gcs_kwargs=None, to_csv_kwargs=None): + + resumable = to_gcs_kwargs.get("resumable", False) + + string_df = StringIO() + dataframe.to_csv(string_df, **to_csv_kwargs) + + media = MediaIoBaseUpload(string_df, mimetype='text/csv', **to_gcs_kwargs) + + request = self.service.objects().insert(bucket=bucket, + name=name, + media_body=media) + + if resumable: + response = None + while response is None: + progress, response = request.next_chunk() + + else: + request.execute() + + def download(self, bucket, name, project_id, service_account, private_key, from_csv_kwargs): + + request = (self.service + .objects() + .get_media(bucket=bucket, object=name) + .execute()) + + in_memory_df = StringIO(request) + + df = pd.read_csv(in_memory_df, **from_csv_kwargs) + + return df + +def from_gcs(bucket, name, project_id, service_account=None, private_key=None, from_csv_kwargs=None): + """ + Read a DataFrame from Google Cloud Storage. + + Parameters + ---------- + bucket : string + Bucket in GCS where the object resides + name : string + Name of the object, or regex matching the name of the object + project_id : string + ProjectId in google + service_account : string + Service account email + private_key : string + Path to private key file + + Returns + ------- + dataframe : Dataframe + """ + + _test_imports() + + if from_csv_kwargs is None: + from_csv_kwargs = {} + + g = GCSConnector(project_id=project_id, + service_account=service_account, + private_key=private_key) + + return g.download(bucket, name, project_id, service_account, private_key, from_csv_kwargs) + + +def to_gcs(dataframe, bucket, name, project_id, + service_account=None, private_key=None, to_gcs_kwargs=None, to_csv_kwargs=None): + """ + Write a DataFrame to Google Cloud Storage. + + Parameters + ---------- + dataframe : DataFrame + DataFrame to be written + bucket : string + Bucket in GCS where the dataframe will be written + name : string + Object name in GCS + project_id : string + ProjectId in google + service_account : string + Service account email + private_key : string + Path to private key file + to_gcs_kwargs : dict + Dictionary of keywords passed directly to insert objects + to_csv_kwargs : dict + Dictionary of keywords passed directly `to_csv` + """ + + _test_imports() + + if to_gcs_kwargs is None: + to_gcs_kwargs = {} + + if to_csv_kwargs is None: + to_csv_kwargs = {} + + gcs_connection = GCSConnector(project_id=project_id, + service_account=service_account, + private_key=private_key) + + gcs_connection.upload(dataframe=dataframe, + bucket=bucket, + name=name, + project_id=project_id, + to_gcs_kwargs=to_gcs_kwargs, + to_csv_kwargs=to_csv_kwargs) diff --git a/pandas/io/tests/test_gcs.py b/pandas/io/tests/test_gcs.py new file mode 100644 index 0000000000000..d468985a3c168 --- /dev/null +++ b/pandas/io/tests/test_gcs.py @@ -0,0 +1,79 @@ +import pandas.io.gcs as gcs +import pandas.util.testing as tm +import pandas as pd +from time import sleep + +import subprocess + +import nose + +PROJECT_ID = "eighth-physics-623" + +def missing_gsutil(): + try: + subprocess.call(['which', 'gsutil']) + return False + except OSError: + return True + +def test_requirements(): + try: + gcs._test_imports() + except (ImportError, NotImplementedError) as import_exception: + raise nose.SkipTest(import_exception) + +class TestGCSConnectorIntegration(tm.TestCase): + def setUp(self): + test_requirements() + + if not PROJECT_ID: + raise nose.SkipTest("Cannot run integration tests without a project id") + + self.sut = gcs.GCSConnector(PROJECT_ID) + + def test_should_be_able_to_make_a_connector(self): + self.assertTrue(self.sut is not None, 'Could not create a GCSConnector') + + def test_should_be_able_to_get_valid_credentials(self): + credentials = self.sut.get_credentials() + self.assertFalse(credentials.invalid, 'Returned credentials invalid') + + def test_should_be_able_to_get_a_cloudstorage_service(self): + credentials = self.sut.get_credentials() + cloudstorage_service = self.sut.get_service(credentials) + self.assertTrue(cloudstorage_service is not None, 'No service returned') + +class TestGCSReadWrite(tm.TestCase): + + def setUp(self): + test_requirements() + + if not PROJECT_ID: + raise nose.SkipTest("Cannot run write tests without a project id") + if missing_gsutil(): + raise nose.SkipTest("Cannot run write tests without a gsutil.") + + @classmethod + def setUpClass(cls): + if PROJECT_ID and not missing_gsutil(): + subprocess.call(["gsutil", "mb", "gs://pandas-write-test"]) + + @classmethod + def tearDownClass(cls): + if PROJECT_ID and not missing_gsutil(): + subprocess.call(['gsutil', 'rb', '-f', 'gs://pandas-write-test']) + + def test_upload_data(self): + #test that we can upload data and that from_csv_kwargs works correctly + fake_df = pd.DataFrame({'a': [1, 2, 3]}, index=pd.Index([1, 2, 3], name='test_idx')) + gcs.to_gcs(fake_df, "pandas-write-test", "new_test.csv", project_id=PROJECT_ID) + + sleep(60) + + result = gcs.from_gcs("pandas-write-test", "new_test.csv", project_id=PROJECT_ID, + from_csv_kwargs={'index_col': 'test_idx'}) + + tm.assert_frame_equal(fake_df, result) + +if __name__ == '__main__': + nose.runmodule(argv=[__file__, '-vvs', '-x'], exit=False)
Hi, This isn't ready for primetime yet, but I wanted to see if there was feedback, since it would be a new io module. Basic usage: ``` import pandas.io.gcs as gcs import pandas as pd import numpy as np df = pd.DataFrame({ 'a': np.random.normal(size=1e4), 'b': np.random.normal(size=1e4) }) gcs.to_gcs(df, "th-code", "pandas2.csv", "eighth-physics-623", to_gcs_kwargs={'resumable': True}, to_csv_kwargs={'index': False}) i = gcs.from_gcs("th-code", "pandas2.csv", "eighth-physics-623") ``` This borrows some of the connection patterns from `gbq`, though it can do service account auth in addition to OAuth2WebServer auth. Might be nice at some point to centralize google api connection stuff. If this is accepted the code to connect to google's APIs will be in 3 places. I'm not sure everything this would need to be accepted, besides tests...
https://api.github.com/repos/pandas-dev/pandas/pulls/8936
2014-11-29T21:17:54Z
2015-05-09T15:58:22Z
null
2015-05-09T15:58:22Z
BUG: fix doctests in pandas.core.common
diff --git a/pandas/core/common.py b/pandas/core/common.py index 759f5f1dfaf7a..6aff67412d677 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -404,9 +404,13 @@ def array_equivalent(left, right, strict_nan=False): Examples -------- - >>> array_equivalent(np.array([1, 2, nan]), np.array([1, 2, nan])) + >>> array_equivalent( + ... np.array([1, 2, np.nan]), + ... np.array([1, 2, np.nan])) True - >>> array_equivalent(np.array([1, nan, 2]), np.array([1, 2, nan])) + >>> array_equivalent( + ... np.array([1, np.nan, 2]), + ... np.array([1, 2, np.nan])) False """ @@ -2171,8 +2175,8 @@ def iterpairs(seq): Examples -------- - >>> iterpairs([1, 2, 3, 4]) - [(1, 2), (2, 3), (3, 4) + >>> list(iterpairs([1, 2, 3, 4])) + [(1, 2), (2, 3), (3, 4)] """ # input may not be sliceable seq_it = iter(seq)
$ nosetests pandas/core/common.py --with-doc -v
https://api.github.com/repos/pandas-dev/pandas/pulls/8931
2014-11-29T17:08:12Z
2014-11-30T11:35:55Z
2014-11-30T11:35:55Z
2014-11-30T20:40:31Z
BUG: moving the utf encoding line to the first line (before from __futur...
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index fe070cff2e0ea..b145400afe13b 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pandas.compat import range import numpy as np diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 814da043d0319..a91c2573cc84e 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function import re from datetime import datetime, timedelta diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index dc82abfb40e02..a54c3bb84874d 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=E1101,E1103,W0232 from datetime import datetime diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 0d13b6513b377..d42306627f9ca 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime import re diff --git a/pandas/tests/test_compat.py b/pandas/tests/test_compat.py index 0d38bb23d6aa7..242b54c84d0ee 100644 --- a/pandas/tests/test_compat.py +++ b/pandas/tests/test_compat.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ Testing that functions from compat work as expected """ diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 8d012b871d8ca..86831a8485786 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function # pylint: disable-msg=W0612,E1101 diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 3e8534762ec05..ba3daf1b52045 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -1,5 +1,5 @@ -from __future__ import print_function # -*- coding: utf-8 -*- +from __future__ import print_function import re from pandas.compat import range, zip, lrange, StringIO, PY3, lzip, u diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index f4c8b9ecdbc86..5e78e8dc44bea 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index ef3fc03fc8d22..8533e85bcc309 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import print_function import nose diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 5265318d2c831..4fe3127e7ea39 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=E1101,E1103,W0232 from datetime import datetime, timedelta diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 60c5676a99506..8e2e6e612a1a3 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101 import sys import nose diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 37b557743b731..45f089f5e0a53 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=W0102 import nose diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 2873cd81d4744..d69e224ae9933 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime, timedelta, date, time import numpy as np diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 2171b8e8428a4..a10467cf7ab4a 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101,W0141 import datetime import itertools diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 3ec00fee1d151..2a605cba8a6c0 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from __future__ import division, print_function from functools import partial diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 7f902827ba5db..744dd31755c81 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable=W0612,E1101 from datetime import datetime diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 6ef8c1820400a..94c6bb9e2a4aa 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime from pandas.compat import range, lrange import os diff --git a/pandas/tests/test_panelnd.py b/pandas/tests/test_panelnd.py index 92083afb38f41..67d015b940885 100644 --- a/pandas/tests/test_panelnd.py +++ b/pandas/tests/test_panelnd.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from datetime import datetime import os import operator diff --git a/pandas/tests/test_reshape.py b/pandas/tests/test_reshape.py index 3cc2d94789a8d..f89d04f6fb2df 100644 --- a/pandas/tests/test_reshape.py +++ b/pandas/tests/test_reshape.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101 from copy import deepcopy from datetime import datetime, timedelta diff --git a/pandas/tests/test_rplot.py b/pandas/tests/test_rplot.py index ddfce477a320d..c58f17550a137 100644 --- a/pandas/tests/test_rplot.py +++ b/pandas/tests/test_rplot.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pandas.compat import range import pandas.tools.rplot as rplot import pandas.util.testing as tm diff --git a/pandas/tests/test_stats.py b/pandas/tests/test_stats.py index cb3fdcafd4056..eaaf89a52c2dc 100644 --- a/pandas/tests/test_stats.py +++ b/pandas/tests/test_stats.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pandas import compat import nose diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index a7d3c53c31e3d..06f507a50f785 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # pylint: disable-msg=E1101,W0612 from datetime import datetime, timedelta, date diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py index 5c26fce2b111e..9cc4d9e11c02e 100644 --- a/pandas/tests/test_tseries.py +++ b/pandas/tests/test_tseries.py @@ -1,4 +1,4 @@ - +# -*- coding: utf-8 -*- import nose from numpy import nan import numpy as np diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py index 8c56ba0e0f548..aed24f958a8f5 100644 --- a/pandas/tests/test_util.py +++ b/pandas/tests/test_util.py @@ -1,4 +1,4 @@ - +# -*- coding: utf-8 -*- import warnings import nose
``` ERROR: Failure: SyntaxError (Non-ASCII character '\xc3' in file /home/fvia/bloom/pandas/pandas/tests/test_format.py on line 825, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details (test_format.py, line 825)) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/8930
2014-11-29T16:53:50Z
2014-12-03T22:31:15Z
2014-12-03T22:31:15Z
2014-12-03T22:31:30Z
BUG: allow numpy.array as c values to scatterplot
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 11cf2450d2f28..9392e62ec00ec 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -156,6 +156,11 @@ Bug Fixes and the last offset is not calculated from the start of the range (:issue:`8683`) + +- Bug where DataFrame.plot(kind='scatter') fails when checking if an np.array is in the DataFrame (:issue:`8852`) + + + - Bug in `pd.infer_freq`/`DataFrame.inferred_freq` that prevented proper sub-daily frequency inference when the index contained DST days (:issue:`8772`). - Bug where index name was still used when plotting a series with ``use_index=False`` (:issue:`8558`). diff --git a/pandas/core/common.py b/pandas/core/common.py index f7f944bb418e9..e5ff353104fe9 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2504,6 +2504,38 @@ def is_list_like(arg): not isinstance(arg, compat.string_and_binary_types)) +def is_hashable(arg): + """Return True if hash(arg) will succeed, False otherwise. + + Some types will pass a test against collections.Hashable but fail when they + are actually hashed with hash(). + + Distinguish between these and other types by trying the call to hash() and + seeing if they raise TypeError. + + Examples + -------- + >>> a = ([],) + >>> isinstance(a, collections.Hashable) + True + >>> is_hashable(a) + False + """ + # don't consider anything not collections.Hashable, so as not to broaden + # the definition of hashable beyond that. For example, old-style classes + # are not collections.Hashable but they won't fail hash(). + if not isinstance(arg, collections.Hashable): + return False + + # narrow the definition of hashable if hash(arg) fails in practice + try: + hash(arg) + except TypeError: + return False + else: + return True + + def is_sequence(x): try: iter(x) diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 9465247056e27..63927fd4adc45 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -1,5 +1,7 @@ +import collections from datetime import datetime import re +import sys import nose from nose.tools import assert_equal @@ -398,6 +400,55 @@ def test_is_list_like(): assert not com.is_list_like(f) +def test_is_hashable(): + + # all new-style classes are hashable by default + class HashableClass(object): + pass + + class UnhashableClass1(object): + __hash__ = None + + class UnhashableClass2(object): + def __hash__(self): + raise TypeError("Not hashable") + + hashable = ( + 1, 'a', tuple(), (1,), HashableClass(), + ) + not_hashable = ( + [], UnhashableClass1(), + ) + abc_hashable_not_really_hashable = ( + ([],), UnhashableClass2(), + ) + + for i in hashable: + assert isinstance(i, collections.Hashable) + assert com.is_hashable(i) + for i in not_hashable: + assert not isinstance(i, collections.Hashable) + assert not com.is_hashable(i) + for i in abc_hashable_not_really_hashable: + assert isinstance(i, collections.Hashable) + assert not com.is_hashable(i) + + # numpy.array is no longer collections.Hashable as of + # https://github.com/numpy/numpy/pull/5326, just test + # pandas.common.is_hashable() + assert not com.is_hashable(np.array([])) + + # old-style classes in Python 2 don't appear hashable to + # collections.Hashable but also seem to support hash() by default + if sys.version_info[0] == 2: + class OldStyleClass(): + pass + c = OldStyleClass() + assert not isinstance(c, collections.Hashable) + assert not com.is_hashable(c) + hash(c) # this will not raise + + def test_ensure_int32(): values = np.arange(10, dtype=np.int32) result = com._ensure_int32(values) diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 06902dded0da4..1e1e12a8679a4 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -1645,6 +1645,31 @@ def test_plot_scatter_with_c(self): self.assertIs(ax.collections[0].colorbar, None) self._check_colors(ax.collections, facecolors=['r']) + # Ensure that we can pass an np.array straight through to matplotlib, + # this functionality was accidentally removed previously. + # See https://github.com/pydata/pandas/issues/8852 for bug report + # + # Exercise colormap path and non-colormap path as they are independent + # + df = DataFrame({'A': [1, 2], 'B': [3, 4]}) + red_rgba = [1.0, 0.0, 0.0, 1.0] + green_rgba = [0.0, 1.0, 0.0, 1.0] + rgba_array = np.array([red_rgba, green_rgba]) + ax = df.plot(kind='scatter', x='A', y='B', c=rgba_array) + # expect the face colors of the points in the non-colormap path to be + # identical to the values we supplied, normally we'd be on shaky ground + # comparing floats for equality but here we expect them to be + # identical. + self.assertTrue( + np.array_equal( + ax.collections[0].get_facecolor(), + rgba_array)) + # we don't test the colors of the faces in this next plot because they + # are dependent on the spring colormap, which may change its colors + # later. + float_array = np.array([0.0, 1.0]) + df.plot(kind='scatter', x='A', y='B', c=float_array, cmap='spring') + @slow def test_plot_bar(self): df = DataFrame(randn(6, 4), diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index 4f3aa4e8e4a9e..b55f0f0d9c61f 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1403,8 +1403,10 @@ def _make_plot(self): x, y, c, data = self.x, self.y, self.c, self.data ax = self.axes[0] + c_is_column = com.is_hashable(c) and c in self.data.columns + # plot a colorbar only if a colormap is provided or necessary - cb = self.kwds.pop('colorbar', self.colormap or c in self.data.columns) + cb = self.kwds.pop('colorbar', self.colormap or c_is_column) # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'Greys' @@ -1412,7 +1414,7 @@ def _make_plot(self): if c is None: c_values = self.plt.rcParams['patch.facecolor'] - elif c in self.data.columns: + elif c_is_column: c_values = self.data[c].values else: c_values = c @@ -1427,7 +1429,7 @@ def _make_plot(self): img = ax.collections[0] kws = dict(ax=ax) if mpl_ge_1_3_1: - kws['label'] = c if c in self.data.columns else '' + kws['label'] = c if c_is_column else '' self.fig.colorbar(img, **kws) self._add_legend_handle(scatter, label)
Ensure that we can pass an np.array as 'c' straight through to matplotlib, this functionality was accidentally removed previously. Add tests. Closes #8852
https://api.github.com/repos/pandas-dev/pandas/pulls/8929
2014-11-29T16:32:11Z
2014-12-03T22:33:53Z
2014-12-03T22:33:53Z
2014-12-03T22:38:46Z
Implement Categorical.searchsorted(v, side, sorter)
diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index 8378873db9a65..6e411626ca770 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -489,9 +489,9 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to .. ipython:: python def GrowUp(x): - avg_weight = sum(x[x.size == 'S'].weight * 1.5) - avg_weight += sum(x[x.size == 'M'].weight * 1.25) - avg_weight += sum(x[x.size == 'L'].weight) + avg_weight = sum(x[x['size'] == 'S'].weight * 1.5) + avg_weight += sum(x[x['size'] == 'M'].weight * 1.25) + avg_weight += sum(x[x['size'] == 'L'].weight) avg_weight = avg_weight / len(x) return pd.Series(['L',avg_weight,True], index=['size', 'weight', 'adult']) diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 7dfdc88dddbff..9506d00bdcf57 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -776,7 +776,60 @@ def nbytes(self): return self._codes.nbytes + self._categories.values.nbytes def searchsorted(self, v, side='left', sorter=None): - raise NotImplementedError("See https://github.com/pydata/pandas/issues/8420") + """Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted Categorical `self` such that, if the + corresponding elements in `v` were inserted before the indices, the + order of `self` would be preserved. + + Parameters + ---------- + v : array_like + Array-like values or a scalar value, to insert/search for in `self`. + side : {'left', 'right'}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `a`). + sorter : 1-D array_like, optional + Optional array of integer indices that sort `self` into ascending + order. They are typically the result of ``np.argsort``. + + Returns + ------- + indices : array of ints + Array of insertion points with the same shape as `v`. + + See Also + -------- + Series.searchsorted + numpy.searchsorted + + Notes + ----- + Binary search is used to find the required insertion points. + + Examples + -------- + >>> x = pd.Categorical(['apple', 'bread', 'bread', 'cheese', 'milk' ]) + [apple, bread, bread, cheese, milk] + Categories (4, object): [apple < bread < cheese < milk] + >>> x.searchsorted('bread') + 1 + >>> x.searchsorted(['bread']) + array([1]) + >>> x.searchsorted(['bread', 'eggs']) + array([1, 4]) + >>> x.searchsorted(['bread', 'eggs'], side='right') + array([3, 4]) # eggs before milk + >>> x = pd.Categorical(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ]) + >>> x.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + array([3, 5]) # eggs after donuts, after switching milk and donuts + """ + if not self.ordered: + raise ValueError("searchsorted requires an ordered Categorical.") + + values_as_codes = self.categories.values.searchsorted(np.asarray(v), side) + return self.codes.searchsorted(values_as_codes, sorter=sorter) def isnull(self): """ diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 196ad8b7680b9..7e17fd8f3412b 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -888,13 +888,57 @@ def test_nbytes(self): self.assertEqual(cat.nbytes, exp) def test_searchsorted(self): + # https://github.com/pydata/pandas/issues/8420 + s1 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk' ]) + s2 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ]) + c1 = pd.Categorical(s1) + c2 = pd.Categorical(s2) + + # Single item array + res = c1.searchsorted(['bread']) + chk = s1.searchsorted(['bread']) + exp = np.array([1]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # Scalar version of single item array + # Ambiguous what Categorical should return as np.array returns + # a scalar and pd.Series returns an array. + # We get different results depending on whether + # Categorical.searchsorted(v) passes v through np.asarray() + # or pd.Series(v).values. The former returns scalar, the + # latter an array. + # Test code here follows np.array.searchsorted(). + # Commented out lines below follow pd.Series. + res = c1.searchsorted('bread') + chk = np.array(s1).searchsorted('bread') + exp = 1 + #exp = np.array([1]) + #chk = s1.searchsorted('bread') + #exp = np.array([1]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # Searching for a value that is not present in the Categorical + res = c1.searchsorted(['bread', 'eggs']) + chk = s1.searchsorted(['bread', 'eggs']) + exp = np.array([1, 4]) + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) - # See https://github.com/pydata/pandas/issues/8420 - # TODO: implement me... - cat = pd.Categorical([1,2,3]) - def f(): - cat.searchsorted(3) - self.assertRaises(NotImplementedError, f) + # Searching for a value that is not present, to the right + res = c1.searchsorted(['bread', 'eggs'], side='right') + chk = s1.searchsorted(['bread', 'eggs'], side='right') + exp = np.array([3, 4]) # eggs before milk + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) + + # As above, but with a sorter array to reorder an unsorted array + res = c2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + chk = s2.searchsorted(['bread', 'eggs'], side='right', sorter=[0, 1, 2, 3, 5, 4]) + exp = np.array([3, 5]) # eggs after donuts, after switching milk and donuts + self.assert_numpy_array_equal(res, exp) + self.assert_numpy_array_equal(res, chk) def test_deprecated_labels(self): # TODO: labels is deprecated and should be removed in 0.18 or 2017, whatever is earlier
Continued in #8972 This closes #8420, with code that supports searchsorted in Categorical, for both side='left'/'right' and with an optional sorter. The case of side='right' was tricky, as we look to the right only when matching the category name, not when matching the codes. The docstring and unit tests cover the various cases. One thing I wasn't sure about was forcing scalar input to a Series. I copied this behaviour from Series.searchsorted to match its docstring examples. To avoid circular imports from series.py importing categorical.py, I got Series via a local import. Probably there is a better way to do this.
https://api.github.com/repos/pandas-dev/pandas/pulls/8928
2014-11-29T15:55:50Z
2014-12-03T08:27:50Z
null
2014-12-03T08:28:03Z
BUG: fixed chunksize guessed to 0 (py3 only). #8621
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index eacccaa7cba92..bed8ace26b82d 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -99,6 +99,7 @@ Bug Fixes - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Fix negative step support for label-based slices (:issue:`8753`) +- Fixed division by 0 when reading big csv files in python 3 (:issue:`8621`) Old behavior: diff --git a/pandas/core/format.py b/pandas/core/format.py index 89973754a861c..dbfe78d93bdcd 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -1247,7 +1247,7 @@ def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', float_format=None, self.data = [None] * ncols if chunksize is None: - chunksize = (100000 / (len(self.cols) or 1)) or 1 + chunksize = (100000 // (len(self.cols) or 1)) or 1 self.chunksize = int(chunksize) self.data_index = obj.index diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index fc031afe728dc..f14b0bff80545 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -6462,6 +6462,14 @@ def test_to_csv_chunking(self): rs = read_csv(filename,index_col=0) assert_frame_equal(rs, aa) + def test_to_csv_wide_frame_formatting(self): + # Issue #8621 + df = DataFrame(np.random.randn(1, 100010), columns=None, index=None) + with ensure_clean() as filename: + df.to_csv(filename, header=False, index=False) + rs = read_csv(filename, header=None) + assert_frame_equal(rs, df) + def test_to_csv_bug(self): f1 = StringIO('a,1.0\nb,2.0') df = DataFrame.from_csv(f1, header=None)
Fixes https://github.com/pydata/pandas/issues/8621 As mentioned in the github issue its a py3 only bug. I copied the test @rmorgans made
https://api.github.com/repos/pandas-dev/pandas/pulls/8927
2014-11-29T14:03:47Z
2014-12-03T22:37:35Z
2014-12-03T22:37:35Z
2014-12-03T22:37:49Z
ENH: dtype costumization on to_sql (GH8778)
diff --git a/doc/source/io.rst b/doc/source/io.rst index bf8776d4bc396..e05840bfdfd5e 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3413,6 +3413,14 @@ With some databases, writing large DataFrames can result in errors due to packet Because of this, reading the database table back in does **not** generate a categorical. +.. note:: + + You can specify the SQL type of any of the columns by using the dtypes + parameter (a dictionary mapping column names to SQLAlchemy types). This + can be useful in cases where columns with NULL values are inferred by + Pandas to an excessively general datatype (e.g. a boolean column is is + inferred to be object because it has NULLs). + Reading Tables ~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3aa50ad609064..78e915ba83d10 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -61,6 +61,7 @@ API changes Enhancements ~~~~~~~~~~~~ +- Added the ability to specify the SQL type of columns when writing a DataFrame to a database (:issue:`8778`). - Added ability to export Categorical data to Stata (:issue:`8633`). See :ref:`here <io.stata-categorical>` for limitations of categorical variables exported to Stata data files. - Added ability to export Categorical data to to/from HDF5 (:issue:`7621`). Queries work the same as if it was an object array. However, the ``category`` dtyped data is stored in a more efficient manner. See :ref:`here <io.hdf5-categorical>` for an example and caveats w.r.t. prior versions of pandas. - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7201428e6b935..52f37ee24f69a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -922,7 +922,7 @@ def to_msgpack(self, path_or_buf=None, **kwargs): return packers.to_msgpack(path_or_buf, self, **kwargs) def to_sql(self, name, con, flavor='sqlite', schema=None, if_exists='fail', - index=True, index_label=None, chunksize=None): + index=True, index_label=None, chunksize=None, dtype=None): """ Write records stored in a DataFrame to a SQL database. @@ -954,12 +954,15 @@ def to_sql(self, name, con, flavor='sqlite', schema=None, if_exists='fail', chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. + dtype : Dictionary of column name to SQLAlchemy type, default None + Optional datatypes for SQL columns. """ from pandas.io import sql sql.to_sql( self, name, con, flavor=flavor, schema=schema, if_exists=if_exists, - index=index, index_label=index_label, chunksize=chunksize) + index=index, index_label=index_label, chunksize=chunksize, + dtype=dtype) def to_pickle(self, path): """ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 9baae0330926d..bb810b8509ef3 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -484,7 +484,7 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None, def to_sql(frame, name, con, flavor='sqlite', schema=None, if_exists='fail', - index=True, index_label=None, chunksize=None): + index=True, index_label=None, chunksize=None, dtype=None): """ Write records stored in a DataFrame to a SQL database. @@ -517,6 +517,8 @@ def to_sql(frame, name, con, flavor='sqlite', schema=None, if_exists='fail', chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. + dtype : dictionary of column name to SQLAchemy type, default None + optional datatypes for SQL columns. """ if if_exists not in ('fail', 'replace', 'append'): @@ -531,7 +533,7 @@ def to_sql(frame, name, con, flavor='sqlite', schema=None, if_exists='fail', pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index, index_label=index_label, schema=schema, - chunksize=chunksize) + chunksize=chunksize, dtype=dtype) def has_table(table_name, con, flavor='sqlite', schema=None): @@ -596,7 +598,7 @@ class SQLTable(PandasObject): # TODO: support for multiIndex def __init__(self, name, pandas_sql_engine, frame=None, index=True, if_exists='fail', prefix='pandas', index_label=None, - schema=None, keys=None): + schema=None, keys=None, dtype=None): self.name = name self.pd_sql = pandas_sql_engine self.prefix = prefix @@ -605,6 +607,7 @@ def __init__(self, name, pandas_sql_engine, frame=None, index=True, self.schema = schema self.if_exists = if_exists self.keys = keys + self.dtype = dtype if frame is not None: # We want to initialize based on a dataframe @@ -885,6 +888,10 @@ def _sqlalchemy_type(self, col): from sqlalchemy.types import (BigInteger, Float, Text, Boolean, DateTime, Date, Time) + dtype = self.dtype or {} + if col.name in dtype: + return self.dtype[col.name] + if com.is_datetime64_dtype(col): try: tz = col.tzinfo @@ -1099,7 +1106,7 @@ def read_query(self, sql, index_col=None, coerce_float=True, read_sql = read_query def to_sql(self, frame, name, if_exists='fail', index=True, - index_label=None, schema=None, chunksize=None): + index_label=None, schema=None, chunksize=None, dtype=None): """ Write records stored in a DataFrame to a SQL database. @@ -1125,11 +1132,20 @@ def to_sql(self, frame, name, if_exists='fail', index=True, chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. - + dtype : dictionary of column name to SQLAlchemy type, default None + Optional datatypes for SQL columns. + """ + if dtype is not None: + import sqlalchemy.sql.type_api as type_api + for col, my_type in dtype.items(): + if not issubclass(my_type, type_api.TypeEngine): + raise ValueError('The type of %s is not a SQLAlchemy ' + 'type ' % col) + table = SQLTable(name, self, frame=frame, index=index, if_exists=if_exists, index_label=index_label, - schema=schema) + schema=schema, dtype=dtype) table.create() table.insert(chunksize) # check for potentially case sensitivity issues (GH7815) @@ -1297,6 +1313,9 @@ def _create_table_setup(self): return create_stmts def _sql_type_name(self, col): + dtype = self.dtype or {} + if col.name in dtype: + return dtype[col.name] pytype = col.dtype.type pytype_name = "text" if issubclass(pytype, np.floating): @@ -1424,7 +1443,7 @@ def _fetchall_as_list(self, cur): return result def to_sql(self, frame, name, if_exists='fail', index=True, - index_label=None, schema=None, chunksize=None): + index_label=None, schema=None, chunksize=None, dtype=None): """ Write records stored in a DataFrame to a SQL database. @@ -1448,10 +1467,19 @@ def to_sql(self, frame, name, if_exists='fail', index=True, chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. + dtype : dictionary of column_name to SQLite string type, default None + optional datatypes for SQL columns. """ + if dtype is not None: + for col, my_type in dtype.items(): + if not isinstance(my_type, str): + raise ValueError('%s (%s) not a string' % ( + col, str(my_type))) + table = SQLiteTable(name, self, frame=frame, index=index, - if_exists=if_exists, index_label=index_label) + if_exists=if_exists, index_label=index_label, + dtype=dtype) table.create() table.insert(chunksize) diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index 2a7aec30e7c50..eb46df7686d18 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -41,6 +41,8 @@ try: import sqlalchemy + import sqlalchemy.schema + import sqlalchemy.sql.sqltypes as sqltypes SQLALCHEMY_INSTALLED = True except ImportError: SQLALCHEMY_INSTALLED = False @@ -339,7 +341,7 @@ def _transaction_test(self): self.pandasSQL.execute("CREATE TABLE test_trans (A INT, B TEXT)") ins_sql = "INSERT INTO test_trans (A,B) VALUES (1, 'blah')" - + # Make sure when transaction is rolled back, no rows get inserted try: with self.pandasSQL.run_transaction() as trans: @@ -350,7 +352,7 @@ def _transaction_test(self): pass res = self.pandasSQL.read_query('SELECT * FROM test_trans') self.assertEqual(len(res), 0) - + # Make sure when transaction is committed, rows do get inserted with self.pandasSQL.run_transaction() as trans: trans.execute(ins_sql) @@ -1167,6 +1169,26 @@ def test_get_schema_create_table(self): tm.assert_frame_equal(returned_df, blank_test_df) self.drop_table(tbl) + def test_dtype(self): + cols = ['A', 'B'] + data = [(0.8, True), + (0.9, None)] + df = DataFrame(data, columns=cols) + df.to_sql('dtype_test', self.conn) + df.to_sql('dtype_test2', self.conn, dtype={'B': sqlalchemy.Boolean}) + meta = sqlalchemy.schema.MetaData(bind=self.conn) + meta.reflect() + self.assertTrue(isinstance(meta.tables['dtype_test'].columns['B'].type, + sqltypes.TEXT)) + if self.flavor == 'mysql': + my_type = sqltypes.Integer + else: + my_type = sqltypes.Boolean + self.assertTrue(isinstance(meta.tables['dtype_test2'].columns['B'].type, + my_type)) + self.assertRaises(ValueError, df.to_sql, + 'error', self.conn, dtype={'B': bool}) + class TestSQLiteAlchemy(_TestSQLAlchemy): """ @@ -1467,7 +1489,7 @@ def test_datetime_time(self): if self.flavor == 'sqlite': self.assertRaises(sqlite3.InterfaceError, sql.to_sql, df, 'test_time', self.conn) - + def _get_index_columns(self, tbl_name): ixs = sql.read_sql_query( "SELECT * FROM sqlite_master WHERE type = 'index' " + @@ -1485,6 +1507,28 @@ def test_to_sql_save_index(self): def test_transactions(self): self._transaction_test() + def test_dtype(self): + if self.flavor == 'mysql': + raise nose.SkipTest('Not applicable to MySQL legacy') + cols = ['A', 'B'] + data = [(0.8, True), + (0.9, None)] + df = DataFrame(data, columns=cols) + df.to_sql('dtype_test', self.conn) + df.to_sql('dtype_test2', self.conn, dtype={'B': 'bool'}) + + def get_column_type(table, column): + recs = self.conn.execute('PRAGMA table_info(%s)' % table) + for cid, name, ctype, not_null, default, pk in recs: + if name == column: + return ctype + raise ValueError('Table %s, column %s not found' % (table, column)) + + self.assertEqual(get_column_type('dtype_test', 'B'), 'TEXT') + self.assertEqual(get_column_type('dtype_test2', 'B'), 'bool') + self.assertRaises(ValueError, df.to_sql, + 'error', self.conn, dtype={'B': bool}) + class TestMySQLLegacy(TestSQLiteFallback): """ Test the legacy mode against a MySQL database.
This is the proposed general gist of the changes. My ad-hoc testing suggests that this might work. If this is an acceptible design, I will proceed to make the formal test and change the docs (including docstrings) Closes #8778
https://api.github.com/repos/pandas-dev/pandas/pulls/8926
2014-11-29T13:33:44Z
2014-12-02T23:31:30Z
2014-12-02T23:31:30Z
2014-12-02T23:31:44Z
BUG: Option context applies on __enter__
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3aa50ad609064..d299121092987 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -142,7 +142,7 @@ Bug Fixes - +- BUG: Option context applies on __enter__ (:issue:`8514`) diff --git a/pandas/core/config.py b/pandas/core/config.py index 60dc1d7d0341e..2c1865730874d 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -384,19 +384,18 @@ def __init__(self, *args): 'option_context(pat, val, [(pat, val), ...)).' ) - ops = list(zip(args[::2], args[1::2])) + self.ops = list(zip(args[::2], args[1::2])) + + def __enter__(self): undo = [] - for pat, val in ops: + for pat, val in self.ops: undo.append((pat, _get_option(pat, silent=True))) self.undo = undo - for pat, val in ops: + for pat, val in self.ops: _set_option(pat, val, silent=True) - def __enter__(self): - pass - def __exit__(self, *args): if self.undo: for pat, val in self.undo: diff --git a/pandas/tests/test_config.py b/pandas/tests/test_config.py index dc5e9a67bdb65..3a8fdd877f5a0 100644 --- a/pandas/tests/test_config.py +++ b/pandas/tests/test_config.py @@ -425,3 +425,24 @@ def f3(key): options.c = 1 self.assertEqual(len(holder), 1) + def test_option_context_scope(self): + # Ensure that creating a context does not affect the existing + # environment as it is supposed to be used with the `with` statement. + # See https://github.com/pydata/pandas/issues/8514 + + original_value = 60 + context_value = 10 + option_name = 'a' + + self.cf.register_option(option_name, original_value) + + # Ensure creating contexts didn't affect the current context. + ctx = self.cf.option_context(option_name, context_value) + self.assertEqual(self.cf.get_option(option_name), original_value) + + # Ensure the correct value is available inside the context. + with ctx: + self.assertEqual(self.cf.get_option(option_name), context_value) + + # Ensure the current context is reset + self.assertEqual(self.cf.get_option(option_name), original_value)
Option context no longer overrides options when used outside a `with` statement. Added test TestConfig.test_option_config_scope Closes #8514
https://api.github.com/repos/pandas-dev/pandas/pulls/8925
2014-11-29T13:19:45Z
2014-11-29T16:48:19Z
2014-11-29T16:48:19Z
2014-11-29T16:48:19Z
astype checks notnull Fixes: #8732
diff --git a/pandas/core/internals.py b/pandas/core/internals.py index ef33e27d861fd..750b47786dec3 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -398,7 +398,10 @@ def _astype(self, dtype, copy=False, raise_on_error=True, values=None, # force the copy here if values is None: # _astype_nansafe works fine with 1-d only - values = com._astype_nansafe(self.values.ravel(), dtype, copy=True) + if isnull(self.values).any(): + values = com._astype_nansafe(self.values.ravel(), dtype, copy=True) + else: + values = self.values.ravel().astype(dtype) values = values.reshape(self.values.shape) newb = make_block(values, ndim=self.ndim, placement=self.mgr_locs, diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index fc031afe728dc..e19f5a0ff8719 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -2141,6 +2141,22 @@ def setUp(self): self.simple = DataFrame(arr, columns=['one', 'two', 'three'], index=['a', 'b', 'c']) + def test_hasnulls(self): + # Github Issue 8732 + df = tm.makeMissingDataframe() + self.assertEqual(df['A'].notnull().all(), False) + casted = df.astype(np.float64) + expected = DataFrame(df.values.astype(np.float64), + index=df.index, + columns=df.columns) + assert_frame_equal(casted, expected) + + casted = df.astype(np.str) + expected = DataFrame(df.values.astype(np.str), + index=df.index, + columns=df.columns) + assert_frame_equal(casted, expected) + def test_get_axis(self): f = self.frame self.assertEqual(f._get_axis_number(0), 0) diff --git a/vb_suite/astype.py b/vb_suite/astype.py new file mode 100644 index 0000000000000..26deab3a145cb --- /dev/null +++ b/vb_suite/astype.py @@ -0,0 +1,14 @@ +from vbench.api import Benchmark + +common_setup = """from pandas_vb_common import * +from datetime import timedelta +import numpy as np + +N = 1000000 +arr = np.random.randint(1,10,size=1000000) +s = pd.Series(arr) +""" + +astype_test = Benchmark('s.astype(np.str)', + common_setup, + name='astype_test') diff --git a/vb_suite/suite.py b/vb_suite/suite.py index a16d183ae62e2..ee5a49dac2e66 100644 --- a/vb_suite/suite.py +++ b/vb_suite/suite.py @@ -13,6 +13,7 @@ 'indexing', 'io_bench', 'io_sql', + 'astype', 'inference', 'hdfstore_bench', 'join_merge',
As suggested in issue #8732 if there are no nulls, we skip the nan_safe bit.
https://api.github.com/repos/pandas-dev/pandas/pulls/8924
2014-11-29T12:37:50Z
2014-11-29T14:26:28Z
null
2014-11-29T22:29:04Z
TST: harmonize testing namespace in TestCase (GH8023)
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 2a4026094ac10..8af30da103572 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -72,13 +72,15 @@ def reset_testing_mode(): if 'deprecate' in testing_mode: warnings.simplefilter('ignore', DeprecationWarning) + set_testing_mode() + class TestCase(unittest.TestCase): @classmethod def setUpClass(cls): - pd.set_option('chained_assignment','raise') + pd.set_option('chained_assignment', 'raise') @classmethod def tearDownClass(cls): @@ -86,19 +88,7 @@ def tearDownClass(cls): def reset_display_options(self): # reset the display options - pd.reset_option('^display.',silent=True) - - def assert_numpy_array_equal(self, np_array, assert_equal): - """Checks that 'np_array' is equal to 'assert_equal' - - Note that the expected array should not contain `np.nan`! Two numpy arrays are equal if all - elements are equal, which is not possible if `np.nan` is such an element! - - If the expected array includes `np.nan` use `assert_numpy_array_equivalent(...)`. - """ - if np.array_equal(np_array, assert_equal): - return - raise AssertionError('{0} is not equal to {1}.'.format(np_array, assert_equal)) + pd.reset_option('^display.', silent=True) def round_trip_pickle(self, obj, path=None): if path is None: @@ -107,82 +97,6 @@ def round_trip_pickle(self, obj, path=None): pd.to_pickle(obj, path) return pd.read_pickle(path) - def assert_numpy_array_equivalent(self, np_array, assert_equal, strict_nan=False): - """Checks that 'np_array' is equivalent to 'assert_equal' - - Two numpy arrays are equivalent if the arrays have equal non-NaN elements, and - `np.nan` in corresponding locations. - - If the the expected array does not contain `np.nan` `assert_numpy_array_equivalent` is the - similar to `assert_numpy_array_equal()`. If the expected array includes `np.nan` use this - function. - """ - if array_equivalent(np_array, assert_equal, strict_nan=strict_nan): - return - raise AssertionError('{0} is not equivalent to {1}.'.format(np_array, assert_equal)) - - def assert_categorical_equal(self, res, exp): - if not array_equivalent(res.categories, exp.categories): - raise AssertionError('categories not equivalent: {0} vs {1}.'.format(res.categories, - exp.categories)) - if not array_equivalent(res.codes, exp.codes): - raise AssertionError('codes not equivalent: {0} vs {1}.'.format(res.codes, - exp.codes)) - self.assertEqual(res.ordered, exp.ordered, "ordered not the same") - self.assertEqual(res.name, exp.name, "name not the same") - - def assertIs(self, first, second, msg=''): - """Checks that 'first' is 'second'""" - a, b = first, second - assert a is b, "%s: %r is not %r" % (msg.format(a,b), a, b) - - def assertIsNot(self, first, second, msg=''): - """Checks that 'first' is not 'second'""" - a, b = first, second - assert a is not b, "%s: %r is %r" % (msg.format(a,b), a, b) - - def assertIsNone(self, expr, msg=''): - """Checks that 'expr' is None""" - self.assertIs(expr, None, msg) - - def assertIsNotNone(self, expr, msg=''): - """Checks that 'expr' is not None""" - self.assertIsNot(expr, None, msg) - - def assertIn(self, first, second, msg=''): - """Checks that 'first' is in 'second'""" - a, b = first, second - assert a in b, "%s: %r is not in %r" % (msg.format(a,b), a, b) - - def assertNotIn(self, first, second, msg=''): - """Checks that 'first' is not in 'second'""" - a, b = first, second - assert a not in b, "%s: %r is in %r" % (msg.format(a,b), a, b) - - def assertIsInstance(self, obj, cls, msg=''): - """Test that obj is an instance of cls - (which can be a class or a tuple of classes, - as supported by isinstance()).""" - assert isinstance(obj, cls), ( - "%sExpected object to be of type %r, found %r instead" % ( - msg, cls, type(obj))) - - def assertNotIsInstance(self, obj, cls, msg=''): - """Test that obj is not an instance of cls - (which can be a class or a tuple of classes, - as supported by isinstance()).""" - assert not isinstance(obj, cls), ( - "%sExpected object to be of type %r, found %r instead" % ( - msg, cls, type(obj))) - - def assertRaises(self, _exception, _callable=None, *args, **kwargs): - """ compat with 2.6; assert that an exception is raised """ - assertRaises(_exception, _callable, *args, **kwargs) - - def assertRaisesRegexp(self, _exception, _regexp, _callable=None, *args, **kwargs): - """ Port of assertRaisesRegexp from unittest in Python 2.7 - used in with statement """ - assertRaisesRegexp(_exception, _regexp, _callable, *args, **kwargs) - # NOTE: don't pass an NDFrame or index to this function - may not handle it # well. assert_almost_equal = _testing.assert_almost_equal @@ -633,6 +547,109 @@ def isiterable(obj): def is_sorted(seq): return assert_almost_equal(seq, np.sort(np.array(seq))) + +def assertIs(first, second, msg=''): + """Checks that 'first' is 'second'""" + a, b = first, second + assert a is b, "%s: %r is not %r" % (msg.format(a, b), a, b) + + +def assertIsNot(first, second, msg=''): + """Checks that 'first' is not 'second'""" + a, b = first, second + assert a is not b, "%s: %r is %r" % (msg.format(a, b), a, b) + + +def assertIn(first, second, msg=''): + """Checks that 'first' is in 'second'""" + a, b = first, second + assert a in b, "%s: %r is not in %r" % (msg.format(a, b), a, b) + + +def assertNotIn(first, second, msg=''): + """Checks that 'first' is not in 'second'""" + a, b = first, second + assert a not in b, "%s: %r is in %r" % (msg.format(a, b), a, b) + + +def assertIsNone(expr, msg=''): + """Checks that 'expr' is None""" + return assertIs(expr, None, msg) + + +def assertIsNotNone(expr, msg=''): + """Checks that 'expr' is not None""" + return assertIsNot(expr, None, msg) + + +def assertIsInstance(obj, cls, msg=''): + """Test that obj is an instance of cls + (which can be a class or a tuple of classes, + as supported by isinstance()).""" + assert isinstance(obj, cls), ( + "%sExpected object to be of type %r, found %r instead" % ( + msg, cls, type(obj))) + + +def assertNotIsInstance(obj, cls, msg=''): + """Test that obj is not an instance of cls + (which can be a class or a tuple of classes, + as supported by isinstance()).""" + assert not isinstance(obj, cls), ( + "%sExpected object to be of type %r, found %r instead" % ( + msg, cls, type(obj))) + + +def assert_categorical_equal(res, exp): + if not array_equivalent(res.categories, exp.categories): + raise AssertionError( + 'categories not equivalent: {0} vs {1}.'.format(res.categories, + exp.categories)) + if not array_equivalent(res.codes, exp.codes): + raise AssertionError( + 'codes not equivalent: {0} vs {1}.'.format(res.codes, exp.codes)) + + if res.ordered != exp.ordered: + raise AssertionError("ordered not the same") + + if res.name != exp.name: + raise AssertionError("name not the same") + + +def assert_numpy_array_equal(np_array, assert_equal): + """Checks that 'np_array' is equal to 'assert_equal' + + Note that the expected array should not contain `np.nan`! + Two numpy arrays are equal if all + elements are equal, which is not possible if `np.nan` is such an element! + + If the expected array includes `np.nan` use + `assert_numpy_array_equivalent(...)`. + """ + if np.array_equal(np_array, assert_equal): + return + raise AssertionError( + '{0} is not equal to {1}.'.format(np_array, assert_equal)) + + +def assert_numpy_array_equivalent(np_array, assert_equal, strict_nan=False): + """Checks that 'np_array' is equivalent to 'assert_equal' + + Two numpy arrays are equivalent if the arrays have equal non-NaN elements, + and `np.nan` in corresponding locations. + + If the the expected array does not contain `np.nan` + `assert_numpy_array_equivalent` is the similar to + `assert_numpy_array_equal()`. If the expected array includes + `np.nan` use this + function. + """ + if array_equivalent(np_array, assert_equal, strict_nan=strict_nan): + return + raise AssertionError( + '{0} is not equivalent to {1}.'.format(np_array, assert_equal)) + + # This could be refactored to use the NDFrame.equals method def assert_series_equal(left, right, check_dtype=True, check_index_type=False, @@ -1738,3 +1755,11 @@ def use_numexpr(use, min_elements=expr._MIN_ELEMENTS): yield expr._MIN_ELEMENTS = oldmin expr.set_use_numexpr(olduse) + +''' +For Backwards Compatibility. +All assert functions were moved outside of the TestCase to allow importing them +''' +for name, obj in inspect.getmembers(sys.modules[__name__]): + if inspect.isfunction(obj) and name.startswith('assert'): + setattr(TestCase, name, staticmethod(obj))
closes #8023 Merged via https://github.com/pydata/pandas/commit/ace3c46be0ebf12f0eb4b63f22843d76b67ccfde
https://api.github.com/repos/pandas-dev/pandas/pulls/8923
2014-11-29T12:30:02Z
2014-12-01T00:07:21Z
null
2014-12-01T00:57:47Z
CLN: move import to top of file
diff --git a/pandas/core/config.py b/pandas/core/config.py index 60dc1d7d0341e..6768e0af0dfb6 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -51,6 +51,7 @@ import re from collections import namedtuple +from contextlib import contextmanager import warnings from pandas.compat import map, lmap, u import pandas.compat as compat @@ -681,8 +682,6 @@ def pp(name, ks): # # helpers -from contextlib import contextmanager - @contextmanager def config_prefix(prefix):
For consistency with [PEP8](https://www.python.org/dev/peps/pep-0008#id17): ``` Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/8922
2014-11-29T12:01:14Z
2014-11-29T12:32:55Z
2014-11-29T12:32:55Z
2014-12-03T22:40:43Z
DOC: specify return type in to_datetime
diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index 45bea00ac104f..f29ab14ed8745 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -177,7 +177,7 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True, format=None, coerce=False, unit='ns', infer_datetime_format=False): """ - Convert argument to datetime + Convert argument to datetime. Parameters ---------- @@ -198,13 +198,16 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True, coerce : force errors to NaT (False by default) unit : unit of the arg (D,s,ms,us,ns) denote the unit in epoch (e.g. a unix timestamp), which is an integer/float number - infer_datetime_format: boolean, default False + infer_datetime_format : boolean, default False If no `format` is given, try to infer the format based on the first datetime string. Provides a large speed-up in many cases. Returns ------- - ret : datetime if parsing succeeded + ret : datetime if parsing succeeded. Return type depends on input: + - list-like: DatetimeIndex + - Series: Series of datetime64 dtype + - scalar: Timestamp Examples --------
related #8919
https://api.github.com/repos/pandas-dev/pandas/pulls/8921
2014-11-29T00:38:47Z
2014-11-29T13:44:17Z
2014-11-29T13:44:17Z
2014-11-29T13:44:21Z
BUG/ENH: cleanup for Timestamp arithmetic
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index d6d36fd8d14ba..b13f762d0fd27 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -66,9 +66,9 @@ Enhancements - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). - Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`. - Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. -- ``Timedelta`` arithmetic returns ``NotImplemented`` in unknown cases, allowing extensions by custom classes (:issue:`8813`). -- ``Timedelta`` now supports arithemtic with ``numpy.ndarray`` objects of the appropriate dtype (numpy 1.8 or newer only) (:issue:`8884`). -- Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`). +- ``Timestamp`` and ``Timedelta`` arithmetic and comparisons return ``NotImplemented`` in unknown cases, allowing extensions by custom classes (:issue:`8813`, :issue:`8916`). +- ``Timestamp`` and ``Timedelta`` now support arithmetic and comparisons with ``numpy.ndarray`` objects of the appropriate dtype (numpy 1.8 or newer only) (:issue:`8884`, :issue:`8916`). +- Added ``Timestamp.to_datetime64`` and ``Timedelta.to_timedelta64`` methods to the public API (:issue:`8884`, :issue:`8916`). .. _whatsnew_0152.performance: @@ -93,6 +93,7 @@ Bug Fixes - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`). - ``Timedelta`` kwargs may now be numpy ints and floats (:issue:`8757`). - Fixed several outstanding bugs for ``Timedelta`` arithmetic and comparisons (:issue:`8813`, :issue:`5963`, :issue:`5436`). +- The difference of two ``Timestamp`` objects is now a ``pandas.Timedelta`` rather than only a ``datetime.timedelta`` (:issue:`8865`). - ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) - ``slice`` string method now takes step into account (:issue:`8754`) - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index fc031afe728dc..ece2a4ee4dded 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -5004,32 +5004,39 @@ def check(df,df2): df = DataFrame(np.random.randint(10, size=(10, 2)), columns=['a', 'b']) df2 = DataFrame({'a': date_range('20010101', periods=len(df)), 'b': date_range('20100101', periods=len(df))}) - check(df,df2) + check(df, df2) + # check(df, pd.Timestamp('2000-01-01')) + # check(df2, 123) def test_timestamp_compare(self): # make sure we can compare Timestamps on the right AND left hand side # GH4982 df = DataFrame({'dates1': date_range('20010101', periods=10), - 'dates2': date_range('20010102', periods=10), - 'intcol': np.random.randint(1000000000, size=10), - 'floatcol': np.random.randn(10), - 'stringcol': list(tm.rands(10))}) - df.loc[np.random.rand(len(df)) > 0.5, 'dates2'] = pd.NaT + 'dates2': date_range('20010101', periods=10)}) + df.loc[::2, 'dates2'] = pd.NaT ops = {'gt': 'lt', 'lt': 'gt', 'ge': 'le', 'le': 'ge', 'eq': 'eq', 'ne': 'ne'} for left, right in ops.items(): left_f = getattr(operator, left) right_f = getattr(operator, right) + nat_cmp_value = True if left != 'ne' else False + # no nats - expected = left_f(df, Timestamp('20010109')) - result = right_f(Timestamp('20010109'), df) - tm.assert_frame_equal(result, expected) + ts = Timestamp('20010109') + expected = DataFrame(left_f(df.values, ts), columns=df.columns) + left_result = left_f(df, ts) + right_result = right_f(ts, df) + tm.assert_frame_equal(left_result, expected) + tm.assert_frame_equal(right_result, expected) # nats - expected = left_f(df, Timestamp('nat')) - result = right_f(Timestamp('nat'), df) - tm.assert_frame_equal(result, expected) + values = (np.zeros if left != 'ne' else np.ones)((10, 2), bool) + expected = DataFrame(values, columns=df.columns) + left_result = left_f(df, Timestamp('nat')) + right_result = right_f(Timestamp('nat'), df) + tm.assert_frame_equal(left_result, expected) + tm.assert_frame_equal(right_result, expected) def test_modulo(self): diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py index b523fb1d56290..5bc2565ff3db6 100644 --- a/pandas/tseries/base.py +++ b/pandas/tseries/base.py @@ -316,7 +316,7 @@ def __add__(self, other): return self._add_delta(other) elif com.is_integer(other): return self.shift(other) - elif isinstance(other, (tslib.Timestamp, datetime)): + elif isinstance(other, (tslib.Timestamp, datetime, np.datetime64)): return self._add_datelike(other) else: # pragma: no cover return NotImplemented @@ -339,14 +339,18 @@ def __sub__(self, other): return self._add_delta(-other) elif com.is_integer(other): return self.shift(-other) - elif isinstance(other, (tslib.Timestamp, datetime)): + elif isinstance(other, (tslib.Timestamp, datetime, np.datetime64)): return self._sub_datelike(other) else: # pragma: no cover return NotImplemented cls.__sub__ = __sub__ def __rsub__(self, other): - return -self + other + from pandas.tseries.tdi import TimedeltaIndex + if isinstance(self, TimedeltaIndex): + return -self + other + else: + return -(self - other) cls.__rsub__ = __rsub__ cls.__iadd__ = __add__ diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index 494a9cc95dc49..e726f66320af7 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -3,6 +3,7 @@ from __future__ import division from datetime import datetime, timedelta, time import nose +import operator from distutils.version import LooseVersion import numpy as np @@ -288,6 +289,30 @@ def test_compare_timedelta_series(self): expected = pd.Series([False, True]) tm.assert_series_equal(actual, expected) + def test_compare_timedelta_ndarray(self): + lhs = pd.to_timedelta(['1 day', '3 days']).values + rhs = Timedelta('2 day') + + nat = Timedelta('nat') + expected_nat = np.array([False, False]) + + ops = {'gt': 'lt', 'lt': 'gt', 'ge': 'le', 'le': 'ge', 'eq': 'eq', + 'ne': 'ne'} + + for left, right in ops.items(): + left_f = getattr(operator, left) + right_f = getattr(operator, right) + expected = left_f(lhs, rhs) + + result = right_f(rhs, lhs) + self.assert_numpy_array_equal(result, expected) + + expected = ~expected_nat if left == 'ne' else expected_nat + result = left_f(lhs, nat) + self.assert_numpy_array_equal(result, expected) + result = right_f(nat, lhs) + self.assert_numpy_array_equal(result, expected) + def test_ops_notimplemented(self): class Other: pass @@ -299,6 +324,8 @@ class Other: self.assertTrue(td.__truediv__(other) is NotImplemented) self.assertTrue(td.__mul__(other) is NotImplemented) self.assertTrue(td.__floordiv__(td) is NotImplemented) + self.assertTrue(td.__lt__(other) is NotImplemented) + self.assertTrue(td.__eq__(other) is NotImplemented) def test_fields(self): rng = to_timedelta('1 days, 10:11:12') diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 436f9f3b9c9b3..5bfcb7a09978a 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -3680,6 +3680,30 @@ def test_timestamp_compare_series(self): result = right_f(Timestamp('nat'), s_nat) tm.assert_series_equal(result, expected) + def test_timestamp_compare_ndarray(self): + lhs = pd.to_datetime(['1999-12-31', '2000-01-02']).values + rhs = Timestamp('2000-01-01') + + nat = Timestamp('nat') + expected_nat = np.array([False, False]) + + ops = {'gt': 'lt', 'lt': 'gt', 'ge': 'le', 'le': 'ge', 'eq': 'eq', + 'ne': 'ne'} + + for left, right in ops.items(): + left_f = getattr(operator, left) + right_f = getattr(operator, right) + expected = left_f(lhs, rhs) + + result = right_f(rhs, lhs) + self.assert_numpy_array_equal(result, expected) + + expected = ~expected_nat if left == 'ne' else expected_nat + result = left_f(lhs, nat) + self.assert_numpy_array_equal(result, expected) + result = right_f(nat, lhs) + self.assert_numpy_array_equal(result, expected) + class TestSlicing(tm.TestCase): diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py index 9adcbb4ea4a41..7d9427ce0ae00 100644 --- a/pandas/tseries/tests/test_tslib.py +++ b/pandas/tseries/tests/test_tslib.py @@ -1,14 +1,14 @@ +from distutils.version import LooseVersion +import datetime import nose - import numpy as np from pandas import tslib -import datetime - -from pandas.core.api import Timestamp, Series +from pandas.core.api import Timestamp, Timedelta, Series from pandas.tslib import period_asfreq, period_ordinal from pandas.tseries.index import date_range from pandas.tseries.frequencies import get_freq +import pandas as pd import pandas.tseries.offsets as offsets import pandas.util.testing as tm from pandas.util.testing import assert_series_equal @@ -136,6 +136,20 @@ def test_constructor_with_stringoffset(self): self.assertEqual(repr(result), expected_repr) self.assertEqual(result, eval(repr(result))) + def test_conversion(self): + ts = Timestamp('2000-01-01') + + result = ts.to_pydatetime() + expected = datetime.datetime(2000, 1, 1) + self.assertEqual(result, expected) + self.assertEqual(type(result), type(expected)) + + result = ts.to_datetime64() + expected = np.datetime64(ts.value, 'ns') + self.assertEqual(result, expected) + self.assertEqual(type(result), type(expected)) + self.assertEqual(result.dtype, expected.dtype) + def test_repr(self): dates = ['2014-03-07', '2014-01-01 09:00', '2014-01-01 00:00:00.000000001'] timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/America/Los_Angeles'] @@ -232,13 +246,13 @@ def test_tz(self): conv = local.tz_convert('US/Eastern') self.assertEqual(conv.nanosecond, 5) self.assertEqual(conv.hour, 19) - + def test_tz_localize_ambiguous(self): - + ts = Timestamp('2014-11-02 01:00') ts_dst = ts.tz_localize('US/Eastern', ambiguous=True) ts_no_dst = ts.tz_localize('US/Eastern', ambiguous=False) - + rng = date_range('2014-11-02', periods=3, freq='H', tz='US/Eastern') self.assertEqual(rng[1], ts_dst) self.assertEqual(rng[2], ts_no_dst) @@ -675,8 +689,8 @@ def test_addition_subtraction_types(self): self.assertEqual(type(timestamp_instance + 1), Timestamp) self.assertEqual(type(timestamp_instance - 1), Timestamp) - # Timestamp + datetime not supported, though subtraction is supported and yields timedelta - self.assertEqual(type(timestamp_instance - datetime_instance), datetime.timedelta) + # Timestamp + datetime not supported, though subtraction is supported and yields Timedelta + self.assertEqual(type(timestamp_instance - datetime_instance), Timedelta) self.assertEqual(type(timestamp_instance + timedelta_instance), Timestamp) self.assertEqual(type(timestamp_instance - timedelta_instance), Timestamp) @@ -686,6 +700,48 @@ def test_addition_subtraction_types(self): self.assertEqual(type(timestamp_instance + timedelta64_instance), Timestamp) self.assertEqual(type(timestamp_instance - timedelta64_instance), Timestamp) + def test_ops_ndarray(self): + ts = Timestamp('2000-01-01') + + # timedelta operations + other = pd.to_timedelta(['1 day']).values + expected = pd.to_datetime(['2000-01-02']).values + self.assert_numpy_array_equal(ts + other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(other + ts, expected) + self.assertRaises(TypeError, lambda: ts + np.array([1])) + self.assertRaises(TypeError, lambda: np.array([1]) + ts) + + expected = pd.to_datetime(['1999-12-31']).values + self.assert_numpy_array_equal(ts - other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(-other + ts, expected) + self.assertRaises(TypeError, lambda: ts - np.array([1])) + self.assertRaises(TypeError, lambda: np.array([1]) - ts) + + # datetime operations + other = pd.to_datetime(['1999-12-31']).values + expected = pd.to_timedelta(['1 days']).values + self.assert_numpy_array_equal(ts - other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(other - ts, -expected) + + tsz = Timestamp('2000-01-01', tz='EST') + self.assertRaises(ValueError, lambda: ts > tsz) + self.assertRaises(ValueError, + lambda: pd.to_datetime(['2000-01-02']).values > tsz) + + def test_ops_notimplemented(self): + class Other: + pass + other = Other() + + ts = Timestamp('2000-01-01') + self.assertTrue(ts.__add__(other) is NotImplemented) + self.assertTrue(ts.__sub__(other) is NotImplemented) + self.assertTrue(ts.__lt__(other) is NotImplemented) + self.assertTrue(ts.__eq__(other) is NotImplemented) + def test_addition_subtraction_preserve_frequency(self): timestamp_instance = date_range('2014-03-05', periods=1, freq='D')[0] timedelta_instance = datetime.timedelta(days=1) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index 8efc174d6890b..e23832b04a5d6 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -531,11 +531,14 @@ class Timestamp(_Timestamp): self.nanosecond/3600.0/1e+9 )/24.0) + # cython extension types like _Timestamp don't use reversed operators like + # __radd__ or __rsub__, so define them here instead def __radd__(self, other): - # __radd__ on cython extension types like _Timestamp is not used, so - # define it here instead return self + other + def __rsub__(self, other): + return -(self - other) + _nat_strings = set(['NaT','nat','NAT','nan','NaN','NAN']) class NaTType(_NaT): @@ -721,8 +724,6 @@ _reverse_ops[Py_GT] = Py_LT _reverse_ops[Py_GE] = Py_LE -cdef str _NDIM_STRING = "ndim" - # This is PITA. Because we inherit from datetime, which has very specific # construction requirements, we need to do object instantiation in python # (see Timestamp class above). This will serve as a C extension type that @@ -743,10 +744,12 @@ cdef class _Timestamp(datetime): int ndim if isinstance(other, _Timestamp): + # print '_timestamp' if isinstance(other, _NaT): return _cmp_nat_dt(other, self, _reverse_ops[op]) ots = other elif isinstance(other, datetime): + # print 'datetime' if self.nanosecond == 0: val = self.to_datetime() return PyObject_RichCompareBool(val, other, op) @@ -755,31 +758,35 @@ cdef class _Timestamp(datetime): ots = Timestamp(other) except ValueError: return self._compare_outside_nanorange(other, op) - else: - ndim = getattr(other, _NDIM_STRING, -1) - - if ndim != -1: - if ndim == 0: - if isinstance(other, np.datetime64): - other = Timestamp(other) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - - # only allow ==, != ops - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, - type(other).__name__)) - return PyObject_RichCompare(other, self, _reverse_ops[op]) + elif isinstance(other, np.datetime64): + # print 'convert dt64' + return PyObject_RichCompare(self, Timestamp(other), op) + elif hasattr(other, 'dtype'): + # print 'dtype', type(other), other.dtype, other + if self.tz is None and self.offset is None: + # allow comparison to ndarrays; use the reverse op because it's + # necessary when comparing to pd.Series + return PyObject_RichCompare(other, self.to_datetime64(), + _reverse_ops[op]) + # This terrible hack lets us invoke normal numpy broadcasting rules + # even though we set __array_priority__ > + # ndarray.__array_priority__ (for the benefit of arithmetic) + # return NotImplemented + elif self.__array_priority__ == 0: + # print 'priority == 0' + return NotImplemented else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, type(other).__name__)) + # print 'priority set to 0' + # print(self.__array_priority__) + new_obj = Timestamp(self.value, self.offset, self.tz) + new_obj.__array_priority__ = 0 + new_obj._allow_cmp_int_dtype = True + return PyObject_RichCompare(other, new_obj, _reverse_ops[op]) + elif hasattr(self, '_allow_cmp_int_dtype') and isinstance(other, long): + ots = other = Timestamp(other) + else: + # print 'not implemented', type(other), other, self.__array_priority__ + return NotImplemented self._assert_tzawareness_compat(other) return _cmp_scalar(self.value, ots.value, op) @@ -825,6 +832,13 @@ cdef class _Timestamp(datetime): dts.hour, dts.min, dts.sec, dts.us, ts.tzinfo) + cpdef to_datetime64(self): + """ Returns a numpy.datetime64 object with 'ns' precision """ + return np.datetime64(self.value, 'ns') + + # higher than np.ndarray and np.matrix + __array_priority__ = 100 + def __add__(self, other): cdef int64_t other_int @@ -845,9 +859,14 @@ cdef class _Timestamp(datetime): result = Timestamp(normalize_date(result)) return result - # index/series like - elif hasattr(other, '_typ'): - return other + self + elif hasattr(other, 'dtype'): + if self.tz is None and self.offset is None: + if other.dtype.kind not in ['m', 'M']: + # raise rather than letting numpy return wrong answer + raise TypeError('cannot add operand with type %r to ' + 'Timestamp' % other.dtype) + return self.to_datetime64() + other + return NotImplemented result = datetime.__add__(self, other) if isinstance(result, datetime): @@ -861,17 +880,23 @@ cdef class _Timestamp(datetime): neg_other = -other return self + neg_other - # a Timestamp-DatetimeIndex -> yields a negative TimedeltaIndex - elif getattr(other,'_typ',None) == 'datetimeindex': - return -other.__sub__(self) - - # a Timestamp-TimedeltaIndex -> yields a negative TimedeltaIndex - elif getattr(other,'_typ',None) == 'timedeltaindex': - return (-other).__add__(self) + if hasattr(other, 'dtype'): + if self.tz is None and self.offset is None: + if other.dtype.kind not in ['m', 'M']: + # raise rather than letting numpy return wrong answer + raise TypeError('cannot subtract operand with type %r ' + 'from Timestamp' % other.dtype) + return self.to_datetime64() - other + return NotImplemented elif other is NaT: return NaT - return datetime.__sub__(self, other) + + result = datetime.__sub__(self, other) + if isinstance(result, timedelta): + result = Timedelta(result) + # TODO: handle ns precision? + return result cpdef _get_field(self, field): out = get_date_field(np.array([self.value], dtype=np.int64), field) @@ -907,6 +932,9 @@ cdef class _NaT(_Timestamp): # py3k needs this defined here return hash(self.value) + # less than np.ndarray + __array_priority__ = 0 + def __richcmp__(_NaT self, object other, int op): cdef int ndim = getattr(other, 'ndim', -1) @@ -917,8 +945,7 @@ cdef class _NaT(_Timestamp): if isinstance(other, np.datetime64): other = Timestamp(other) else: - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, type(other).__name__)) + return NotImplemented return PyObject_RichCompare(other, self, _reverse_ops[op]) def __add__(self, other): @@ -1508,38 +1535,19 @@ cdef class _Timedelta(timedelta): _Timedelta ots int ndim - if isinstance(other, _Timedelta): - if isinstance(other, _NaT): - return _cmp_nat_dt(other, self, _reverse_ops[op]) + if isinstance(other, _NaT): + return NotImplemented + elif isinstance(other, _Timedelta): ots = other - elif isinstance(other, timedelta): - ots = Timedelta(other) + elif isinstance(other, (timedelta, np.timedelta64)): + return PyObject_RichCompareBool(self, Timedelta(other), op) + elif hasattr(other, 'dtype'): + # allow comparison to ndarrays; use the reverse op because it's + # necessary when comparing to pd.Series + return PyObject_RichCompare(other, self.to_timedelta64(), + _reverse_ops[op]) else: - ndim = getattr(other, _NDIM_STRING, -1) - - if ndim != -1: - if ndim == 0: - if isinstance(other, np.timedelta64): - other = Timedelta(other) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - - # only allow ==, != ops - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, - type(other).__name__)) - return PyObject_RichCompare(other, self, _reverse_ops[op]) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, type(other).__name__)) - + return NotImplemented return _cmp_scalar(self.value, ots.value, op) def _ensure_components(_Timedelta self): @@ -1925,7 +1933,9 @@ class Timedelta(_Timedelta): if hasattr(other, 'dtype'): if other.dtype.kind not in ['m', 'M']: # raise rathering than letting numpy return wrong answer - return NotImplemented + raise TypeError('cannot calculate %s between Timedelta ' + 'and array with dtype %r' + % (name, other.dtype)) return op(self.to_timedelta64(), other) if not self._validate_ops_compat(other):
Fixes #8865 (Timestamp - Timestamp -> Timedelta) This PR cleans up and extends `Timestamp` arithmetic similarly to my treatment for `Timedelta` in #8884. It includes a new `to_datetime64()` method, and arithmetic now works between Timestamp and ndarrays. I also ensure comparison operations work properly between all of (Timestamp, Timedelta, NaT) and ndarrays. Implementation notes: wide use of the `NotImplemented` singleton let me cleanup some complex logic. I also strove to reduce the tight-coupling of `Timestamp`/`Timedelta` to pandas itself by removing use of the `_typ` property in tslib (I honestly don't quite understand why it needs to exist) and by not treating series/index any differently from any other ndarray-like objects. CC @jreback @jorisvandenbossche @immerrr
https://api.github.com/repos/pandas-dev/pandas/pulls/8916
2014-11-28T05:37:15Z
2014-12-09T23:26:55Z
null
2014-12-09T23:27:02Z
ENH: adds ability to generate bq schema from df
diff --git a/doc/source/io.rst b/doc/source/io.rst index bf8776d4bc396..852e7e6392a09 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3643,6 +3643,14 @@ data quickly, but it is not a direct replacement for a transactional database. You can access the management console to determine project id's by: <https://code.google.com/apis/console/b/0/?noredirect> +As of 0.15.2, the gbq module has a function ``generate_bq_schema`` which +will produce the dictionary representation of the schema. + +.. code-block:: python + + df = pandas.DataFrame({'A': [1.0]}) + gbq.generate_bq_schema(df, default_type='STRING') + .. warning:: To use this module, you will need a valid BigQuery account. See diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index eacccaa7cba92..b53d16ee7cec5 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -69,6 +69,7 @@ Enhancements - ``Timedelta`` arithmetic returns ``NotImplemented`` in unknown cases, allowing extensions by custom classes (:issue:`8813`). - ``Timedelta`` now supports arithemtic with ``numpy.ndarray`` objects of the appropriate dtype (numpy 1.8 or newer only) (:issue:`8884`). - Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`). +- Added ``gbq.generate_bq_schema`` function to the gbq module (:issue:`8325`). .. _whatsnew_0152.performance: diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index 20c1e9f591081..572a8be5c65e8 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -444,3 +444,31 @@ def to_gbq(dataframe, destination_table, project_id=None, chunksize=10000, dataset_id, table_id = destination_table.rsplit('.',1) connector.load_data(dataframe, dataset_id, table_id, chunksize, verbose) + +def generate_bq_schema(df, default_type='STRING'): + """ Given a passed df, generate the associated big query schema. + + Parameters + ---------- + df : DataFrame + default_type : string + The default big query type in case the type of the column + does not exist in the schema. + """ + + type_mapping = { + 'i': 'INTEGER', + 'b': 'BOOLEAN', + 'f': 'FLOAT', + 'O': 'STRING', + 'S': 'STRING', + 'U': 'STRING', + 'M': 'TIMESTAMP' + } + + fields = [] + for column_name, dtype in df.dtypes.iteritems(): + fields.append({'name': column_name, + 'type': type_mapping.get(dtype.kind, default_type)}) + + return {'fields': fields} diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py index 0f595f75bc66f..2f79cc8ba1826 100644 --- a/pandas/io/tests/test_gbq.py +++ b/pandas/io/tests/test_gbq.py @@ -277,6 +277,17 @@ def test_google_upload_errors_should_raise_exception(self): with tm.assertRaises(gbq.UnknownGBQException): gbq.to_gbq(bad_df, 'pydata_pandas_bq_testing.new_test', project_id = PROJECT_ID) + def test_generate_bq_schema(self): + + df = tm.makeMixedDataFrame() + schema = gbq.generate_bq_schema(df) + + test_schema = {'fields': [{'name': 'A', 'type': 'FLOAT'}, + {'name': 'B', 'type': 'FLOAT'}, + {'name': 'C', 'type': 'STRING'}, + {'name': 'D', 'type': 'TIMESTAMP'}]} + + self.assertEqual(schema, test_schema) @classmethod def tearDownClass(cls):
I need this function for some other work I have in a branch (to_gbq w/ a new table and to_gbq with staging in gcs). I saw issue #8325 and thought this might be a good intermediate step.
https://api.github.com/repos/pandas-dev/pandas/pulls/8915
2014-11-28T04:41:41Z
2014-12-03T22:38:33Z
2014-12-03T22:38:33Z
2014-12-03T22:38:40Z
DOC: Issue #8805
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 237012a71aeb4..a464b687209cb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3279,7 +3279,7 @@ def update(self, other, join='left', overwrite=True, filter_func=None, Parameters ---------- other : DataFrame, or object coercible into a DataFrame - join : {'left', 'right', 'outer', 'inner'}, default 'left' + join : {'left'}, default 'left' overwrite : boolean, default True If True then overwrite values for common keys in the calling frame filter_func : callable(1d-array) -> 1d-array<boolean>, default None
xref #8805 Documentation suggests other types of join, but only 'left' is implemented.
https://api.github.com/repos/pandas-dev/pandas/pulls/8912
2014-11-27T20:07:45Z
2014-11-28T01:02:21Z
2014-11-28T01:02:21Z
2014-11-28T01:02:25Z
ENH: make Series work with map objects the same way as generators
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 1e84762b60caa..2429aa2c696fa 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -69,6 +69,30 @@ Enhancements - ``Timedelta`` arithmetic returns ``NotImplemented`` in unknown cases, allowing extensions by custom classes (:issue:`8813`). - ``Timedelta`` now supports arithemtic with ``numpy.ndarray`` objects of the appropriate dtype (numpy 1.8 or newer only) (:issue:`8884`). - Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`). +- ``Series`` now works with map objects the same way as generators (:issue:`8909`). + + previous behaviour: + + .. code-block:: python + + In [1]: pd.Series(map(lambda x: x, range(3)), index=range(10, 13)) + Out[1]: + 10 <map object at 0x7f817181d7f0> + 11 <map object at 0x7f817181d7f0> + 12 <map object at 0x7f817181d7f0> + dtype: object + + current behavior: + + .. ipython:: python + + In [2]: pd.Series(map(lambda x: x, range(3)), index=range(10, 13)) + Out[2]: + 10 0 + 11 1 + 12 2 + dtype: int64 + .. _whatsnew_0152.performance: diff --git a/pandas/core/series.py b/pandas/core/series.py index 68bf4f0f022d7..081e5c50946bc 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -183,7 +183,8 @@ def __init__(self, data=None, index=None, dtype=None, name=None, raise ValueError("cannot specify a dtype with a Categorical") if name is None: name = data.name - elif isinstance(data, types.GeneratorType): + elif (isinstance(data, types.GeneratorType) or + (compat.PY3 and isinstance(data, map))): data = list(data) elif isinstance(data, (set, frozenset)): raise TypeError("{0!r} type is unordered" diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c4c2eebacb0e9..c096c44b69eea 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -632,6 +632,19 @@ def test_constructor_generator(self): exp.index = lrange(10, 20) assert_series_equal(result, exp) + def test_constructor_map(self): + # GH8909 + m = map(lambda x: x, range(10)) + + result = Series(m) + exp = Series(lrange(10)) + assert_series_equal(result, exp) + + m = map(lambda x: x, range(10)) + result = Series(m, index=lrange(10, 20)) + exp.index = lrange(10, 20) + assert_series_equal(result, exp) + def test_constructor_categorical(self): cat = pd.Categorical([0, 1, 2, 0, 1, 2], ['a', 'b', 'c'], fastpath=True) cat.name = 'foo'
https://api.github.com/repos/pandas-dev/pandas/pulls/8909
2014-11-27T16:28:25Z
2014-12-03T22:43:46Z
2014-12-03T22:43:46Z
2014-12-04T02:36:45Z
BUG: DatetimeIndex with time object as key
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 1e84762b60caa..b740ac948dc05 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -97,6 +97,7 @@ Bug Fixes - ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) - ``slice`` string method now takes step into account (:issue:`8754`) - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) +- Bug in ``DatetimeIndex`` when using ``time`` object as key (:issue:`8667`) - Fix negative step support for label-based slices (:issue:`8753`) Old behavior: diff --git a/pandas/index.pyx b/pandas/index.pyx index 73d886f10b241..9be7e7404f3fe 100644 --- a/pandas/index.pyx +++ b/pandas/index.pyx @@ -545,8 +545,14 @@ cdef class DatetimeEngine(Int64Engine): val = _to_i8(val) return self._get_loc_duplicates(val) values = self._get_index_values() - conv = _to_i8(val) - loc = values.searchsorted(conv, side='left') + + try: + conv = _to_i8(val) + loc = values.searchsorted(conv, side='left') + except TypeError: + self._date_check_type(val) + raise KeyError(val) + if loc == len(values) or util.get_value_at(values, loc) != conv: raise KeyError(val) return loc diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index b7a18da3924c8..5265318d2c831 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -1886,6 +1886,27 @@ def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): self.assertEqual(str(index.reindex([])[0].tz), 'US/Eastern') self.assertEqual(str(index.reindex(np.array([]))[0].tz), 'US/Eastern') + def test_time_loc(self): # GH8667 + from datetime import time + from pandas.index import _SIZE_CUTOFF + + ns = _SIZE_CUTOFF + np.array([-100, 100]) + key = time(15, 11, 30) + start = key.hour * 3600 + key.minute * 60 + key.second + step = 24 * 3600 + + for n in ns: + idx = pd.date_range('2014-11-26', periods=n, freq='S') + ts = pd.Series(np.random.randn(n), index=idx) + i = np.arange(start, n, step) + + tm.assert_array_equal(ts.index.get_loc(key), i) + tm.assert_series_equal(ts[key], ts.iloc[i]) + + left, right = ts.copy(), ts.copy() + left[key] *= -10 + right.iloc[i] *= -10 + tm.assert_series_equal(left, right) class TestPeriodIndex(Base, tm.TestCase): _holder = PeriodIndex diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index 202e30cc2eb5e..e7c001ac57c0a 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -1210,6 +1210,10 @@ def get_value(self, series, key): return self.get_value_maybe_box(series, key) + if isinstance(key, time): + locs = self.indexer_at_time(key) + return series.take(locs) + try: return _maybe_box(self, Index.get_value(self, series, key), series, key) except KeyError: @@ -1219,10 +1223,6 @@ def get_value(self, series, key): except (TypeError, ValueError, KeyError): pass - if isinstance(key, time): - locs = self.indexer_at_time(key) - return series.take(locs) - try: return self.get_value_maybe_box(series, key) except (TypeError, ValueError, KeyError): @@ -1250,6 +1250,9 @@ def get_loc(self, key): stamp = Timestamp(key, tz=self.tz) return self._engine.get_loc(stamp) + if isinstance(key, time): + return self.indexer_at_time(key) + try: return Index.get_loc(self, key) except (KeyError, ValueError): @@ -1258,9 +1261,6 @@ def get_loc(self, key): except (TypeError, KeyError, ValueError): pass - if isinstance(key, time): - return self.indexer_at_time(key) - try: stamp = Timestamp(key, tz=self.tz) return self._engine.get_loc(stamp)
closes https://github.com/pydata/pandas/issues/8667 on master: ``` >>> from datetime import time >>> from pandas.index import _SIZE_CUTOFF >>> n = _SIZE_CUTOFF + 100 >>> idx = pd.date_range('2014-11-26', periods=n, freq='S') >>> ts = pd.Series(np.random.randn(n), index=idx) >>> key = time(15, 0) >>> ts[key] TypeError: 'datetime.time' object is not iterable >>> ts.index.get_loc(key) TypeError: unorderable types: int() > datetime.time() ``` above would work on master branch if `n` was smaller than `_SIZE_CUTOFF`. `_SIZE_CUTOFF` is set [here](https://github.com/pydata/pandas/blob/e5fe75e8d40e6b94eabf54882a17ab05341c9929/pandas/index.pyx#L68)
https://api.github.com/repos/pandas-dev/pandas/pulls/8907
2014-11-27T14:54:46Z
2014-11-29T22:03:08Z
2014-11-29T22:03:08Z
2014-11-30T15:11:42Z
PERF: add exact kw to to_datetime to enable faster regex format parsing
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 10b23605cca85..7e8a4c7ba4faf 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -78,6 +78,7 @@ Enhancements - Added ``gbq.generate_bq_schema`` function to the gbq module (:issue:`8325`). - ``Series`` now works with map objects the same way as generators (:issue:`8909`). - Added context manager to ``HDFStore`` for automatic closing (:issue:`8791`). +- ``to_datetime`` gains an ``exact`` keyword to allow for a format to not require an exact match for a provided format string (if its ``False). ``exact`` defaults to ``True`` (meaning that exact matching is still the default) (:issue:`8904`) .. _whatsnew_0152.performance: @@ -85,6 +86,8 @@ Performance ~~~~~~~~~~~ - Reduce memory usage when skiprows is an integer in read_csv (:issue:`8681`) +- Performance boost for ``to_datetime`` conversions with a passed ``format=``, and the ``exact=False`` (:issue:`8904`) + .. _whatsnew_0152.experimental: Experimental @@ -141,6 +144,7 @@ Bug Fixes - Report a ``TypeError`` when invalid/no paramaters are passed in a groupby (:issue:`8015`) - Regression in DatetimeIndex iteration with a Fixed/Local offset timezone (:issue:`8890`) +- Bug in ``to_datetime`` when parsing a nanoseconds using the ``%f`` format (:issue:`8989`) - Bug in packaging pandas with ``py2app/cx_Freeze`` (:issue:`8602`, :issue:`8831`) - Bug in ``groupby`` signatures that didn't include \*args or \*\*kwargs (:issue:`8733`). - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo and when it receives no data from Yahoo (:issue:`8761`), (:issue:`8783`). diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py index 12e10a71c67b2..7a428fd629125 100644 --- a/pandas/tseries/tests/test_timeseries.py +++ b/pandas/tseries/tests/test_timeseries.py @@ -4123,6 +4123,32 @@ def test_to_datetime_format_time(self): for s, format, dt in data: self.assertEqual(to_datetime(s, format=format), dt) + def test_to_datetime_with_non_exact(self): + + # 8904 + # exact kw + if sys.version_info < (2, 7): + raise nose.SkipTest('on python version < 2.7') + + s = Series(['19MAY11','foobar19MAY11','19MAY11:00:00:00','19MAY11 00:00:00Z']) + result = to_datetime(s,format='%d%b%y',exact=False) + expected = to_datetime(s.str.extract('(\d+\w+\d+)'),format='%d%b%y') + assert_series_equal(result, expected) + + def test_parse_nanoseconds_with_formula(self): + + # GH8989 + # trunctaing the nanoseconds when a format was provided + for v in ["2012-01-01 09:00:00.000000001", + "2012-01-01 09:00:00.000001", + "2012-01-01 09:00:00.001", + "2012-01-01 09:00:00.001000", + "2012-01-01 09:00:00.001000000", + ]: + expected = pd.to_datetime(v) + result = pd.to_datetime(v, format="%Y-%m-%d %H:%M:%S.%f") + self.assertEqual(result,expected) + def test_to_datetime_format_weeks(self): data = [ ['2009324', '%Y%W%w', Timestamp('2009-08-13')], diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index f29ab14ed8745..e680fa06a9c8e 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -174,7 +174,7 @@ def _guess_datetime_format_for_array(arr, **kwargs): return _guess_datetime_format(arr[non_nan_elements[0]], **kwargs) def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True, - format=None, coerce=False, unit='ns', + format=None, exact=True, coerce=False, unit='ns', infer_datetime_format=False): """ Convert argument to datetime. @@ -194,7 +194,11 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True, box : boolean, default True If True returns a DatetimeIndex, if False returns ndarray of values format : string, default None - strftime to parse time, eg "%d/%m/%Y" + strftime to parse time, eg "%d/%m/%Y", note that "%f" will parse + all the way up to nanoseconds + exact : boolean, True by default + If True, require an exact format match. + If False, allow the format to match anywhere in the target string. coerce : force errors to NaT (False by default) unit : unit of the arg (D,s,ms,us,ns) denote the unit in epoch (e.g. a unix timestamp), which is an integer/float number @@ -273,7 +277,7 @@ def _convert_listlike(arg, box, format): if result is None: try: result = tslib.array_strptime( - arg, format, coerce=coerce + arg, format, exact=exact, coerce=coerce ) except (tslib.OutOfBoundsDatetime): if errors == 'raise': diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index d7c5d656d71e0..4cb6c93bdf3d0 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -2123,13 +2123,25 @@ cdef inline convert_to_timedelta64(object ts, object unit, object coerce): raise ValueError("Invalid type for timedelta scalar: %s" % type(ts)) return ts.astype('timedelta64[ns]') -def array_strptime(ndarray[object] values, object fmt, coerce=False): +def array_strptime(ndarray[object] values, object fmt, bint exact=True, bint coerce=False): + """ + Parameters + ---------- + values : ndarray of string-like objects + fmt : string-like regex + exact : matches must be exact if True, search if False + coerce : if invalid values found, coerce to NaT + """ + cdef: Py_ssize_t i, n = len(values) pandas_datetimestruct dts ndarray[int64_t] iresult - int year, month, day, minute, hour, second, fraction, weekday, julian - object val + int year, month, day, minute, hour, second, weekday, julian, tz + int week_of_year, week_of_year_start + int64_t us, ns + object val, group_key, ampm, found + dict found_key global _TimeRE_cache, _regex_cache with _cache_lock: @@ -2198,22 +2210,35 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False): else: val = str(val) - found = format_regex.match(val) - if not found: - if coerce: - iresult[i] = iNaT - continue - raise ValueError("time data %r does not match format %r" % - (values[i], fmt)) - if len(val) != found.end(): - if coerce: - iresult[i] = iNaT - continue - raise ValueError("unconverted data remains: %s" % - values[i][found.end():]) + # exact matching + if exact: + found = format_regex.match(val) + if not found: + if coerce: + iresult[i] = iNaT + continue + raise ValueError("time data %r does not match format %r (match)" % + (values[i], fmt)) + if len(val) != found.end(): + if coerce: + iresult[i] = iNaT + continue + raise ValueError("unconverted data remains: %s" % + values[i][found.end():]) + + # search + else: + found = format_regex.search(val) + if not found: + if coerce: + iresult[i] = iNaT + continue + raise ValueError("time data %r does not match format %r (search)" % + (values[i], fmt)) + year = 1900 month = day = 1 - hour = minute = second = fraction = 0 + hour = minute = second = ns = us = 0 tz = -1 # Default to -1 to signify that values not known; not critical to have, # though @@ -2278,9 +2303,11 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False): second = int(found_dict['S']) elif parse_code == 10: s = found_dict['f'] - # Pad to always return microseconds. - s += "0" * (6 - len(s)) - fraction = int(s) + # Pad to always return nanoseconds + s += "0" * (9 - len(s)) + us = long(s) + ns = us % 1000 + us = us / 1000 elif parse_code == 11: weekday = locale_time.f_weekday.index(found_dict['A'].lower()) elif parse_code == 12: @@ -2345,7 +2372,8 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False): dts.hour = hour dts.min = minute dts.sec = second - dts.us = fraction + dts.us = us + dts.ps = ns * 1000 iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts) try: @@ -4287,7 +4315,7 @@ class TimeRE(dict): base.__init__({ # The " \d" part of the regex is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", - 'f': r"(?P<f>[0-9]{1,6})", + 'f': r"(?P<f>[0-9]{1,9})", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])", 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", @@ -4368,10 +4396,14 @@ _TimeRE_cache = TimeRE() _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache _regex_cache = {} -def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): +cdef _calc_julian_from_U_or_W(int year, int week_of_year, int day_of_week, int week_starts_Mon): """Calculate the Julian day based on the year, week of the year, and day of the week, with week_start_day representing whether the week of the year assumes the week starts on Sunday or Monday (6 or 0).""" + + cdef: + int first_weekday, week_0_length, days_to_week + first_weekday = datetime_date(year, 1, 1).weekday() # If we are dealing with the %U directive (week starts on Sunday), it's # easier to just shift the view to Sunday being the first day of the diff --git a/vb_suite/timeseries.py b/vb_suite/timeseries.py index c67cdabdc1a06..f0c3961ae0277 100644 --- a/vb_suite/timeseries.py +++ b/vb_suite/timeseries.py @@ -156,6 +156,14 @@ def date_range(start=None, end=None, periods=None, freq=None): Benchmark('to_datetime(strings,format="%Y%m%d")', setup, start_date=datetime(2012, 7, 1)) +setup = common_setup + """ +s = Series(['19MAY11','19MAY11:00:00:00']*100000) +""" +timeseries_with_format_no_exact = Benchmark("to_datetime(s,format='%d%b%y',exact=False)", \ + setup, start_date=datetime(2014, 11, 26)) +timeseries_with_format_replace = Benchmark("to_datetime(s.str.replace(':\S+$',''),format='%d%b%y')", \ + setup, start_date=datetime(2014, 11, 26)) + # ---- infer_freq # infer_freq
closes #8989 closes #8903 Clearly the default is exact=True for back-compat but allows for a match starting at the beginning (has always been like this), but doesn't require the string to ONLY match the format, IOW, can be extra stuff after the match. Avoids having to do a regex replace first. ``` In [21]: s = Series(['19MAY11','19MAY11:00:00:00']*100000) In [22]: %timeit pd.to_datetime(s.str.replace(':\S+$',''),format='%d%b%y') 1 loops, best of 3: 828 ms per loop In [23]: %timeit pd.to_datetime(s,format='%d%b%y',exact=False) 1 loops, best of 3: 603 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/8904
2014-11-27T02:48:55Z
2014-12-05T14:32:51Z
2014-12-05T14:32:51Z
2014-12-05T14:33:51Z
WIP: add multi-multi index support to join
diff --git a/pandas/core/index.py b/pandas/core/index.py index a4eca1216ea84..2c4d25b30148b 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1372,6 +1372,7 @@ def _join_multi(self, other, how, return_indexers=True): raise ValueError("cannot join with no level specified and no overlapping names") if len(overlap) > 1: raise NotImplementedError("merging with more than one level overlap on a multi-index is not implemented") + jl = overlap[0] # make the indices into mi's that match @@ -1392,7 +1393,74 @@ def _join_multi(self, other, how, return_indexers=True): return result # 2 multi-indexes - raise NotImplementedError("merging with both multi-indexes is not implemented") + left_values = other.get_level_values(jl) + left_joined, left_lidx, left_ridx = self._join_level(left_values, jl, how=how, + return_indexers=True) + right_values = self.get_level_values(jl) + right_joined, right_lidx, right_ridx = other._join_level(right_values, jl, how=how, + return_indexers=True) + + # new levels + levels = list(left_joined.levels) + levels_names = set([ l.name for l in levels ]) + levels += [ l for l in right_joined.levels if l.name not in levels_names ] + + # number of reps of labels + l = len(left_joined)*len(right_joined) + + # new labels + lidx = com._ensure_int64(left_lidx) + ridx = com._ensure_int64(right_lidx) + labels = [] + indexers = [] + + def _get_labels(joined, name, indexer): + ln = joined._get_level_number(name) + lev_labels = np.tile(joined.labels[ln],l/len(joined.labels[ln])) + rev_indexer = lib.get_reverse_indexer(indexer,l) + new_labels = com.take_nd(rev_indexer, lev_labels, + allow_fill=False) + omit_mask = new_labels != -1 + new_indexer = np.arange(len(lev_labels))[omit_mask] + + return new_labels, new_indexer + + for level in levels: + + name = level.name + + in_left = name in left_joined.names + in_right = name in right_joined.names + + if not in_left and in_right: + new_labels, new_indexer = _get_labels(right_joined, name, ridx) + else: + # left or the joined + new_labels, new_indexer = _get_labels(left_joined, name, lidx) + + labels.append(new_labels) + indexers.append(new_indexer) + + import pdb; pdb.set_trace() + + return MultiIndex(labels=labels,levels=levels), left_lidx, right_ridx + + #sjl = self._get_level_number(jl) + #left_indexer = np.array(sorted(list(set(np.arange(len(self.levels)))-set([sjl])))) + #ojl = other._get_level_number(jl) + #right_indexer = np.array(sorted(list(set(np.arange(len(other.levels)))-set([ojl])))) + + #tuples = [] + #for left, right in zip(self.take(lidx).values, other.take(ridx).values): + # def _create_tuple(left, right, i): + # t = [] + # t.extend(list(np.array(left).take(left_indexer))) + # t.append(left[i]) + # t.extend(list(np.array(right).take(right_indexer))) + # return tuple(t) + + #tuples = [ _create_tuple(left, right, sjl) + #return MultiIndex.from_tuples(tuples,names=_create_tuple(self.names,other.names,sjl)), lidx, ridx def _join_non_unique(self, other, how='left', return_indexers=False): from pandas.tools.merge import _get_join_indexers diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index 6645391aeda64..8ec66bd358666 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -1049,8 +1049,6 @@ def test_join_multi_levels(self): ).set_index(['household_id','asset_id']).reindex(columns=['male','wealth','name','share']) assert_frame_equal(result,expected) - assert_frame_equal(result,expected) - # equivalency result2 = merge(household.reset_index(),portfolio.reset_index(),on=['household_id'],how='inner').set_index(['household_id','asset_id']) assert_frame_equal(result2,expected) @@ -1097,9 +1095,8 @@ def test_join_multi_levels2(self): log_return = [.09604978, -.06524096, .03532373, .09604978, -.06524096, .03532373, .03025441, .036997] )).set_index(["household_id", "asset_id", "t"]).reindex(columns=['share','log_return']) - def f(): - household.join(log_return, how='inner') - self.assertRaises(NotImplementedError, f) + result = household.join(log_return, how='inner') + assert_frame_equal(result,expected) # this is the equivalency result = merge(household.reset_index(),log_return.reset_index(),on=['asset_id'],how='inner').set_index(['household_id','asset_id','t']) @@ -1113,9 +1110,8 @@ def f(): log_return = [None, None, .09604978, -.06524096, .03532373, .09604978, -.06524096, .03532373, .03025441, .036997, None, None] )).set_index(["household_id", "asset_id", "t"]) - def f(): - household.join(log_return, how='outer') - self.assertRaises(NotImplementedError, f) + result = household.join(log_return, how='outer') + assert_frame_equal(result,expected) def _check_join(left, right, result, join_col, how='left', lsuffix='_x', rsuffix='_y'):
closes #6360
https://api.github.com/repos/pandas-dev/pandas/pulls/8898
2014-11-26T14:45:41Z
2015-05-09T16:06:08Z
null
2022-10-13T00:16:17Z
COMPAT: windows compat for tests for dtype inference in parser xref (GH8833)
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py index 7b8bdeb1f38b8..228dad984bb3c 100644 --- a/pandas/io/tests/test_parsers.py +++ b/pandas/io/tests/test_parsers.py @@ -3173,8 +3173,9 @@ def test_dtype_and_names_error(self): tm.assert_frame_equal(result, expected) # fallback casting - result = self.read_csv(StringIO(data),sep='\s+',header=None,names=['a','b'],dtype={'a' : int}) + result = self.read_csv(StringIO(data),sep='\s+',header=None,names=['a','b'],dtype={'a' : np.int32}) expected = DataFrame([[1,1],[2,2],[3,3]],columns=['a','b']) + expected['a'] = expected['a'].astype(np.int32) tm.assert_frame_equal(result, expected) data = """ @@ -3184,7 +3185,7 @@ def test_dtype_and_names_error(self): """ # fallback casting, but not castable with tm.assertRaisesRegexp(ValueError, 'cannot safely convert'): - self.read_csv(StringIO(data),sep='\s+',header=None,names=['a','b'],dtype={'a' : int}) + self.read_csv(StringIO(data),sep='\s+',header=None,names=['a','b'],dtype={'a' : np.int32}) def test_fallback_to_python(self): # GH 6607 diff --git a/pandas/parser.pyx b/pandas/parser.pyx index eb80a51728765..afaa5219ab0cd 100644 --- a/pandas/parser.pyx +++ b/pandas/parser.pyx @@ -1060,7 +1060,7 @@ cdef class TextReader: if na_count > 0: raise Exception('Integer column has NA values') - if dtype[1:] != 'i8': + if result is not None and dtype[1:] != 'i8': result = result.astype(dtype) return result, na_count @@ -1069,7 +1069,7 @@ cdef class TextReader: result, na_count = _try_double(self.parser, i, start, end, na_filter, na_hashset, na_flist) - if dtype[1:] != 'f8': + if result is not None and dtype[1:] != 'f8': result = result.astype(dtype) return result, na_count
https://api.github.com/repos/pandas-dev/pandas/pulls/8896
2014-11-26T01:32:09Z
2014-11-26T01:32:36Z
2014-11-26T01:32:36Z
2016-02-12T17:40:26Z
modified: pandas/io/ga.py
diff --git a/pandas/io/ga.py b/pandas/io/ga.py index 57de5c6f5abb4..7646e973fa3aa 100644 --- a/pandas/io/ga.py +++ b/pandas/io/ga.py @@ -25,18 +25,32 @@ NO_CALLBACK = auth.OOB_CALLBACK_URN DOC_URL = auth.DOC_URL -_QUERY_PARAMS = """metrics : list of str +_QUERY_PARAMS = """ +metrics : list of str Un-prefixed metric names (e.g., 'visitors' and not 'ga:visitors') + dimensions : list of str Un-prefixed dimension variable names + start_date : str/date/datetime + end_date : str/date/datetime, optional Defaults to today + segment : list of str, optional + filters : list of str, optional + start_index : int, default 1 + max_results : int, default 10000 - If >10000, must specify chunksize or ValueError will be raised""" + If >10000, must specify chunksize or ValueError will be raised + +sort : bool/list, default None + dimension / metric to sort on within the query to GA. Note that reverse + sorts work as expected, such as sort = '-pageviews'. Note that behaviour + is passed on to the parser, so that the resulting DataFrame is sorted + to match. """ _QUERY_DOC = """ Construct a google analytics query using given parameters @@ -54,8 +68,6 @@ Parameters ---------- %s -sort : bool/list, default True - Sort output by index or list of columns chunksize : int, optional If max_results >10000, specifies the number of rows per iteration index_col : str/list of str/dict, optional @@ -99,12 +111,11 @@ def reset_token_store(): @Substitution(extras=_AUTH_PARAMS) @Appender(_GA_READER_DOC) -def read_ga(metrics, dimensions, start_date, **kwargs): +def read_ga(**kwargs): lst = ['secrets', 'scope', 'token_file_name', 'redirect'] - reader_kwds = dict((p, kwargs.pop(p)) for p in lst if p in kwargs) + reader_kwds = {p : kwargs.pop(p) for p in lst if p in kwargs} reader = GAnalytics(**reader_kwds) - return reader.get_data(metrics=metrics, start_date=start_date, - dimensions=dimensions, **kwargs) + return reader.get_data(**kwargs) class OAuthDataReader(object): @@ -160,7 +171,7 @@ def _create_flow(self, secrets): %s """ % DOC_URL return auth.get_flow(secrets, self.scope, self.redirect_url) - + class GDataReader(OAuthDataReader): """ @@ -244,80 +255,143 @@ def create_query(self, *args, **kwargs): @Substitution(extras='') @Appender(_GA_READER_DOC) - def get_data(self, metrics, start_date, end_date=None, - dimensions=None, segment=None, filters=None, start_index=1, - max_results=10000, index_col=None, parse_dates=True, - keep_date_col=False, date_parser=None, na_values=None, - converters=None, sort=True, dayfirst=False, - account_name=None, account_id=None, property_name=None, - property_id=None, profile_name=None, profile_id=None, - chunksize=None): - if chunksize is None and max_results > 10000: + def get_data(self, **kwargs): + params = {\ + 'metrics' : None, + 'start_date' : None, + 'end_date' : None, + 'dimensions' : None, + 'segment' : None, + 'filters' : None, + 'start_index' : 1, + 'max_results' : 10000, + 'index_col' : None, + 'parse_dates' : True, + 'keep_date_col' : False, + 'date_parser' : None, + 'na_values' : None, + 'converters' : None, + 'sort' : None, + 'dayfirst' : False, + 'account_name' : None, + 'account_id' : None, + 'property_name' : None, + 'property_id' : None, + 'profile_name' : None, + 'profile_id' : None, + 'chunksize' : None,} + + params.update(kwargs) + + if params['chunksize'] is None and params['max_results'] > 10000: raise ValueError('Google API returns maximum of 10,000 rows, ' 'please set chunksize') - account = self.get_account(account_name, account_id) - web_property = self.get_web_property(account.get('id'), property_name, - property_id) + account = self.get_account(params['account_name'], + params['account_id']) + + web_property = self.get_web_property(account.get('id'), + params['property_name'], + params['property_id']) + profile = self.get_profile(account.get('id'), web_property.get('id'), - profile_name, profile_id) + params['profile_name'], + params['profile_id']) profile_id = profile.get('id') - if index_col is None and dimensions is not None: - if isinstance(dimensions, compat.string_types): - dimensions = [dimensions] - index_col = _clean_index(list(dimensions), parse_dates) - + if params['index_col'] is None and params['dimensions'] is not None: + if isinstance(params['dimensions'], compat.string_types): + dimensions = [params.pop('dimensions')] + index_col = _clean_index(list(dimensions), parse_dates).tolist() + + else: + dimensions = params['dimensions'] + + updated_params = {\ + 'profile_id' : profile_id, + 'dimensions' : dimensions, } + + params.update(updated_params) + def _read(start, result_size): - query = self.create_query(profile_id, metrics, start_date, - end_date=end_date, dimensions=dimensions, - segment=segment, filters=filters, - start_index=start, - max_results=result_size) - + query = self.create_query(**params) + try: rs = query.execute() rows = rs.get('rows', []) col_info = rs.get('columnHeaders', []) - return self._parse_data(rows, col_info, index_col, - parse_dates=parse_dates, - keep_date_col=keep_date_col, - date_parser=date_parser, - dayfirst=dayfirst, - na_values=na_values, - converters=converters, sort=sort) + + parse_items = ['index_col', 'parse_dates', 'keep_date_col', \ + 'date_parser', 'dayfirst', 'na_values', \ + 'converters', 'sort'] + + # in case a reverse sort has been sent to GA... + def _maybe_fix_sort(item): + if item[0] is '-': + params['ascending'] = False + return item[1:] + + else: + params['ascending'] = True + return item + + if params['sort'] is not None: + if params['sort'].__class__ is str: + temp = _maybe_fix_sort(params['sort']) + + else: + temp = [_maybe_fix_sort(item) \ + for item in params['sort']] + + params['sort'] = temp + + to_parse = {item : params[item] for item in parse_items} + + return self._parse_data(rows, col_info, **to_parse) + except HttpError as inst: raise ValueError('Google API error %s: %s' % (inst.resp.status, - inst._get_reason())) - - if chunksize is None: - return _read(start_index, max_results) + inst._get_reason())) + + if params['chunksize'] is None: + return _read(params['start_index'], params['max_results']) def iterator(): - curr_start = start_index + curr_start = params['start_index'] - while curr_start < max_results: - yield _read(curr_start, chunksize) - curr_start += chunksize + while curr_start < params['max_results']: + yield _read(curr_start, params['chunksize']) + curr_start += params['chunksize'] return iterator() - def _parse_data(self, rows, col_info, index_col, parse_dates=True, - keep_date_col=False, date_parser=None, dayfirst=False, - na_values=None, converters=None, sort=True): + def _parse_data(self, rows, col_info, **kwargs): # TODO use returned column types - col_names = _get_col_names(col_info) - df = psr._read(rows, dict(index_col=index_col, parse_dates=parse_dates, - date_parser=date_parser, dayfirst=dayfirst, - na_values=na_values, - keep_date_col=keep_date_col, - converters=converters, - header=None, names=col_names)) - - if isinstance(sort, bool) and sort: - return df.sort_index() - elif isinstance(sort, (compat.string_types, list, tuple, np.ndarray)): - return df.sort_index(by=sort) + parse_opts = {\ + 'index_col' : None, + 'parse_dates' : True, + 'keep_date_col' : False, + 'date_parser' : None, + 'dayfirst' : False, + 'na_values' : None, + 'converters' : None, + 'sort' : True, + 'ascending' : True, + 'header' : None, } + + parse_opts.update(kwargs) + asc = parse_opts.pop('ascending') + + parse_opts['names'] = _get_col_names(col_info) + df = psr._read(rows, parse_opts) + + if isinstance(parse_opts['sort'], bool) and sort: + return df.sort() + + elif isinstance(parse_opts['sort'], \ + (compat.string_types, list, tuple, np.ndarray)): + return df.sort(columns=parse_opts['sort'], \ + ascending=asc) return df @@ -325,68 +399,118 @@ def _parse_data(self, rows, col_info, index_col, parse_dates=True, class GAnalytics(GDataReader): @Appender(_QUERY_DOC) - def create_query(self, profile_id, metrics, start_date, end_date=None, - dimensions=None, segment=None, filters=None, - start_index=None, max_results=10000, **kwargs): - qry = format_query(profile_id, metrics, start_date, end_date=end_date, - dimensions=dimensions, segment=segment, - filters=filters, start_index=start_index, - max_results=max_results, **kwargs) + def create_query(self, **kwargs): + qry = format_query(**kwargs) + try: return self.service.data().ga().get(**qry) except TypeError as error: raise ValueError('Error making query: %s' % error) -def format_query(ids, metrics, start_date, end_date=None, dimensions=None, - segment=None, filters=None, sort=None, start_index=None, - max_results=10000, **kwargs): - if isinstance(metrics, compat.string_types): - metrics = [metrics] - met = ','.join(['ga:%s' % x for x in metrics]) - - start_date = pd.to_datetime(start_date).strftime('%Y-%m-%d') - if end_date is None: - end_date = datetime.today() - end_date = pd.to_datetime(end_date).strftime('%Y-%m-%d') - - qry = dict(ids='ga:%s' % str(ids), - metrics=met, - start_date=start_date, - end_date=end_date) +def format_query(**kwargs): + qry = {} qry.update(kwargs) - - names = ['dimensions', 'filters', 'sort'] - lst = [dimensions, filters, sort] - [_maybe_add_arg(qry, n, d) for n, d in zip(names, lst)] - - if isinstance(segment, compat.string_types): - if re.match("^[a-zA-Z0-9\-\_]+$", segment): - _maybe_add_arg(qry, 'segment', segment, 'gaid:') + + start_date = pd.to_datetime(qry.pop('start_date')).strftime('%Y-%m-%d') + + if qry['end_date'] is None: + end_date = datetime.today() + end_date = pd.to_datetime(qry.pop('end_date')).strftime('%Y-%m-%d') + + qry_updates = {\ + 'ids' : 'ga:{0}'.format(str(qry.pop('profile_id'))), + 'start_date': start_date, + 'end_date' : end_date, } + qry.update(qry_updates) + + names = ['dimensions', 'metrics'] + lst = [qry['dimensions'], qry['metrics']] + [_maybe_add_arg(qry, n, d) \ + for n, d in zip(names, lst)] + + [_maybe_add_filter_arg(qry, n, d) \ + for n, d in zip(['filters'], [qry['filters']])] + + [_maybe_add_sort_arg(qry, n, d) \ + for n, d in zip(['sort'], [qry['sort']])] + + if isinstance(qry['segment'], compat.string_types): + if re.match("^[a-zA-Z0-9\-\_]+$", qry['segment']): + _maybe_add_arg(qry, 'segment', qry['segment'], 'gaid:') else: - _maybe_add_arg(qry, 'segment', segment, 'dynamic::ga') - elif isinstance(segment, int): - _maybe_add_arg(qry, 'segment', segment, 'gaid:') - elif segment: + _maybe_add_arg(qry, 'segment', qry['segment'], 'dynamic::ga') + + elif isinstance(qry['segment'], int): + _maybe_add_arg(qry, 'segment', qry['segment'], 'gaid:') + + elif qry['segment']: raise ValueError("segment must be string for dynamic and int ID") - if start_index is not None: - qry['start_index'] = str(start_index) + if qry['start_index'] is not None: + qry['start_index'] = str(qry['start_index']) - if max_results is not None: - qry['max_results'] = str(max_results) - - return qry + if qry['max_results'] is not None: + qry['max_results'] = str(qry['max_results']) + + items = ['ids', 'metrics', 'start_date', 'end_date', 'dimensions', \ + 'segment', 'filters', 'sort', 'start_index', 'max_results'] + + return {item : qry.pop(item) for item in items if (item in qry \ + and qry[item] is not None)} def _maybe_add_arg(query, field, data, prefix='ga'): if data is not None: if isinstance(data, (compat.string_types, int)): data = [data] - data = ','.join(['%s:%s' % (prefix, x) for x in data]) + data = ','.join(['{0}:{1}'.format(prefix, x) for x in data]) query[field] = data - - + + +def _maybe_add_sort_arg(query, field, data): + if data is not None: + if isinstance(data, (compat.string_types, int)): + data = [data] + + def _prefix(char): + if char is '-': + return '-ga' + else: + return 'ga' + + def _no_neg(item): + if item[0] is '-': + return item[1:] + else: + return item + + data = ','.join(['{0}:{1}'.format(_prefix(x[0]), _no_neg(x)) \ + for x in data]) + + query[field] = data + + +def _maybe_add_filter_arg(query, field, data, prefix='ga'): + if data is not None: + if isinstance(data, (compat.string_types, int)): + data = [data] + + if len(data) > 1: + lookup = {'AND' : ';', 'OR' : ','} + + args = data[0::2] + rules = [rule.upper() for rule in data[1::2]] + + res = ''.join(['{0}:{1}'.format(prefix, arg) + rule \ + for (arg, rule) in zip(args, [lookup[x] \ + for x in rules])]) + '{0}:{1}'.format(prefix, data[-1]) + query[field] = res + + else: + query[field] = prefix + ':' + data[0] + + def _get_match(obj_store, name, id, **kwargs): key, val = None, None if len(kwargs) > 0: @@ -406,8 +530,8 @@ def _get_match(obj_store, name, id, **kwargs): for item in obj_store.get('items'): if name_ok(item) or id_ok(item) or key_ok(item): return item - - + + def _clean_index(index_dims, parse_dates): _should_add = lambda lst: pd.Index(lst).isin(index_dims).all() to_remove = []
``` ENH I've made a number of alterations to this module to improve the usability of it. 1. A feature has been added to the 'filters' keyword, in that compound filters can now be created with AND and OR combinations as in the API, while still allowing the user to create the filters via lists of strings without the 'ga:' prefix. In particulare, compound filters can be formed as: filters = ['filter_00', 'and', 'filter_01', 'or', 'filter_02'] where no defuault behaviour has been created, thus ensuring that the compound item is formed the way the user intends it to be. The 'and' and 'or' separators are case-insensitive. 2. The 'sort' keyword is now passed to the query, and works as it should with the API. That is, the current 'sort' keyword only acts on the retrieved data when the parser is constructing the local DataFrame object. This behaviour is now changed, in that the 'sort' keyword is included in the query, as well as acting as previous on the parser. Reverse-ordering as in the API is maintained by simply including negaitve sign in front of the metric / dimension that is being sorted on. This is a sublte but important difference, in that the user can now include something like: sort = '-pageviews' to obtain the top N-many results in a query, which is currently not possible without obtaining all results and sorting them locally. Defualt behaviour has been altered, in that the defualt sort is now None (sent to query) while the local dataframe is still sorted on it's index. 3. I didn't like the combination of positional and named keyword arguments in the methods, so I have altered the bahaviour of the module to use only named keyword aguments. Thus, the user is now able to form a query as a single dictionary item and pass it to, say, the read_ga() method. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/8895
2014-11-26T00:23:40Z
2015-03-25T23:20:41Z
null
2015-03-25T23:51:50Z
fix to_datetime default error suppression
diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index 45bea00ac104f..4f68d9fbb5afb 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -173,7 +173,7 @@ def _guess_datetime_format_for_array(arr, **kwargs): if len(non_nan_elements): return _guess_datetime_format(arr[non_nan_elements[0]], **kwargs) -def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True, +def to_datetime(arg, errors='raise', dayfirst=False, utc=None, box=True, format=None, coerce=False, unit='ns', infer_datetime_format=False): """ @@ -182,8 +182,8 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True, Parameters ---------- arg : string, datetime, array of strings (with possible NAs) - errors : {'ignore', 'raise'}, default 'ignore' - Errors are ignored by default (values left untouched) + errors : {'ignore', 'raise'}, default 'raise' + Option to ignore errors and leave the values that raise them untouched. dayfirst : boolean, default False If True parses dates with the day first, eg 20/01/2005 Warning: dayfirst=True is not strict, but will prefer to parse
null
https://api.github.com/repos/pandas-dev/pandas/pulls/8894
2014-11-25T22:54:50Z
2015-05-09T16:06:43Z
null
2022-10-13T00:16:17Z
ENH/VIS: Pass DataFrame column to size argument in DataFrame.scatter
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst index f30d6c9d5d4c0..42fa3da67ff4b 100644 --- a/doc/source/visualization.rst +++ b/doc/source/visualization.rst @@ -8,7 +8,7 @@ import pandas as pd from numpy.random import randn, rand, randint np.random.seed(123456) - from pandas import DataFrame, Series, date_range, options + from pandas import DataFrame, Series, date_range, options, Categorical import pandas.util.testing as tm np.set_printoptions(precision=4, suppress=True) import matplotlib.pyplot as plt @@ -587,20 +587,43 @@ each point: plt.close('all') -You can pass other keywords supported by matplotlib ``scatter``. -Below example shows a bubble chart using a dataframe column values as bubble size. +You can also pass a column name as the ``s`` (size) argument to have +the point sizes scale according to that column's values. Currently +this is only supported for string column names. + +The minimum and +maximum sizes of the bubbles (in points) are controlled by the +``size_range`` argument, with a default range of ``(50, 1000)``. The +below example shows a bubble chart using a dataframe column values +as bubble size. + +.. ipython:: python + + @savefig scatter_plot_sizes.png + df.plot(kind='scatter', x='a', y='b', s='c'); + +.. ipython:: python + :suppress: + + plt.close('all') + +Categorical columns can also be used to set point sizes, producing +a set of equally spaced point sizes: .. ipython:: python - @savefig scatter_plot_bubble.png - df.plot(kind='scatter', x='a', y='b', s=df['c']*200); + df['group'] = Categorical(randint(1, 4, 50)) + @savefig scatter_plot_categorical_sizes.png + df.plot(kind='scatter', x='a', y='b', s='group') .. ipython:: python :suppress: plt.close('all') -See the :meth:`scatter <matplotlib.axes.Axes.scatter>` method and the +You can pass other keywords supported by matplotlib ``scatter``, e.g. ``alpha`` +to control the transparency of points. See the +:meth:`scatter <matplotlib.axes.Axes.scatter>` method and the `matplotlib scatter documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`__ for more. .. _visualization.hexbin: diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 6688f106f922e..6ecba9e0e0ad8 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -66,6 +66,7 @@ Enhancements - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). - Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`. - Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. +- Added support for passing a column name as the size argument to ``DataFrame.plot(kind='scatter')``, along with a ``size_range`` argument to control scaling (:issue:`8244`). .. _whatsnew_0152.performance: diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 74ec6d22ca4cd..0cf886aa58b76 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -9,7 +9,8 @@ from datetime import datetime, date -from pandas import Series, DataFrame, MultiIndex, PeriodIndex, date_range +from pandas import (Series, DataFrame, MultiIndex, PeriodIndex, date_range, + Categorical) from pandas.compat import (range, lrange, StringIO, lmap, lzip, u, zip, iteritems, OrderedDict) from pandas.util.decorators import cache_readonly @@ -1645,6 +1646,32 @@ def test_plot_scatter_with_c(self): self.assertIs(ax.collections[0].colorbar, None) self._check_colors(ax.collections, facecolors=['r']) + @slow + def test_plot_scatter_with_size(self): + df = DataFrame(randn(6, 3), + index=list(string.ascii_letters[:6]), + columns=['x', 'y', 'z']) + df['group'] = Categorical(random.randint(1, 4, 6)) + + size_range = (100, 500) + ax1 = df.plot(kind='scatter', x='x', y='y', s='z', + size_range=size_range) + point_sizes1 = ax1.collections[0]._sizes + self.assertGreaterEqual(min(point_sizes1), size_range[0]) + self.assertLessEqual(max(point_sizes1), size_range[1]) + + # Categorical size column + ax2 = df.plot(kind='scatter', x='x', y='y', s='group', + size_range=size_range) + point_sizes2 = ax2.collections[0]._sizes + self.assertGreaterEqual(min(point_sizes2), size_range[0]) + self.assertLessEqual(max(point_sizes2), size_range[1]) + unique_sizes = np.unique(point_sizes2) + self.assertEqual( + len(unique_sizes), + len(df['group'].cat.categories) + ) + @slow def test_plot_bar(self): df = DataFrame(randn(6, 4), diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index cb669b75e5c96..75d8af651dcb8 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -1374,7 +1374,8 @@ def _get_errorbars(self, label=None, index=None, xerr=True, yerr=True): class ScatterPlot(MPLPlot): _layout_type = 'single' - def __init__(self, data, x, y, c=None, **kwargs): + def __init__(self, data, x, y, c=None, s=None, + size_range=(50, 1000), **kwargs): MPLPlot.__init__(self, data, **kwargs) if x is None or y is None: raise ValueError( 'scatter requires and x and y column') @@ -1387,6 +1388,16 @@ def __init__(self, data, x, y, c=None, **kwargs): self.x = x self.y = y self.c = c + self.size_range = size_range + + # Set up size scaling if necessary, need to do this before plot + # generation starts and non-numeric data thrown away + if s is None: + self.s_values = self.plt.rcParams['lines.markersize'] + elif isinstance(s, str) and s in self.data.columns: + self.s_values = self._convert_column_to_size(s) + else: + self.s_values = s @property def nseries(self): @@ -1415,12 +1426,14 @@ def _make_plot(self): else: c_values = c + if self.legend and hasattr(self, 'label'): label = self.label else: label = None scatter = ax.scatter(data[x].values, data[y].values, c=c_values, - label=label, cmap=cmap, **self.kwds) + s=self.s_values, label=label, cmap=cmap, + **self.kwds) if cb: img = ax.collections[0] kws = dict(ax=ax) @@ -1437,6 +1450,23 @@ def _make_plot(self): err_kwds['ecolor'] = scatter.get_facecolor()[0] ax.errorbar(data[x].values, data[y].values, linestyle='none', **err_kwds) + def _convert_column_to_size(self, col_name): + min_size, max_size = self.size_range + size_col = self.data[col_name] + + if com.is_categorical_dtype(size_col): + n_categories = len(size_col.cat.categories) + cat_sizes = np.linspace(min_size, max_size, num=n_categories) + size_mapper = Series(cat_sizes, index=size_col.cat.categories) + point_sizes = size_col.map(size_mapper) + else: + vals = self.data[col_name].values + val_range = vals.max() - vals.min() + normalized_vals = (vals - vals.min()) / val_range + point_sizes = (min_size + (normalized_vals * (max_size - min_size))) + + return point_sizes + def _post_plot_logic(self): ax = self.axes[0] x, y = self.x, self.y
Originally discussed in #8244. Currently this only uses the column from the dataframe if the `s` argument is a string, supporting int column names is ambiguous and liable to break existing code, but if people can think of a good way to do this I'll try to add it. Example output: ``` python import pandas as pd import numpy as np import random df = pd.DataFrame({ 'x': np.linspace(0, 50, 6), 'y': np.linspace(0, 20, 6), 'cat_column': random.sample('abcdabcdabcd', 6) }) df['cat_column'] = pd.Categorical(df['cat_column']) # Numeric column: linear scaling of point sizes df.plot(kind='scatter', x='x', y='y', s='x') ``` ![image](https://cloud.githubusercontent.com/assets/1460294/5163679/70a09820-7422-11e4-8bf3-7a15fb072f71.png) ``` python # Categorical columns: fixed set of sizes df.plot(kind='scatter', x='x', y='y', s='cat_column') ``` ![image](https://cloud.githubusercontent.com/assets/1460294/5163691/91671f16-7422-11e4-92fd-18b7f67b5b41.png) The minimum and maximum point sizes we scale have a default range of `(50, 1000)`, and can be adjusted with the `size_range` arg: ``` python # Smaller range of sizes than default df.plot(kind='scatter', x='x', y='y', s='x', size_range=(200, 800)) ``` ![image](https://cloud.githubusercontent.com/assets/1460294/5163729/04e4f44a-7423-11e4-9e85-902d9dd1caaa.png) Picking good defaults for the range of sizes is pretty hard as these sizes are absolute- matplotlib sets the size in terms of points. The ability to tweak up and down with the `size_range` arg is probably going to be needed, but open to suggestions on good defaults. .
https://api.github.com/repos/pandas-dev/pandas/pulls/8885
2014-11-24T10:47:40Z
2015-05-09T20:11:46Z
null
2022-10-13T00:16:16Z
BUG/ENH: cleanup for Timedelta arithmetic
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 6688f106f922e..d559b343e2013 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -66,6 +66,11 @@ Enhancements - Added support for ``utcfromtimestamp()``, ``fromtimestamp()``, and ``combine()`` on `Timestamp` class (:issue:`5351`). - Added Google Analytics (`pandas.io.ga`) basic documentation (:issue:`8835`). See :ref:`here<remote_data.ga>`. - Added flag ``order_categoricals`` to ``StataReader`` and ``read_stata`` to select whether to order imported categorical data (:issue:`8836`). See :ref:`here <io.stata-categorical>` for more information on importing categorical variables from Stata data files. +- ``Timedelta`` arithmetic returns ``NotImplemented`` in unknown cases, allowing extensions +by custom classes (:issue:`8813`). +- ``Timedelta`` now supports arithemtic with ``numpy.ndarray`` objects of the appropriate +dtype (numpy 1.8 or newer only) (:issue:`8884`). +- Added ``Timedelta.to_timedelta64`` method to the public API (:issue:`8884`). .. _whatsnew_0152.performance: @@ -89,6 +94,8 @@ Bug Fixes - Bug in slicing a multi-index with an empty list and at least one boolean indexer (:issue:`8781`) - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`). - ``Timedelta`` kwargs may now be numpy ints and floats (:issue:`8757`). +- Fixed several outstanding bugs for ``Timedelta`` arithmetic and comparisons +(:issue:`8813`, :issue:`5963`, :issue:`5436`). - ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) - ``slice`` string method now takes step into account (:issue:`8754`) - Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py index d47544149c381..b523fb1d56290 100644 --- a/pandas/tseries/base.py +++ b/pandas/tseries/base.py @@ -321,6 +321,7 @@ def __add__(self, other): else: # pragma: no cover return NotImplemented cls.__add__ = __add__ + cls.__radd__ = __add__ def __sub__(self, other): from pandas.core.index import Index @@ -344,6 +345,10 @@ def __sub__(self, other): return NotImplemented cls.__sub__ = __sub__ + def __rsub__(self, other): + return -self + other + cls.__rsub__ = __rsub__ + cls.__iadd__ = __add__ cls.__isub__ = __sub__ diff --git a/pandas/tseries/tdi.py b/pandas/tseries/tdi.py index 7fb897aecc809..5a946acac2baa 100644 --- a/pandas/tseries/tdi.py +++ b/pandas/tseries/tdi.py @@ -311,7 +311,7 @@ def _evaluate_with_timedelta_like(self, other, op, opstr): result = self._maybe_mask_results(result,convert='float64') return Index(result,name=self.name,copy=False) - raise TypeError("can only perform ops with timedelta like values") + return NotImplemented def _add_datelike(self, other): diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index 9ad2a090ee0cf..494a9cc95dc49 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -4,6 +4,7 @@ from datetime import datetime, timedelta, time import nose +from distutils.version import LooseVersion import numpy as np import pandas as pd @@ -45,12 +46,12 @@ def test_construction(self): self.assertEqual(Timedelta(days=10,seconds=10).value, expected) self.assertEqual(Timedelta(days=10,milliseconds=10*1000).value, expected) self.assertEqual(Timedelta(days=10,microseconds=10*1000*1000).value, expected) - + # test construction with np dtypes # GH 8757 - timedelta_kwargs = {'days':'D', 'seconds':'s', 'microseconds':'us', + timedelta_kwargs = {'days':'D', 'seconds':'s', 'microseconds':'us', 'milliseconds':'ms', 'minutes':'m', 'hours':'h', 'weeks':'W'} - npdtypes = [np.int64, np.int32, np.int16, + npdtypes = [np.int64, np.int32, np.int16, np.float64, np.float32, np.float16] for npdtype in npdtypes: for pykwarg, npkwarg in timedelta_kwargs.items(): @@ -163,9 +164,17 @@ def test_identity(self): def test_conversion(self): for td in [ Timedelta(10,unit='d'), Timedelta('1 days, 10:11:12.012345') ]: - self.assertTrue(td == Timedelta(td.to_pytimedelta())) - self.assertEqual(td,td.to_pytimedelta()) - self.assertEqual(td,np.timedelta64(td.value,'ns')) + pydt = td.to_pytimedelta() + self.assertTrue(td == Timedelta(pydt)) + self.assertEqual(td, pydt) + self.assertTrue(isinstance(pydt, timedelta) + and not isinstance(pydt, Timedelta)) + + self.assertEqual(td, np.timedelta64(td.value, 'ns')) + td64 = td.to_timedelta64() + self.assertEqual(td64, np.timedelta64(td.value, 'ns')) + self.assertEqual(td, td64) + self.assertTrue(isinstance(td64, np.timedelta64)) # this is NOT equal and cannot be roundtriped (because of the nanos) td = Timedelta('1 days, 10:11:12.012345678') @@ -204,6 +213,15 @@ def test_ops(self): self.assertRaises(TypeError, lambda : td + 2) self.assertRaises(TypeError, lambda : td - 2) + def test_ops_offsets(self): + td = Timedelta(10, unit='d') + self.assertEqual(Timedelta(241, unit='h'), td + pd.offsets.Hour(1)) + self.assertEqual(Timedelta(241, unit='h'), pd.offsets.Hour(1) + td) + self.assertEqual(240, td / pd.offsets.Hour(1)) + self.assertEqual(1 / 240.0, pd.offsets.Hour(1) / td) + self.assertEqual(Timedelta(239, unit='h'), td - pd.offsets.Hour(1)) + self.assertEqual(Timedelta(-239, unit='h'), pd.offsets.Hour(1) - td) + def test_freq_conversion(self): td = Timedelta('1 days 2 hours 3 ns') @@ -214,6 +232,74 @@ def test_freq_conversion(self): result = td / np.timedelta64(1,'ns') self.assertEquals(result, td.value) + def test_ops_ndarray(self): + td = Timedelta('1 day') + + # timedelta, timedelta + other = pd.to_timedelta(['1 day']).values + expected = pd.to_timedelta(['2 days']).values + self.assert_numpy_array_equal(td + other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(other + td, expected) + self.assertRaises(TypeError, lambda: td + np.array([1])) + self.assertRaises(TypeError, lambda: np.array([1]) + td) + + expected = pd.to_timedelta(['0 days']).values + self.assert_numpy_array_equal(td - other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(-other + td, expected) + self.assertRaises(TypeError, lambda: td - np.array([1])) + self.assertRaises(TypeError, lambda: np.array([1]) - td) + + expected = pd.to_timedelta(['2 days']).values + self.assert_numpy_array_equal(td * np.array([2]), expected) + self.assert_numpy_array_equal(np.array([2]) * td, expected) + self.assertRaises(TypeError, lambda: td * other) + self.assertRaises(TypeError, lambda: other * td) + + self.assert_numpy_array_equal(td / other, np.array([1])) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(other / td, np.array([1])) + + # timedelta, datetime + other = pd.to_datetime(['2000-01-01']).values + expected = pd.to_datetime(['2000-01-02']).values + self.assert_numpy_array_equal(td + other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(other + td, expected) + + expected = pd.to_datetime(['1999-12-31']).values + self.assert_numpy_array_equal(-td + other, expected) + if LooseVersion(np.__version__) >= '1.8': + self.assert_numpy_array_equal(other - td, expected) + + def test_ops_series(self): + # regression test for GH8813 + td = Timedelta('1 day') + other = pd.Series([1, 2]) + expected = pd.Series(pd.to_timedelta(['1 day', '2 days'])) + tm.assert_series_equal(expected, td * other) + tm.assert_series_equal(expected, other * td) + + def test_compare_timedelta_series(self): + # regresssion test for GH5963 + s = pd.Series([timedelta(days=1), timedelta(days=2)]) + actual = s > timedelta(days=1) + expected = pd.Series([False, True]) + tm.assert_series_equal(actual, expected) + + def test_ops_notimplemented(self): + class Other: + pass + other = Other() + + td = Timedelta('1 day') + self.assertTrue(td.__add__(other) is NotImplemented) + self.assertTrue(td.__sub__(other) is NotImplemented) + self.assertTrue(td.__truediv__(other) is NotImplemented) + self.assertTrue(td.__mul__(other) is NotImplemented) + self.assertTrue(td.__floordiv__(td) is NotImplemented) + def test_fields(self): rng = to_timedelta('1 days, 10:11:12') self.assertEqual(rng.days,1) diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx index aed6dea264be6..8efc174d6890b 100644 --- a/pandas/tslib.pyx +++ b/pandas/tslib.pyx @@ -531,6 +531,12 @@ class Timestamp(_Timestamp): self.nanosecond/3600.0/1e+9 )/24.0) + def __radd__(self, other): + # __radd__ on cython extension types like _Timestamp is not used, so + # define it here instead + return self + other + + _nat_strings = set(['NaT','nat','NAT','nan','NaN','NAN']) class NaTType(_NaT): """(N)ot-(A)-(T)ime, the time equivalent of NaN""" @@ -1883,8 +1889,12 @@ class Timedelta(_Timedelta): """ array view compat """ return np.timedelta64(self.value).view(dtype) - def _validate_ops_compat(self, other, op): - # return a boolean if we are compat with operating + def to_timedelta64(self): + """ Returns a numpy.timedelta64 object with 'ns' precision """ + return np.timedelta64(self.value, 'ns') + + def _validate_ops_compat(self, other): + # return True if we are compat with operating if _checknull_with_nat(other): return True elif isinstance(other, (Timedelta, timedelta, np.timedelta64)): @@ -1893,55 +1903,58 @@ class Timedelta(_Timedelta): return True elif hasattr(other,'delta'): return True - raise TypeError("cannot operate add a Timedelta with op {op} for {typ}".format(op=op,typ=type(other))) - - def __add__(self, other): - - # a Timedelta with Series/Index like - if hasattr(other,'_typ'): - return other + self - - # an offset - elif hasattr(other,'delta') and not isinstance(other, Timedelta): - return self + other.delta - - # a datetimelike - elif isinstance(other, (Timestamp, datetime, np.datetime64)): - return Timestamp(other) + self - - self._validate_ops_compat(other,'__add__') - - other = Timedelta(other) - if other is NaT: - return NaT - return Timedelta(self.value + other.value, unit='ns') - - def __sub__(self, other): - - # a Timedelta with Series/Index like - if hasattr(other,'_typ'): - neg_other = -other - return neg_other + self - - # an offset - elif hasattr(other,'delta') and not isinstance(other, Timedelta): - return self - other.delta + return False - self._validate_ops_compat(other,'__sub__') + # higher than np.ndarray and np.matrix + __array_priority__ = 100 + + def _binary_op_method_timedeltalike(op, name): + # define a binary operation that only works if the other argument is + # timedelta like or an array of timedeltalike + def f(self, other): + # an offset + if hasattr(other, 'delta') and not isinstance(other, Timedelta): + return op(self, other.delta) + + # a datetimelike + if (isinstance(other, (datetime, np.datetime64)) + and not isinstance(other, (Timestamp, NaTType))): + return op(self, Timestamp(other)) + + # nd-array like + if hasattr(other, 'dtype'): + if other.dtype.kind not in ['m', 'M']: + # raise rathering than letting numpy return wrong answer + return NotImplemented + return op(self.to_timedelta64(), other) + + if not self._validate_ops_compat(other): + return NotImplemented + + other = Timedelta(other) + if other is NaT: + return NaT + return Timedelta(op(self.value, other.value), unit='ns') + f.__name__ = name + return f - other = Timedelta(other) - if other is NaT: - return NaT - return Timedelta(self.value - other.value, unit='ns') + __add__ = _binary_op_method_timedeltalike(lambda x, y: x + y, '__add__') + __radd__ = _binary_op_method_timedeltalike(lambda x, y: x + y, '__radd__') + __sub__ = _binary_op_method_timedeltalike(lambda x, y: x - y, '__sub__') + __rsub__ = _binary_op_method_timedeltalike(lambda x, y: y - x, '__rsub__') def __mul__(self, other): + # nd-array like + if hasattr(other, 'dtype'): + return other * self.to_timedelta64() + if other is NaT: return NaT # only integers allowed if not is_integer_object(other): - raise TypeError("cannot multiply a Timedelta with {typ}".format(typ=type(other))) + return NotImplemented return Timedelta(other*self.value, unit='ns') @@ -1949,35 +1962,42 @@ class Timedelta(_Timedelta): def __truediv__(self, other): - # a timedelta64 IS an integer object as well - if is_timedelta64_object(other): - return self.value/float(_delta_to_nanoseconds(other)) + if hasattr(other, 'dtype'): + return self.to_timedelta64() / other # pure integers - elif is_integer_object(other): + if is_integer_object(other): return Timedelta(self.value/other, unit='ns') - self._validate_ops_compat(other,'__div__') + if not self._validate_ops_compat(other): + return NotImplemented other = Timedelta(other) if other is NaT: return NaT - return self.value/float(other.value) - def _make_invalid(opstr): + def __rtruediv__(self, other): + if hasattr(other, 'dtype'): + return other / self.to_timedelta64() - def _invalid(other): - raise TypeError("cannot perform {opstr} with {typ}".format(opstr=opstr,typ=type(other))) + if not self._validate_ops_compat(other): + return NotImplemented - __rtruediv__ = _make_invalid('__rtruediv__') + other = Timedelta(other) + if other is NaT: + return NaT + return float(other.value) / self.value if not PY3: __div__ = __truediv__ - __rdiv__ = _make_invalid('__rtruediv__') + __rdiv__ = __rtruediv__ + + def _not_implemented(self, *args, **kwargs): + return NotImplemented - __floordiv__ = _make_invalid('__floordiv__') - __rfloordiv__ = _make_invalid('__rfloordiv__') + __floordiv__ = _not_implemented + __rfloordiv__ = _not_implemented def _op_unary_method(func, name):
Fixes #8813 Fixes #5963 Fixes #5436 If the other argument has a dtype attribute, I assume that it is ndarray-like and convert the `Timedelta` into a `np.timedelta64` object. Alternatively, we could just return `NotImplemented` and let the other type handle it, but this has the bonus of making `Timedelta` compatible with ndarrays. I also added a `Timedelta.to_timedelta64()` method to the public API. I couldn't find a listing for `Timedelta` in the API docs -- we should probably add that, right? Next up would be a similar treatment for `Timestamp`. CC @immerrr
https://api.github.com/repos/pandas-dev/pandas/pulls/8884
2014-11-24T05:08:33Z
2014-11-26T02:30:02Z
2014-11-26T02:30:01Z
2014-11-26T10:45:31Z
REF: refactor **kwargs usage
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index fd9ef5d2e319a..73d6a17f4f2f3 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -913,7 +913,7 @@ def argsort(self, ascending=True, **kwargs): result = result[::-1] return result - def order(self, inplace=False, ascending=True, na_position='last', **kwargs): + def order(self, inplace=False, ascending=True, na_position='last'): """ Sorts the Category by category value returning a new Categorical by default. Only ordered Categoricals can be sorted! @@ -972,7 +972,7 @@ def order(self, inplace=False, ascending=True, na_position='last', **kwargs): name=self.name, fastpath=True) - def sort(self, inplace=True, ascending=True, na_position='last', **kwargs): + def sort(self, inplace=True, ascending=True, na_position='last'): """ Sorts the Category inplace by category value. Only ordered Categoricals can be sorted! @@ -997,7 +997,8 @@ def sort(self, inplace=True, ascending=True, na_position='last', **kwargs): -------- Category.order """ - return self.order(inplace=inplace, ascending=ascending, **kwargs) + return self.order(inplace=inplace, ascending=ascending, + na_position=na_position) def ravel(self, order='C'): """ Return a flattened (numpy) array. @@ -1033,7 +1034,7 @@ def to_dense(self): """ return np.asarray(self) - def fillna(self, fill_value=None, method=None, limit=None, **kwargs): + def fillna(self, fill_value=None, method=None, limit=None): """ Fill NA/NaN values using the specified method. Parameters diff --git a/pandas/core/common.py b/pandas/core/common.py index 4de63cf59bd1c..2298fbe4afc65 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -1559,7 +1559,7 @@ def backfill_2d(values, limit=None, mask=None, dtype=None): return values -def _clean_interp_method(method, order=None, **kwargs): +def _clean_interp_method(method, order=None): valid = ['linear', 'time', 'index', 'values', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'barycentric', 'polynomial', 'krogh', 'piecewise_polynomial', @@ -1574,7 +1574,7 @@ def _clean_interp_method(method, order=None, **kwargs): def interpolate_1d(xvalues, yvalues, method='linear', limit=None, - fill_value=None, bounds_error=False, **kwargs): + fill_value=None, bounds_error=False, order=None): """ Logic for the 1-d interpolation. The result should be 1-d, inputs xvalues and yvalues will each be 1-d arrays of the same length. @@ -1657,14 +1657,14 @@ def _interp_limit(invalid, limit): result[firstIndex:][invalid] = _interpolate_scipy_wrapper( valid_x, valid_y, new_x, method=method, fill_value=fill_value, - bounds_error=bounds_error, **kwargs) + bounds_error=bounds_error, order=order) if limit: result[violate_limit] = np.nan return result def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None, - bounds_error=False, order=None, **kwargs): + bounds_error=False, order=None): """ passed off to scipy.interpolate.interp1d. method is scipy's kind. Returns an array interpolated at new_x. Add any new methods to diff --git a/pandas/core/config.py b/pandas/core/config.py index b59e07251ce3e..e974689470c46 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -109,7 +109,11 @@ def _set_option(*args, **kwargs): "arguments") # default to false - silent = kwargs.get('silent', False) + silent = kwargs.pop('silent', False) + + if kwargs: + raise TypeError('_set_option() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) for k, v in zip(args[::2], args[1::2]): key = _get_single_key(k, silent) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 18500fd05b5f8..c5668f4979e64 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -267,7 +267,7 @@ def _construct_axes_from_arguments(self, args, kwargs, require_all=False): raise TypeError( "not enough/duplicate arguments specified!") - axes = dict([(a, kwargs.get(a)) for a in self._AXIS_ORDERS]) + axes = dict([(a, kwargs.pop(a, None)) for a in self._AXIS_ORDERS]) return axes, kwargs @classmethod @@ -444,8 +444,13 @@ def transpose(self, *args, **kwargs): new_axes = self._construct_axes_dict_from( self, [self._get_axis(x) for x in axes_names]) new_values = self.values.transpose(axes_numbers) - if kwargs.get('copy') or (len(args) and args[-1]): + if kwargs.pop('copy', None) or (len(args) and args[-1]): new_values = new_values.copy() + + if kwargs: + raise TypeError('transpose() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) + return self._constructor(new_values, **new_axes).__finalize__(self) def swapaxes(self, axis1, axis2, copy=True): @@ -540,8 +545,12 @@ def swaplevel(self, i, j, axis=0): def rename(self, *args, **kwargs): axes, kwargs = self._construct_axes_from_arguments(args, kwargs) - copy = kwargs.get('copy', True) - inplace = kwargs.get('inplace', False) + copy = kwargs.pop('copy', True) + inplace = kwargs.pop('inplace', False) + + if kwargs: + raise TypeError('rename() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) if (com._count_not_none(*axes.values()) == 0): raise TypeError('must pass an index to rename') @@ -1531,10 +1540,12 @@ def reindex_like(self, other, method=None, copy=True, limit=None): ------- reindexed : same as input """ - d = other._construct_axes_dict(method=method, copy=copy, limit=limit) + d = other._construct_axes_dict(axes=self._AXIS_ORDERS, + method=method, copy=copy, limit=limit) + return self.reindex(**d) - def drop(self, labels, axis=0, level=None, inplace=False, **kwargs): + def drop(self, labels, axis=0, level=None, inplace=False): """ Return new object with labels in requested axis removed @@ -1708,11 +1719,15 @@ def reindex(self, *args, **kwargs): # construct the args axes, kwargs = self._construct_axes_from_arguments(args, kwargs) - method = com._clean_reindex_fill_method(kwargs.get('method')) - level = kwargs.get('level') - copy = kwargs.get('copy', True) - limit = kwargs.get('limit') - fill_value = kwargs.get('fill_value', np.nan) + method = com._clean_reindex_fill_method(kwargs.pop('method', None)) + level = kwargs.pop('level', None) + copy = kwargs.pop('copy', True) + limit = kwargs.pop('limit', None) + fill_value = kwargs.pop('fill_value', np.nan) + + if kwargs: + raise TypeError('reindex() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) self._consolidate_inplace() @@ -1917,7 +1932,7 @@ def tail(self, n=5): #---------------------------------------------------------------------- # Attribute access - def __finalize__(self, other, method=None, **kwargs): + def __finalize__(self, other, method=None): """ propagate metadata from other to self @@ -3422,7 +3437,7 @@ def shift(self, periods=1, freq=None, axis=0, **kwds): return self._constructor(new_data).__finalize__(self) - def slice_shift(self, periods=1, axis=0, **kwds): + def slice_shift(self, periods=1, axis=0): """ Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the shifted axis will be smaller @@ -4053,7 +4068,7 @@ def logical_func(self, axis=None, bool_only=None, skipna=None, desc="Return the mean absolute deviation of the values " "for the requested axis") @Appender(_num_doc) - def mad(self, axis=None, skipna=None, level=None, **kwargs): + def mad(self, axis=None, skipna=None, level=None): if skipna is None: skipna = True if axis is None: @@ -4111,7 +4126,7 @@ def stat_func(self, axis=None, skipna=None, level=None, ddof=1, desc="Return the compound percentage of the values for " "the requested axis") @Appender(_num_doc) - def compound(self, axis=None, skipna=None, level=None, **kwargs): + def compound(self, axis=None, skipna=None, level=None): if skipna is None: skipna = True return (1 + self).prod(axis=axis, skipna=skipna, level=level) - 1 diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 0be046bbdec42..d2d40f01c99a4 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -910,7 +910,7 @@ def nth(self, n, dropna=None): return result - def cumcount(self, **kwargs): + def cumcount(self, ascending=True): """ Number each item in each group from 0 to the length of that group - 1. @@ -955,7 +955,6 @@ def cumcount(self, **kwargs): """ self._set_selection_from_grouper() - ascending = kwargs.pop('ascending', True) index = self._selected_obj.index cumcounts = self._cumcount_array(ascending=ascending) @@ -1016,15 +1015,13 @@ def tail(self, n=5): tail = obj[in_tail] return tail - def _cumcount_array(self, arr=None, **kwargs): + def _cumcount_array(self, arr=None, ascending=True): """ arr is where cumcount gets its values from note: this is currently implementing sort=False (though the default is sort=True) for groupby in general """ - ascending = kwargs.pop('ascending', True) - if arr is None: arr = np.arange(self.grouper._max_groupsize, dtype='int64') @@ -3094,7 +3091,7 @@ def filter(self, func, dropna=True, *args, **kwargs): for name, group in gen: object.__setattr__(group, 'name', name) - res = func(group) + res = func(group, *args, **kwargs) try: res = res.squeeze() diff --git a/pandas/core/index.py b/pandas/core/index.py index 0cad537855857..da94a8d64aab4 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -415,7 +415,7 @@ def __unicode__(self): quote_strings=True) return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype) - def to_series(self, **kwargs): + def to_series(self): """ Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index @@ -1604,7 +1604,7 @@ def _get_nearest_indexer(self, target, limit): left_indexer, right_indexer) return indexer - def get_indexer_non_unique(self, target, **kwargs): + def get_indexer_non_unique(self, target): """ return an indexer suitable for taking from a non unique index return the labels in the same order as the target, and return a missing indexer into the target (missing are marked as -1 @@ -3766,7 +3766,7 @@ def append(self, other): return Index(new_tuples) def argsort(self, *args, **kwargs): - return self.values.argsort() + return self.values.argsort(*args, **kwargs) def repeat(self, n): return MultiIndex(levels=self.levels, diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 4453c7eaf1fda..d5c39a8e2a5cf 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -278,7 +278,7 @@ def delete(self, loc): def apply(self, func, **kwargs): """ apply the function to my values; return a block if we are not one """ - result = func(self.values) + result = func(self.values, **kwargs) if not isinstance(result, Block): result = make_block(values=_block_shape(result), placement=self.mgr_locs,) diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 2b2d28d62f758..f77ed59df8ac1 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -145,7 +145,12 @@ def _init_data(self, data, copy, dtype, **kwargs): if dtype is not None: dtype = self._validate_dtype(dtype) - passed_axes = [kwargs.get(a) for a in self._AXIS_ORDERS] + passed_axes = [kwargs.pop(a, None) for a in self._AXIS_ORDERS] + + if kwargs: + raise TypeError('_init_data() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) + axes = None if isinstance(data, BlockManager): if any(x is not None for x in passed_axes): @@ -471,7 +476,11 @@ def get_value(self, *args, **kwargs): raise TypeError('There must be an argument for each axis, you gave' ' {0} args, but {1} are required'.format(nargs, nreq)) - takeable = kwargs.get('takeable') + takeable = kwargs.pop('takeable', None) + + if kwargs: + raise TypeError('get_value() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) if takeable is True: lower = self._iget_item_cache(args[0]) @@ -506,7 +515,11 @@ def set_value(self, *args, **kwargs): raise TypeError('There must be an argument for each axis plus the ' 'value provided, you gave {0} args, but {1} are ' 'required'.format(nargs, nreq)) - takeable = kwargs.get('takeable') + takeable = kwargs.pop('takeable', None) + + if kwargs: + raise TypeError('set_value() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) try: if takeable is True: @@ -607,7 +620,7 @@ def _needs_reindex_multi(self, axes, method, level): """ don't allow a multi reindex on Panel or above ndim """ return False - def dropna(self, axis=0, how='any', inplace=False, **kwargs): + def dropna(self, axis=0, how='any', inplace=False): """ Drop 2D from panel, holding passed axis constant @@ -1065,7 +1078,7 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None, return self._construct_return_type(result, axes) - def _construct_return_type(self, result, axes=None, **kwargs): + def _construct_return_type(self, result, axes=None): """ return the type for the ndim of the result """ ndim = getattr(result,'ndim',None) diff --git a/pandas/core/series.py b/pandas/core/series.py index 901faef484377..a929b8eeba74d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2374,6 +2374,11 @@ def dropna(self, axis=0, inplace=False, **kwargs): inplace : boolean, default False Do operation in place. """ + kwargs.pop('how', None) + if kwargs: + raise TypeError('dropna() got an unexpected keyword ' + 'argument "{0}"'.format(list(kwargs.keys())[0])) + axis = self._get_axis_number(axis or 0) result = remove_na(self) if inplace: diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index 40d6d2151155a..3dd8c2594cd46 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -369,6 +369,26 @@ def test_split_compat(self): self.assertTrue(len(np.array_split(o,5)) == 5) self.assertTrue(len(np.array_split(o,2)) == 2) + def test_unexpected_keyword(self): # GH8597 + from pandas.util.testing import assertRaisesRegexp + + df = DataFrame(np.random.randn(5, 2), columns=['jim', 'joe']) + ca = pd.Categorical([0, 0, 2, 2, 3, np.nan]) + ts = df['joe'].copy() + ts[2] = np.nan + + with assertRaisesRegexp(TypeError, 'unexpected keyword'): + df.drop('joe', axis=1, in_place=True) + + with assertRaisesRegexp(TypeError, 'unexpected keyword'): + df.reindex([1, 0], inplace=True) + + with assertRaisesRegexp(TypeError, 'unexpected keyword'): + ca.fillna(0, inplace=True) + + with assertRaisesRegexp(TypeError, 'unexpected keyword'): + ts.fillna(0, in_place=True) + class TestSeries(tm.TestCase, Generic): _typ = Series _comparator = lambda self, x, y: assert_series_equal(x,y) @@ -602,7 +622,7 @@ def test_interp_scipy_basic(self): result = s.interpolate(method='slinear') assert_series_equal(result, expected) - result = s.interpolate(method='slinear', donwcast='infer') + result = s.interpolate(method='slinear', downcast='infer') assert_series_equal(result, expected) # nearest expected = Series([1, 3, 3, 12, 12, 25]) diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 9534bc5dd2e7c..9498c7e1207c3 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -4708,26 +4708,6 @@ def test_regression_whitelist_methods(self) : expected = getattr(frame,op)(level=level,axis=axis) assert_frame_equal(result, expected) - def test_regression_kwargs_whitelist_methods(self): - # GH8733 - - 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=['first', 'second']) - raw_frame = DataFrame(np.random.randn(10, 3), index=index, - columns=Index(['A', 'B', 'C'], name='exp')) - - grouped = raw_frame.groupby(level=0, axis=1) - grouped.all(test_kwargs='Test kwargs') - grouped.any(test_kwargs='Test kwargs') - grouped.cumcount(test_kwargs='Test kwargs') - grouped.mad(test_kwargs='Test kwargs') - grouped.cummin(test_kwargs='Test kwargs') - grouped.skew(test_kwargs='Test kwargs') - grouped.cumprod(test_kwargs='Test kwargs') - def test_groupby_blacklist(self): from string import ascii_lowercase letters = np.array(list(ascii_lowercase))
related issue: https://github.com/pydata/pandas/issues/8597. among changes: [tests/test_generic.py](https://github.com/pydata/pandas/blob/0a2ea0ac39a74771d54b91522728f6092b0ef897/pandas/tests/test_generic.py#L603) `downcast` is misspelled `donwcast`, but no error is raised, because of how `**kwargs` is used. [core/categorical.py:sort](https://github.com/pydata/pandas/blob/0a2ea0ac39a74771d54b91522728f6092b0ef897/pandas/core/categorical.py#L945) `na_position` is not passed to `self.order`. [core/categorical.py:fillna](https://github.com/pydata/pandas/blob/0a2ea0ac39a74771d54b91522728f6092b0ef897/pandas/core/categorical.py#L981) `Categorical.fillna` does not support `inplace` as opposed to say `Series.fillna` or `DataFrame.fillna`, but `**kwargs` being there causes below code to just silently ignore passed argument: ``` >>> ca = pd.Categorical([0, 0, 2, 2, 3, np.nan]) >>> ca.fillna(0, inplace=True) [0, 0, 2, 2, 3, 0] Categories (3, int64): [0 < 2 < 3] >>> ca [0, 0, 2, 2, 3, NaN] Categories (3, int64): [0 < 2 < 3] ``` [This test](https://github.com/pydata/pandas/blob/0a2ea0ac39a74771d54b91522728f6092b0ef897/pandas/tests/test_groupby.py#L4418) is basically testing that you can specify _any_ keyword argument and it is just silently ignored. I cannot think of any case that this would be a good idea, or has any use case. multiple instances where `*args` or `*kwargs` are not passed to inner function or have any use at all, as can be seen in the PR diff.
https://api.github.com/repos/pandas-dev/pandas/pulls/8883
2014-11-23T22:20:35Z
2015-03-04T20:42:39Z
null
2015-03-05T12:46:51Z
DOC: Add Nano to offsets table
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index 7b0b0fdf624e8..ac3302ae40fa7 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -487,7 +487,7 @@ frequency increment. Specific offset logic like "month", "business day", or Second, "one second" Milli, "one millisecond" Micro, "one microsecond" - + Nano, "one nanosecond" The basic ``DateOffset`` takes the same arguments as ``dateutil.relativedelta``, which works like:
https://api.github.com/repos/pandas-dev/pandas/pulls/8879
2014-11-22T13:31:42Z
2014-11-22T16:48:54Z
2014-11-22T16:48:54Z
2014-11-22T21:16:26Z
DOC: Suppress warnings in visualization.rst
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst index 7f8d0e529fc8b..6bef7f6f456c8 100644 --- a/doc/source/visualization.rst +++ b/doc/source/visualization.rst @@ -387,7 +387,6 @@ The existing interface ``DataFrame.boxplot`` to plot boxplot still can be used. np.random.seed(123456) .. ipython:: python - :okwarning: df = DataFrame(rand(10,5)) plt.figure(); @@ -1271,7 +1270,7 @@ or columns needed, given the other. .. ipython:: python @savefig frame_plot_subplots_layout.png - df.plot(subplots=True, layout=(3, 2), figsize=(6, 6), sharex=False); + df.plot(subplots=True, layout=(2, 3), figsize=(6, 6), sharex=False); .. ipython:: python :suppress: @@ -1282,22 +1281,23 @@ The above example is identical to using .. ipython:: python - df.plot(subplots=True, layout=(3, -1), figsize=(6, 6), sharex=False); + df.plot(subplots=True, layout=(2, -1), figsize=(6, 6), sharex=False); .. ipython:: python :suppress: plt.close('all') -The required number of columns (2) is inferred from the number of series to plot -and the given number of rows (3). +The required number of columns (3) is inferred from the number of series to plot +and the given number of rows (2). Also, you can pass multiple axes created beforehand as list-like via ``ax`` keyword. This allows to use more complicated layout. The passed axes must be the same number as the subplots being drawn. -When multiple axes are passed via ``ax`` keyword, ``layout``, ``sharex`` and ``sharey`` keywords are ignored. -These must be configured when creating axes. +When multiple axes are passed via ``ax`` keyword, ``layout``, ``sharex`` and ``sharey`` keywords +don't affect to the output. You should explicitly pass ``sharex=False`` and ``sharey=False``, +otherwise you will see a warning. .. ipython:: python @@ -1306,9 +1306,9 @@ These must be configured when creating axes. target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]] target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]] - df.plot(subplots=True, ax=target1, legend=False); + df.plot(subplots=True, ax=target1, legend=False, sharex=False, sharey=False); @savefig frame_plot_subplots_multi_ax.png - (-df).plot(subplots=True, ax=target2, legend=False); + (-df).plot(subplots=True, ax=target2, legend=False, sharex=False, sharey=False); .. ipython:: python :suppress: diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index 4195baf4874f1..591ef8081d878 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -5,6 +5,7 @@ import itertools import os import string +import warnings from distutils.version import LooseVersion from datetime import datetime, date @@ -1297,12 +1298,12 @@ def test_subplots_multiple_axes(self): df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10])) - returned = df.plot(subplots=True, ax=axes[0]) + returned = df.plot(subplots=True, ax=axes[0], sharex=False, sharey=False) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) self.assertEqual(returned.shape, (3, )) self.assertIs(returned[0].figure, fig) # draw on second row - returned = df.plot(subplots=True, ax=axes[1]) + returned = df.plot(subplots=True, ax=axes[1], sharex=False, sharey=False) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) self.assertEqual(returned.shape, (3, )) self.assertIs(returned[0].figure, fig) @@ -1319,18 +1320,23 @@ def test_subplots_multiple_axes(self): # (show warning is tested in # TestDataFrameGroupByPlots.test_grouped_box_multiple_axes fig, axes = self.plt.subplots(2, 2) - df = DataFrame(np.random.rand(10, 4), - index=list(string.ascii_letters[:10])) - - returned = df.plot(subplots=True, ax=axes, layout=(2, 1)) - self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) - self.assertEqual(returned.shape, (4, )) - - returned = df.plot(subplots=True, ax=axes, layout=(2, -1)) - self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) - self.assertEqual(returned.shape, (4, )) - - returned = df.plot(subplots=True, ax=axes, layout=(-1, 2)) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + df = DataFrame(np.random.rand(10, 4), + index=list(string.ascii_letters[:10])) + + returned = df.plot(subplots=True, ax=axes, layout=(2, 1), + sharex=False, sharey=False) + self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) + self.assertEqual(returned.shape, (4, )) + + returned = df.plot(subplots=True, ax=axes, layout=(2, -1), + sharex=False, sharey=False) + self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) + self.assertEqual(returned.shape, (4, )) + + returned = df.plot(subplots=True, ax=axes, layout=(-1, 2), + sharex=False, sharey=False) self._check_axes_shape(returned, axes_num=4, layout=(2, 2)) self.assertEqual(returned.shape, (4, )) @@ -1338,7 +1344,8 @@ def test_subplots_multiple_axes(self): fig, axes = self.plt.subplots(1, 1) df = DataFrame(np.random.rand(10, 1), index=list(string.ascii_letters[:10])) - axes = df.plot(subplots=True, ax=[axes]) + + axes = df.plot(subplots=True, ax=[axes], sharex=False, sharey=False) self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) self.assertEqual(axes.shape, (1, )) @@ -3122,13 +3129,14 @@ class TestDataFrameGroupByPlots(TestPlotBase): @slow def test_boxplot(self): grouped = self.hist_df.groupby(by='gender') - axes = _check_plot_works(grouped.boxplot, return_type='axes') + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + axes = _check_plot_works(grouped.boxplot, return_type='axes') self._check_axes_shape(list(axes.values()), axes_num=2, layout=(1, 2)) axes = _check_plot_works(grouped.boxplot, subplots=False, return_type='axes') self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) - tuples = lzip(string.ascii_letters[:10], range(10)) df = DataFrame(np.random.rand(10, 3), index=MultiIndex.from_tuples(tuples)) @@ -3149,6 +3157,30 @@ def test_boxplot(self): return_type='axes') self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + @slow + def test_grouped_plot_fignums(self): + n = 10 + weight = Series(np.random.normal(166, 20, size=n)) + height = Series(np.random.normal(60, 10, size=n)) + with tm.RNGContext(42): + gender = tm.choice(['male', 'female'], size=n) + df = DataFrame({'height': height, 'weight': weight, 'gender': gender}) + gb = df.groupby('gender') + + res = gb.plot() + self.assertEqual(len(self.plt.get_fignums()), 2) + self.assertEqual(len(res), 2) + tm.close() + + res = gb.boxplot(return_type='axes') + self.assertEqual(len(self.plt.get_fignums()), 1) + self.assertEqual(len(res), 2) + tm.close() + + # now works with GH 5610 as gender is excluded + res = df.groupby('gender').hist() + tm.close() + def test_series_plot_color_kwargs(self): # GH1890 ax = Series(np.arange(12) + 1).plot(color='green') @@ -3219,6 +3251,21 @@ def test_grouped_hist(self): with tm.assert_produces_warning(FutureWarning): df.hist(by='C', figsize='default') + @slow + def test_grouped_hist2(self): + n = 10 + weight = Series(np.random.normal(166, 20, size=n)) + height = Series(np.random.normal(60, 10, size=n)) + with tm.RNGContext(42): + gender_int = tm.choice([0, 1], size=n) + df_int = DataFrame({'height': height, 'weight': weight, + 'gender': gender_int}) + gb = df_int.groupby('gender') + axes = gb.hist() + self.assertEqual(len(axes), 2) + self.assertEqual(len(self.plt.get_fignums()), 2) + tm.close() + @slow def test_grouped_box_return_type(self): df = self.hist_df @@ -3334,15 +3381,21 @@ def test_grouped_box_multiple_axes(self): self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(2, 2)) fig, axes = self.plt.subplots(2, 3) - returned = df.boxplot(column=['height', 'weight', 'category'], by='gender', - return_type='axes', ax=axes[0]) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + returned = df.boxplot(column=['height', 'weight', 'category'], + by='gender', return_type='axes', ax=axes[0]) returned = np.array(list(returned.values())) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) self.assert_numpy_array_equal(returned, axes[0]) self.assertIs(returned[0].figure, fig) + # draw on second row - returned = df.groupby('classroom').boxplot(column=['height', 'weight', 'category'], - return_type='axes', ax=axes[1]) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + returned = df.groupby('classroom').boxplot( + column=['height', 'weight', 'category'], + return_type='axes', ax=axes[1]) returned = np.array(list(returned.values())) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) self.assert_numpy_array_equal(returned, axes[1]) @@ -3469,6 +3522,32 @@ def test_invalid_colormap(self): with tm.assertRaises(ValueError): df.plot(colormap='invalid_colormap') + def test_series_groupby_plotting_nominally_works(self): + n = 10 + weight = Series(np.random.normal(166, 20, size=n)) + height = Series(np.random.normal(60, 10, size=n)) + with tm.RNGContext(42): + gender = tm.choice(['male', 'female'], size=n) + + weight.groupby(gender).plot() + tm.close() + height.groupby(gender).hist() + tm.close() + #Regression test for GH8733 + height.groupby(gender).plot(alpha=0.5) + tm.close() + + def test_plotting_with_float_index_works(self): + # GH 7025 + df = DataFrame({'def': [1,1,1,2,2,2,3,3,3], + 'val': np.random.randn(9)}, + index=[1.0,2.0,3.0,1.0,2.0,3.0,1.0,2.0,3.0]) + + df.groupby('def')['val'].plot() + tm.close() + df.groupby('def')['val'].apply(lambda x: x.plot()) + tm.close() + def assert_is_valid_plot_return_object(objs): import matplotlib.pyplot as plt diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 1d309e2a6389f..a9c3d47656ee5 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -35,11 +35,6 @@ import pandas as pd from numpy.testing import assert_equal -def _skip_if_mpl_not_installed(): - try: - import matplotlib.pyplot as plt - except ImportError: - raise nose.SkipTest("matplotlib not installed") def commonSetUp(self): self.dateRange = bdate_range('1/1/2005', periods=250) @@ -4653,88 +4648,6 @@ def test_groupby_blacklist(self): with tm.assertRaisesRegexp(AttributeError, msg): getattr(gb, bl) - def test_series_groupby_plotting_nominally_works(self): - _skip_if_mpl_not_installed() - - n = 10 - weight = Series(np.random.normal(166, 20, size=n)) - height = Series(np.random.normal(60, 10, size=n)) - with tm.RNGContext(42): - gender = tm.choice(['male', 'female'], size=n) - - weight.groupby(gender).plot() - tm.close() - height.groupby(gender).hist() - tm.close() - #Regression test for GH8733 - height.groupby(gender).plot(alpha=0.5) - tm.close() - - def test_plotting_with_float_index_works(self): - _skip_if_mpl_not_installed() - - # GH 7025 - df = DataFrame({'def': [1,1,1,2,2,2,3,3,3], - 'val': np.random.randn(9)}, - index=[1.0,2.0,3.0,1.0,2.0,3.0,1.0,2.0,3.0]) - - df.groupby('def')['val'].plot() - tm.close() - df.groupby('def')['val'].apply(lambda x: x.plot()) - tm.close() - - @slow - def test_frame_groupby_plot_boxplot(self): - _skip_if_mpl_not_installed() - - import matplotlib.pyplot as plt - import matplotlib as mpl - mpl.use('Agg') - tm.close() - - n = 10 - weight = Series(np.random.normal(166, 20, size=n)) - height = Series(np.random.normal(60, 10, size=n)) - with tm.RNGContext(42): - gender = tm.choice(['male', 'female'], size=n) - df = DataFrame({'height': height, 'weight': weight, 'gender': gender}) - gb = df.groupby('gender') - - res = gb.plot() - self.assertEqual(len(plt.get_fignums()), 2) - self.assertEqual(len(res), 2) - tm.close() - - res = gb.boxplot() - self.assertEqual(len(plt.get_fignums()), 1) - self.assertEqual(len(res), 2) - tm.close() - - # now works with GH 5610 as gender is excluded - res = df.groupby('gender').hist() - tm.close() - - @slow - def test_frame_groupby_hist(self): - _skip_if_mpl_not_installed() - import matplotlib.pyplot as plt - import matplotlib as mpl - mpl.use('Agg') - tm.close() - - n = 10 - weight = Series(np.random.normal(166, 20, size=n)) - height = Series(np.random.normal(60, 10, size=n)) - with tm.RNGContext(42): - gender_int = tm.choice([0, 1], size=n) - df_int = DataFrame({'height': height, 'weight': weight, - 'gender': gender_int}) - gb = df_int.groupby('gender') - axes = gb.hist() - self.assertEqual(len(axes), 2) - self.assertEqual(len(plt.get_fignums()), 2) - tm.close() - def test_tab_completion(self): grp = self.mframe.groupby(level='second') results = set([v for v in dir(grp) if not v.startswith('_')])
Closes #8234. Sorry to take a long. I understand there are 2 warnings: 1. Warning in /Users/sin/Documents/Git/pandas/doc/source/visualization.rst at block ending on line 1275 This is raised from `mpl` as plotting empty axes for demonstration purpose. Thus simply suppressed. 2. Warning in /Users/sin/Documents/Git/pandas/doc/source/visualization.rst at block ending on line 1312 This is a warning displayed when passing multiple axes. Added explanations.
https://api.github.com/repos/pandas-dev/pandas/pulls/8877
2014-11-22T04:28:48Z
2015-02-12T14:22:59Z
2015-02-12T14:22:59Z
2015-02-15T01:33:27Z
DOC: Add where and mask to API doc
diff --git a/doc/source/api.rst b/doc/source/api.rst index 079cf152095c5..d2f94c22f0335 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -394,6 +394,8 @@ Reindexing / Selection / Label manipulation Series.take Series.tail Series.truncate + Series.where + Series.mask Missing data handling ~~~~~~~~~~~~~~~~~~~~~ @@ -689,6 +691,8 @@ Indexing, iteration DataFrame.tail DataFrame.xs DataFrame.isin + DataFrame.where + DataFrame.mask DataFrame.query For more information on ``.at``, ``.iat``, ``.ix``, ``.loc``, and
https://api.github.com/repos/pandas-dev/pandas/pulls/8876
2014-11-22T02:54:48Z
2014-11-22T16:49:21Z
2014-11-22T16:49:21Z
2014-11-22T21:16:17Z
BUG: missing nose import for skip test
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index 47f9762eb0fa3..3e8534762ec05 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -27,6 +27,8 @@ option_context, reset_option) from datetime import datetime +import nose + _frame = DataFrame(tm.getSeriesData()) @@ -1190,7 +1192,6 @@ def test_frame_info_encoding(self): fmt.set_option('display.max_rows', 200) def test_pprint_thing(self): - import nose from pandas.core.common import pprint_thing as pp_t if PY3: @@ -3036,6 +3037,5 @@ def test_tz_dateutil(self): self.assertEqual(str(dt_datetime_us), str(Timestamp(dt_datetime_us))) if __name__ == '__main__': - import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
nose.SkipTest used but nose not imported.
https://api.github.com/repos/pandas-dev/pandas/pulls/8867
2014-11-21T02:24:20Z
2014-11-21T14:05:11Z
2014-11-21T14:05:11Z
2014-11-21T14:05:16Z
DOC: Clean up Stata documentation
diff --git a/doc/source/io.rst b/doc/source/io.rst index 9686a72d43cf8..bf8776d4bc396 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3670,22 +3670,27 @@ into a .dta file. The format version of this file is always 115 (Stata 12). df.to_stata('stata.dta') *Stata* data files have limited data type support; only strings with 244 or -fewer characters, ``int8``, ``int16``, ``int32`` and ``float64`` can be stored -in ``.dta`` files. *Stata* reserves certain values to represent -missing data. Furthermore, when a value is encountered outside of the -permitted range, the data type is upcast to the next larger size. For -example, ``int8`` values are restricted to lie between -127 and 100, and so -variables with values above 100 will trigger a conversion to ``int16``. ``nan`` -values in floating points data types are stored as the basic missing data type -(``.`` in *Stata*). It is not possible to indicate missing data values for -integer data types. +fewer characters, ``int8``, ``int16``, ``int32``, ``float32` and ``float64`` +can be stored +in ``.dta`` files. Additionally, *Stata* reserves certain values to represent +missing data. Exporting a non-missing value that is outside of the +permitted range in Stata for a particular data type will retype the variable +to the next larger size. For example, ``int8`` values are restricted to lie +between -127 and 100 in Stata, and so variables with values above 100 will +trigger a conversion to ``int16``. ``nan`` values in floating points data +types are stored as the basic missing data type (``.`` in *Stata*). + +.. note:: + + It is not possible to export missing data values for integer data types. + The *Stata* writer gracefully handles other data types including ``int64``, -``bool``, ``uint8``, ``uint16``, ``uint32`` and ``float32`` by upcasting to +``bool``, ``uint8``, ``uint16``, ``uint32`` by casting to the smallest supported type that can represent the data. For example, data with a type of ``uint8`` will be cast to ``int8`` if all values are less than 100 (the upper bound for non-missing ``int8`` data in *Stata*), or, if values are -outside of this range, the data is cast to ``int16``. +outside of this range, the variable is cast to ``int16``. .. warning:: @@ -3701,50 +3706,41 @@ outside of this range, the data is cast to ``int16``. 115 dta file format. Attempting to write *Stata* dta files with strings longer than 244 characters raises a ``ValueError``. -.. warning:: - - *Stata* data files only support text labels for categorical data. Exporting - data frames containing categorical data will convert non-string categorical values - to strings. - -Writing data to/from Stata format files with a ``category`` dtype was implemented in 0.15.2. - .. _io.stata_reader: -Reading from STATA format +Reading from Stata format ~~~~~~~~~~~~~~~~~~~~~~~~~ -The top-level function ``read_stata`` will read a dta format file -and return a DataFrame: -The class :class:`~pandas.io.stata.StataReader` will read the header of the -given dta file at initialization. Its method -:func:`~pandas.io.stata.StataReader.data` will read the observations, -converting them to a DataFrame which is returned: +The top-level function ``read_stata`` will read a dta files +and return a DataFrame. Alternatively, the class :class:`~pandas.io.stata.StataReader` +can be used if more granular access is required. :class:`~pandas.io.stata.StataReader` +reads the header of the dta file at initialization. The method +:func:`~pandas.io.stata.StataReader.data` reads and converts observations to a DataFrame. .. ipython:: python pd.read_stata('stata.dta') -Currently the ``index`` is retrieved as a column on read back. +Currently the ``index`` is retrieved as a column. The parameter ``convert_categoricals`` indicates whether value labels should be read and used to create a ``Categorical`` variable from them. Value labels can also be retrieved by the function ``variable_labels``, which requires data to be -called before (see ``pandas.io.stata.StataReader``). +called before use (see ``pandas.io.stata.StataReader``). The parameter ``convert_missing`` indicates whether missing value representations in Stata should be preserved. If ``False`` (the default), missing values are represented as ``np.nan``. If ``True``, missing values are represented using ``StataMissingValue`` objects, and columns containing missing -values will have ``dtype`` set to ``object``. +values will have ```object`` data type. -The StataReader supports .dta Formats 104, 105, 108, 113-115 and 117. -Alternatively, the function :func:`~pandas.io.stata.read_stata` can be used +:func:`~pandas.read_stata` and :class:`~pandas.io.stata.StataReader` supports .dta +formats 104, 105, 108, 113-115 (Stata 10-12) and 117 (Stata 13+). .. note:: - Setting ``preserve_dtypes=False`` will upcast all integer data types to - ``int64`` and all floating point data types to ``float64``. By default, + Setting ``preserve_dtypes=False`` will upcast to the standard pandas data types: + ``int64`` for all integer types and ``float64`` for floating poitn data. By default, the Stata data types are preserved when importing. .. ipython:: python @@ -3775,14 +3771,13 @@ is lost when exporting. Labeled data can similarly be imported from *Stata* data files as ``Categorical`` variables using the keyword argument ``convert_categoricals`` (``True`` by default). -By default, imported ``Categorical`` variables are ordered according to the -underlying numerical data. However, setting ``order_categoricals=False`` will -import labeled data as ``Categorical`` variables without an order. +The keyword argument ``order_categoricals`` (``True`` by default) determines + whether imported ``Categorical`` variables are ordered. .. note:: When importing categorical data, the values of the variables in the *Stata* - data file are not generally preserved since ``Categorical`` variables always + data file are not preserved since ``Categorical`` variables always use integer data types between ``-1`` and ``n-1`` where ``n`` is the number of categories. If the original values in the *Stata* data file are required, these can be imported by setting ``convert_categoricals=False``, which will @@ -3795,7 +3790,7 @@ import labeled data as ``Categorical`` variables without an order. .. note:: - *Stata* suppots partially labeled series. These series have value labels for + *Stata* supports partially labeled series. These series have value labels for some but not all data values. Importing a partially labeled series will produce a ``Categorial`` with string categories for the values that are labeled and numeric categories for values with no label.
Clean up and simplification of Stata documentation.
https://api.github.com/repos/pandas-dev/pandas/pulls/8858
2014-11-19T16:21:09Z
2014-11-20T07:38:44Z
2014-11-20T07:38:44Z
2015-06-04T20:46:57Z
Clarify encoding kwarg on to_csv
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0ea53920ffe3c..237012a71aeb4 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1137,8 +1137,8 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, mode : str Python write mode, default 'w' encoding : string, optional - a string representing the encoding to use if the contents are - non-ascii, for python versions prior to 3 + A string representing the encoding to use in the output file, + defaults to 'ascii' on Python 2 and 'utf-8' on Python 3. line_terminator : string, default '\\n' The newline character or character sequence to use in the output file
https://api.github.com/repos/pandas-dev/pandas/pulls/8857
2014-11-19T16:04:43Z
2014-11-20T10:58:48Z
2014-11-20T10:58:48Z
2014-11-20T11:15:00Z
BUG: DataFrame.stack(..., dropna=False) with partial MultiIndex.
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 8d6e3cb0512b4..ef1a9c011d19c 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -113,7 +113,8 @@ Bug Fixes - Bug where ``get_data_google``returned object dtypes (:issue:`3995`) - +- Bug in ``DataFrame.stack(..., dropna=False)`` when the DataFrame's ``columns`` is a ``MultiIndex`` + whose ``labels`` do not reference all its ``levels``. (:issue:`8844`) diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py index d576f788a831f..5ed823d690028 100644 --- a/pandas/core/reshape.py +++ b/pandas/core/reshape.py @@ -648,7 +648,9 @@ def _convert_level_number(level_num, columns): # time to ravel the values new_data = {} level_vals = this.columns.levels[-1] - levsize = len(level_vals) + level_labels = sorted(set(this.columns.labels[-1])) + level_vals_used = level_vals[level_labels] + levsize = len(level_labels) drop_cols = [] for key in unique_groups: loc = this.columns.get_loc(key) @@ -661,7 +663,7 @@ def _convert_level_number(level_num, columns): elif slice_len != levsize: chunk = this.ix[:, this.columns[loc]] chunk.columns = level_vals.take(chunk.columns.labels[-1]) - value_slice = chunk.reindex(columns=level_vals).values + value_slice = chunk.reindex(columns=level_vals_used).values else: if frame._is_mixed_type: value_slice = this.ix[:, this.columns[loc]].values @@ -685,7 +687,7 @@ def _convert_level_number(level_num, columns): new_names = [this.index.name] # something better? new_levels.append(frame.columns.levels[level_num]) - new_labels.append(np.tile(np.arange(levsize), N)) + new_labels.append(np.tile(level_labels, N)) new_names.append(frame.columns.names[level_num]) new_index = MultiIndex(levels=new_levels, labels=new_labels, diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index fc031afe728dc..b1d6ce4cf19ae 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -12266,6 +12266,56 @@ def test_stack_datetime_column_multiIndex(self): expected = DataFrame([1, 2, 3, 4], index=eidx, columns=ecols) assert_frame_equal(result, expected) + def test_stack_partial_multiIndex(self): + # GH 8844 + def _test_stack_with_multiindex(multiindex): + df = DataFrame(np.arange(3 * len(multiindex)).reshape(3, len(multiindex)), + columns=multiindex) + for level in (-1, 0, 1, [0, 1], [1, 0]): + result = df.stack(level=level, dropna=False) + + if isinstance(level, int): + # Stacking a single level should not make any all-NaN rows, + # so df.stack(level=level, dropna=False) should be the same + # as df.stack(level=level, dropna=True). + expected = df.stack(level=level, dropna=True) + if isinstance(expected, Series): + assert_series_equal(result, expected) + else: + assert_frame_equal(result, expected) + + df.columns = MultiIndex.from_tuples(df.columns.get_values(), + names=df.columns.names) + expected = df.stack(level=level, dropna=False) + if isinstance(expected, Series): + assert_series_equal(result, expected) + else: + assert_frame_equal(result, expected) + + full_multiindex = MultiIndex.from_tuples([('B', 'x'), ('B', 'z'), + ('A', 'y'), + ('C', 'x'), ('C', 'u')], + names=['Upper', 'Lower']) + for multiindex_columns in ([0, 1, 2, 3, 4], + [0, 1, 2, 3], [0, 1, 2, 4], + [0, 1, 2], [1, 2, 3], [2, 3, 4], + [0, 1], [0, 2], [0, 3], + [0], [2], [4]): + _test_stack_with_multiindex(full_multiindex[multiindex_columns]) + if len(multiindex_columns) > 1: + multiindex_columns.reverse() + _test_stack_with_multiindex(full_multiindex[multiindex_columns]) + + df = DataFrame(np.arange(6).reshape(2, 3), columns=full_multiindex[[0, 1, 3]]) + result = df.stack(dropna=False) + expected = DataFrame([[0, 2], [1, nan], [3, 5], [4, nan]], + index=MultiIndex(levels=[[0, 1], ['u', 'x', 'y', 'z']], + labels=[[0, 0, 1, 1], [1, 3, 1, 3]], + names=[None, 'Lower']), + columns=Index(['B', 'C'], name='Upper'), + dtype=df.dtypes[0]) + assert_frame_equal(result, expected) + def test_repr_with_mi_nat(self): df = DataFrame({'X': [1, 2]}, index=[[pd.NaT, pd.Timestamp('20130101')], ['a', 'b']])
Closes #8844 Fixes `DataFrame.stack(..., dropna=False)` when the columns consist of a "partial" `MultiIndex`, i.e. one in which the `labels` don't reference all the `levels`.
https://api.github.com/repos/pandas-dev/pandas/pulls/8855
2014-11-19T07:09:27Z
2014-12-02T11:14:42Z
2014-12-02T11:14:42Z
2014-12-02T20:13:13Z
BUG: Panel4D setitem by indexer to Series fails for mixed-dtype
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 6688f106f922e..d66e4059a99e2 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -151,3 +151,4 @@ Bug Fixes of the level names are numbers (:issue:`8584`). - Bug in ``MultiIndex`` where ``__contains__`` returns wrong result if index is not lexically sorted or unique (:issue:`7724`) +- Bug for mixed-dtype Panel4D that prevented doing a setitem to a series using an indexer (:issue:`8854`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 048e4af20d02f..60993703b30bf 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -419,9 +419,14 @@ def can_do_equal_len(): if not len(labels) == 1 or not np.iterable(value): return False + try: + axis_number = next(i for i in range(len(plane_indexer)) + if _is_null_slice(plane_indexer[i])) + except StopIteration: + axis_number = 0 l = len(value) item = labels[0] - index = self.obj[item].index + index = self.obj[item].axes[axis_number] # equal len list/ndarray if len(index) == l: diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 6ef8c1820400a..9a48dbde1adcb 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -408,6 +408,14 @@ def test_setitem_by_indexer_mixed_type(self): # GH 8702 self.panel4d['foo'] = 'bar' + # Series + # GH 8854 + panel4dc = self.panel4d.copy() + s = panel4dc.iloc[0,0,:,0] + s.iloc[:] = 1 + panel4dc.iloc[0,0,:,0] = s + self.assertTrue((panel4dc.iloc[0,0,:,0].values == 1).all()) + # scalar panel4dc = self.panel4d.copy() panel4dc.iloc[0] = 1 @@ -417,8 +425,6 @@ def test_setitem_by_indexer_mixed_type(self): self.assertTrue(panel4dc.iloc[1].values.all()) self.assertTrue((panel4dc.iloc[2].values == 'foo').all()) - - def test_comparisons(self): p1 = tm.makePanel4D() p2 = tm.makePanel4D()
This is another tweak to `_setitem_with_indexer` that allows it better to comprehend higher dimensional frames of mixed-dtype. With this tweak setting by indexer to a Series now works. Unfortunately setting to a DataFrame is still broken. I plan to open an issue for that.
https://api.github.com/repos/pandas-dev/pandas/pulls/8854
2014-11-19T06:02:11Z
2015-05-09T16:06:55Z
null
2022-10-13T00:16:15Z
BUG: type change breaks BlockManager integrity
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 8d6e3cb0512b4..944a78ad3691e 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -71,6 +71,7 @@ Bug Fixes - ``Timedelta`` kwargs may now be numpy ints and floats (:issue:`8757`). - ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) - ``slice`` string method now takes step into account (:issue:`8754`) +- Bug in ``BlockManager`` where setting values with different type would break block integrity (:issue:`8850`) - Fix negative step support for label-based slices (:issue:`8753`) Old behavior: diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 306aebede2476..14c4fb17c2b34 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2985,7 +2985,7 @@ def value_getitem(placement): loc = [loc] blknos = self._blknos[loc] - blklocs = self._blklocs[loc] + blklocs = self._blklocs[loc].copy() unfit_mgr_locs = [] unfit_val_locs = [] diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 5bc7558efb471..37b557743b731 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -430,6 +430,17 @@ def test_set_change_dtype(self): mgr2.set('quux', randn(N)) self.assertEqual(mgr2.get('quux').dtype, np.float_) + def test_set_change_dtype_slice(self): # GH8850 + cols = MultiIndex.from_tuples([('1st','a'), ('2nd','b'), ('3rd','c')]) + df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols) + df['2nd'] = df['2nd'] * 2.0 + + self.assertEqual(sorted(df.blocks.keys()), ['float64', 'int64']) + assert_frame_equal(df.blocks['float64'], + DataFrame([[1.0, 4.0], [4.0, 10.0]], columns=cols[:2])) + assert_frame_equal(df.blocks['int64'], + DataFrame([[3], [6]], columns=cols[2:])) + def test_copy(self): shallow = self.mgr.copy(deep=False)
closes https://github.com/pydata/pandas/issues/8850 on master: ``` >>> cols = MultiIndex.from_tuples([('1st', 'a'), ('2nd', 'b'), ('3rd', 'c')]) >>> df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols) >>> df['2nd'] = df['2nd'] * 2.0 # type change in block manager /usr/lib/python3.4/site-packages/numpy/lib/function_base.py:3612: FutureWarning: in the future negative indices will not be ignored by `numpy.delete`. "`numpy.delete`.", FutureWarning) >>> df.values ... File "/usr/lib/python3.4/site-packages/pandas-0.15.1_72_gf504885-py3.4-linux-x86_64.egg/pandas/core/internals.py", line 2392, in _verify_integrity tot_items)) AssertionError: Number of manager items must equal union of block items # manager items: 3, # tot_items: 4 >>> df.blocks ... File "/usr/lib/python3.4/site-packages/pandas-0.15.1_72_gf504885-py3.4-linux-x86_64.egg/pandas/core/internals.py", line 2392, in _verify_integrity tot_items)) AssertionError: Number of manager items must equal union of block items # manager items: 3, # tot_items: 4 ``` `._data` is also broken: ``` >>> df._data BlockManager Items: 1st a 2nd b 3rd c Axis 1: Int64Index([0, 1], dtype='int64') FloatBlock: slice(0, 1, 1), 1 x 2, dtype: float64 IntBlock: slice(1, 3, 1), 2 x 2, dtype: int64 FloatBlock: slice(1, 2, 1), 1 x 2, dtype: float64 ``` integer block is bigger than what it should be and overlaps with one of the float blocks.
https://api.github.com/repos/pandas-dev/pandas/pulls/8853
2014-11-19T03:07:16Z
2014-11-20T22:55:08Z
2014-11-20T22:55:08Z
2014-11-21T01:00:59Z
BUG: Defined .size attribute across NDFrame objects to provide compat with numpy 1.9.1
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index b51da47563b1b..a06dae2aea4e0 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -75,7 +75,7 @@ Bug Fixes - +- Defined ``.size`` attribute across ``NDFrame`` objects to provide compat with numpy >= 1.9.1; buggy with ``np.array_split`` (:issue:`8846`) - Skip testing of histogram plots for matplotlib <= 1.2 (:issue:`8648`). diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 89c6e5836022e..7201428e6b935 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -381,6 +381,11 @@ def ndim(self): "Number of axes / array dimensions" return self._data.ndim + @property + def size(self): + "number of elements in the NDFrame" + return np.prod(self.shape) + def _expand_axes(self, key): new_axes = [] for k, ax in zip(key, self.axes): diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py index 1fe1b552649ed..f4c8b9ecdbc86 100644 --- a/pandas/tests/test_generic.py +++ b/pandas/tests/test_generic.py @@ -352,6 +352,21 @@ def test_head_tail(self): self._compare(o.head(-3), o.head(7)) self._compare(o.tail(-3), o.tail(7)) + + def test_size_compat(self): + # GH8846 + # size property should be defined + + o = self._construct(shape=10) + self.assertTrue(o.size == np.prod(o.shape)) + self.assertTrue(o.size == 10**len(o.axes)) + + def test_split_compat(self): + # xref GH8846 + o = self._construct(shape=10) + self.assertTrue(len(np.array_split(o,5)) == 5) + self.assertTrue(len(np.array_split(o,2)) == 2) + class TestSeries(tm.TestCase, Generic): _typ = Series _comparator = lambda self, x, y: assert_series_equal(x,y) @@ -1422,8 +1437,8 @@ def test_equals(self): self.assertTrue(a.equals(c)) self.assertTrue(a.equals(d)) self.assertFalse(a.equals(e)) - self.assertTrue(e.equals(f)) - + self.assertTrue(e.equals(f)) + def test_describe_raises(self): with tm.assertRaises(NotImplementedError): tm.makePanel().describe()
closes #8846
https://api.github.com/repos/pandas-dev/pandas/pulls/8847
2014-11-18T11:09:54Z
2014-11-18T11:56:11Z
2014-11-18T11:56:11Z
2014-11-18T11:56:11Z
BUG: Implement step in slice StringMethod
diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index c85a9376fc93f..f8b20eaace50e 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -69,6 +69,7 @@ Bug Fixes - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`). - ``Timedelta`` kwargs may now be numpy ints and floats (:issue:`8757`). - ``sql_schema`` now generates dialect appropriate ``CREATE TABLE`` statements (:issue:`8697`) +- ``slice`` string method now takes step into account (:issue:`8754`) diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 78780bc9618f7..2c2a98c0c5434 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -666,7 +666,7 @@ def str_split(arr, pat=None, n=None, return_type='series'): return res -def str_slice(arr, start=None, stop=None, step=1): +def str_slice(arr, start=None, stop=None, step=None): """ Slice substrings from each element in array @@ -674,6 +674,7 @@ def str_slice(arr, start=None, stop=None, step=1): ---------- start : int or None stop : int or None + step : int or None Returns ------- @@ -993,8 +994,8 @@ def center(self, width): return self._wrap_result(result) @copy(str_slice) - def slice(self, start=None, stop=None, step=1): - result = str_slice(self.series, start, stop) + def slice(self, start=None, stop=None, step=None): + result = str_slice(self.series, start, stop, step) return self._wrap_result(result) @copy(str_slice) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 02808ebf0b340..a7d3c53c31e3d 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -628,6 +628,7 @@ def test_empty_str_methods(self): tm.assert_series_equal(empty_str, empty.str.center(42)) tm.assert_series_equal(empty_list, empty.str.split('a')) tm.assert_series_equal(empty_str, empty.str.slice(stop=1)) + tm.assert_series_equal(empty_str, empty.str.slice(step=1)) tm.assert_series_equal(empty_str, empty.str.strip()) tm.assert_series_equal(empty_str, empty.str.lstrip()) tm.assert_series_equal(empty_str, empty.str.rstrip()) @@ -922,6 +923,17 @@ def test_slice(self): exp = Series(['foo', 'bar', NA, 'baz']) tm.assert_series_equal(result, exp) + for start, stop, step in [(0, 3, -1), (None, None, -1), + (3, 10, 2), (3, 0, -1)]: + try: + result = values.str.slice(start, stop, step) + expected = Series([s[start:stop:step] if not isnull(s) else NA for s in + values]) + tm.assert_series_equal(result, expected) + except: + print('failed on %s:%s:%s' % (start, stop, step)) + raise + # mixed mixed = Series(['aafootwo', NA, 'aabartwo', True, datetime.today(), None, 1, 2.]) @@ -933,6 +945,10 @@ def test_slice(self): tm.assert_isinstance(rs, Series) tm.assert_almost_equal(rs, xp) + rs = Series(mixed).str.slice(2, 5, -1) + xp = Series(['oof', NA, 'rab', NA, NA, + NA, NA, NA]) + # unicode values = Series([u('aafootwo'), u('aabartwo'), NA, u('aabazqux')]) @@ -941,6 +957,10 @@ def test_slice(self): exp = Series([u('foo'), u('bar'), NA, u('baz')]) tm.assert_series_equal(result, exp) + result = values.str.slice(0, -1, 2) + exp = Series([u('afow'), u('abrw'), NA, u('abzu')]) + tm.assert_series_equal(result, exp) + def test_slice_replace(self): pass @@ -1151,6 +1171,10 @@ def test_string_slice_get_syntax(self): expected = s.str.slice(stop=3) assert_series_equal(result, expected) + result = s.str[2::-1] + expected = s.str.slice(start=2, step=-1) + assert_series_equal(result, expected) + def test_string_slice_out_of_bounds(self): s = Series([(1, 2), (1,), (3,4,5)])
Resolves #8754. Turned out to be dead simple too :)
https://api.github.com/repos/pandas-dev/pandas/pulls/8843
2014-11-17T20:48:47Z
2014-11-18T10:14:22Z
2014-11-18T10:14:22Z
2014-11-18T10:14:55Z
ENH: Allow unicode separators in to_csv & read_csv
diff --git a/pandas/core/common.py b/pandas/core/common.py index 759f5f1dfaf7a..2e97382d2c6ff 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2695,12 +2695,17 @@ class UnicodeReader: A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. - On Python 3, this is replaced (below) by csv.reader, which handles + On Python 3, this is replaced (above) by csv.reader, which handles unicode. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): f = UTF8Recoder(f, encoding) + if 'delimiter' in kwds and isinstance(kwds['delimiter'], unicode): + if encoding is None: + kwds['delimiter'] = kwds['delimiter'].encode() + else: + kwds['delimiter'] = kwds['delimiter'].encode(encoding) self.reader = csv.reader(f, dialect=dialect, **kwds) def next(self): @@ -2723,9 +2728,19 @@ class UnicodeWriter: def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = StringIO() + self.encoder = codecs.getincrementalencoder(encoding)() + + if 'delimiter' in kwds and isinstance(kwds['delimiter'], unicode): + # python built-in csv reader can't handle non-ascii delimiters + # no matter what. + try: + kwds['delimiter'] = str(kwds['delimiter']) + except UnicodeEncodeError: # pragma: no cover + raise ValueError('cannot coerce delimiter %r to str' % + kwds['delimiter']) + self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f - self.encoder = codecs.getincrementalencoder(encoding)() self.quoting = kwds.get("quoting", None) def writerow(self, row): diff --git a/pandas/core/format.py b/pandas/core/format.py index 89973754a861c..e94a01a8ce352 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -1176,6 +1176,29 @@ def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', float_format=None, if path_or_buf is None: path_or_buf = StringIO() + if not compat.PY3 and isinstance(sep, compat.text_type): + try: + if encoding is None: + sep = sep.encode() + else: + sep = sep.encode(encoding) + except UnicodeEncodeError as e: + raise ValueError('must specify single-byte separator' + ' compatible with encoding. (%s)' % e) + try: + if encoding is None: + decoded_sep = sep.decode() + else: + decoded_sep = sep.decode(encoding) + sep = decoded_sep.encode('utf8') + except (UnicodeEncodeError, UnicodeDecodeError) as e: + raise ValueError('must specify seprator encodable into utf8' + ' (%s)' % e) + + if len(sep) > 1: + raise NotImplementedError('separators that are multi-byte in' + ' utf8 are not supported in Python 2.') + self.path_or_buf = path_or_buf self.sep = sep diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index b23aa017138e1..bd8bd75412937 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -25,6 +25,8 @@ import pandas.tslib as tslib import pandas.parser as _parser +MAX_ORDINAL_FOR_CHAR = 128 + class ParserWarning(Warning): pass @@ -602,15 +604,37 @@ def _clean_options(self, options, engine): fallback_reason = "the 'c' engine does not support"\ " sep=None with delim_whitespace=False" engine = 'python' - elif sep is not None and len(sep) > 1: - if engine == 'c' and sep == '\s+': + + if sep is not None and engine not in ('python', 'python-fwf'): + if len(sep) > 1 and sep == '\s+': result['delim_whitespace'] = True del result['delimiter'] - elif engine not in ('python', 'python-fwf'): + elif len(sep) > 1: # wait until regex engine integrated fallback_reason = "the 'c' engine does not support"\ " regex separators" engine = 'python' + elif len(sep) == 1 and isinstance(sep, compat.text_type): + try: + if options.get('encoding'): + sep_bytes = sep.encode(options['encoding']) + else: + sep_bytes = sep.encode() + except UnicodeEncodeError as e: + raise ValueError('sep is not compatible with given' + ' encoding. (%s)' % e) + if len(sep_bytes) == 1: + sep = sep_bytes + else: + # python 2 CSV reader always works with bytes, so we can't + # do anything else here but fail. + if not compat.PY3: + raise ValueError('Must specify single byte sep' + ' character') + fallback_reason = "the 'c' engine does not support"\ + " multi-byte separators" + engine = 'python' + if fallback_reason and engine_specified: raise ValueError(fallback_reason) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index fc031afe728dc..c36a95d58ff46 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -6632,6 +6632,114 @@ def test_to_csv_path_is_none(self): recons = pd.read_csv(StringIO(csv_str), index_col=0) assert_frame_equal(self.frame, recons) + def test_to_csv_read_csv_ascii_sep_as_unicode(self): + df = DataFrame({u('c/\u03c3'): [1, 2, 3]}) + sep = u('|') + with ensure_clean() as path: + df.to_csv(path, encoding='UTF-8', sep=sep) + df2 = read_csv(path, index_col=0, encoding='UTF-8', sep=sep) + assert_frame_equal(df, df2) + + df.to_csv(path, encoding='UTF-8', index=False, sep=sep) + df2 = read_csv(path, index_col=None, encoding='UTF-8', + sep=sep) + assert_frame_equal(df, df2) + self.frame.to_csv(path, sep=sep) + recons = read_csv(path, index_col=0, sep=sep) + + assert_frame_equal(self.frame, recons) + + def test_to_csv_read_csv_non_ascii_unicode_sep(self): + df = DataFrame({u('c/\u03c3'): [1, 2, 3]}) + sep = u('\u2202') + with ensure_clean() as path: + with tm.assertRaisesRegexp(ValueError, 'separator'): + df2 = read_csv(path, index_col=None, encoding='UTF-8', + sep=sep, engine='c') + if compat.PY3: + # non-ascii separators won't work in Python 2, so can't do this + # regardless + df.to_csv(path, encoding='UTF-8', index=False, sep=sep) + df2 = read_csv(path, index_col=None, encoding='UTF-8', + sep=sep, engine='python') + def test_to_csv_unicode_delimiter_with_encodings(self): + df = DataFrame({u('c/\u03c3'): [1, 2, 3]}) + # broken bar varies based on encoding + sep = b'\xa6'.decode('latin1') + # broken bar in latin1 is single byte, so that's okay in Python 3 only + encoding = 'latin1' + with ensure_clean() as path: + if compat.PY3: + df.to_csv(path, encoding=encoding, sep=sep) + # explicit engine fails + with tm.assertRaisesRegexp(ValueError, 'sep'): + pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep, engine='c') + df2 = pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep) + assert_frame_equal(df, df2) + else: + # can't ever work in Python 2 that works only with single-byte UTF8 + # seps + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + df.to_csv(path, encoding=encoding, sep=sep) + # these two are based on validation before any reads + with tm.assertRaisesRegexp(ValueError, 'sep'): + pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep, engine='c') + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep, engine='python') + # and with utf8 encoding we have a similar set of constraints + encoding = 'utf8' + if compat.PY3: + df.to_csv(path, encoding=encoding, sep=sep) + # explicit engine fails + with tm.assertRaisesRegexp(ValueError, 'sep'): + pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep, engine='c') + with tm.assertRaisesRegexp(ValueError, 'sep'): + # however fallback doesn't work this time because sep is multibyte + pd.read_csv(path, index_col=0, encoding=encoding, sep=sep) + else: + # can't ever work in Python 2 that works only with single-byte UTF8 + # seps + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + df.to_csv(path, encoding=encoding, sep=sep) + # these two are based on validation before any reads + with tm.assertRaisesRegexp(ValueError, 'sep'): + pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep, engine='c') + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep, engine='c') + + # however, single-byte utf8 characters are fine + sep = compat.unichr(255) + encoding = 'utf8' + + df.to_csv(path, encoding=encoding, sep=sep) + + df2 = pd.read_csv(path, index_col=0, encoding=encoding, + sep=sep) + assert_frame_equal(df, df2) + + def test_to_csv_from_csv_unicode_delimiter_no_encoding(self): + # works with ascii + buf = StringIO() + sep = u(',') + self.frame.to_csv(buf, sep=sep) + buf.seek(0) + recons = pd.read_csv(buf, index_col=0, sep=sep) + assert_frame_equal(self.frame, recons) + # fails otherwise + with tm.assertRaisesRegexp(ValueError, 'sep'): + sep = compat.unichr(255) + self.frame.to_csv(buf, sep) + with tm.assertRaisesRegexp(ValueError, 'sep'): + sep = compat.unichr(255) + pd.read_csv(buf, sep) + def test_info(self): io = StringIO() self.frame.info(buf=io) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c4c2eebacb0e9..16fa82cd8d3ae 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -4482,7 +4482,6 @@ def test_rank_inf(self): iranks = iseries.rank() assert_series_equal(iranks, exp) - def test_from_csv(self): with ensure_clean() as path: @@ -4533,6 +4532,99 @@ def test_to_csv_unicode_index(self): assert_series_equal(s, s2) + def test_to_csv_unicode_delimiter_with_encodings(self): + # broken bar varies based on encoding + sep = b'\xa6'.decode('latin1') + # broken bar in latin1 is single byte, so that's okay in Python 3 only + encoding = 'latin1' + buf = StringIO() + s = Series([u("\u05d0"), "d2"], index=[u("\u05d0"), u("\u05d1")]) + if compat.PY3: + buf = StringIO() + s.to_csv(buf, encoding=encoding, sep=sep) + buf.seek(0) + s2 = Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep) + assert_series_equal(s, s2) + buf.seek(0) + # explicit engine fails + with tm.assertRaisesRegexp(ValueError, 'sep'): + Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep, engine='c') + # but fallback should work + s2 = Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep) + assert_series_equal(s, s2) + else: + # can't ever work in Python 2 that works only with single-byte UTF8 + # seps + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + buf = StringIO() + s.to_csv(buf, encoding=encoding, sep=sep) + # these two are based on validation before any reads + with tm.assertRaisesRegexp(ValueError, 'sep'): + buf = StringIO() + Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep, engine='c') + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + buf = StringIO() + Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep, engine='python') + # and with utf8 encoding we have a similar set of constraints + encoding = 'utf8' + if compat.PY3: + buf = StringIO() + s.to_csv(buf, encoding=encoding, sep=sep) + buf.seek(0) + # explicit engine fails + with tm.assertRaisesRegexp(ValueError, 'sep'): + Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep, engine='c') + with tm.assertRaisesRegexp(ValueError, 'sep'): + # however fallback doesn't work this time because sep is multibyte + Series.from_csv(buf, index_col=0, encoding=encoding, sep=sep) + else: + # can't ever work in Python 2 that works only with single-byte UTF8 + # seps + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + buf = StringIO() + s.to_csv(buf, encoding=encoding, sep=sep) + # these two are based on validation before any reads + with tm.assertRaisesRegexp(ValueError, 'sep'): + buf = StringIO() + Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep, engine='c') + with tm.assertRaisesRegexp(NotImplementedError, 'sep'): + buf = StringIO() + Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep, engine='python') + + # however, single-byte utf8 characters are fine + sep = compat.unichr(255) + encoding = 'utf8' + + s.to_csv(buf, encoding=encoding, sep=sep) + buf.seek(0) + + s2 = Series.from_csv(buf, index_col=0, encoding=encoding, + sep=sep) + assert_series_equal(s, s2) + + def test_to_csv_from_csv_unicode_delimiter_no_encoding(self): + with ensure_clean() as path: + # works with ascii + sep = u(',') + self.ts.to_csv(path, sep=sep) + recons = Series.from_csv(path, index_col=0, sep=sep) + assert_series_equal(self.ts, recons) + # fails otherwise + with tm.assertRaisesRegexp(ValueError, 'sep'): + sep = compat.unichr(255) + self.ts.to_csv(path, sep) + with tm.assertRaisesRegexp(ValueError, 'sep'): + sep = compat.unichr(255) + Series.from_csv(path, sep) + def test_tolist(self): rs = self.ts.tolist() xp = self.ts.values.tolist()
- single byte UTF8 separators will always work if utf8 encoding is specified (i.e. seps in range(256)) - single byte delimiters with encodings will always work in Python 3, but will not work in Python 2 if they are multibyte when coerced to UTF8 - multi byte delimiters with encodings will not work on reads with C engine and will not work with writes in Python 2. (but I believe they'll work in Python 3 if they're considered to be length 1). Closes #6035. This was slightly complicated validation-wise, but I think it's in a good place with tests and such. I'll squash together the commits and make sure I've covered the relevant cases in tests. I also noticed some weirdness with passing `delimiter` as a keyword argument that might need to be addressed in the future. CC @maxgrenderjones, @Midnighter if you want to take a look.
https://api.github.com/repos/pandas-dev/pandas/pulls/8841
2014-11-17T16:40:39Z
2015-05-09T16:07:09Z
null
2022-10-13T00:16:15Z
TST: add tests for index.groupby (GH5620)
diff --git a/pandas/core/index.py b/pandas/core/index.py index 2de9b2fac9aa9..6702a21167850 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1555,6 +1555,20 @@ def _possibly_promote(self, other): return self, other def groupby(self, to_groupby): + """ + Group the index labels by a given array of values. + + Parameters + ---------- + to_groupby : array + Values used to determine the groups. + + Returns + ------- + groups : dict + {group name -> group labels} + + """ return self._groupby(self.values, _values_from_object(to_groupby)) def map(self, mapper): diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index adb5e7d07fbe6..cca8324b42b93 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -1137,6 +1137,11 @@ def get_reindex_type(target): self.assertEqual(reindexed.levels[0].dtype.type, np.int64) self.assertEqual(reindexed.levels[1].dtype.type, np.float64) + def test_groupby(self): + idx = Index(range(5)) + groups = idx.groupby(np.array([1,1,2,2,2])) + exp = {1: [0, 1], 2: [2, 3, 4]} + tm.assert_dict_equal(groups, exp) class Numeric(Base): @@ -3524,6 +3529,17 @@ def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array(self): self.assertEqual(idx.reindex([], level=1)[0].levels[1].dtype.type, np.object_) + def test_groupby(self): + groups = self.index.groupby(np.array([1, 1, 1, 2, 2, 2])) + labels = self.index.get_values().tolist() + exp = {1: labels[:3], 2: labels[3:]} + tm.assert_dict_equal(groups, exp) + + # GH5620 + groups = self.index.groupby(self.index) + exp = dict((key, [key]) for key in self.index) + tm.assert_dict_equal(groups, exp) + def test_get_combined_index(): from pandas.core.index import _get_combined_index
Closes #5620 Also added a docstring.
https://api.github.com/repos/pandas-dev/pandas/pulls/8840
2014-11-17T15:15:44Z
2014-11-18T10:15:13Z
2014-11-18T10:15:13Z
2014-11-18T10:15:19Z