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 |
|---|---|---|---|---|---|---|---|
Use set literal syntax for set prettyprinting | diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 543eea399f447..3099b1553325b 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -28,6 +28,9 @@ Other Enhancements
API changes
~~~~~~~~~~~
+- Prettyprinting sets (e.g. in DataFrame cells) now uses set literal syntax (``{x, y}``) instead of
+ Legacy Python syntax (``set([x, y])``).
+
.. _whatsnew_0171.deprecations:
Deprecations
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 2411925207696..279ff3b177954 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -3194,7 +3194,7 @@ def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds):
bounds length of printed sequence, depending on options
"""
if isinstance(seq, set):
- fmt = u("set([%s])")
+ fmt = u("{%s}")
else:
fmt = u("[%s]") if hasattr(seq, '__setitem__') else u("(%s)")
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index 14ff9e65c3e20..bf2cfc6216a60 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -191,13 +191,14 @@ def test_repr_chop_threshold(self):
self.assertEqual(repr(df), ' 0 1\n0 0.1 0.5\n1 0.5 -0.1')
def test_repr_obeys_max_seq_limit(self):
- import pandas.core.common as com
-
with option_context("display.max_seq_items",2000):
self.assertTrue(len(com.pprint_thing(lrange(1000))) > 1000)
with option_context("display.max_seq_items",5):
- self.assertTrue(len(com.pprint_thing(lrange(1000)))< 100)
+ self.assertTrue(len(com.pprint_thing(lrange(1000))) < 100)
+
+ def test_repr_set(self):
+ self.assertEqual(com.pprint_thing(set([1])), '{1}')
def test_repr_is_valid_construction_code(self):
# for the case of Index, where the repr is traditional rather then stylized
| https://api.github.com/repos/pandas-dev/pandas/pulls/11215 | 2015-10-01T13:29:08Z | 2015-10-11T15:23:04Z | null | 2015-10-12T08:59:00Z | |
BUG: GH11206 where pd.isnull did not consider numpy NaT null | diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index 2c07c28066faf..9367c42f8d39a 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -582,7 +582,7 @@ def time_frame_interpolate_some_good_infer(self):
self.df.interpolate(downcast='infer')
-class frame_isnull(object):
+class frame_isnull_floats_no_null(object):
goal_time = 0.2
def setup(self):
@@ -593,6 +593,33 @@ def time_frame_isnull(self):
isnull(self.df)
+class frame_isnull_floats(object):
+ goal_time = 0.2
+
+ def setup(self):
+ np.random.seed(1234)
+ self.sample = np.array([np.nan, 1.0])
+ self.data = np.random.choice(self.sample, (1000, 1000))
+ self.df = DataFrame(self.data)
+
+ def time_frame_isnull(self):
+ isnull(self.df)
+
+
+class frame_isnull_obj(object):
+ goal_time = 0.2
+
+ def setup(self):
+ np.random.seed(1234)
+ self.sample = np.array([NaT, np.nan, None, np.datetime64('NaT'),
+ np.timedelta64('NaT'), 0, 1, 2.0, '', 'abcd'])
+ self.data = np.random.choice(self.sample, (1000, 1000))
+ self.df = DataFrame(self.data)
+
+ def time_frame_isnull(self):
+ isnull(self.df)
+
+
class frame_iteritems(object):
goal_time = 0.2
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index f2008727017f8..f8801cfdf9785 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -156,6 +156,7 @@ Bug Fixes
- Bug in output formatting when using an index of ambiguous times (:issue:`11619`)
- Bug in comparisons of Series vs list-likes (:issue:`11339`)
- Bug in ``DataFrame.replace`` with a ``datetime64[ns, tz]`` and a non-compat to_replace (:issue:`11326`, :issue:`11153`)
+- Bug in ``isnull`` where ``numpy.datetime64('NaT')`` in a ``numpy.array`` was not determined to be null(:issue:`11206`)
- Bug in list-like indexing with a mixed-integer Index (:issue:`11320`)
- Bug in ``pivot_table`` with ``margins=True`` when indexes are of ``Categorical`` dtype (:issue:`10993`)
- Bug in ``DataFrame.plot`` cannot use hex strings colors (:issue:`10299`)
diff --git a/pandas/lib.pyx b/pandas/lib.pyx
index 1a1f04cba1cb9..f7978c4791538 100644
--- a/pandas/lib.pyx
+++ b/pandas/lib.pyx
@@ -1,3 +1,4 @@
+# cython: profile=False
cimport numpy as np
cimport cython
import numpy as np
@@ -54,7 +55,8 @@ from datetime import datetime as pydatetime
# this is our tseries.pxd
from datetime cimport *
-from tslib cimport convert_to_tsobject, convert_to_timedelta64
+from tslib cimport (convert_to_tsobject, convert_to_timedelta64,
+ _check_all_nulls)
import tslib
from tslib import NaT, Timestamp, Timedelta
@@ -245,8 +247,6 @@ def time64_to_datetime(ndarray[int64_t, ndim=1] arr):
return result
-cdef inline int64_t get_timedelta64_value(val):
- return val.view('i8')
#----------------------------------------------------------------------
# isnull / notnull related
@@ -346,10 +346,10 @@ def isnullobj(ndarray[object] arr):
cdef ndarray[uint8_t] result
n = len(arr)
- result = np.zeros(n, dtype=np.uint8)
+ result = np.empty(n, dtype=np.uint8)
for i from 0 <= i < n:
val = arr[i]
- result[i] = val is NaT or _checknull(val)
+ result[i] = _check_all_nulls(val)
return result.view(np.bool_)
@cython.wraparound(False)
diff --git a/pandas/src/datetime.pxd b/pandas/src/datetime.pxd
index f2f764c785894..5f7de8244d17e 100644
--- a/pandas/src/datetime.pxd
+++ b/pandas/src/datetime.pxd
@@ -1,3 +1,4 @@
+# cython: profile=False
from numpy cimport int64_t, int32_t, npy_int64, npy_int32, ndarray
from cpython cimport PyObject
@@ -59,6 +60,7 @@ cdef extern from "numpy/ndarrayobject.h":
cdef extern from "numpy_helper.h":
npy_datetime get_datetime64_value(object o)
+ npy_timedelta get_timedelta64_value(object o)
cdef extern from "numpy/npy_common.h":
diff --git a/pandas/src/numpy_helper.h b/pandas/src/numpy_helper.h
index 8b79bbe79ff2f..9f406890c4e68 100644
--- a/pandas/src/numpy_helper.h
+++ b/pandas/src/numpy_helper.h
@@ -40,7 +40,11 @@ get_nat(void) {
PANDAS_INLINE npy_datetime
get_datetime64_value(PyObject* obj) {
return ((PyDatetimeScalarObject*) obj)->obval;
+}
+PANDAS_INLINE npy_timedelta
+get_timedelta64_value(PyObject* obj) {
+ return ((PyTimedeltaScalarObject*) obj)->obval;
}
PANDAS_INLINE int
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 89826209fa46d..57448e2d018dc 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -179,6 +179,13 @@ def test_isnull_nat():
exp = np.array([True])
assert(np.array_equal(result, exp))
+def test_isnull_numpy_nat():
+ arr = np.array([NaT, np.datetime64('NaT'), np.timedelta64('NaT'),
+ np.datetime64('NaT', 's')])
+ result = isnull(arr)
+ expected = np.array([True] * 4)
+ tm.assert_numpy_array_equal(result, expected)
+
def test_isnull_datetime():
assert (not isnull(datetime.now()))
assert notnull(datetime.now())
diff --git a/pandas/tslib.pxd b/pandas/tslib.pxd
index 3cb7e94c65100..5e0c88604206c 100644
--- a/pandas/tslib.pxd
+++ b/pandas/tslib.pxd
@@ -7,3 +7,4 @@ cdef bint _is_utc(object)
cdef bint _is_tzlocal(object)
cdef object _get_dst_info(object)
cdef bint _nat_scalar_rules[6]
+cdef bint _check_all_nulls(obj)
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 0d47c2526df14..713cf08bfc3e2 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -3,6 +3,7 @@
cimport numpy as np
from numpy cimport (int8_t, int32_t, int64_t, import_array, ndarray,
NPY_INT64, NPY_DATETIME, NPY_TIMEDELTA)
+from datetime cimport get_datetime64_value, get_timedelta64_value
import numpy as np
# GH3363
@@ -707,12 +708,28 @@ NaT = NaTType()
iNaT = util.get_nat()
-
cdef inline bint _checknull_with_nat(object val):
""" utility to check if a value is a nat or not """
return val is None or (
PyFloat_Check(val) and val != val) or val is NaT
+cdef inline bint _check_all_nulls(object val):
+ """ utility to check if a value is any type of null """
+ cdef bint res
+ if PyFloat_Check(val):
+ res = val != val
+ elif val is NaT:
+ res = 1
+ elif val is None:
+ res = 1
+ elif is_datetime64_object(val):
+ res = get_datetime64_value(val) == NPY_NAT
+ elif is_timedelta64_object(val):
+ res = get_timedelta64_value(val) == NPY_NAT
+ else:
+ res = 0
+ return res
+
cdef inline bint _cmp_nat_dt(_NaT lhs, _Timestamp rhs, int op) except -1:
return _nat_scalar_rules[op]
| closes #11206
| https://api.github.com/repos/pandas-dev/pandas/pulls/11212 | 2015-09-30T23:23:51Z | 2015-11-20T14:51:21Z | 2015-11-20T14:51:21Z | 2015-11-20T14:51:30Z |
err#8038: Index.shift() gives confusing error message when no Datetim… | diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index c4e8ae44011ec..61282343f7667 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -98,7 +98,7 @@ Enhancements
API changes
~~~~~~~~~~~
-
+- raise ``NotImplementedError`` in ``Index.shift`` for non-supported index types (:issue:`8083`)
- min and max reductions on ``datetime64`` and ``timedelta64`` dtyped series now
result in ``NaT`` and not ``nan`` (:issue:`11245`).
- Regression from 0.16.2 for output formatting of long floats/nan, restored in (:issue:`11302`)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 9ccde5502ec1b..b0cd72e572c09 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -1461,12 +1461,7 @@ def shift(self, periods=1, freq=None):
-------
shifted : Index
"""
- if periods == 0:
- # OK because immutable
- return self
-
- offset = periods * freq
- return Index([idx + offset for idx in self], name=self.name)
+ raise NotImplementedError("Not supported for type %s" % type(self).__name__)
def argsort(self, *args, **kwargs):
"""
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index bd02836953ffd..88700fc8c8605 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -53,6 +53,13 @@ def test_pickle_compat_construction(self):
# need an object to create with
self.assertRaises(TypeError, self._holder)
+ def test_shift_index(self):
+ # err8083 test the base class for shift
+ idx = self.create_index()
+ self.assertRaises(NotImplementedError, idx.shift, 1)
+
+ self.assertRaises(NotImplementedError, idx.shift, 1, 2)
+
def test_numeric_compat(self):
idx = self.create_index()
@@ -3425,6 +3432,32 @@ def setUp(self):
def create_index(self):
return date_range('20130101', periods=5)
+ def test_shift(self):
+ # test shift for datetimeIndex and non datetimeIndex
+ # err8083
+
+ drange = self.create_index()
+ result = drange.shift(1)
+ expected = DatetimeIndex(['2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05',
+ '2013-01-06'], freq='D')
+ self.assert_index_equal(result, expected)
+
+ result = drange.shift(0)
+ expected = DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
+ '2013-01-05'], freq='D')
+ self.assert_index_equal(result, expected)
+
+ result = drange.shift(-1)
+ expected = DatetimeIndex(['2012-12-31','2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04'],
+ freq='D')
+ self.assert_index_equal(result, expected)
+
+ result = drange.shift(3, freq='2D')
+ expected = DatetimeIndex(['2013-01-07', '2013-01-08', '2013-01-09', '2013-01-10',
+ '2013-01-11'],freq='D')
+ self.assert_index_equal(result, expected)
+
+
def test_construction_with_alt(self):
i = pd.date_range('20130101',periods=5,freq='H',tz='US/Eastern')
@@ -3688,6 +3721,16 @@ def setUp(self):
def create_index(self):
return period_range('20130101', periods=5, freq='D')
+ def test_shift(self):
+ # test shift for PeriodIndex
+ # err8083
+
+ drange = self.create_index()
+ result = drange.shift(1)
+ expected = PeriodIndex(['2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05',
+ '2013-01-06'], freq='D')
+ self.assert_index_equal(result, expected)
+
def test_pickle_compat_construction(self):
pass
@@ -3784,6 +3827,21 @@ def setUp(self):
def create_index(self):
return pd.to_timedelta(range(5), unit='d') + pd.offsets.Hour(1)
+ def test_shift(self):
+ # test shift for TimedeltaIndex
+ # err8083
+
+ drange = self.create_index()
+ result = drange.shift(1)
+ expected = TimedeltaIndex(['1 days 01:00:00', '2 days 01:00:00', '3 days 01:00:00',
+ '4 days 01:00:00', '5 days 01:00:00'],freq='D')
+ self.assert_index_equal(result, expected)
+
+ result = drange.shift(3, freq='2D')
+ expected = TimedeltaIndex(['2 days 01:00:00', '3 days 01:00:00', '4 days 01:00:00',
+ '5 days 01:00:00', '6 days 01:00:00'],freq='D')
+ self.assert_index_equal(result, expected)
+
def test_get_loc(self):
idx = pd.to_timedelta(['0 days', '1 days', '2 days'])
diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py
index d5382e8057f4b..b063360b91280 100644
--- a/pandas/tseries/base.py
+++ b/pandas/tseries/base.py
@@ -516,9 +516,10 @@ def shift(self, n, freq=None):
if freq is not None and freq != self.freq:
if isinstance(freq, compat.string_types):
freq = frequencies.to_offset(freq)
- result = Index.shift(self, n, freq)
+ offset = n * freq
+ result = self + offset
- if hasattr(self,'tz'):
+ if hasattr(self, 'tz'):
result.tz = self.tz
return result
| …eIndex
closes #8038
| https://api.github.com/repos/pandas-dev/pandas/pulls/11211 | 2015-09-30T22:59:02Z | 2015-11-18T20:12:21Z | null | 2017-01-18T13:36:08Z |
Add ability to set the allowLargeResults option in BigQuery #10474 | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 9def8be621aed..cf1ae24366fa8 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -4091,7 +4091,7 @@ destination DataFrame as well as a preferred column order as follows:
data_frame = pd.read_gbq('SELECT * FROM test_dataset.test_table',
index_col='index_column_name',
- col_order=['col1', 'col2', 'col3'], projectid)
+ col_order=['col1', 'col2', 'col3'], projectid=projectid)
.. note::
@@ -4102,6 +4102,45 @@ destination DataFrame as well as a preferred column order as follows:
You can toggle the verbose output via the ``verbose`` flag which defaults to ``True``.
+You can send the query results directly to a table in BigQuery by setting the ``destination_table`` argument.
+
+For example,
+
+.. code-block:: python
+
+ df.read_gbq('SELECT * FROM test_dataset.test_table', project_id=projectid, destination_table='my_dataset.my_table')
+
+.. note::
+
+ When the ``destination_table`` argument is set, an empty dataframe will be returned.
+
+.. note::
+
+ The destination table and destination dataset will automatically be created if they do not already exist.
+
+The ``if_exists`` argument can be used to dictate whether to ``'fail'``, ``'replace'``
+or ``'append'`` if the destination table already exists when using the ``destination_table`` argument.
+The default value is ``'fail'``.
+
+For example, assume that ``if_exists`` is set to ``'fail'``. The following snippet will raise
+a ``TableCreationError`` if the destination table already exists.
+
+.. code-block:: python
+
+ df.read_gbq('SELECT * FROM test_dataset.test_table',
+ project_id=projectid,
+ destination_table='my_dataset.my_table',
+ if_exists='fail')
+
+.. note::
+
+ If you plan to run a query that may return larger results, you can set the ``allow_large_results`` argument
+ which defaults to ``False``. Setting the ``allow_large_results`` argument will effectively set the BigQuery
+ ``'allowLargeResults'`` option to true in the BigQuery job configuration.
+
+ Queries that return large results will take longer to execute, even if the result set is small,
+ and are subject to `additional limitations <https://cloud.google.com/bigquery/querying-data?hl=en#largequeryresults>`__.
+
Writing DataFrames
''''''''''''''''''
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 9990d2bd1c78d..9facde9e82c88 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -333,6 +333,8 @@ Google BigQuery Enhancements
- ``InvalidColumnOrder`` and ``InvalidPageToken`` in the gbq module will raise ``ValueError`` instead of ``IOError``.
- The ``generate_bq_schema()`` function is now deprecated and will be removed in a future version (:issue:`11121`)
- Update the gbq module to support Python 3 (:issue:`11094`).
+- Modify :func:`pandas.io.gbq.read_gbq()` to allow users to redirect the query results to a destination table via the `destination_table` parameter. See the :ref:`docs <io.bigquery>` for more details (:issue:`11209`)
+- Modify :func:`pandas.io.gbq.read_gbq()` to allow users to allow users to set the ``'allowLargeResults'`` option in the BigQuery job configuration via the ``allow_large_results`` parameter. (:issue:`11209`)
.. _whatsnew_0170.enhancements.other:
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index e9568db06f391..d19b6ee456f81 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -195,7 +195,7 @@ def process_insert_errors(insert_errors, verbose):
raise StreamingInsertError
- def run_query(self, query, verbose=True):
+ def run_query(self, query, verbose=True, destination_table=None, if_exists='fail', allow_large_results=False):
from apiclient.errors import HttpError
from oauth2client.client import AccessTokenRefreshError
@@ -211,6 +211,48 @@ def run_query(self, query, verbose=True):
}
}
+ if destination_table:
+ if if_exists not in ('fail', 'replace', 'append'):
+ raise ValueError("'{0}' is not valid for if_exists".format(if_exists))
+
+ if '.' not in destination_table:
+ raise NotFoundException("Invalid Table Name. Should be of the form 'datasetId.tableId' ")
+
+ dataset_id, table_id = destination_table.rsplit('.', 1)
+
+ job_data['configuration']['query'] = {
+ 'query': query,
+ 'destinationTable': {
+ "projectId": self.project_id,
+ "datasetId": dataset_id,
+ "tableId": table_id,
+ },
+ 'writeDisposition': 'WRITE_EMPTY', # A 'duplicate' error is returned in the job result if table exists
+ 'allowLargeResults': 'false' # If true, allows the query to produce large result tables.
+ }
+
+ if allow_large_results:
+ job_data['configuration']['query']['allowLargeResults'] = 'true'
+
+ table = _Table(self.project_id, dataset_id)
+
+ if table.exists(table_id):
+ if if_exists == 'fail':
+ raise TableCreationError("Could not create the table because it already exists. "
+ "Change the if_exists parameter to append or replace data.")
+ elif if_exists == 'replace':
+ # If the table already exists, instruct BigQuery to overwrite the table data.
+ job_data['configuration']['query']['writeDisposition'] = 'WRITE_TRUNCATE'
+ elif if_exists == 'append':
+ # If the table already exists, instruct BigQuery to append to the table data.
+ job_data['configuration']['query']['writeDisposition'] = 'WRITE_APPEND'
+
+ dataset = _Dataset(self.project_id)
+
+ # create the destination dataset if it does not already exist
+ if not dataset.exists(dataset_id):
+ dataset.create(dataset_id)
+
try:
query_reply = job_collection.insert(projectId=self.project_id, body=job_data).execute()
except AccessTokenRefreshError:
@@ -237,6 +279,9 @@ def run_query(self, query, verbose=True):
# Only read schema on first page
schema = query_reply['schema']
+ if destination_table:
+ return schema, list()
+
# Loop through each page of data
while 'rows' in query_reply and current_row < total_rows:
page = query_reply['rows']
@@ -385,7 +430,8 @@ def _parse_entry(field_value, field_type):
return field_value
-def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False, verbose=True):
+def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False, verbose=True,
+ destination_table=None, if_exists='fail', allow_large_results=False):
"""Load data from Google BigQuery.
THIS IS AN EXPERIMENTAL LIBRARY
@@ -412,6 +458,15 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=Fals
if multiple accounts are used.
verbose : boolean (default True)
Verbose output
+ destination_table : string
+ Name of table to be written, in the form 'dataset.tablename'
+ if_exists : {'fail', 'replace', 'append'}, default 'fail'
+ 'fail': If table exists, do nothing.
+ 'replace': If table exists, drop it, recreate it, and insert data.
+ 'append': If table exists, insert data. Create if does not exist.
+ allow_large_results : boolean (default False)
+ Enables the Google BigQuery allowLargeResults option which is necessary for
+ queries that may return larger results.
Returns
-------
@@ -424,7 +479,11 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=Fals
raise TypeError("Missing required parameter: project_id")
connector = GbqConnector(project_id, reauth=reauth)
- schema, pages = connector.run_query(query, verbose=verbose)
+ schema, pages = connector.run_query(query,
+ verbose=verbose,
+ destination_table=destination_table,
+ if_exists=if_exists,
+ allow_large_results=allow_large_results)
dataframe_list = []
while len(pages) > 0:
page = pages.pop()
diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py
index cc1e901d8f119..8b55594044696 100644
--- a/pandas/io/tests/test_gbq.py
+++ b/pandas/io/tests/test_gbq.py
@@ -204,28 +204,32 @@ class TestReadGBQIntegration(tm.TestCase):
@classmethod
def setUpClass(cls):
# - GLOBAL CLASS FIXTURES -
- # put here any instruction you want to execute only *ONCE* *BEFORE* executing *ALL* tests
- # described below.
+ # put here any instruction you want to execute only *ONCE* *BEFORE* executing *ALL* tests
+ # described below.
if not PROJECT_ID:
raise nose.SkipTest("Cannot run integration tests without a project id")
test_requirements()
+ clean_gbq_environment()
+
+ gbq._Dataset(PROJECT_ID).create(DATASET_ID + "7")
def setUp(self):
# - PER-TEST FIXTURES -
- # put here any instruction you want to be run *BEFORE* *EVERY* test is executed.
+ # put here any instruction you want to be run *BEFORE* *EVERY* test is executed.
pass
@classmethod
def tearDownClass(cls):
# - GLOBAL CLASS FIXTURES -
# put here any instruction you want to execute only *ONCE* *AFTER* executing all tests.
- pass
+
+ clean_gbq_environment()
def tearDown(self):
# - PER-TEST FIXTURES -
- # put here any instructions you want to be run *AFTER* *EVERY* test is executed.
+ # put here any instructions you want to be run *AFTER* *EVERY* test is executed.
pass
def test_should_properly_handle_valid_strings(self):
@@ -357,6 +361,77 @@ def test_zero_rows(self):
expected_result = DataFrame(columns=['title', 'language'])
self.assert_frame_equal(df, expected_result)
+ def test_redirect_query_results_to_destination_table_default(self):
+ destination_table = "{0}.{1}".format(DATASET_ID + "7", TABLE_ID + "1")
+ test_size = 100
+
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table)
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), PROJECT_ID)
+ self.assertEqual(result['NUM_ROWS'][0], test_size)
+
+ def test_redirect_query_results_to_destination_table_if_table_exists_fail(self):
+ destination_table = "{0}.{1}".format(DATASET_ID + "7", TABLE_ID + "2")
+ test_size = 100
+
+ # Test redirecting the query results to a destination table without specifying the if_exists parameter
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table)
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), PROJECT_ID)
+ self.assertEqual(result['NUM_ROWS'][0], test_size)
+
+ # Confirm that the default action is to to fail if the table exists and if_exists parameter is not provided
+ with tm.assertRaises(gbq.TableCreationError):
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table)
+
+ # Test the if_exists parameter with value 'fail'
+ with tm.assertRaises(gbq.TableCreationError):
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table, if_exists='fail')
+
+ def test_redirect_query_results_to_destination_table_if_table_exists_append(self):
+ destination_table = "{0}.{1}".format(DATASET_ID + "7", TABLE_ID + "3")
+ test_size = 100
+
+ # Initialize table with sample data
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table)
+
+ # Test the if_exists parameter with value 'append'
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table, if_exists='append')
+
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), PROJECT_ID)
+ self.assertEqual(result['NUM_ROWS'][0], test_size * 2)
+
+ # Try redirecting data an existing table with different schema, confirm failure
+ with tm.assertRaises(gbq.GenericGBQException):
+ gbq.read_gbq("SELECT title FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table, if_exists='append')
+
+ def test_redirect_query_results_to_destination_table_if_table_exists_replace(self):
+ destination_table = "{0}.{1}".format(DATASET_ID + "7", TABLE_ID + "4")
+ test_size = 100
+
+ # Initialize table with sample data
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table)
+
+ # Test the if_exists parameter with the value 'replace'
+ gbq.read_gbq("SELECT title FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table, if_exists='replace')
+
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), PROJECT_ID)
+ self.assertEqual(result['NUM_ROWS'][0], test_size)
+
+ def test_redirect_query_results_to_destination_table_dataset_does_not_exist(self):
+ destination_table = "{0}.{1}".format(DATASET_ID + "8", TABLE_ID + "5")
+ test_size = 100
+ gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] LIMIT " + str(test_size), PROJECT_ID,
+ destination_table=destination_table)
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), PROJECT_ID)
+ self.assertEqual(result['NUM_ROWS'][0], test_size)
class TestToGBQIntegration(tm.TestCase):
# Changes to BigQuery table schema may take up to 2 minutes as of May 2015
| - Modify `read_gbq()` to allow users to redirect the query results to a destination table via the `destination_table` parameter
- Modify `read_gbq()` to allow users to allow users to set the `'allowLargeResults'` option in the BigQuery job configuration via the `allow_large_results` parameter
cc @aaront
| https://api.github.com/repos/pandas-dev/pandas/pulls/11209 | 2015-09-30T21:35:26Z | 2015-10-02T15:25:42Z | null | 2015-10-02T15:25:42Z |
Copy on Write via weakrefs | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9e1eda4714734..ba6d17997f0b1 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1894,7 +1894,9 @@ def __getitem__(self, key):
is_mi_columns = isinstance(self.columns, MultiIndex)
try:
if key in self.columns and not is_mi_columns:
- return self._getitem_column(key)
+ result = self._getitem_column(key)
+ result._is_column_view = True
+ return result
except:
pass
@@ -2244,7 +2246,6 @@ def __setitem__(self, key, value):
self._set_item(key, value)
def _setitem_slice(self, key, value):
- self._check_setitem_copy()
self.ix._setitem_with_indexer(key, value)
def _setitem_array(self, key, value):
@@ -2255,7 +2256,6 @@ def _setitem_array(self, key, value):
(len(key), len(self.index)))
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
- self._check_setitem_copy()
self.ix._setitem_with_indexer(indexer, value)
else:
if isinstance(value, DataFrame):
@@ -2265,7 +2265,6 @@ def _setitem_array(self, key, value):
self[k1] = value[k2]
else:
indexer = self.ix._convert_to_indexer(key, axis=1)
- self._check_setitem_copy()
self.ix._setitem_with_indexer((slice(None), indexer), value)
def _setitem_frame(self, key, value):
@@ -2275,7 +2274,6 @@ def _setitem_frame(self, key, value):
raise TypeError('Must pass DataFrame with boolean values only')
self._check_inplace_setting(value)
- self._check_setitem_copy()
self.where(-key, value, inplace=True)
def _ensure_valid_index(self, value):
@@ -2311,11 +2309,6 @@ def _set_item(self, key, value):
value = self._sanitize_column(key, value)
NDFrame._set_item(self, key, value)
- # check if we are modifying a copy
- # try to set first as we want an invalid
- # value exeption to occur first
- if len(self):
- self._check_setitem_copy()
def insert(self, loc, column, value, allow_duplicates=False):
"""
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6aec297c31d2b..746648772b01b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -83,7 +83,8 @@ class NDFrame(PandasObject):
_internal_names = ['_data', '_cacher', '_item_cache', '_cache',
'is_copy', '_subtyp', '_index',
'_default_kind', '_default_fill_value', '_metadata',
- '__array_struct__', '__array_interface__']
+ '__array_struct__', '__array_interface__', '_children',
+ '_is_column_view']
_internal_names_set = set(_internal_names)
_accessors = frozenset([])
_metadata = []
@@ -105,6 +106,9 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
object.__setattr__(self, 'is_copy', None)
object.__setattr__(self, '_data', data)
object.__setattr__(self, '_item_cache', {})
+ object.__setattr__(self, '_children', [])
+ object.__setattr__(self, '_is_column_view', False)
+
def _validate_dtype(self, dtype):
""" validate the passed dtype """
@@ -1074,13 +1078,19 @@ def get(self, key, default=None):
-------
value : type of items contained in object
"""
+
try:
return self[key]
except (KeyError, ValueError, IndexError):
return default
def __getitem__(self, item):
- return self._get_item_cache(item)
+ result = self._get_item_cache(item)
+
+ if isinstance(item, str):
+ result._is_column_view = True
+
+ return result
def _get_item_cache(self, item):
""" return the cached item, item represents a label indexer """
@@ -1174,9 +1184,6 @@ def _maybe_update_cacher(self, clear=False, verify_is_copy=True):
except:
pass
- if verify_is_copy:
- self._check_setitem_copy(stacklevel=5, t='referant')
-
if clear:
self._clear_item_cache()
@@ -1201,9 +1208,16 @@ def _slice(self, slobj, axis=0, kind=None):
# but only in a single-dtyped view slicable case
is_copy = axis!=0 or result._is_view
result._set_is_copy(self, copy=is_copy)
+
+ self._children.append(weakref.ref(result))
+
return result
def _set_item(self, key, value):
+
+ # If children are views, reset to copies before setting.
+ self._convert_views_to_copies()
+
self._data.set(key, value)
self._clear_item_cache()
@@ -1216,103 +1230,21 @@ def _set_is_copy(self, ref=None, copy=True):
else:
self.is_copy = None
- def _check_is_chained_assignment_possible(self):
- """
- check if we are a view, have a cacher, and are of mixed type
- if so, then force a setitem_copy check
-
- should be called just near setting a value
-
- will return a boolean if it we are a view and are cached, but a single-dtype
- meaning that the cacher should be updated following setting
- """
- if self._is_view and self._is_cached:
- ref = self._get_cacher()
- if ref is not None and ref._is_mixed_type:
- self._check_setitem_copy(stacklevel=4, t='referant', force=True)
- return True
- elif self.is_copy:
- self._check_setitem_copy(stacklevel=4, t='referant')
- return False
-
- def _check_setitem_copy(self, stacklevel=4, t='setting', force=False):
- """
-
- Parameters
- ----------
- stacklevel : integer, default 4
- the level to show of the stack when the error is output
- t : string, the type of setting error
- force : boolean, default False
- if True, then force showing an error
-
- validate if we are doing a settitem on a chained copy.
-
- If you call this function, be sure to set the stacklevel such that the
- user will see the error *at the level of setting*
+ def _convert_views_to_copies(self):
+ # Don't set on views.
+ if self._is_view and not self._is_column_view:
+ self._data = self._data.copy()
- It is technically possible to figure out that we are setting on
- a copy even WITH a multi-dtyped pandas object. In other words, some blocks
- may be views while other are not. Currently _is_view will ALWAYS return False
- for multi-blocks to avoid having to handle this case.
+ # Before setting values, make sure children converted to copies.
+ for child in self._children:
- df = DataFrame(np.arange(0,9), columns=['count'])
- df['group'] = 'b'
-
- # this technically need not raise SettingWithCopy if both are view (which is not
- # generally guaranteed but is usually True
- # however, this is in general not a good practice and we recommend using .loc
- df.iloc[0:5]['group'] = 'a'
-
- """
-
- if force or self.is_copy:
-
- value = config.get_option('mode.chained_assignment')
- if value is None:
- return
-
- # see if the copy is not actually refererd; if so, then disolve
- # the copy weakref
- try:
- gc.collect(2)
- if not gc.get_referents(self.is_copy()):
- self.is_copy = None
- return
- except:
- pass
-
- # we might be a false positive
- try:
- if self.is_copy().shape == self.shape:
- self.is_copy = None
- return
- except:
- pass
-
- # a custom message
- if isinstance(self.is_copy, string_types):
- t = self.is_copy
-
- elif t == 'referant':
- t = ("\n"
- "A value is trying to be set on a copy of a slice from a "
- "DataFrame\n\n"
- "See the caveats in the documentation: "
- "http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy")
-
- else:
- t = ("\n"
- "A value is trying to be set on a copy of a slice from a "
- "DataFrame.\n"
- "Try using .loc[row_indexer,col_indexer] = value instead\n\n"
- "See the caveats in the documentation: "
- "http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy")
-
- if value == 'raise':
- raise SettingWithCopyError(t)
- elif value == 'warn':
- warnings.warn(t, SettingWithCopyWarning, stacklevel=stacklevel)
+ # Make sure children of children converted.
+ child()._convert_views_to_copies()
+
+ if child()._is_view and not self._is_column_view:
+ child()._data = child()._data.copy()
+
+ self._children=[]
def __delitem__(self, key):
"""
@@ -2229,6 +2161,7 @@ def __finalize__(self, other, method=None, **kwargs):
return self
def __getattr__(self, name):
+
"""After regular attribute access, try looking up the name
This allows simpler access to columns for interactive use.
"""
@@ -2252,6 +2185,7 @@ def __setattr__(self, name, value):
# 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)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 8b4528ef451ef..ab5ba8d00a7f4 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -57,6 +57,7 @@ def __iter__(self):
raise NotImplementedError('ix is not iterable')
def __getitem__(self, key):
+
if type(key) is tuple:
try:
values = self.obj.get_value(*key)
@@ -111,6 +112,9 @@ def _get_setitem_indexer(self, key):
raise IndexingError(key)
def __setitem__(self, key, value):
+ # Make sure changes don't propagate to children
+ self.obj._convert_views_to_copies()
+
indexer = self._get_setitem_indexer(key)
self._setitem_with_indexer(indexer, value)
@@ -199,6 +203,7 @@ def _has_valid_positional_setitem_indexer(self, indexer):
def _setitem_with_indexer(self, indexer, value):
self._has_valid_setitem_indexer(indexer)
+
# also has the side effect of consolidating in-place
from pandas import Panel, DataFrame, Series
info_axis = self.obj._info_axis_number
@@ -508,8 +513,6 @@ def can_do_equal_len():
if isinstance(value, ABCPanel):
value = self._align_panel(indexer, value)
- # check for chained assignment
- self.obj._check_is_chained_assignment_possible()
# actually do the set
self.obj._consolidate_inplace()
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 11645311467d5..8c54065a6c428 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -714,10 +714,7 @@ def setitem(key, value):
self._set_with(key, value)
# do the setitem
- cacher_needs_updating = self._check_is_chained_assignment_possible()
setitem(key, value)
- if cacher_needs_updating:
- self._maybe_update_cacher()
def _set_with_engine(self, key, value):
values = self._values
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 3a26be2ca1032..ef9ea44f92cd2 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -1681,6 +1681,104 @@ def test_set_attribute(self):
assert_equal(df.y, 5)
assert_series_equal(df['y'], Series([2, 4, 6], name='y'))
+ def test_copy_on_write(self):
+
+ #######
+ # FORWARD PROPAGATION TESTS
+ #######
+
+ # Test various slicing methods add to _children
+
+ df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
+ self.assertTrue(len(df._children)==0)
+
+
+ views = dict()
+
+ views['loc'] = df.loc[0:0,]
+ views['iloc'] = df.iloc[0:1,]
+ views['ix'] = df.ix[0:0,]
+ views['loc_of_loc'] = views['loc'].loc[0:0,]
+
+ copies = dict()
+ for v in views.keys():
+ self.assertTrue(views[v]._is_view)
+ copies[v] = views[v].copy()
+
+
+
+ df.loc[0,'col1'] = -88
+
+ for v in views.keys():
+ tm.assert_frame_equal(views[v], copies[v])
+ self.assertFalse(views[v]._is_view)
+
+ # Test different forms of value setting
+ # all trigger conversions
+
+ parent = dict()
+ views = dict()
+ copies = dict()
+ for v in ['loc', 'iloc', 'ix', 'column', 'attribute']:
+ parent[v] = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
+ views[v] = parent[v].loc[0:0,]
+ copies[v] = views[v].copy()
+ self.assertTrue( views[v]._is_view )
+
+ parent['loc'].loc[0, 'col1'] = -88
+ parent['iloc'].iloc[0, 0] = -88
+ parent['ix'].ix[0, 'col1'] = -88
+ parent['column']['col1'] = -88
+ parent['attribute'].col1 = -88
+
+
+ for v in views.keys():
+ tm.assert_frame_equal(views[v], copies[v])
+ self.assertFalse(views[v]._is_view)
+
+ ########
+ # No Backward Propogation
+ #######
+ df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
+ df_copy = df.copy()
+
+ views = dict()
+
+ views['loc'] = df.loc[0:0,]
+ views['iloc'] = df.iloc[0:1,]
+ views['ix'] = df.ix[0:0,]
+ views['loc_of_loc'] = views['loc'].loc[0:0,]
+
+ for v in views.keys():
+ views[v].loc[0:0,] = -99
+
+ tm.assert_frame_equal(df, df_copy)
+
+ ###
+ # Dictionary-like access to single columns SHOULD give views
+ ###
+
+ # If change child, should back-propagate
+ df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
+ v = df['col1']
+ self.assertTrue(v._is_view)
+ self.assertTrue(v._is_column_view)
+ v.loc[0]=-88
+ self.assertTrue(df.loc[0,'col1'] == -88)
+ self.assertTrue(v._is_view)
+
+ # If change parent, should forward-propagate
+ df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
+ v = df['col1']
+ self.assertTrue(v._is_view)
+ self.assertTrue(v._is_column_view)
+ df.loc[0, 'col1']=-88
+ self.assertTrue(v.loc[0] == -88)
+ self.assertTrue(v._is_view)
+
+
+
+
class TestPanel(tm.TestCase, Generic):
_typ = Panel
| Aims to eventually close #10954 , alternative to #10973
In the interest of advancing the discussion on this, here's a skeleton of a different copy on write implementation.
**Currently**
When setting on a view, converts to copy.
```
df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
intermediate = df.loc[1:1,]
intermediate['col1'] = -99
intermediate
Out[8]:
col1 col2
1 -99 4
df
Out[9]:
col1 col2
0 1 3
1 2 4
```
Chained-indexing will ALWAYS fail.
```
df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
df.loc[1:1,]['col1'] = -99
df
Out[11]:
col1 col2
1 2 4
```
`SettingWithCopy` warning disabled, thought not fully removed (figure this is too early stage to really chase that down).
Forward Protection for `loc` setting (proof of concept, added oct 2):
```
df = pd.DataFrame({'col1':[1,2], 'col2':[3,4]})
intermediate = df.loc[1:1,]
df.loc[1,'col1'] = -99
intermediate
Out[11]:
col1 col2
0 1 3
1 2 4
```
**Goals / Places I'd love help**
- We've discussed keeps full-column slices as views, since we can guarantee these will always be views. I created an attribute called `_is_column_view` that can be set to `True` when a slice is a full column (e.g. `new = df['col1']`, but I'm not sure how to actually figure out if a slice is a full column, so right now it's initialized as `False` and just stays that way.
- This has no protection against forward propagation -- situations where one sets values on a Frame and they propagate to views of that Frame. There IS a framework to address it, but it's incomplete. As it stands:
- Frames now have a `_children` list attribute to keep references to their child `views`.
- Before setting, there's a call to a function to try and convert the children from `views` to `copies`.
But as it stand, I don't know how to really manage those references (i.e. how to put references to children in that `_children` list).
@jreback
@shoyer
@JanSchulz
@TomAugspurger
| https://api.github.com/repos/pandas-dev/pandas/pulls/11207 | 2015-09-30T17:11:45Z | 2015-11-01T16:35:56Z | null | 2020-09-06T18:44:21Z |
PERF: vectorized DateOffset with months | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 03cac12436898..79d0788efad82 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1056,6 +1056,7 @@ Performance Improvements
- 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`)
- Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`)
- Regression from 0.16.1 in constructing ``DataFrame`` from nested dictionary (:issue:`11084`)
+- Performance improvements in addition/subtraction operations for ``DateOffset`` with ``Series`` or ``DatetimeIndex`` (issue:`10744`, :issue:`11205`)
.. _whatsnew_0170.bug_fixes:
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index e15be45ef305a..0dac09a243d36 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -261,16 +261,12 @@ def apply_index(self, i):
# relativedelta/_offset path only valid for base DateOffset
if (self._use_relativedelta and
set(self.kwds).issubset(relativedelta_fast)):
+
months = ((self.kwds.get('years', 0) * 12
+ self.kwds.get('months', 0)) * self.n)
if months:
- base = (i.to_period('M') + months).to_timestamp()
- time = i.to_perioddelta('D')
- days = i.to_perioddelta('M') - time
- # minimum prevents month-end from wrapping
- day_offset = np.minimum(days,
- to_timedelta(base.days_in_month - 1, unit='D'))
- i = base + day_offset + time
+ shifted = tslib.shift_months(i.asi8, months)
+ i = i._shallow_copy(shifted)
weeks = (self.kwds.get('weeks', 0)) * self.n
if weeks:
@@ -1081,7 +1077,9 @@ def apply(self, other):
@apply_index_wraps
def apply_index(self, i):
- return self._end_apply_index(i, 'M')
+ months = self.n - 1 if self.n >= 0 else self.n
+ shifted = tslib.shift_months(i.asi8, months, 'end')
+ return i._shallow_copy(shifted)
def onOffset(self, dt):
if self.normalize and not _is_normalized(dt):
@@ -1106,7 +1104,9 @@ def apply(self, other):
@apply_index_wraps
def apply_index(self, i):
- return self._beg_apply_index(i, 'M')
+ months = self.n + 1 if self.n < 0 else self.n
+ shifted = tslib.shift_months(i.asi8, months, 'start')
+ return i._shallow_copy(shifted)
def onOffset(self, dt):
if self.normalize and not _is_normalized(dt):
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 957cdcc009e1c..ed174bc285e4f 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -2565,32 +2565,32 @@ def test_datetime64_with_DateOffset(self):
for klass, assert_func in zip([Series, DatetimeIndex],
[self.assert_series_equal,
tm.assert_index_equal]):
- s = klass(date_range('2000-01-01', '2000-01-31'))
+ s = klass(date_range('2000-01-01', '2000-01-31'), name='a')
result = s + pd.DateOffset(years=1)
result2 = pd.DateOffset(years=1) + s
- exp = klass(date_range('2001-01-01', '2001-01-31'))
+ exp = klass(date_range('2001-01-01', '2001-01-31'), name='a')
assert_func(result, exp)
assert_func(result2, exp)
result = s - pd.DateOffset(years=1)
- exp = klass(date_range('1999-01-01', '1999-01-31'))
+ exp = klass(date_range('1999-01-01', '1999-01-31'), name='a')
assert_func(result, exp)
s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'),
- pd.Timestamp('2000-02-15', tz='US/Central')])
+ pd.Timestamp('2000-02-15', tz='US/Central')], name='a')
result = s + pd.offsets.Day()
result2 = pd.offsets.Day() + s
exp = klass([Timestamp('2000-01-16 00:15:00', tz='US/Central'),
- Timestamp('2000-02-16', tz='US/Central')])
+ Timestamp('2000-02-16', tz='US/Central')], name='a')
assert_func(result, exp)
assert_func(result2, exp)
s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'),
- pd.Timestamp('2000-02-15', tz='US/Central')])
+ pd.Timestamp('2000-02-15', tz='US/Central')], name='a')
result = s + pd.offsets.MonthEnd()
result2 = pd.offsets.MonthEnd() + s
exp = klass([Timestamp('2000-01-31 00:15:00', tz='US/Central'),
- Timestamp('2000-02-29', tz='US/Central')])
+ Timestamp('2000-02-29', tz='US/Central')], name='a')
assert_func(result, exp)
assert_func(result2, exp)
diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py
index fadad91e6842a..f618b2593597e 100644
--- a/pandas/tseries/tests/test_tslib.py
+++ b/pandas/tseries/tests/test_tslib.py
@@ -949,6 +949,17 @@ def compare_local_to_utc(tz_didx, utc_didx):
tslib.maybe_get_tz('Asia/Tokyo'))
self.assert_numpy_array_equal(result, np.array([tslib.iNaT], dtype=np.int64))
+ def test_shift_months(self):
+ s = DatetimeIndex([Timestamp('2000-01-05 00:15:00'), Timestamp('2000-01-31 00:23:00'),
+ Timestamp('2000-01-01'), Timestamp('2000-02-29'), Timestamp('2000-12-31')])
+ for years in [-1, 0, 1]:
+ for months in [-2, 0, 2]:
+ actual = DatetimeIndex(tslib.shift_months(s.asi8, years * 12 + months))
+ expected = DatetimeIndex([x + offsets.DateOffset(years=years, months=months) for x in s])
+ tm.assert_index_equal(actual, expected)
+
+
+
class TestTimestampOps(tm.TestCase):
def test_timestamp_and_datetime(self):
self.assertEqual((Timestamp(datetime.datetime(2013, 10, 13)) - datetime.datetime(2013, 10, 12)).days, 1)
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 7b3e404f7504c..398c5f0232de1 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -3847,6 +3847,7 @@ def get_time_micros(ndarray[int64_t] dtindex):
return micros
+
@cython.wraparound(False)
def get_date_field(ndarray[int64_t] dtindex, object field):
'''
@@ -4386,6 +4387,75 @@ cpdef normalize_date(object dt):
raise TypeError('Unrecognized type: %s' % type(dt))
+cdef inline int _year_add_months(pandas_datetimestruct dts,
+ int months):
+ '''new year number after shifting pandas_datetimestruct number of months'''
+ return dts.year + (dts.month + months - 1) / 12
+
+cdef inline int _month_add_months(pandas_datetimestruct dts,
+ int months):
+ '''new month number after shifting pandas_datetimestruct number of months'''
+ cdef int new_month = (dts.month + months) % 12
+ return 12 if new_month == 0 else new_month
+
+@cython.wraparound(False)
+def shift_months(int64_t[:] dtindex, int months, object day=None):
+ '''
+ Given an int64-based datetime index, shift all elements
+ specified number of months using DateOffset semantics
+
+ day: {None, 'start', 'end'}
+ * None: day of month
+ * 'start' 1st day of month
+ * 'end' last day of month
+ '''
+ cdef:
+ Py_ssize_t i
+ int days_in_month
+ pandas_datetimestruct dts
+ int count = len(dtindex)
+ int64_t[:] out = np.empty(count, dtype='int64')
+
+ for i in range(count):
+ if dtindex[i] == NPY_NAT:
+ out[i] = NPY_NAT
+ else:
+ pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts)
+
+ if day is None:
+ dts.year = _year_add_months(dts, months)
+ dts.month = _month_add_months(dts, months)
+ #prevent day from wrapping around month end
+ days_in_month = days_per_month_table[is_leapyear(dts.year)][dts.month-1]
+ dts.day = min(dts.day, days_in_month)
+ elif day == 'start':
+ dts.year = _year_add_months(dts, months)
+ dts.month = _month_add_months(dts, months)
+
+ # offset semantics - when subtracting if at the start anchor
+ # point, shift back by one more month
+ if months <= 0 and dts.day == 1:
+ dts.year = _year_add_months(dts, -1)
+ dts.month = _month_add_months(dts, -1)
+ else:
+ dts.day = 1
+ elif day == 'end':
+ days_in_month = days_per_month_table[is_leapyear(dts.year)][dts.month-1]
+ dts.year = _year_add_months(dts, months)
+ dts.month = _month_add_months(dts, months)
+
+ # similar semantics - when adding shift forward by one
+ # month if already at an end of month
+ if months >= 0 and dts.day == days_in_month:
+ dts.year = _year_add_months(dts, 1)
+ dts.month = _month_add_months(dts, 1)
+
+ days_in_month = days_per_month_table[is_leapyear(dts.year)][dts.month-1]
+ dts.day = days_in_month
+
+ out[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts)
+ return np.asarray(out)
+
#----------------------------------------------------------------------
# Don't even ask
| This is a follow-up to https://github.com/pydata/pandas/pull/10744. In that, vectorized versions of some offsets were implemented, mostly by changing to periods and back.
The case of shifting by years/months (which is actually most useful to me) required some extra hoops and had poorer performance - this PR implements a special cython routine for that, for about a 10x improvement.
```
In [3]: s = pd.Series(pd.date_range('1900-1-1', periods=100000))
# Master
In [4]: %timeit s + pd.DateOffset(months=1)
1 loops, best of 3: 140 ms per loop
# PR
In [2]: %timeit s + pd.DateOffset(months=1)
100 loops, best of 3: 14.2 ms per loo
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11205 | 2015-09-30T00:03:30Z | 2015-10-02T02:15:07Z | 2015-10-02T02:15:07Z | 2015-10-04T17:01:51Z |
Fixed pandas.DataFrame().join() function. | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9e1eda4714734..5215df316147d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4175,7 +4175,7 @@ def append(self, other, ignore_index=False, verify_integrity=False):
return concat(to_concat, ignore_index=ignore_index,
verify_integrity=verify_integrity)
- def join(self, other, on=None, how='left', lsuffix='', rsuffix='',
+ def join(self, other, on=None, left_on=None, right_on=None, how='left', lsuffix='', rsuffix='',
sort=False):
"""
Join columns with other DataFrame either on index or on a key
@@ -4193,6 +4193,10 @@ def join(self, other, on=None, how='left', lsuffix='', rsuffix='',
columns given, the passed DataFrame must have a MultiIndex. Can
pass an array as the join key if not already contained in the
calling DataFrame. Like an Excel VLOOKUP operation
+ left_on : column name, tuple/list of column names, or array-like
+ Column(s) to use for joining, otherwise join on index.
+ right_on : column name, tuple/list of column names, or array-like
+ Column(s) to use for joining, otherwise join on index.
how : {'left', 'right', 'outer', 'inner'}
How to handle indexes of the two objects. Default: 'left'
for joining on index, None otherwise
@@ -4219,10 +4223,10 @@ def join(self, other, on=None, how='left', lsuffix='', rsuffix='',
joined : DataFrame
"""
# For SparseDataFrame's benefit
- return self._join_compat(other, on=on, how=how, lsuffix=lsuffix,
+ return self._join_compat(other, on=on, left_on=left_on, right_on=right_on, how=how, lsuffix=lsuffix,
rsuffix=rsuffix, sort=sort)
- def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
+ def _join_compat(self, other, on=None, left_on=None, right_on=None, how='left', lsuffix='', rsuffix='',
sort=False):
from pandas.tools.merge import merge, concat
@@ -4232,8 +4236,19 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
other = DataFrame({other.name: other})
if isinstance(other, DataFrame):
- return merge(self, other, left_on=on, how=how,
- left_index=on is None, right_index=True,
+ if left_on == None and on != None:
+ left_on = on
+ if right_on == None and on != None:
+ right_on = on
+
+ '''Workaround to preserve the documented behavior of join()'''
+ if right_on == None and left_on == None and on != None:
+ left_on = on
+ on = None
+
+ return merge(self, other, left_on=left_on, right_on=right_on, how=how,
+ left_index=((on is None) and (left_on is None)),
+ right_index=((on is None) and (right_on is None)),
suffixes=(lsuffix, rsuffix), sort=sort)
else:
if on is not None:
| Added on_right and on_left keywords.
Now a right.join(left,on=key) works as expected.
Old behavior is archived by right.join(left,left_on=key)
Tested multi-index funtionallity.
```
import pandas as pd
from copy import copy
print pd.__file__
left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3','A4'],
'key': ['K0', 'K1', 'K3', 'K4','K5']})
right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
'key': ['K0', 'K2', 'K1', 'K3']},
index=[4,5,6,7])
print left.join(right,on='key',how="outer",rsuffix="_r")
```
Old result:
```
A key C key_r
0 A0 K0 NaN NaN
1 A1 K1 NaN NaN
2 A2 K3 NaN NaN
3 A3 K4 NaN NaN
4 A4 K5 NaN NaN
4 NaN 4 C0 K0
4 NaN 5 C1 K2
4 NaN 6 C2 K1
4 NaN 7 C3 K3
```
New result:
```
A key C
0 A0 K0 C0
1 A1 K1 C2
2 A2 K3 C3
3 A3 K4 NaN
4 A4 K5 NaN
5 NaN K2 C1
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11203 | 2015-09-29T19:51:34Z | 2015-10-05T11:05:55Z | null | 2015-10-05T11:05:55Z |
BUG: groupby list of keys with same length as index | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index c8ab9599cd92a..11596fe5d4ee3 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1184,3 +1184,4 @@ Bug Fixes
- Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`)
- Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`)
- Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`)
+- Bug in ``.groupby`` when number of keys to group by is same as length of index (:issue:`11185`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 9748a594a9b6f..e837445e9e348 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -2111,6 +2111,7 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True):
# what are we after, exactly?
match_axis_length = len(keys) == len(group_axis)
any_callable = any(callable(g) or isinstance(g, dict) for g in keys)
+ any_groupers = any(isinstance(g, Grouper) for g in keys)
any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray))
for g in keys)
@@ -2123,7 +2124,8 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True):
all_in_columns = False
if (not any_callable and not all_in_columns
- and not any_arraylike and match_axis_length
+ and not any_arraylike and not any_groupers
+ and match_axis_length
and level is None):
keys = [com._asarray_tuplesafe(keys)]
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 42d5af587a859..8eb641ce8f494 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2989,6 +2989,18 @@ def test_groupby_list_infer_array_like(self):
result = df.groupby(['foo', 'bar']).mean()
expected = df.groupby([df['foo'], df['bar']]).mean()[['val']]
+ def test_groupby_keys_same_size_as_index(self):
+ # GH 11185
+ freq = 's'
+ index = pd.date_range(start=np.datetime64(
+ '2015-09-29T11:34:44-0700'), periods=2, freq=freq)
+ df = pd.DataFrame([['A', 10], ['B', 15]], columns=[
+ 'metric', 'values'], index=index)
+ result = df.groupby([pd.Grouper(level=0, freq=freq), 'metric']).mean()
+ expected = df.set_index([df.index, 'metric'])
+
+ assert_frame_equal(result, expected)
+
def test_groupby_nat_exclude(self):
# GH 6992
df = pd.DataFrame({'values': np.random.randn(8),
| Fixes issue #11185
| https://api.github.com/repos/pandas-dev/pandas/pulls/11202 | 2015-09-29T19:06:15Z | 2015-10-01T10:45:44Z | 2015-10-01T10:45:44Z | 2015-10-01T10:45:52Z |
API: read_excel signature | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 94da87aef73e1..9def8be621aed 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1980,9 +1980,10 @@ Excel files
-----------
The :func:`~pandas.read_excel` method can read Excel 2003 (``.xls``) and
-Excel 2007 (``.xlsx``) files using the ``xlrd`` Python
-module and use the same parsing code as the above to convert tabular data into
-a DataFrame. See the :ref:`cookbook<cookbook.excel>` for some
+Excel 2007+ (``.xlsx``) files using the ``xlrd`` Python
+module. The :meth:`~DataFrame.to_excel` instance method is used for
+saving a ``DataFrame`` to Excel. Generally the semantics are
+similar to working with :ref:`csv<io.read_csv_table>` data. See the :ref:`cookbook<cookbook.excel>` for some
advanced strategies
.. _io.excel_reader:
@@ -1990,90 +1991,74 @@ advanced strategies
Reading Excel Files
'''''''''''''''''''
-.. versionadded:: 0.17
+In the most basic use-case, ``read_excel`` takes a path to an Excel
+file, and the ``sheetname`` indicating which sheet to parse.
-``read_excel`` can read a ``MultiIndex`` index, by passing a list of columns to ``index_col``
-and a ``MultiIndex`` column by passing a list of rows to ``header``. If either the ``index``
-or ``columns`` have serialized level names those will be read in as well by specifying
-the rows/columns that make up the levels.
-
-.. ipython:: python
+.. code-block:: python
- # MultiIndex index - no names
- df = pd.DataFrame({'a':[1,2,3,4], 'b':[5,6,7,8]},
- index=pd.MultiIndex.from_product([['a','b'],['c','d']]))
- df.to_excel('path_to_file.xlsx')
- df = pd.read_excel('path_to_file.xlsx', index_col=[0,1])
- df
+ # Returns a DataFrame
+ read_excel('path_to_file.xls', sheetname='Sheet1')
- # MultiIndex index - with names
- df.index = df.index.set_names(['lvl1', 'lvl2'])
- df.to_excel('path_to_file.xlsx')
- df = pd.read_excel('path_to_file.xlsx', index_col=[0,1])
- df
- # MultiIndex index and column - with names
- df.columns = pd.MultiIndex.from_product([['a'],['b', 'd']], names=['c1', 'c2'])
- df.to_excel('path_to_file.xlsx')
- df = pd.read_excel('path_to_file.xlsx',
- index_col=[0,1], header=[0,1])
- df
+.. _io.excel.excelfile_class:
-.. ipython:: python
- :suppress:
+``ExcelFile`` class
++++++++++++++++++++
- import os
- os.remove('path_to_file.xlsx')
+To faciliate working with multiple sheets from the same file, the ``ExcelFile``
+class can be used to wrap the file and can be be passed into ``read_excel``
+There will be a performance benefit for reading multiple sheets as the file is
+read into memory only once.
-.. warning::
+.. code-block:: python
- Excel files saved in version 0.16.2 or prior that had index names will still able to be read in,
- but the ``has_index_names`` argument must specified to ``True``.
+ xlsx = pd.ExcelFile('path_to_file.xls)
+ df = pd.read_excel(xlsx, 'Sheet1')
-.. versionadded:: 0.16
+The ``ExcelFile`` class can also be used as a context manager.
-``read_excel`` can read more than one sheet, by setting ``sheetname`` to either
-a list of sheet names, a list of sheet positions, or ``None`` to read all sheets.
+.. code-block:: python
-.. versionadded:: 0.13
+ with pd.ExcelFile('path_to_file.xls') as xls:
+ df1 = pd.read_excel(xls, 'Sheet1')
+ df2 = pd.read_excel(xls, 'Sheet2')
-Sheets can be specified by sheet index or sheet name, using an integer or string,
-respectively.
+The ``sheet_names`` property will generate
+a list of the sheet names in the file.
-.. versionadded:: 0.12
+The primary use-case for an ``ExcelFile`` is parsing multiple sheets with
+different parameters
-``ExcelFile`` has been moved to the top level namespace.
+.. code-block:: python
-There are two approaches to reading an excel file. The ``read_excel`` function
-and the ``ExcelFile`` class. ``read_excel`` is for reading one file
-with file-specific arguments (ie. identical data formats across sheets).
-``ExcelFile`` is for reading one file with sheet-specific arguments (ie. various data
-formats across sheets). Choosing the approach is largely a question of
-code readability and execution speed.
+ data = {}
+ # For when Sheet1's format differs from Sheet2
+ with pd.ExcelFile('path_to_file.xls') as xls:
+ data['Sheet1'] = pd.read_excel(xls, 'Sheet1', index_col=None, na_values=['NA'])
+ data['Sheet2'] = pd.read_excel(xls, 'Sheet2', index_col=1)
-Equivalent class and function approaches to read a single sheet:
+Note that if the same parsing parameters are used for all sheets, a list
+of sheet names can simply be passed to ``read_excel`` with no loss in performance.
.. code-block:: python
# using the ExcelFile class
- xls = pd.ExcelFile('path_to_file.xls')
- data = xls.parse('Sheet1', index_col=None, na_values=['NA'])
+ data = {}
+ with pd.ExcelFile('path_to_file.xls') as xls:
+ data['Sheet1'] = read_excel(xls, 'Sheet1', index_col=None, na_values=['NA'])
+ data['Sheet2'] = read_excel(xls, 'Sheet2', index_col=None, na_values=['NA'])
- # using the read_excel function
- data = read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
+ # equivalent using the read_excel function
+ data = read_excel('path_to_file.xls', ['Sheet1', 'Sheet2'], index_col=None, na_values=['NA'])
-Equivalent class and function approaches to read multiple sheets:
+.. versionadded:: 0.12
-.. code-block:: python
+``ExcelFile`` has been moved to the top level namespace.
- data = {}
- # For when Sheet1's format differs from Sheet2
- xls = pd.ExcelFile('path_to_file.xls')
- data['Sheet1'] = xls.parse('Sheet1', index_col=None, na_values=['NA'])
- data['Sheet2'] = xls.parse('Sheet2', index_col=1)
+.. versionadded:: 0.17
+
+``read_excel`` can take an ``ExcelFile`` object as input
- # For when Sheet1's format is identical to Sheet2
- data = read_excel('path_to_file.xls', ['Sheet1','Sheet2'], index_col=None, na_values=['NA'])
.. _io.excel.specifying_sheets:
@@ -2125,6 +2110,72 @@ Using a list to get multiple sheets:
# Returns the 1st and 4th sheet, as a dictionary of DataFrames.
read_excel('path_to_file.xls',sheetname=['Sheet1',3])
+.. versionadded:: 0.16
+
+``read_excel`` can read more than one sheet, by setting ``sheetname`` to either
+a list of sheet names, a list of sheet positions, or ``None`` to read all sheets.
+
+.. versionadded:: 0.13
+
+Sheets can be specified by sheet index or sheet name, using an integer or string,
+respectively.
+
+.. _io.excel.reading_multiindex:
+
+Reading a ``MultiIndex``
+++++++++++++++++++++++++
+
+.. versionadded:: 0.17
+
+``read_excel`` can read a ``MultiIndex`` index, by passing a list of columns to ``index_col``
+and a ``MultiIndex`` column by passing a list of rows to ``header``. If either the ``index``
+or ``columns`` have serialized level names those will be read in as well by specifying
+the rows/columns that make up the levels.
+
+For example, to read in a ``MultiIndex`` index without names:
+
+.. ipython:: python
+
+ df = pd.DataFrame({'a':[1,2,3,4], 'b':[5,6,7,8]},
+ index=pd.MultiIndex.from_product([['a','b'],['c','d']]))
+ df.to_excel('path_to_file.xlsx')
+ df = pd.read_excel('path_to_file.xlsx', index_col=[0,1])
+ df
+
+If the index has level names, they will parsed as well, using the same
+parameters.
+
+.. ipython:: python
+
+ df.index = df.index.set_names(['lvl1', 'lvl2'])
+ df.to_excel('path_to_file.xlsx')
+ df = pd.read_excel('path_to_file.xlsx', index_col=[0,1])
+ df
+
+
+If the source file has both ``MultiIndex`` index and columns, lists specifying each
+should be passed to ``index_col`` and ``header``
+
+.. ipython:: python
+
+ df.columns = pd.MultiIndex.from_product([['a'],['b', 'd']], names=['c1', 'c2'])
+ df.to_excel('path_to_file.xlsx')
+ df = pd.read_excel('path_to_file.xlsx',
+ index_col=[0,1], header=[0,1])
+ df
+
+.. ipython:: python
+ :suppress:
+
+ import os
+ os.remove('path_to_file.xlsx')
+
+.. warning::
+
+ Excel files saved in version 0.16.2 or prior that had index names will still able to be read in,
+ but the ``has_index_names`` argument must specified to ``True``.
+
+
Parsing Specific Columns
++++++++++++++++++++++++
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 03cac12436898..3169d977750e1 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -937,6 +937,8 @@ Other API Changes
- When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column
was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`)
- some numeric reduction operators would return ``ValueError``, rather than ``TypeError`` on object types that includes strings and numbers (:issue:`11131`)
+- Passing currently unsupported ``chunksize`` argument to ``read_excel`` or ``ExcelFile.parse`` will now raise ``NotImplementedError`` (:issue:`8011`)
+- Allow an ``ExcelFile`` object to be passed into ``read_excel`` (:issue:`11198`)
- ``DatetimeIndex.union`` does not infer ``freq`` if ``self`` and the input have ``None`` as ``freq`` (:issue:`11086`)
- ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`)
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index d90a8b8e90a93..a7a844cdfcb40 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -70,12 +70,20 @@ def get_writer(engine_name):
except KeyError:
raise ValueError("No Excel writer '%s'" % engine_name)
-
-excel_doc_common = """
+def read_excel(io, sheetname=0, header=0, skiprows=None, skip_footer=0,
+ index_col=None, parse_cols=None, parse_dates=False,
+ date_parser=None, na_values=None, thousands=None,
+ convert_float=True, has_index_names=None, converters=None,
+ engine=None, **kwds):
+ """
Read an Excel table into a pandas DataFrame
Parameters
- ----------%(io)s
+ ----------
+ io : string, file-like object, pandas ExcelFile, or xlrd workbook.
+ 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
sheetname : string, int, mixed list of strings/ints, or None, default 0
Strings are used for sheet names, Integers are used in zero-indexed sheet
@@ -122,18 +130,24 @@ def get_writer(engine_name):
na_values : list-like, default None
List of additional strings to recognize as NA/NaN
thousands : str, default None
- Thousands separator
+ Thousands separator for parsing string columns to numeric. Note that
+ this parameter is only necessary for columns stored as TEXT in Excel,
+ any numeric columns will automatically be parsed, regardless of display
+ format.
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN
values are overridden, otherwise they're appended to
verbose : boolean, default False
- Indicate number of NA values placed in non-numeric columns%(eng)s
+ 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
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
internally
has_index_names : boolean, default None
- DEPCRECATED: for version 0.17+ index names will be automatically inferred
+ DEPRECATED: for version 0.17+ index names will be automatically inferred
based on index_col. To read Excel output from 0.16.2 and prior that
had saved index names, use True.
@@ -144,28 +158,21 @@ def get_writer(engine_name):
for more information on when a Dict of Dataframes is returned.
"""
-read_excel_kwargs = dict()
-read_excel_kwargs['io'] = """
- io : string, file-like object, or xlrd workbook.
- 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"""
-read_excel_kwargs['eng'] = """
- 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"""
-
-@Appender(excel_doc_common % read_excel_kwargs)
-def read_excel(io, sheetname=0, **kwds):
- engine = kwds.pop('engine', None)
- return ExcelFile(io, engine=engine).parse(sheetname=sheetname, **kwds)
+ if not isinstance(io, ExcelFile):
+ io = ExcelFile(io, engine=engine)
+ return io._parse_excel(
+ sheetname=sheetname, header=header, skiprows=skiprows,
+ index_col=index_col, parse_cols=parse_cols, parse_dates=parse_dates,
+ date_parser=date_parser, na_values=na_values, thousands=thousands,
+ convert_float=convert_float, has_index_names=has_index_names,
+ skip_footer=skip_footer, converters=converters, **kwds)
class ExcelFile(object):
"""
Class for parsing tabular excel sheets into DataFrame objects.
- Uses xlrd. See ExcelFile.parse for more documentation
+ Uses xlrd. See read_excel for more documentation
Parameters
----------
@@ -207,23 +214,16 @@ def __init__(self, io, **kwds):
raise ValueError('Must explicitly set engine if not passing in'
' buffer or path for io.')
- @Appender(excel_doc_common % dict(io='', eng=''))
def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0,
index_col=None, parse_cols=None, parse_dates=False,
- date_parser=None, na_values=None, thousands=None, chunksize=None,
+ date_parser=None, na_values=None, thousands=None,
convert_float=True, has_index_names=None, converters=None, **kwds):
+ """
+ Parse specified sheet(s) into a DataFrame
- skipfooter = kwds.pop('skipfooter', None)
- if skipfooter is not None:
- skip_footer = skipfooter
-
- _validate_header_arg(header)
- if has_index_names is not None:
- warn("\nThe has_index_names argument is deprecated; index names "
- "will be automatically inferred based on index_col.\n"
- "This argmument is still necessary if reading Excel output "
- "from 0.16.2 or prior with index names.", FutureWarning,
- stacklevel=3)
+ Equivalent to read_excel(ExcelFile, ...) See the read_excel
+ docstring for more info on accepted parameters
+ """
return self._parse_excel(sheetname=sheetname, header=header,
skiprows=skiprows,
@@ -232,7 +232,7 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0,
parse_cols=parse_cols,
parse_dates=parse_dates,
date_parser=date_parser, na_values=na_values,
- thousands=thousands, chunksize=chunksize,
+ thousands=thousands,
skip_footer=skip_footer,
convert_float=convert_float,
converters=converters,
@@ -274,8 +274,25 @@ def _excel2num(x):
def _parse_excel(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,
+ thousands=None, convert_float=True,
verbose=False, **kwds):
+
+ skipfooter = kwds.pop('skipfooter', None)
+ if skipfooter is not None:
+ skip_footer = skipfooter
+
+ _validate_header_arg(header)
+ if has_index_names is not None:
+ warn("\nThe has_index_names argument is deprecated; index names "
+ "will be automatically inferred based on index_col.\n"
+ "This argmument is still necessary if reading Excel output "
+ "from 0.16.2 or prior with index names.", FutureWarning,
+ stacklevel=3)
+
+ if 'chunksize' in kwds:
+ raise NotImplementedError("Reading an Excel file in chunks "
+ "is not implemented")
+
import xlrd
from xlrd import (xldate, XL_CELL_DATE,
XL_CELL_ERROR, XL_CELL_BOOLEAN,
@@ -416,7 +433,6 @@ def _parse_cell(cell_contents,cell_typ):
date_parser=date_parser,
skiprows=skiprows,
skip_footer=skip_footer,
- chunksize=chunksize,
**kwds)
output[asheetname] = parser.read()
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 614b42cb156a8..13bb116638b98 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -158,76 +158,67 @@ def setUp(self):
def test_parse_cols_int(self):
dfref = self.get_csv_refdf('test1')
- excel = self.get_excelfile('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)
+ df1 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ parse_cols=3)
+ df2 = self.get_exceldf('test1', '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):
- excel = self.get_excelfile('test1')
dfref = self.get_csv_refdf('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])
+ df1 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ parse_cols=[0, 2, 3])
+ df2 = self.get_exceldf('test1', '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):
- excel = self.get_excelfile('test1')
dfref = self.get_csv_refdf('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')
+ df2 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ parse_cols='A:D')
+ df3 = self.get_exceldf('test1', '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')
+ df2 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ parse_cols='A,C,D')
+ df3 = self.get_exceldf('test1', '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')
+ df2 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ parse_cols='A,C:D')
+ df3 = self.get_exceldf('test1', '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):
- excel = self.get_excelfile('test2')
-
- parsed = excel.parse('Sheet1')
+ parsed = self.get_exceldf('test2', 'Sheet1')
expected = DataFrame([['aaaa', 'bbbbb']], columns=['Test', 'Test1'])
tm.assert_frame_equal(parsed, expected)
def test_excel_cell_error_na(self):
- excel = self.get_excelfile('test3')
-
- parsed = excel.parse('Sheet1')
+ parsed = self.get_exceldf('test3', 'Sheet1')
expected = DataFrame([[np.nan]], columns=['Test'])
tm.assert_frame_equal(parsed, expected)
@@ -235,13 +226,13 @@ def test_excel_passes_na(self):
excel = self.get_excelfile('test4')
- parsed = excel.parse('Sheet1', keep_default_na=False,
+ parsed = read_excel(excel, '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.parse('Sheet1', keep_default_na=True,
+ parsed = read_excel(excel, 'Sheet1', keep_default_na=True,
na_values=['apple'])
expected = DataFrame([[np.nan], [1], [np.nan], [np.nan], ['rabbit']],
columns=['Test'])
@@ -252,35 +243,45 @@ def test_excel_table_sheet_by_index(self):
excel = self.get_excelfile('test1')
dfref = self.get_csv_refdf('test1')
+ df1 = read_excel(excel, 0, index_col=0, parse_dates=True)
+ df2 = read_excel(excel, 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)
+
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)
+ df3 = read_excel(excel, 0, index_col=0, parse_dates=True, skipfooter=1)
+ df4 = read_excel(excel, 0, index_col=0, parse_dates=True, skip_footer=1)
+ tm.assert_frame_equal(df3, df1.ix[:-1])
+ tm.assert_frame_equal(df3, df4)
+
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)
import xlrd
- self.assertRaises(xlrd.XLRDError, excel.parse, 'asdf')
+ with tm.assertRaises(xlrd.XLRDError):
+ read_excel(excel, 'asdf')
def test_excel_table(self):
- excel = self.get_excelfile('test1')
dfref = self.get_csv_refdf('test1')
- df1 = excel.parse('Sheet1', index_col=0, parse_dates=True)
- df2 = excel.parse('Sheet2', skiprows=[1], index_col=0,
- parse_dates=True)
+ df1 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True)
+ df2 = self.get_exceldf('test1', '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)
- 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)
+ df3 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ skipfooter=1)
+ df4 = self.get_exceldf('test1', 'Sheet1', index_col=0, parse_dates=True,
+ skip_footer=1)
tm.assert_frame_equal(df3, df1.ix[:-1])
tm.assert_frame_equal(df3, df4)
@@ -384,8 +385,6 @@ def test_read_excel_blank_with_header(self):
tm.assert_frame_equal(actual, expected)
-
-
class XlrdTests(ReadingTestsBase):
"""
This is the base class for the xlrd tests, and 3 different file formats
@@ -395,10 +394,15 @@ class XlrdTests(ReadingTestsBase):
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)
+ expected = read_excel(pth, 'Sheet1', index_col=0, parse_dates=True)
+ with open(pth, 'rb') as f:
+ actual = read_excel(f, 'Sheet1', index_col=0, parse_dates=True)
+ tm.assert_frame_equal(expected, actual)
+
+ with open(pth, 'rb') as f:
+ xls = ExcelFile(f)
+ actual = read_excel(xls, 'Sheet1', index_col=0, parse_dates=True)
+ tm.assert_frame_equal(expected, actual)
def test_read_xlrd_Book(self):
_skip_if_no_xlwt()
@@ -410,7 +414,7 @@ def test_read_xlrd_Book(self):
book = xlrd.open_workbook(pth)
with ExcelFile(book, engine="xlrd") as xl:
- result = xl.parse("SheetA")
+ result = read_excel(xl, "SheetA")
tm.assert_frame_equal(df, result)
result = read_excel(book, sheetname="SheetA", engine="xlrd")
@@ -450,7 +454,7 @@ def test_reader_closes_file(self):
f = open(pth, 'rb')
with ExcelFile(f) as xlsx:
# parses okay
- xlsx.parse('Sheet1', index_col=0)
+ read_excel(xlsx, 'Sheet1', index_col=0)
self.assertTrue(f.closed)
@@ -650,6 +654,12 @@ def test_read_excel_bool_header_arg(self):
pd.read_excel(os.path.join(self.dirpath, 'test1' + self.ext),
header=arg)
+ def test_read_excel_chunksize(self):
+ #GH 8011
+ with tm.assertRaises(NotImplementedError):
+ pd.read_excel(os.path.join(self.dirpath, 'test1' + self.ext),
+ chunksize=100)
+
class XlsReaderTests(XlrdTests, tm.TestCase):
ext = '.xls'
engine_name = 'xlrd'
@@ -700,10 +710,11 @@ def test_excel_sheet_by_name_raise(self):
gt = DataFrame(np.random.randn(10, 2))
gt.to_excel(pth)
xl = ExcelFile(pth)
- df = xl.parse(0)
+ df = read_excel(xl, 0)
tm.assert_frame_equal(gt, df)
- self.assertRaises(xlrd.XLRDError, xl.parse, '0')
+ with tm.assertRaises(xlrd.XLRDError):
+ read_excel(xl, '0')
def test_excelwriter_contextmanager(self):
_skip_if_no_xlrd()
@@ -714,8 +725,8 @@ def test_excelwriter_contextmanager(self):
self.frame2.to_excel(writer, 'Data2')
with ExcelFile(pth) as reader:
- found_df = reader.parse('Data1')
- found_df2 = reader.parse('Data2')
+ found_df = read_excel(reader, 'Data1')
+ found_df2 = read_excel(reader, 'Data2')
tm.assert_frame_equal(found_df, self.frame)
tm.assert_frame_equal(found_df2, self.frame2)
@@ -769,7 +780,7 @@ def test_mixed(self):
with ensure_clean(self.ext) as path:
self.mixed_frame.to_excel(path, 'test1')
reader = ExcelFile(path)
- recons = reader.parse('test1', index_col=0)
+ recons = read_excel(reader, 'test1', index_col=0)
tm.assert_frame_equal(self.mixed_frame, recons)
def test_tsframe(self):
@@ -780,7 +791,7 @@ def test_tsframe(self):
with ensure_clean(self.ext) as path:
df.to_excel(path, 'test1')
reader = ExcelFile(path)
- recons = reader.parse('test1')
+ recons = read_excel(reader, 'test1')
tm.assert_frame_equal(df, recons)
def test_basics_with_nan(self):
@@ -804,7 +815,7 @@ def test_int_types(self):
dtype=np_type)
frame.to_excel(path, 'test1')
reader = ExcelFile(path)
- recons = reader.parse('test1')
+ recons = read_excel(reader, 'test1')
int_frame = frame.astype(np.int64)
tm.assert_frame_equal(int_frame, recons)
recons2 = read_excel(path, 'test1')
@@ -824,7 +835,7 @@ def test_float_types(self):
frame = DataFrame(np.random.random_sample(10), dtype=np_type)
frame.to_excel(path, 'test1')
reader = ExcelFile(path)
- recons = reader.parse('test1').astype(np_type)
+ recons = read_excel(reader, 'test1').astype(np_type)
tm.assert_frame_equal(frame, recons, check_dtype=False)
def test_bool_types(self):
@@ -836,7 +847,7 @@ def test_bool_types(self):
frame = (DataFrame([1, 0, True, False], dtype=np_type))
frame.to_excel(path, 'test1')
reader = ExcelFile(path)
- recons = reader.parse('test1').astype(np_type)
+ recons = read_excel(reader, 'test1').astype(np_type)
tm.assert_frame_equal(frame, recons)
def test_inf_roundtrip(self):
@@ -846,7 +857,7 @@ def test_inf_roundtrip(self):
with ensure_clean(self.ext) as path:
frame.to_excel(path, 'test1')
reader = ExcelFile(path)
- recons = reader.parse('test1')
+ recons = read_excel(reader, 'test1')
tm.assert_frame_equal(frame, recons)
def test_sheets(self):
@@ -866,9 +877,9 @@ def test_sheets(self):
self.tsframe.to_excel(writer, 'test2')
writer.save()
reader = ExcelFile(path)
- recons = reader.parse('test1', index_col=0)
+ recons = read_excel(reader, 'test1', index_col=0)
tm.assert_frame_equal(self.frame, recons)
- recons = reader.parse('test2', index_col=0)
+ recons = read_excel(reader, 'test2', index_col=0)
tm.assert_frame_equal(self.tsframe, recons)
np.testing.assert_equal(2, len(reader.sheet_names))
np.testing.assert_equal('test1', reader.sheet_names[0])
@@ -889,7 +900,7 @@ def test_colaliases(self):
col_aliases = Index(['AA', 'X', 'Y', 'Z'])
self.frame2.to_excel(path, 'test1', header=col_aliases)
reader = ExcelFile(path)
- rs = reader.parse('test1', index_col=0)
+ rs = read_excel(reader, 'test1', index_col=0)
xp = self.frame2.copy()
xp.columns = col_aliases
tm.assert_frame_equal(xp, rs)
@@ -912,7 +923,7 @@ def test_roundtrip_indexlabels(self):
index_label=['test'],
merge_cells=self.merge_cells)
reader = ExcelFile(path)
- recons = reader.parse('test1',
+ recons = read_excel(reader, 'test1',
index_col=0,
).astype(np.int64)
frame.index.names = ['test']
@@ -924,7 +935,7 @@ def test_roundtrip_indexlabels(self):
index_label=['test', 'dummy', 'dummy2'],
merge_cells=self.merge_cells)
reader = ExcelFile(path)
- recons = reader.parse('test1',
+ recons = read_excel(reader, 'test1',
index_col=0,
).astype(np.int64)
frame.index.names = ['test']
@@ -936,7 +947,7 @@ def test_roundtrip_indexlabels(self):
index_label='test',
merge_cells=self.merge_cells)
reader = ExcelFile(path)
- recons = reader.parse('test1',
+ recons = read_excel(reader, 'test1',
index_col=0,
).astype(np.int64)
frame.index.names = ['test']
@@ -953,7 +964,7 @@ def test_roundtrip_indexlabels(self):
df = df.set_index(['A', 'B'])
reader = ExcelFile(path)
- recons = reader.parse('test1', index_col=[0, 1])
+ recons = read_excel(reader, 'test1', index_col=[0, 1])
tm.assert_frame_equal(df, recons, check_less_precise=True)
def test_excel_roundtrip_indexname(self):
@@ -966,7 +977,7 @@ def test_excel_roundtrip_indexname(self):
df.to_excel(path, merge_cells=self.merge_cells)
xf = ExcelFile(path)
- result = xf.parse(xf.sheet_names[0],
+ result = read_excel(xf, xf.sheet_names[0],
index_col=0)
tm.assert_frame_equal(result, df)
@@ -982,7 +993,7 @@ def test_excel_roundtrip_datetime(self):
tsf.index = [x.date() for x in self.tsframe.index]
tsf.to_excel(path, 'test1', merge_cells=self.merge_cells)
reader = ExcelFile(path)
- recons = reader.parse('test1')
+ recons = read_excel(reader, 'test1')
tm.assert_frame_equal(self.tsframe, recons)
# GH4133 - excel output format strings
@@ -1015,8 +1026,8 @@ def test_excel_date_datetime_format(self):
reader1 = ExcelFile(filename1)
reader2 = ExcelFile(filename2)
- rs1 = reader1.parse('test1', index_col=None)
- rs2 = reader2.parse('test1', index_col=None)
+ rs1 = read_excel(reader1, 'test1', index_col=None)
+ rs2 = read_excel(reader2, 'test1', index_col=None)
tm.assert_frame_equal(rs1, rs2)
@@ -1034,7 +1045,7 @@ def test_to_excel_periodindex(self):
xp.to_excel(path, 'sht1')
reader = ExcelFile(path)
- rs = reader.parse('sht1', index_col=0, parse_dates=True)
+ rs = read_excel(reader, 'sht1', index_col=0, parse_dates=True)
tm.assert_frame_equal(xp, rs.to_period('M'))
def test_to_excel_multiindex(self):
@@ -1053,7 +1064,7 @@ def test_to_excel_multiindex(self):
# round trip
frame.to_excel(path, 'test1', merge_cells=self.merge_cells)
reader = ExcelFile(path)
- df = reader.parse('test1', index_col=[0, 1],
+ df = read_excel(reader, 'test1', index_col=[0, 1],
parse_dates=False)
tm.assert_frame_equal(frame, df)
self.assertEqual(frame.index.names, df.index.names)
@@ -1070,7 +1081,7 @@ def test_to_excel_multiindex_dates(self):
tsframe.index.names = ['time', 'foo']
tsframe.to_excel(path, 'test1', merge_cells=self.merge_cells)
reader = ExcelFile(path)
- recons = reader.parse('test1',
+ recons = read_excel(reader, 'test1',
index_col=[0, 1])
tm.assert_frame_equal(tsframe, recons)
@@ -1096,7 +1107,7 @@ def test_to_excel_multiindex_no_write_index(self):
# Read it back in.
reader = ExcelFile(path)
- frame3 = reader.parse('test1')
+ frame3 = read_excel(reader, 'test1')
# Test that it is the same as the initial frame.
tm.assert_frame_equal(frame1, frame3)
@@ -1112,7 +1123,7 @@ def test_to_excel_float_format(self):
df.to_excel(filename, 'test1', float_format='%.2f')
reader = ExcelFile(filename)
- rs = reader.parse('test1', index_col=None)
+ rs = read_excel(reader, 'test1', index_col=None)
xp = DataFrame([[0.12, 0.23, 0.57],
[12.32, 123123.20, 321321.20]],
index=['A', 'B'], columns=['X', 'Y', 'Z'])
@@ -1148,7 +1159,7 @@ def test_to_excel_unicode_filename(self):
df.to_excel(filename, 'test1', float_format='%.2f')
reader = ExcelFile(filename)
- rs = reader.parse('test1', index_col=None)
+ rs = read_excel(reader, 'test1', index_col=None)
xp = DataFrame([[0.12, 0.23, 0.57],
[12.32, 123123.20, 321321.20]],
index=['A', 'B'], columns=['X', 'Y', 'Z'])
@@ -1270,7 +1281,7 @@ def roundtrip(df, header=True, parser_hdr=0, index=True):
with ensure_clean(self.ext) as path:
df.to_excel(path, header=header, merge_cells=self.merge_cells, index=index)
xf = ExcelFile(path)
- res = xf.parse(xf.sheet_names[0], header=parser_hdr)
+ res = read_excel(xf, xf.sheet_names[0], header=parser_hdr)
return res
nrows = 5
@@ -1324,7 +1335,7 @@ def roundtrip2(df, header=True, parser_hdr=0, index=True):
with ensure_clean(self.ext) as path:
df.to_excel(path, header=header, merge_cells=self.merge_cells, index=index)
xf = ExcelFile(path)
- res = xf.parse(xf.sheet_names[0], header=parser_hdr)
+ res = read_excel(xf, xf.sheet_names[0], header=parser_hdr)
return res
nrows = 5; ncols = 3
| Replace the `**kwds` in `read_excel` with the actual list of supported keyword args. This doesn't
change any functionality, just nicer for interactive use. Also a bit of clarification on the `thousands`
arg in the docstring.
Additionally, `chunksize` was a parameter in the `ExcelFile.parse` signature, but didn't do anything (xref #8011). I removed this and raise `NotImplementedError` if passed, which is potentially breaking.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11198 | 2015-09-27T15:46:20Z | 2015-09-30T22:05:27Z | null | 2015-10-04T17:01:35Z |
CLN: GH11170, * import is removed from test_internals.py | diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py
index 61966674bc104..00553102e172f 100644
--- a/pandas/tests/test_internals.py
+++ b/pandas/tests/test_internals.py
@@ -7,10 +7,13 @@
import numpy as np
import re
+import itertools
from pandas import Index, MultiIndex, DataFrame, DatetimeIndex, Series, Categorical
from pandas.compat import OrderedDict, lrange
from pandas.sparse.array import SparseArray
-from pandas.core.internals import *
+from pandas.core.internals import (BlockPlacement, SingleBlockManager, make_block,
+ BlockManager)
+import pandas.core.common as com
import pandas.core.internals as internals
import pandas.util.testing as tm
import pandas as pd
@@ -664,8 +667,8 @@ def test_interleave(self):
def test_interleave_non_unique_cols(self):
df = DataFrame([
- [Timestamp('20130101'), 3.5],
- [Timestamp('20130102'), 4.5]],
+ [pd.Timestamp('20130101'), 3.5],
+ [pd.Timestamp('20130102'), 4.5]],
columns=['x', 'x'],
index=[1, 2])
| closes #11170
| https://api.github.com/repos/pandas-dev/pandas/pulls/11197 | 2015-09-27T13:11:46Z | 2015-09-27T14:28:49Z | 2015-09-27T14:28:49Z | 2015-09-27T14:28:49Z |
PERF: compare freq strings (timeseries plotting perf) | diff --git a/pandas/src/period.pyx b/pandas/src/period.pyx
index 1dbf469a946b5..2a7c2135f8045 100644
--- a/pandas/src/period.pyx
+++ b/pandas/src/period.pyx
@@ -439,10 +439,12 @@ def extract_ordinals(ndarray[object] values, freq):
ndarray[int64_t] ordinals = np.empty(n, dtype=np.int64)
object p
+ freqstr = Period._maybe_convert_freq(freq).freqstr
+
for i in range(n):
p = values[i]
ordinals[i] = p.ordinal
- if p.freq != freq:
+ if p.freqstr != freqstr:
raise ValueError("%s is wrong freq" % p)
return ordinals
| See overview in #11084
| https://api.github.com/repos/pandas-dev/pandas/pulls/11194 | 2015-09-26T13:25:31Z | 2015-10-01T11:20:29Z | 2015-10-01T11:20:29Z | 2015-10-01T11:20:29Z |
COMPAT: platform_int fixes in groupby ops, #11189 | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index e72f7c6c6a6bf..9748a594a9b6f 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1379,8 +1379,9 @@ def size(self):
"""
ids, _, ngroup = self.group_info
+ ids = com._ensure_platform_int(ids)
out = np.bincount(ids[ids != -1], minlength=ngroup)
- return Series(out, index=self.result_index)
+ return Series(out, index=self.result_index, dtype='int64')
@cache_readonly
def _max_groupsize(self):
@@ -1808,15 +1809,17 @@ def indices(self):
@cache_readonly
def group_info(self):
ngroups = self.ngroups
- obs_group_ids = np.arange(ngroups, dtype='int64')
+ obs_group_ids = np.arange(ngroups)
rep = np.diff(np.r_[0, self.bins])
+ rep = com._ensure_platform_int(rep)
if ngroups == len(self.bins):
- comp_ids = np.repeat(np.arange(ngroups, dtype='int64'), rep)
+ comp_ids = np.repeat(np.arange(ngroups), rep)
else:
- comp_ids = np.repeat(np.r_[-1, np.arange(ngroups, dtype='int64')], rep)
+ comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep)
- return comp_ids, obs_group_ids, ngroups
+ return comp_ids.astype('int64', copy=False), \
+ obs_group_ids.astype('int64', copy=False), ngroups
@cache_readonly
def ngroups(self):
@@ -2565,8 +2568,8 @@ def nunique(self, dropna=True):
# group boundries are where group ids change
# unique observations are where sorted values change
- idx = com._ensure_int64(np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]])
- inc = com._ensure_int64(np.r_[1, val[1:] != val[:-1]])
+ idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]]
+ inc = np.r_[1, val[1:] != val[:-1]]
# 1st item of each group is a new unique observation
mask = isnull(val)
@@ -2577,7 +2580,7 @@ def nunique(self, dropna=True):
inc[mask & np.r_[False, mask[:-1]]] = 0
inc[idx] = 1
- out = np.add.reduceat(inc, idx)
+ out = np.add.reduceat(inc, idx).astype('int64', copy=False)
return Series(out if ids[0] != -1 else out[1:],
index=self.grouper.result_index,
name=self.name)
@@ -2666,6 +2669,8 @@ def value_counts(self, normalize=False, sort=True, ascending=False,
mi = MultiIndex(levels=levels, labels=labels, names=names,
verify_integrity=False)
+ if com.is_integer_dtype(out):
+ out = com._ensure_int64(out)
return Series(out, index=mi)
# for compat. with algos.value_counts need to ensure every
@@ -2695,6 +2700,8 @@ def value_counts(self, normalize=False, sort=True, ascending=False,
mi = MultiIndex(levels=levels, labels=labels, names=names,
verify_integrity=False)
+ if com.is_integer_dtype(out):
+ out = com._ensure_int64(out)
return Series(out, index=mi)
def count(self):
@@ -2703,9 +2710,10 @@ def count(self):
val = self.obj.get_values()
mask = (ids != -1) & ~isnull(val)
+ ids = com._ensure_platform_int(ids)
out = np.bincount(ids[mask], minlength=ngroups) if ngroups != 0 else []
- return Series(out, index=self.grouper.result_index, name=self.name)
+ return Series(out, index=self.grouper.result_index, name=self.name, dtype='int64')
def _apply_to_column_groupbys(self, func):
""" return a pass thru """
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 03b2ea5597ab6..11645311467d5 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1137,7 +1137,7 @@ def count(self, level=None):
lev = lev.insert(cnt, _get_na_value(lev.dtype.type))
out = np.bincount(lab[notnull(self.values)], minlength=len(lev))
- return self._constructor(out, index=lev).__finalize__(self)
+ return self._constructor(out, index=lev, dtype='int64').__finalize__(self)
def mode(self):
"""Returns the mode(s) of the dataset.
diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py
index 2e7fb2adf2fd4..b94c91f72802a 100644
--- a/pandas/tests/test_tseries.py
+++ b/pandas/tests/test_tseries.py
@@ -9,6 +9,7 @@
import pandas.lib as lib
import pandas._period as period
import pandas.algos as algos
+from pandas.core import common as com
from pandas.tseries.holiday import Holiday, SA, next_monday,USMartinLutherKingJr,USMemorialDay,AbstractHolidayCalendar
import datetime
from pandas import DateOffset
@@ -480,10 +481,10 @@ def test_group_ohlc():
def _check(dtype):
obj = np.array(np.random.randn(20),dtype=dtype)
- bins = np.array([6, 12, 20], dtype=np.int64)
+ bins = np.array([6, 12, 20])
out = np.zeros((3, 4), dtype)
counts = np.zeros(len(out), dtype=np.int64)
- labels = np.repeat(np.arange(3, dtype='int64'), np.diff(np.r_[0, bins]))
+ labels = com._ensure_int64(np.repeat(np.arange(3), np.diff(np.r_[0, bins])))
func = getattr(algos,'group_ohlc_%s' % dtype)
func(out, counts, obj[:, None], labels)
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py
index 7052348e2e6a4..b48f077bd6f6d 100644
--- a/pandas/tseries/tests/test_resample.py
+++ b/pandas/tseries/tests/test_resample.py
@@ -936,7 +936,7 @@ def test_resample_group_info(self): # GH10914
mask = np.r_[True, vals[1:] != vals[:-1]]
mask |= np.r_[True, bins[1:] != bins[:-1]]
- arr = np.bincount(bins[mask] - 1, minlength=len(ix))
+ arr = np.bincount(bins[mask] - 1, minlength=len(ix)).astype('int64',copy=False)
right = Series(arr, index=ix)
assert_series_equal(left, right)
@@ -950,7 +950,7 @@ def test_resample_size(self):
ix = date_range(start=left.index.min(), end=ts.index.max(), freq='7T')
bins = np.searchsorted(ix.values, ts.index.values, side='right')
- val = np.bincount(bins, minlength=len(ix) + 1)[1:]
+ val = np.bincount(bins, minlength=len(ix) + 1)[1:].astype('int64',copy=False)
right = Series(val, index=ix)
assert_series_equal(left, right)
| closes #11189
| https://api.github.com/repos/pandas-dev/pandas/pulls/11191 | 2015-09-25T22:57:53Z | 2015-09-25T23:51:09Z | 2015-09-25T23:51:09Z | 2015-09-25T23:51:09Z |
DOC: fix bunch of doc build warnings | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index bc4b463e52302..14d712c822bdb 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -1090,7 +1090,7 @@ decreasing.
Note that the same result could have been achieved using
:ref:`fillna <missing_data.fillna>` (except for ``method='nearest'``) or
-:ref:`interpolate <missing_data.interpolation>`:
+:ref:`interpolate <missing_data.interpolate>`:
.. ipython:: python
diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst
index 2b3a1b927cbbf..f51603750d61b 100644
--- a/doc/source/comparison_with_sas.rst
+++ b/doc/source/comparison_with_sas.rst
@@ -34,7 +34,7 @@ Data Structures
---------------
General Terminology Translation
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. csv-table::
:header: "pandas", "SAS"
diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst
index 5d26ca2414690..3e8e866c057e4 100644
--- a/doc/source/contributing.rst
+++ b/doc/source/contributing.rst
@@ -154,8 +154,8 @@ Creating a Development Environment
An easy way to create a *pandas* development environment is as follows.
-- Install either :ref:`Install Anaconda <install-anaconda>` or :ref:`Install miniconda <install-miniconda>`
-- Make sure that you have :ref:`cloned the repository <contributing-forking>`
+- Install either :ref:`Install Anaconda <install.anaconda>` or :ref:`Install miniconda <install.miniconda>`
+- Make sure that you have :ref:`cloned the repository <contributing.forking>`
- ``cd`` to the pandas source directory
Tell ``conda`` to create a new environment, named ``pandas_dev``, or any name you would like for this environment by running:
@@ -339,7 +339,7 @@ follow the Numpy Docstring Standard (see above), but you don't need to install
this because a local copy of ``numpydoc`` is included in the *pandas* source
code.
-It is easiest to :ref:`create a development environment <contributing-dev_env>`, then install:
+It is easiest to :ref:`create a development environment <contributing.dev_env>`, then install:
::
@@ -567,7 +567,7 @@ It is also useful to run tests in your current environment. You can simply do it
which would be equivalent to ``asv run --quick --show-stderr --python=same``. This
will launch every test only once, display stderr from the benchmarks and use your
-local ``python'' that comes from your $PATH.
+local ``python`` that comes from your $PATH.
Information on how to write a benchmark can be found in
`*asv*'s documentation http://asv.readthedocs.org/en/latest/writing_benchmarks.html`.
diff --git a/doc/source/install.rst b/doc/source/install.rst
index 5c5f6bdcf0ddf..3c624a9d25a0c 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -179,7 +179,7 @@ To install pandas for Python 3 you may need to use the package ``python3-pandas`
Installing from source
~~~~~~~~~~~~~~~~~~~~~~
-See the :ref:`contributing documentation <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a devevlopment environment <contributing-dev_env>` if you wish to create a *pandas* development environment.
+See the :ref:`contributing documentation <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a development environment <contributing.dev_env>` if you wish to create a *pandas* development environment.
Running the test suite
~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/io.rst b/doc/source/io.rst
index 6affbedad3ae2..ceebef187fe7f 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -2075,11 +2075,11 @@ Equivalent class and function approaches to read multiple sheets:
# For when Sheet1's format is identical to Sheet2
data = read_excel('path_to_file.xls', ['Sheet1','Sheet2'], index_col=None, na_values=['NA'])
+.. _io.excel.specifying_sheets:
+
Specifying Sheets
+++++++++++++++++
-.. _io.specifying_sheets:
-
.. note :: The second argument is ``sheetname``, not to be confused with ``ExcelFile.sheet_names``
.. note :: An ExcelFile's attribute ``sheet_names`` provides access to a list of sheets.
@@ -3924,7 +3924,7 @@ For more information see the examples the SQLAlchemy `documentation <http://docs
Advanced SQLAlchemy queries
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
+'''''''''''''''''''''''''''
You can use SQLAlchemy constructs to describe your query.
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst
index 150f728871ef3..2b1e77653a415 100644
--- a/doc/source/timeseries.rst
+++ b/doc/source/timeseries.rst
@@ -1768,7 +1768,6 @@ TZ aware Dtypes
s_aware
Both of these ``Series`` can be manipulated via the ``.dt`` accessor, see :ref:`here <basics.dt_accessors>`.
-See the :ref:`docs <timeseries.dtypes>` for more details.
For example, to localize and convert a naive stamp to timezone aware.
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index f9bef3d9c7f4a..a78d776403528 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -179,7 +179,7 @@ Other enhancements
This method is also exposed by the lower level ``Index.get_indexer`` and ``Index.get_loc`` methods.
-- The ``read_excel()`` function's :ref:`sheetname <_io.specifying_sheets>` argument now accepts a list and ``None``, to get multiple or all sheets respectively. If more than one sheet is specified, a dictionary is returned. (:issue:`9450`)
+- The ``read_excel()`` function's :ref:`sheetname <io.excel.specifying_sheets>` argument now accepts a list and ``None``, to get multiple or all sheets respectively. If more than one sheet is specified, a dictionary is returned. (:issue:`9450`)
.. code-block:: python
diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt
index 79a0c48238be7..e1a58a443aa55 100755
--- a/doc/source/whatsnew/v0.16.1.txt
+++ b/doc/source/whatsnew/v0.16.1.txt
@@ -97,7 +97,7 @@ values NOT in the categories, similarly to how you can reindex ANY pandas index.
df2.reindex(pd.Categorical(['a','e'],categories=list('abcde')))
df2.reindex(pd.Categorical(['a','e'],categories=list('abcde'))).index
-See the :ref:`documentation <advanced.categoricalindex>` for more. (:issue:`7629`, :issue:`10038`, :issue:`10039`)
+See the :ref:`documentation <indexing.categoricalindex>` for more. (:issue:`7629`, :issue:`10038`, :issue:`10039`)
.. _whatsnew_0161.enhancements.sample:
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 6be913e1e5f51..08b453eccd380 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -453,7 +453,7 @@ Other enhancements
- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`)
-- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`)
+- Enable writing Excel files in :ref:`memory <io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`)
- Enable serialization of lists and dicts to strings in ``ExcelWriter`` (:issue:`8188`)
@@ -967,7 +967,7 @@ Deprecations
``DataFrame.add(other, fill_value=0)`` and ``DataFrame.mul(other, fill_value=1.)``
(:issue:`10735`).
- ``TimeSeries`` deprecated in favor of ``Series`` (note that this has been alias since 0.13.0), (:issue:`10890`)
-- ``SparsePanel`` deprecated and will be removed in a future version (:issue:``)
+- ``SparsePanel`` deprecated and will be removed in a future version (:issue:`11157`).
- ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`)
- Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`)
- ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`)
| Fixes mainly some linking errors
| https://api.github.com/repos/pandas-dev/pandas/pulls/11184 | 2015-09-24T09:33:39Z | 2015-09-24T21:58:27Z | 2015-09-24T21:58:27Z | 2015-09-24T21:58:27Z |
DOC: XportReader not top-level API | diff --git a/doc/source/api.rst b/doc/source/api.rst
index b1fe77c298d71..77c59ec70e8df 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -89,7 +89,6 @@ SAS
:toctree: generated/
read_sas
- XportReader
SQL
~~~
| @kshedden `XportReader` is not top-level API, so it was erroring in the doc build.
I now removed it from api.rst (the `TextFileReader` what you get back with chunksize for read_csv is also not included), but I can also adapt it to use `.. currentmodule:: pandas.io.sas` so it builds correctly if you want.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11183 | 2015-09-24T08:54:12Z | 2015-09-25T12:11:12Z | 2015-09-25T12:11:12Z | 2015-09-25T12:11:12Z |
API: raise on header=bool in parsers | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 6be913e1e5f51..3d4d113940dec 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -907,6 +907,23 @@ Changes to ``Categorical.unique``
cat
cat.unique()
+Changes to ``bool`` passed as ``header`` in Parsers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In earlier versions of pandas, if a bool was passed the ``header`` argument of
+``read_csv``, ``read_excel``, or ``read_html`` it was implicitly converted to
+an integer, resulting in ``header=0`` for ``False`` and ``header=1`` for ``True``
+(:issue:`6113`)
+
+A ``bool`` input to ``header`` will now raise a ``TypeError``
+
+.. code-block :: python
+
+ In [29]: df = pd.read_csv('data.csv', header=False)
+ TypeError: Passing a bool to header is invalid. Use header=None for no header or
+ header=int or list-like of ints to specify the row(s) making up the column names
+
+
.. _whatsnew_0170.api_breaking.other:
Other API Changes
diff --git a/pandas/io/common.py b/pandas/io/common.py
index e13c402b454d1..b9cdd44e52555 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -194,6 +194,12 @@ def _expand_user(filepath_or_buffer):
return os.path.expanduser(filepath_or_buffer)
return filepath_or_buffer
+def _validate_header_arg(header):
+ if isinstance(header, bool):
+ raise TypeError("Passing a bool to header is invalid. "
+ "Use header=None for no header or "
+ "header=int or list-like of ints to specify "
+ "the row(s) making up the column names")
def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
compression=None):
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 5767af1ad3862..d90a8b8e90a93 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -11,7 +11,7 @@
from pandas.core.frame import DataFrame
from pandas.io.parsers import TextParser
-from pandas.io.common import _is_url, _urlopen
+from pandas.io.common import _is_url, _urlopen, _validate_header_arg
from pandas.tseries.period import Period
from pandas import json
from pandas.compat import (map, zip, reduce, range, lrange, u, add_metaclass,
@@ -217,6 +217,7 @@ def parse(self, sheetname=0, header=0, skiprows=None, skip_footer=0,
if skipfooter is not None:
skip_footer = skipfooter
+ _validate_header_arg(header)
if has_index_names is not None:
warn("\nThe has_index_names argument is deprecated; index names "
"will be automatically inferred based on index_col.\n"
diff --git a/pandas/io/html.py b/pandas/io/html.py
index cb2ee7b1c1e3f..f175702dedabc 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -13,7 +13,7 @@
import numpy as np
-from pandas.io.common import _is_url, urlopen, parse_url
+from pandas.io.common import _is_url, urlopen, parse_url, _validate_header_arg
from pandas.io.parsers import TextParser
from pandas.compat import (lrange, lmap, u, string_types, iteritems,
raise_with_traceback, binary_type)
@@ -861,5 +861,6 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None,
if isinstance(skiprows, numbers.Integral) and skiprows < 0:
raise ValueError('cannot skip rows starting from the end of the '
'data (you passed a negative value)')
+ _validate_header_arg(header)
return _parse(flavor, io, match, header, index_col, skiprows,
parse_dates, tupleize_cols, thousands, attrs, encoding)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 15e11193fd1b7..8ac1aed9d9af7 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -17,7 +17,7 @@
from pandas.core.common import AbstractMethodError
from pandas.core.config import get_option
from pandas.io.date_converters import generic_parser
-from pandas.io.common import get_filepath_or_buffer
+from pandas.io.common import get_filepath_or_buffer, _validate_header_arg
from pandas.tseries import tools
from pandas.util.decorators import Appender
@@ -673,6 +673,8 @@ def _clean_options(self, options, engine):
# really delete this one
keep_default_na = result.pop('keep_default_na')
+ _validate_header_arg(options['header'])
+
if index_col is True:
raise ValueError("The value of index_col couldn't be 'True'")
if _is_index_col(index_col):
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 657789fe8ce9b..e20703398b5f6 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -384,6 +384,8 @@ def test_read_excel_blank_with_header(self):
tm.assert_frame_equal(actual, expected)
+
+
class XlrdTests(ReadingTestsBase):
"""
This is the base class for the xlrd tests, and 3 different file formats
@@ -641,7 +643,12 @@ def test_excel_oldindex_format(self):
has_index_names=False)
tm.assert_frame_equal(actual, expected, check_names=False)
-
+ def test_read_excel_bool_header_arg(self):
+ #GH 6114
+ for arg in [True, False]:
+ with tm.assertRaises(TypeError):
+ pd.read_excel(os.path.join(self.dirpath, 'test1' + self.ext),
+ header=arg)
class XlsReaderTests(XlrdTests, tm.TestCase):
ext = '.xls'
diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py
index c00517ab92f96..5c8c15c7c2ae0 100644
--- a/pandas/io/tests/test_html.py
+++ b/pandas/io/tests/test_html.py
@@ -637,6 +637,11 @@ def test_wikipedia_states_table(self):
result = self.read_html(data, 'Arizona', header=1)[0]
nose.tools.assert_equal(result['sq mi'].dtype, np.dtype('float64'))
+ def test_bool_header_arg(self):
+ #GH 6114
+ for arg in [True, False]:
+ with tm.assertRaises(TypeError):
+ read_html(self.spam_data, header=arg)
def _lang_enc(filename):
return os.path.splitext(os.path.basename(filename))[0].split('_')
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index c9ae2f6029530..799c573b13c8b 100755
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -4117,6 +4117,22 @@ def test_single_char_leading_whitespace(self):
skipinitialspace=True)
tm.assert_frame_equal(result, expected)
+ def test_bool_header_arg(self):
+ # GH 6114
+ data = """\
+MyColumn
+ a
+ b
+ a
+ b"""
+ for arg in [True, False]:
+ with tm.assertRaises(TypeError):
+ pd.read_csv(StringIO(data), header=arg)
+ with tm.assertRaises(TypeError):
+ pd.read_table(StringIO(data), header=arg)
+ with tm.assertRaises(TypeError):
+ pd.read_fwf(StringIO(data), header=arg)
+
class TestMiscellaneous(tm.TestCase):
# for tests that don't fit into any of the other classes, e.g. those that
| closes #6113
Passing `header=True|False` to `read_csv` (and brethren), `read_excel`, and `read_html` will now raise a `TypeError`, rather than being coerced to an int.
I had thought about converting `False` to `None` but thought that could break someone's code in a very subtle way if they were somehow depending on the old behavior. But happy to change that if it seems better.
If you want to push this in for 0.17 I can add a doc-note or this could easily wait.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11182 | 2015-09-24T00:13:08Z | 2015-09-24T11:32:00Z | 2015-09-24T11:32:00Z | 2015-09-26T15:17:44Z |
improves groupby.get_group_index when shape is a long sequence | diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index 98b0ec73fb23c..9bece56e15c90 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -293,6 +293,14 @@ def setup(self):
def time_frame_duplicated(self):
self.df.duplicated()
+class frame_duplicated_wide(object):
+ goal_time = 0.2
+
+ def setup(self):
+ self.df = DataFrame(np.random.randn(1000, 100).astype(str))
+
+ def time_frame_duplicated_wide(self):
+ self.df.T.duplicated()
class frame_fancy_lookup(object):
goal_time = 0.2
@@ -929,4 +937,4 @@ def setup(self):
self.s = Series((['abcdefg', np.nan] * 500000))
def time_series_string_vector_slice(self):
- self.s.str[:5]
\ No newline at end of file
+ self.s.str[:5]
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index bf3dfa227732e..ca2c7dfc36353 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1044,6 +1044,7 @@ Performance Improvements
- Performance improvements in ``Categorical.value_counts`` (:issue:`10804`)
- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` and ``SeriesGroupby.transform`` (:issue:`10820`, :issue:`11077`)
- Performance improvements in ``DataFrame.drop_duplicates`` with integer dtypes (:issue:`10917`)
+- Performance improvements in ``DataFrame.duplicated`` with wide frames. (:issue:`11180`)
- 4x improvement in ``timedelta`` string parsing (:issue:`6755`, :issue:`10426`)
- 8x improvement in ``timedelta64`` and ``datetime64`` ops (:issue:`6755`)
- Significantly improved performance of indexing ``MultiIndex`` with slicers (:issue:`10287`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index c486c414081f2..e72f7c6c6a6bf 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -3739,10 +3739,17 @@ def get_group_index(labels, shape, sort, xnull):
An array of type int64 where two elements are equal if their corresponding
labels are equal at all location.
"""
+ def _int64_cut_off(shape):
+ acc = long(1)
+ for i, mul in enumerate(shape):
+ acc *= long(mul)
+ if not acc < _INT64_MAX:
+ return i
+ return len(shape)
+
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)))
+ nlev = _int64_cut_off(shape)
# compute flat ids for the first `nlev` levels
stride = np.prod(shape[1:nlev], dtype='i8')
| closes #10161
xref https://github.com/pydata/pandas/issues/10161#issuecomment-142701582
``` python
In [5]: df = DataFrame(np.random.randn(5000, 100).astype(str))
In [6]: %timeit df.duplicated()
1 loops, best of 3: 151 ms per loop
In [7]: %timeit df.T.duplicated()
1 loops, best of 3: 1.39 s per loop
```
part of this is because of taking the transpose (maybe cache locality). i.e. below performs better even though the shape is the same as `df.T` in above:
``` python
In [8]: df = DataFrame(np.random.randn(100, 5000).astype(str))
In [9]: %timeit df.duplicated()
1 loops, best of 3: 965 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11180 | 2015-09-23T22:56:20Z | 2015-09-25T12:19:03Z | null | 2015-09-26T13:15:50Z |
BUG: indexing with boolean-like Index, #11119 | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9e1eda4714734..fa16e72760faf 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1941,8 +1941,8 @@ def _getitem_array(self, key):
warnings.warn("Boolean Series key will be reindexed to match "
"DataFrame index.", UserWarning)
elif len(key) != len(self.index):
- raise ValueError('Item wrong length %d instead of %d.' %
- (len(key), len(self.index)))
+ indexer = self.ix._convert_to_indexer(key, axis=1)
+ return self.take(indexer, axis=1, convert=True)
# check_bool_indexer will throw exception if Series key cannot
# be reindexed to match DataFrame rows
key = check_bool_indexer(self.index, key)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 8b4528ef451ef..6b54b3266f79a 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1077,50 +1077,56 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
return labels.get_locs(obj)
elif is_list_like_indexer(obj):
if is_bool_indexer(obj):
- obj = check_bool_indexer(labels, obj)
- inds, = obj.nonzero()
- return inds
- else:
- if isinstance(obj, Index):
- objarr = obj.values
+ if is_bool_indexer(list(labels)):
+ pass
+ elif len(obj) == self.obj.shape[axis]:
+ obj = check_bool_indexer(labels, obj)
+ inds, = obj.nonzero()
+ return inds
else:
- objarr = _asarray_tuplesafe(obj)
+ raise ValueError('Item wrong length %d instead of %d.' %
+ (len(obj), len(self.obj.index)))
+
+ if isinstance(obj, Index):
+ objarr = obj.values
+ else:
+ objarr = _asarray_tuplesafe(obj)
- # The index may want to handle a list indexer differently
- # by returning an indexer or raising
- indexer = labels._convert_list_indexer(objarr, kind=self.name)
- if indexer is not None:
- return indexer
+ # The index may want to handle a list indexer differently
+ # by returning an indexer or raising
+ indexer = labels._convert_list_indexer(objarr, kind=self.name)
+ if indexer is not None:
+ return indexer
- # this is not the most robust, but...
- if (isinstance(labels, MultiIndex) and
- not isinstance(objarr[0], tuple)):
- level = 0
- _, indexer = labels.reindex(objarr, level=level)
+ # this is not the most robust, but...
+ if (isinstance(labels, MultiIndex) and
+ not isinstance(objarr[0], tuple)):
+ level = 0
+ _, indexer = labels.reindex(objarr, level=level)
- # take all
- if indexer is None:
- indexer = np.arange(len(labels))
+ # take all
+ if indexer is None:
+ indexer = np.arange(len(labels))
- check = labels.levels[0].get_indexer(objarr)
- else:
- level = None
+ check = labels.levels[0].get_indexer(objarr)
+ else:
+ level = None
- # unique index
- if labels.is_unique:
- indexer = check = labels.get_indexer(objarr)
+ # unique index
+ if labels.is_unique:
+ indexer = check = labels.get_indexer(objarr)
- # non-unique (dups)
- else:
- (indexer,
- missing) = labels.get_indexer_non_unique(objarr)
- check = indexer
+ # non-unique (dups)
+ else:
+ (indexer,
+ missing) = labels.get_indexer_non_unique(objarr)
+ check = indexer
- mask = check == -1
- if mask.any():
- raise KeyError('%s not in index' % objarr[mask])
+ mask = check == -1
+ if mask.any():
+ raise KeyError('%s not in index' % objarr[mask])
- return _values_from_object(indexer)
+ return _values_from_object(indexer)
else:
try:
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 75daabe2dab67..2009123e03098 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -943,6 +943,12 @@ def test_booleanindex(self):
subIndex = self.strIndex[list(boolIdx)]
for i, val in enumerate(subIndex):
self.assertEqual(subIndex.get_loc(val), i)
+
+ def test_booleanLabel(self):
+ df = pd.DataFrame({True: [1,2,5,9],
+ False: [6,1,13,8]})
+ self.assert_frame_equal(df[df[True]>3], df[2:])
+ self.assert_frame_equal(df[[False,True]], df)
def test_fancy(self):
sl = self.strIndex[[1, 2, 3]]
| closes #11119
| https://api.github.com/repos/pandas-dev/pandas/pulls/11178 | 2015-09-23T17:29:37Z | 2016-01-11T13:45:22Z | null | 2016-01-11T14:15:44Z |
Update 10min.rst | diff --git a/doc/source/10min.rst b/doc/source/10min.rst
index 359ec76533520..91e607757e4f1 100644
--- a/doc/source/10min.rst
+++ b/doc/source/10min.rst
@@ -30,7 +30,7 @@
This is a short introduction to pandas, geared mainly for new users.
You can see more complex recipes in the :ref:`Cookbook<cookbook>`
-Customarily, we import as follows
+Customarily, we import as follows:
.. ipython:: python
| https://api.github.com/repos/pandas-dev/pandas/pulls/11177 | 2015-09-23T15:02:30Z | 2015-09-24T01:14:58Z | 2015-09-24T01:14:58Z | 2015-09-24T01:15:01Z | |
DOC: header=None in SAS docs | diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst
index fd42c97c9cbc0..2b3a1b927cbbf 100644
--- a/doc/source/comparison_with_sas.rst
+++ b/doc/source/comparison_with_sas.rst
@@ -142,10 +142,10 @@ and did not have column names, the pandas command would be:
.. code-block:: python
- tips = pd.read_csv('tips.csv', sep='\t', header=False)
+ tips = pd.read_csv('tips.csv', sep='\t', header=None)
# alternatively, read_table is an alias to read_csv with tab delimiter
- tips = pd.read_table('tips.csv', header=False)
+ tips = pd.read_table('tips.csv', header=None)
In addition to text/csv, pandas supports a variety of other data formats
such as Excel, HDF5, and SQL databases. These are all read via a ``pd.read_*``
| Fixed a typo where I had `header=False`
Side note, it might be nice to change the actual behavior, not the first time it's tripped me up. I guess there already is an issue, #6113
| https://api.github.com/repos/pandas-dev/pandas/pulls/11176 | 2015-09-23T11:35:04Z | 2015-09-23T11:53:01Z | 2015-09-23T11:53:01Z | 2015-09-23T23:19:53Z |
issue #11119 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index c2c7ca2410068..1a976bf0d921e 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -916,7 +916,7 @@ Other API Changes
- When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column
was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`)
- some numeric reduction operators would return ``ValueError``, rather than ``TypeError`` on object types that includes strings and numbers (:issue:`11131`)
-
+- ``DatetimeIndex.union`` does not infer ``freq`` if ``self`` and the input have ``None`` as ``freq`` (:issue:`11086`)
- ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`)
=============================== ===============================================================
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9d40cf3921b98..cd0d85b756cf0 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1939,7 +1939,11 @@ def _getitem_array(self, key):
warnings.warn("Boolean Series key will be reindexed to match "
"DataFrame index.", UserWarning)
elif len(key) != len(self.index):
- raise ValueError('Item wrong length %d instead of %d.' %
+ if len(key) == self.ndim:
+ indexer = self.ix._convert_to_indexer(key, axis=1)
+ return self.take(indexer, axis=1, convert=True)
+ else:
+ raise ValueError('Item wrong length %d instead of %d.' %
(len(key), len(self.index)))
# check_bool_indexer will throw exception if Series key cannot
# be reindexed to match DataFrame rows
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 8b4528ef451ef..95d1f4d9f11a6 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1076,7 +1076,8 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
elif is_nested_tuple(obj, labels):
return labels.get_locs(obj)
elif is_list_like_indexer(obj):
- if is_bool_indexer(obj):
+ if (is_bool_indexer(obj) and (len(labels) == len(self.obj.index)
+ or not is_bool_indexer(list(labels)))):
obj = check_bool_indexer(labels, obj)
inds, = obj.nonzero()
return inds
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 5fdc0ce86a0b4..ac2358cb3d231 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -51,7 +51,7 @@
_default_encoding = 'UTF-8'
def _ensure_decoded(s):
- """ if we have bytes, decode them to unicde """
+ """ if we have bytes, decode them to unicode """
if isinstance(s, np.bytes_):
s = s.decode('UTF-8')
return s
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 75daabe2dab67..2009123e03098 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -943,6 +943,12 @@ def test_booleanindex(self):
subIndex = self.strIndex[list(boolIdx)]
for i, val in enumerate(subIndex):
self.assertEqual(subIndex.get_loc(val), i)
+
+ def test_booleanLabel(self):
+ df = pd.DataFrame({True: [1,2,5,9],
+ False: [6,1,13,8]})
+ self.assert_frame_equal(df[df[True]>3], df[2:])
+ self.assert_frame_equal(df[[False,True]], df)
def test_fancy(self):
sl = self.strIndex[[1, 2, 3]]
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index c2dc625bd6ece..8f6b924ebd850 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -895,7 +895,8 @@ def union(self, other):
result = Index.union(this, other)
if isinstance(result, DatetimeIndex):
result.tz = this.tz
- if result.freq is None:
+ if (result.freq is None and
+ (this.freq is not None or other.freq is not None)):
result.offset = to_offset(result.inferred_freq)
return result
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index c4eb0e0cddfc9..957cdcc009e1c 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -2551,6 +2551,15 @@ def test_intersection_bug_1708(self):
result = index_1 & index_2
self.assertEqual(len(result), 0)
+ def test_union_freq_both_none(self):
+ #GH11086
+ expected = bdate_range('20150101', periods=10)
+ expected.freq = None
+
+ result = expected.union(expected)
+ tm.assert_index_equal(result, expected)
+ self.assertIsNone(result.freq)
+
# GH 10699
def test_datetime64_with_DateOffset(self):
for klass, assert_func in zip([Series, DatetimeIndex],
| Closes #11119
| https://api.github.com/repos/pandas-dev/pandas/pulls/11175 | 2015-09-23T03:15:23Z | 2015-09-23T17:03:53Z | null | 2023-05-11T01:13:11Z |
ENH: Restore original convert_objects and add _convert | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index 14d712c822bdb..e11c612a510db 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -1711,36 +1711,26 @@ then the more *general* one will be used as the result of the operation.
object conversion
~~~~~~~~~~~~~~~~~
-.. note::
-
- The syntax of :meth:`~DataFrame.convert_objects` changed in 0.17.0. See
- :ref:`API changes <whatsnew_0170.api_breaking.convert_objects>`
- for more details.
-
-:meth:`~DataFrame.convert_objects` is a method that converts columns from
-the ``object`` dtype to datetimes, timedeltas or floats. For example, to
-attempt conversion of object data that are *number like*, e.g. could be a
-string that represents a number, pass ``numeric=True``. By default, this will
-attempt a soft conversion and so will only succeed if the entire column is
-convertible. To force the conversion, add the keyword argument ``coerce=True``.
-This will force strings and number-like objects to be numbers if
-possible, and other values will be set to ``np.nan``.
+:meth:`~DataFrame.convert_objects` is a method to try to force conversion of types from the ``object`` dtype to other types.
+To force conversion of specific types that are *number like*, e.g. could be a string that represents a number,
+pass ``convert_numeric=True``. This will force strings and numbers alike to be numbers if possible, otherwise
+they will be set to ``np.nan``.
.. ipython:: python
df3['D'] = '1.'
df3['E'] = '1'
- df3.convert_objects(numeric=True).dtypes
+ df3.convert_objects(convert_numeric=True).dtypes
# same, but specific dtype conversion
df3['D'] = df3['D'].astype('float16')
df3['E'] = df3['E'].astype('int32')
df3.dtypes
-To force conversion to ``datetime64[ns]``, pass ``datetime=True`` and ``coerce=True``.
+To force conversion to ``datetime64[ns]``, pass ``convert_dates='coerce'``.
This will convert any datetime-like object to dates, forcing other values to ``NaT``.
This might be useful if you are reading in data which is mostly dates,
-but occasionally contains non-dates that you wish to represent as missing.
+but occasionally has non-dates intermixed and you want to represent as missing.
.. ipython:: python
@@ -1749,15 +1739,10 @@ but occasionally contains non-dates that you wish to represent as missing.
'foo', 1.0, 1, pd.Timestamp('20010104'),
'20010105'], dtype='O')
s
- s.convert_objects(datetime=True, coerce=True)
+ s.convert_objects(convert_dates='coerce')
-Without passing ``coerce=True``, :meth:`~DataFrame.convert_objects` will attempt
-*soft* conversion of any *object* dtypes, meaning that if all
+In addition, :meth:`~DataFrame.convert_objects` will attempt the *soft* conversion of any *object* dtypes, meaning that if all
the objects in a Series are of the same type, the Series will have that dtype.
-Note that setting ``coerce=True`` does not *convert* arbitrary types to either
-``datetime64[ns]`` or ``timedelta64[ns]``. For example, a series containing string
-dates will not be converted to a series of datetimes. To convert between types,
-see :ref:`converting to timestamps <timeseries.converting>`.
gotchas
~~~~~~~
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 61c34fc071282..79ca3f369d2ad 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -640,71 +640,6 @@ New Behavior:
Timestamp.now()
Timestamp.now() + offsets.DateOffset(years=1)
-.. _whatsnew_0170.api_breaking.convert_objects:
-
-Changes to convert_objects
-^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-``DataFrame.convert_objects`` keyword arguments have been shortened. (:issue:`10265`)
-
-===================== =============
-Previous Replacement
-===================== =============
-``convert_dates`` ``datetime``
-``convert_numeric`` ``numeric``
-``convert_timedelta`` ``timedelta``
-===================== =============
-
-Coercing types with ``DataFrame.convert_objects`` is now implemented using the
-keyword argument ``coerce=True``. Previously types were coerced by setting a
-keyword argument to ``'coerce'`` instead of ``True``, as in ``convert_dates='coerce'``.
-
-.. ipython:: python
-
- df = pd.DataFrame({'i': ['1','2'],
- 'f': ['apple', '4.2'],
- 's': ['apple','banana']})
- df
-
-The old usage of ``DataFrame.convert_objects`` used ``'coerce'`` along with the
-type.
-
-.. code-block:: python
-
- In [2]: df.convert_objects(convert_numeric='coerce')
-
-Now the ``coerce`` keyword must be explicitly used.
-
-.. ipython:: python
-
- df.convert_objects(numeric=True, coerce=True)
-
-In earlier versions of pandas, ``DataFrame.convert_objects`` would not coerce
-numeric types when there were no values convertible to a numeric type. This returns
-the original DataFrame with no conversion.
-
-.. code-block:: python
-
- In [1]: df = pd.DataFrame({'s': ['a','b']})
- In [2]: df.convert_objects(convert_numeric='coerce')
- Out[2]:
- s
- 0 a
- 1 b
-
-The new behavior will convert all non-number-like strings to ``NaN``,
-when ``coerce=True`` is passed explicity.
-
-.. ipython:: python
-
- pd.DataFrame({'s': ['a','b']})
- df.convert_objects(numeric=True, coerce=True)
-
-In earlier versions of pandas, the default behavior was to try and convert
-datetimes and timestamps. The new default is for ``DataFrame.convert_objects``
-to do nothing, and so it is necessary to pass at least one conversion target
-in the method call.
-
Changes to Index Comparisons
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -992,6 +927,7 @@ Deprecations
- ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`)
- Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`)
- ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`)
+- ``DataFrame.convert_objects`` has been deprecated in favor of type-specific function ``pd.to_datetime``, ``pd.to_timestamp`` and ``pd.to_numeric`` (:issue:`11133`).
.. _whatsnew_0170.prior_deprecations:
@@ -1187,3 +1123,5 @@ Bug Fixes
- Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`)
- Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`)
- Bug in ``.groupby`` when number of keys to group by is same as length of index (:issue:`11185`)
+- Bug in ``convert_objects`` where converted values might not be returned if all null and ``coerce`` (:issue:`9589`)
+- Bug in ``convert_objects`` where ``copy`` keyword was not respected (:issue:`9589`)
diff --git a/pandas/__init__.py b/pandas/__init__.py
index dbc697410da80..68a90394cacf1 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -52,6 +52,7 @@
from pandas.tools.pivot import pivot_table, crosstab
from pandas.tools.plotting import scatter_matrix, plot_params
from pandas.tools.tile import cut, qcut
+from pandas.tools.util import to_numeric
from pandas.core.reshape import melt
from pandas.util.print_versions import show_versions
import pandas.util.testing
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 77e58b4f56c32..2d403f904a446 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1858,71 +1858,6 @@ def _maybe_box_datetimelike(value):
_values_from_object = lib.values_from_object
-def _possibly_convert_objects(values,
- datetime=True,
- numeric=True,
- timedelta=True,
- coerce=False,
- copy=True):
- """ if we have an object dtype, try to coerce dates and/or numbers """
-
- conversion_count = sum((datetime, numeric, timedelta))
- if conversion_count == 0:
- import warnings
- warnings.warn('Must explicitly pass type for conversion. Defaulting to '
- 'pre-0.17 behavior where datetime=True, numeric=True, '
- 'timedelta=True and coerce=False', DeprecationWarning)
- datetime = numeric = timedelta = True
- coerce = False
-
- if isinstance(values, (list, tuple)):
- # List or scalar
- values = np.array(values, dtype=np.object_)
- elif not hasattr(values, 'dtype'):
- values = np.array([values], dtype=np.object_)
- elif not is_object_dtype(values.dtype):
- # If not object, do not attempt conversion
- values = values.copy() if copy else values
- return values
-
- # If 1 flag is coerce, ensure 2 others are False
- if coerce:
- if conversion_count > 1:
- raise ValueError("Only one of 'datetime', 'numeric' or "
- "'timedelta' can be True when when coerce=True.")
-
- # Immediate return if coerce
- if datetime:
- return pd.to_datetime(values, errors='coerce', box=False)
- elif timedelta:
- return pd.to_timedelta(values, errors='coerce', box=False)
- elif numeric:
- return lib.maybe_convert_numeric(values, set(), coerce_numeric=True)
-
- # Soft conversions
- if datetime:
- values = lib.maybe_convert_objects(values,
- convert_datetime=datetime)
-
- if timedelta and is_object_dtype(values.dtype):
- # Object check to ensure only run if previous did not convert
- values = lib.maybe_convert_objects(values,
- convert_timedelta=timedelta)
-
- if numeric and is_object_dtype(values.dtype):
- try:
- converted = lib.maybe_convert_numeric(values,
- set(),
- coerce_numeric=True)
- # If all NaNs, then do not-alter
- values = converted if not isnull(converted).all() else values
- values = values.copy() if copy else values
- except:
- pass
-
- return values
-
-
def _possibly_castable(arr):
# return False to force a non-fastpath
diff --git a/pandas/core/convert.py b/pandas/core/convert.py
new file mode 100644
index 0000000000000..3745d4f5f6914
--- /dev/null
+++ b/pandas/core/convert.py
@@ -0,0 +1,132 @@
+"""
+Functions for converting object to other types
+"""
+
+import numpy as np
+
+import pandas as pd
+from pandas.core.common import (_possibly_cast_to_datetime, is_object_dtype,
+ isnull)
+import pandas.lib as lib
+
+# TODO: Remove in 0.18 or 2017, which ever is sooner
+def _possibly_convert_objects(values, convert_dates=True,
+ convert_numeric=True,
+ convert_timedeltas=True,
+ copy=True):
+ """ if we have an object dtype, try to coerce dates and/or numbers """
+
+ # if we have passed in a list or scalar
+ if isinstance(values, (list, tuple)):
+ values = np.array(values, dtype=np.object_)
+ if not hasattr(values, 'dtype'):
+ values = np.array([values], dtype=np.object_)
+
+ # convert dates
+ if convert_dates and values.dtype == np.object_:
+
+ # we take an aggressive stance and convert to datetime64[ns]
+ if convert_dates == 'coerce':
+ new_values = _possibly_cast_to_datetime(
+ values, 'M8[ns]', errors='coerce')
+
+ # if we are all nans then leave me alone
+ if not isnull(new_values).all():
+ values = new_values
+
+ else:
+ values = lib.maybe_convert_objects(
+ values, convert_datetime=convert_dates)
+
+ # convert timedeltas
+ if convert_timedeltas and values.dtype == np.object_:
+
+ if convert_timedeltas == 'coerce':
+ from pandas.tseries.timedeltas import to_timedelta
+ new_values = to_timedelta(values, coerce=True)
+
+ # if we are all nans then leave me alone
+ if not isnull(new_values).all():
+ values = new_values
+
+ else:
+ values = lib.maybe_convert_objects(
+ values, convert_timedelta=convert_timedeltas)
+
+ # convert to numeric
+ if values.dtype == np.object_:
+ if convert_numeric:
+ try:
+ new_values = lib.maybe_convert_numeric(
+ values, set(), coerce_numeric=True)
+
+ # if we are all nans then leave me alone
+ if not isnull(new_values).all():
+ values = new_values
+
+ except:
+ pass
+ else:
+ # soft-conversion
+ values = lib.maybe_convert_objects(values)
+
+ values = values.copy() if copy else values
+
+ return values
+
+
+def _soft_convert_objects(values, datetime=True, numeric=True, timedelta=True,
+ coerce=False, copy=True):
+ """ if we have an object dtype, try to coerce dates and/or numbers """
+
+ conversion_count = sum((datetime, numeric, timedelta))
+ if conversion_count == 0:
+ raise ValueError('At least one of datetime, numeric or timedelta must '
+ 'be True.')
+ elif conversion_count > 1 and coerce:
+ raise ValueError("Only one of 'datetime', 'numeric' or "
+ "'timedelta' can be True when when coerce=True.")
+
+
+ if isinstance(values, (list, tuple)):
+ # List or scalar
+ values = np.array(values, dtype=np.object_)
+ elif not hasattr(values, 'dtype'):
+ values = np.array([values], dtype=np.object_)
+ elif not is_object_dtype(values.dtype):
+ # If not object, do not attempt conversion
+ values = values.copy() if copy else values
+ return values
+
+ # If 1 flag is coerce, ensure 2 others are False
+ if coerce:
+ # Immediate return if coerce
+ if datetime:
+ return pd.to_datetime(values, errors='coerce', box=False)
+ elif timedelta:
+ return pd.to_timedelta(values, errors='coerce', box=False)
+ elif numeric:
+ return pd.to_numeric(values, errors='coerce')
+
+ # Soft conversions
+ if datetime:
+ values = lib.maybe_convert_objects(values,
+ convert_datetime=datetime)
+
+ if timedelta and is_object_dtype(values.dtype):
+ # Object check to ensure only run if previous did not convert
+ values = lib.maybe_convert_objects(values,
+ convert_timedelta=timedelta)
+
+ if numeric and is_object_dtype(values.dtype):
+ try:
+ converted = lib.maybe_convert_numeric(values,
+ set(),
+ coerce_numeric=True)
+ # If all NaNs, then do not-alter
+ values = converted if not isnull(converted).all() else values
+ values = values.copy() if copy else values
+ except:
+ pass
+
+ return values
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9e1eda4714734..08dfe315c4cb2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3543,9 +3543,8 @@ def combine(self, other, func, fill_value=None, overwrite=True):
# convert_objects just in case
return self._constructor(result,
index=new_index,
- columns=new_columns).convert_objects(
- datetime=True,
- copy=False)
+ columns=new_columns)._convert(datetime=True,
+ copy=False)
def combine_first(self, other):
"""
@@ -4026,9 +4025,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
if axis == 1:
result = result.T
- result = result.convert_objects(datetime=True,
- timedelta=True,
- copy=False)
+ result = result._convert(datetime=True, timedelta=True, copy=False)
else:
@@ -4158,7 +4155,7 @@ def append(self, other, ignore_index=False, verify_integrity=False):
other = DataFrame(other.values.reshape((1, len(other))),
index=index,
columns=combined_columns)
- other = other.convert_objects(datetime=True, timedelta=True)
+ other = other._convert(datetime=True, timedelta=True)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6aec297c31d2b..3473dd0f7cd88 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2534,11 +2534,8 @@ def copy(self, deep=True):
data = self._data.copy(deep=deep)
return self._constructor(data).__finalize__(self)
- @deprecate_kwarg(old_arg_name='convert_dates', new_arg_name='datetime')
- @deprecate_kwarg(old_arg_name='convert_numeric', new_arg_name='numeric')
- @deprecate_kwarg(old_arg_name='convert_timedeltas', new_arg_name='timedelta')
- def convert_objects(self, datetime=False, numeric=False,
- timedelta=False, coerce=False, copy=True):
+ def _convert(self, datetime=False, numeric=False, timedelta=False,
+ coerce=False, copy=True):
"""
Attempt to infer better dtype for object columns
@@ -2563,31 +2560,48 @@ def convert_objects(self, datetime=False, numeric=False,
-------
converted : same as input object
"""
+ return self._constructor(
+ self._data.convert(datetime=datetime,
+ numeric=numeric,
+ timedelta=timedelta,
+ coerce=coerce,
+ copy=copy)).__finalize__(self)
+
+ # TODO: Remove in 0.18 or 2017, which ever is sooner
+ def convert_objects(self, convert_dates=True, convert_numeric=False,
+ convert_timedeltas=True, copy=True):
+ """
+ Attempt to infer better dtype for object columns
+
+ Parameters
+ ----------
+ convert_dates : boolean, default True
+ If True, convert to date where possible. If 'coerce', force
+ conversion, with unconvertible values becoming NaT.
+ convert_numeric : boolean, default False
+ If True, attempt to coerce to numbers (including strings), with
+ unconvertible values becoming NaN.
+ convert_timedeltas : boolean, default True
+ If True, convert to timedelta where possible. If 'coerce', force
+ conversion, with unconvertible values becoming NaT.
+ copy : boolean, default True
+ If True, return a copy even if no copy is necessary (e.g. no
+ conversion was done). Note: This is meant for internal use, and
+ should not be confused with inplace.
- # Deprecation code to handle usage change
- issue_warning = False
- if datetime == 'coerce':
- datetime = coerce = True
- numeric = timedelta = False
- issue_warning = True
- elif numeric == 'coerce':
- numeric = coerce = True
- datetime = timedelta = False
- issue_warning = True
- elif timedelta == 'coerce':
- timedelta = coerce = True
- datetime = numeric = False
- issue_warning = True
- if issue_warning:
- warnings.warn("The use of 'coerce' as an input is deprecated. "
- "Instead set coerce=True.",
- FutureWarning)
+ Returns
+ -------
+ converted : same as input object
+ """
+ from warnings import warn
+ warn("convert_objects is deprecated. Use the data-type specific "
+ "converters pd.to_datetime, pd.to_timestamp and pd.to_numeric.",
+ FutureWarning, stacklevel=2)
return self._constructor(
- self._data.convert(datetime=datetime,
- numeric=numeric,
- timedelta=timedelta,
- coerce=coerce,
+ self._data.convert(convert_dates=convert_dates,
+ convert_numeric=convert_numeric,
+ convert_timedeltas=convert_timedeltas,
copy=copy)).__finalize__(self)
#----------------------------------------------------------------------
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index e837445e9e348..40f078a1bbcfe 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -112,7 +112,7 @@ def f(self):
except Exception:
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
if _convert:
- result = result.convert_objects(datetime=True)
+ result = result._convert(datetime=True)
return result
f.__doc__ = "Compute %s of group values" % name
@@ -2882,7 +2882,7 @@ def aggregate(self, arg, *args, **kwargs):
self._insert_inaxis_grouper_inplace(result)
result.index = np.arange(len(result))
- return result.convert_objects(datetime=True)
+ return result._convert(datetime=True)
def _aggregate_multiple_funcs(self, arg):
from pandas.tools.merge import concat
@@ -3123,14 +3123,14 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# as we are stacking can easily have object dtypes here
if (self._selected_obj.ndim == 2 and
self._selected_obj.dtypes.isin(_DATELIKE_DTYPES).any()):
- result = result.convert_objects(numeric=True)
+ result = result._convert(numeric=True)
date_cols = self._selected_obj.select_dtypes(
include=list(_DATELIKE_DTYPES)).columns
result[date_cols] = (result[date_cols]
- .convert_objects(datetime=True,
+ ._convert(datetime=True,
coerce=True))
else:
- result = result.convert_objects(datetime=True)
+ result = result._convert(datetime=True)
return self._reindex_output(result)
@@ -3138,7 +3138,7 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# only coerce dates if we find at least 1 datetime
coerce = True if any([ isinstance(v,Timestamp) for v in values ]) else False
return (Series(values, index=key_index)
- .convert_objects(datetime=True,
+ ._convert(datetime=True,
coerce=coerce))
else:
@@ -3243,7 +3243,7 @@ def transform(self, func, *args, **kwargs):
results = self._try_cast(results, obj[result.columns])
return (DataFrame(results,columns=result.columns,index=obj.index)
- .convert_objects(datetime=True))
+ ._convert(datetime=True))
def _define_paths(self, func, *args, **kwargs):
if isinstance(func, compat.string_types):
@@ -3436,7 +3436,7 @@ def _wrap_aggregated_output(self, output, names=None):
if self.axis == 1:
result = result.T
- return self._reindex_output(result).convert_objects(datetime=True)
+ return self._reindex_output(result)._convert(datetime=True)
def _wrap_agged_blocks(self, items, blocks):
if not self.as_index:
@@ -3454,7 +3454,7 @@ def _wrap_agged_blocks(self, items, blocks):
if self.axis == 1:
result = result.T
- return self._reindex_output(result).convert_objects(datetime=True)
+ return self._reindex_output(result)._convert(datetime=True)
def _reindex_output(self, result):
"""
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 97b54d4ef6ebe..4790f3aa3841e 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -25,6 +25,7 @@
from pandas.core.categorical import Categorical, maybe_to_categorical
from pandas.tseries.index import DatetimeIndex
import pandas.core.common as com
+import pandas.core.convert as convert
from pandas.sparse.array import _maybe_to_sparse, SparseArray
import pandas.lib as lib
import pandas.tslib as tslib
@@ -1517,14 +1518,35 @@ def is_bool(self):
"""
return lib.is_bool_array(self.values.ravel())
- def convert(self, datetime=True, numeric=True, timedelta=True, coerce=False,
- copy=True, by_item=True):
+ # TODO: Refactor when convert_objects is removed since there will be 1 path
+ def convert(self, *args, **kwargs):
""" attempt to coerce any object types to better types
return a copy of the block (if copy = True)
by definition we ARE an ObjectBlock!!!!!
can return multiple blocks!
"""
+ if args:
+ raise NotImplementedError
+ by_item = True if 'by_item' not in kwargs else kwargs['by_item']
+
+ new_inputs = ['coerce','datetime','numeric','timedelta']
+ new_style = False
+ for kw in new_inputs:
+ new_style |= kw in kwargs
+
+ if new_style:
+ fn = convert._soft_convert_objects
+ fn_inputs = new_inputs
+ else:
+ fn = convert._possibly_convert_objects
+ fn_inputs = ['convert_dates','convert_numeric','convert_timedeltas']
+ fn_inputs += ['copy']
+
+ fn_kwargs = {}
+ for key in fn_inputs:
+ if key in kwargs:
+ fn_kwargs[key] = kwargs[key]
# attempt to create new type blocks
blocks = []
@@ -1533,30 +1555,14 @@ def convert(self, datetime=True, numeric=True, timedelta=True, coerce=False,
for i, rl in enumerate(self.mgr_locs):
values = self.iget(i)
- values = com._possibly_convert_objects(
- values.ravel(),
- datetime=datetime,
- numeric=numeric,
- timedelta=timedelta,
- coerce=coerce,
- copy=copy
- ).reshape(values.shape)
+ values = fn(values.ravel(), **fn_kwargs).reshape(values.shape)
values = _block_shape(values, ndim=self.ndim)
- newb = self.make_block(values,
- placement=[rl])
+ newb = make_block(values, ndim=self.ndim, placement=[rl])
blocks.append(newb)
else:
-
- values = com._possibly_convert_objects(
- self.values.ravel(),
- datetime=datetime,
- numeric=numeric,
- timedelta=timedelta,
- coerce=coerce,
- copy=copy
- ).reshape(self.values.shape)
- blocks.append(self.make_block(values))
+ values = fn(self.values.ravel(), **fn_kwargs).reshape(self.values.shape)
+ blocks.append(make_block(values, ndim=self.ndim, placement=self.mgr_locs))
return blocks
@@ -1597,8 +1603,7 @@ def _maybe_downcast(self, blocks, downcast=None):
# split and convert the blocks
result_blocks = []
for blk in blocks:
- result_blocks.extend(blk.convert(datetime=True,
- numeric=False))
+ result_blocks.extend(blk.convert(datetime=True, numeric=False))
return result_blocks
def _can_hold_element(self, element):
diff --git a/pandas/io/tests/test_html.py b/pandas/io/tests/test_html.py
index 5c8c15c7c2ae0..141533a131e42 100644
--- a/pandas/io/tests/test_html.py
+++ b/pandas/io/tests/test_html.py
@@ -527,10 +527,10 @@ def try_remove_ws(x):
'Hamilton Bank, NA', 'The Citizens Savings Bank']
dfnew = df.applymap(try_remove_ws).replace(old, new)
gtnew = ground_truth.applymap(try_remove_ws)
- converted = dfnew.convert_objects(datetime=True, numeric=True)
+ converted = dfnew._convert(datetime=True, numeric=True)
date_cols = ['Closing Date','Updated Date']
- converted[date_cols] = converted[date_cols].convert_objects(datetime=True,
- coerce=True)
+ converted[date_cols] = converted[date_cols]._convert(datetime=True,
+ coerce=True)
tm.assert_frame_equal(converted,gtnew)
@slow
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index adef470965f21..df2a659100305 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -408,7 +408,7 @@ def test_repr(self):
df['datetime1'] = datetime.datetime(2001,1,2,0,0)
df['datetime2'] = datetime.datetime(2001,1,3,0,0)
df.ix[3:6,['obj1']] = np.nan
- df = df.consolidate().convert_objects(datetime=True)
+ df = df.consolidate()._convert(datetime=True)
warnings.filterwarnings('ignore', category=PerformanceWarning)
store['df'] = df
@@ -736,7 +736,7 @@ def test_put_mixed_type(self):
df['datetime1'] = datetime.datetime(2001, 1, 2, 0, 0)
df['datetime2'] = datetime.datetime(2001, 1, 3, 0, 0)
df.ix[3:6, ['obj1']] = np.nan
- df = df.consolidate().convert_objects(datetime=True)
+ df = df.consolidate()._convert(datetime=True)
with ensure_clean_store(self.path) as store:
_maybe_remove(store, 'df')
@@ -1456,7 +1456,7 @@ def check_col(key,name,size):
df_dc.ix[7:9, 'string'] = 'bar'
df_dc['string2'] = 'cool'
df_dc['datetime'] = Timestamp('20010102')
- df_dc = df_dc.convert_objects(datetime=True)
+ df_dc = df_dc._convert(datetime=True)
df_dc.ix[3:5, ['A', 'B', 'datetime']] = np.nan
_maybe_remove(store, 'df_dc')
@@ -1918,7 +1918,7 @@ def test_table_mixed_dtypes(self):
df['datetime1'] = datetime.datetime(2001, 1, 2, 0, 0)
df['datetime2'] = datetime.datetime(2001, 1, 3, 0, 0)
df.ix[3:6, ['obj1']] = np.nan
- df = df.consolidate().convert_objects(datetime=True)
+ df = df.consolidate()._convert(datetime=True)
with ensure_clean_store(self.path) as store:
store.append('df1_mixed', df)
@@ -1974,7 +1974,7 @@ def test_unimplemented_dtypes_table_columns(self):
df['obj1'] = 'foo'
df['obj2'] = 'bar'
df['datetime1'] = datetime.date(2001, 1, 2)
- df = df.consolidate().convert_objects(datetime=True)
+ df = df.consolidate()._convert(datetime=True)
with ensure_clean_store(self.path) as store:
# this fails because we have a date in the object block......
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index 8505150932c90..aff9cd6c558e2 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -417,7 +417,7 @@ def test_read_write_reread_dta14(self):
expected = self.read_csv(self.csv14)
cols = ['byte_', 'int_', 'long_', 'float_', 'double_']
for col in cols:
- expected[col] = expected[col].convert_objects(datetime=True, numeric=True)
+ expected[col] = expected[col]._convert(datetime=True, numeric=True)
expected['float_'] = expected['float_'].astype(np.float32)
expected['date_td'] = pd.to_datetime(expected['date_td'], errors='coerce')
diff --git a/pandas/io/wb.py b/pandas/io/wb.py
index 99b14be0b0b6b..e617a01b73bfd 100644
--- a/pandas/io/wb.py
+++ b/pandas/io/wb.py
@@ -165,7 +165,7 @@ def download(country=['MX', 'CA', 'US'], indicator=['NY.GDP.MKTP.CD', 'NY.GNS.IC
out = reduce(lambda x, y: x.merge(y, how='outer'), data)
out = out.drop('iso_code', axis=1)
out = out.set_index(['country', 'year'])
- out = out.convert_objects(datetime=True, numeric=True)
+ out = out._convert(datetime=True, numeric=True)
return out
else:
msg = "No indicators returned data."
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index b234773359f8c..c488d22da7dfe 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -13,6 +13,7 @@
from pandas.compat import range, long, lrange, lmap, u
from pandas.core.common import notnull, isnull, array_equivalent
import pandas.core.common as com
+import pandas.core.convert as convert
import pandas.util.testing as tm
import pandas.core.config as cf
@@ -1051,33 +1052,32 @@ def test_maybe_convert_string_to_array(self):
tm.assert_numpy_array_equal(result, np.array(['x', 2], dtype=object))
self.assertTrue(result.dtype == object)
-
-def test_dict_compat():
- data_datetime64 = {np.datetime64('1990-03-15'): 1,
- np.datetime64('2015-03-15'): 2}
- data_unchanged = {1: 2, 3: 4, 5: 6}
- expected = {Timestamp('1990-3-15'): 1, Timestamp('2015-03-15'): 2}
- assert(com._dict_compat(data_datetime64) == expected)
- assert(com._dict_compat(expected) == expected)
- assert(com._dict_compat(data_unchanged) == data_unchanged)
-
-
def test_possibly_convert_objects_copy():
values = np.array([1, 2])
- out = com._possibly_convert_objects(values, copy=False)
+ out = convert._possibly_convert_objects(values, copy=False)
assert_true(values is out)
- out = com._possibly_convert_objects(values, copy=True)
+ out = convert._possibly_convert_objects(values, copy=True)
assert_true(values is not out)
values = np.array(['apply','banana'])
- out = com._possibly_convert_objects(values, copy=False)
+ out = convert._possibly_convert_objects(values, copy=False)
assert_true(values is out)
- out = com._possibly_convert_objects(values, copy=True)
+ out = convert._possibly_convert_objects(values, copy=True)
assert_true(values is not out)
-
+
+
+def test_dict_compat():
+ data_datetime64 = {np.datetime64('1990-03-15'): 1,
+ np.datetime64('2015-03-15'): 2}
+ data_unchanged = {1: 2, 3: 4, 5: 6}
+ expected = {Timestamp('1990-3-15'): 1, Timestamp('2015-03-15'): 2}
+ assert(com._dict_compat(data_datetime64) == expected)
+ assert(com._dict_compat(expected) == expected)
+ assert(com._dict_compat(data_unchanged) == data_unchanged)
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index c963222cf4ad9..5acc858840dfa 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -6805,7 +6805,7 @@ def make_dtnat_arr(n,nnat=None):
with ensure_clean('.csv') as pth:
df=DataFrame(dict(a=s1,b=s2))
df.to_csv(pth,chunksize=chunksize)
- recons = DataFrame.from_csv(pth).convert_objects(datetime=True,
+ recons = DataFrame.from_csv(pth)._convert(datetime=True,
coerce=True)
assert_frame_equal(df, recons,check_names=False,check_less_precise=True)
@@ -7516,7 +7516,7 @@ def test_dtypes(self):
def test_convert_objects(self):
oops = self.mixed_frame.T.T
- converted = oops.convert_objects(datetime=True)
+ converted = oops._convert(datetime=True)
assert_frame_equal(converted, self.mixed_frame)
self.assertEqual(converted['A'].dtype, np.float64)
@@ -7529,8 +7529,7 @@ def test_convert_objects(self):
self.mixed_frame['J'] = '1.'
self.mixed_frame['K'] = '1'
self.mixed_frame.ix[0:5,['J','K']] = 'garbled'
- converted = self.mixed_frame.convert_objects(datetime=True,
- numeric=True)
+ converted = self.mixed_frame._convert(datetime=True, numeric=True)
self.assertEqual(converted['H'].dtype, 'float64')
self.assertEqual(converted['I'].dtype, 'int64')
self.assertEqual(converted['J'].dtype, 'float64')
@@ -7552,14 +7551,14 @@ def test_convert_objects(self):
# mixed in a single column
df = DataFrame(dict(s = Series([1, 'na', 3 ,4])))
- result = df.convert_objects(datetime=True, numeric=True)
+ result = df._convert(datetime=True, numeric=True)
expected = DataFrame(dict(s = Series([1, np.nan, 3 ,4])))
assert_frame_equal(result, expected)
def test_convert_objects_no_conversion(self):
mixed1 = DataFrame(
{'a': [1, 2, 3], 'b': [4.0, 5, 6], 'c': ['x', 'y', 'z']})
- mixed2 = mixed1.convert_objects(datetime=True)
+ mixed2 = mixed1._convert(datetime=True)
assert_frame_equal(mixed1, mixed2)
def test_append_series_dict(self):
@@ -11551,7 +11550,7 @@ def test_apply_convert_objects(self):
'F': np.random.randn(11)})
result = data.apply(lambda x: x, axis=1)
- assert_frame_equal(result.convert_objects(datetime=True), data)
+ assert_frame_equal(result._convert(datetime=True), data)
def test_apply_attach_name(self):
result = self.frame.apply(lambda x: x.name)
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 1e707264edebe..35467c6abb9b4 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -3138,8 +3138,7 @@ def test_astype_assignment(self):
assert_frame_equal(df,expected)
df = df_orig.copy()
- df.iloc[:,0:2] = df.iloc[:,0:2].convert_objects(datetime=True,
- numeric=True)
+ df.iloc[:,0:2] = df.iloc[:,0:2]._convert(datetime=True, numeric=True)
expected = DataFrame([[1,2,'3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
assert_frame_equal(df,expected)
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index bd27d11ef14c1..0dad55a9133b6 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1145,7 +1145,7 @@ def test_convert_objects(self):
# GH 4937
p = Panel(dict(A = dict(a = ['1','1.0'])))
expected = Panel(dict(A = dict(a = [1,1.0])))
- result = p.convert_objects(numeric=True, coerce=True)
+ result = p._convert(numeric=True, coerce=True)
assert_panel_equal(result, expected)
def test_dtypes(self):
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index a6d7e63656d68..79de22b507e2a 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -6449,21 +6449,138 @@ def test_apply_dont_convert_dtype(self):
result = s.apply(f, convert_dtype=False)
self.assertEqual(result.dtype, object)
- # GH 10265
def test_convert_objects(self):
+
+ s = Series([1., 2, 3], index=['a', 'b', 'c'])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates=False, convert_numeric=True)
+ assert_series_equal(result, s)
+
+ # force numeric conversion
+ r = s.copy().astype('O')
+ r['a'] = '1'
+ with tm.assert_produces_warning(FutureWarning):
+ result = r.convert_objects(convert_dates=False, convert_numeric=True)
+ assert_series_equal(result, s)
+
+ r = s.copy().astype('O')
+ r['a'] = '1.'
+ with tm.assert_produces_warning(FutureWarning):
+ result = r.convert_objects(convert_dates=False, convert_numeric=True)
+ assert_series_equal(result, s)
+
+ r = s.copy().astype('O')
+ r['a'] = 'garbled'
+ expected = s.copy()
+ expected['a'] = np.nan
+ with tm.assert_produces_warning(FutureWarning):
+ result = r.convert_objects(convert_dates=False, convert_numeric=True)
+ assert_series_equal(result, expected)
+
+ # GH 4119, not converting a mixed type (e.g.floats and object)
+ s = Series([1, 'na', 3, 4])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_numeric=True)
+ expected = Series([1, np.nan, 3, 4])
+ assert_series_equal(result, expected)
+
+ s = Series([1, '', 3, 4])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_numeric=True)
+ expected = Series([1, np.nan, 3, 4])
+ assert_series_equal(result, expected)
+
+ # dates
+ s = Series(
+ [datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime(2001, 1, 3, 0, 0)])
+ s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime(
+ 2001, 1, 3, 0, 0), 'foo', 1.0, 1, Timestamp('20010104'), '20010105'], dtype='O')
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates=True, convert_numeric=False)
+ expected = Series(
+ [Timestamp('20010101'), Timestamp('20010102'), Timestamp('20010103')], dtype='M8[ns]')
+ assert_series_equal(result, expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates='coerce',
+ convert_numeric=False)
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates='coerce',
+ convert_numeric=True)
+ assert_series_equal(result, expected)
+
+ expected = Series(
+ [Timestamp(
+ '20010101'), Timestamp('20010102'), Timestamp('20010103'),
+ lib.NaT, lib.NaT, lib.NaT, Timestamp('20010104'), Timestamp('20010105')], dtype='M8[ns]')
+ with tm.assert_produces_warning(FutureWarning):
+ result = s2.convert_objects(convert_dates='coerce',
+ convert_numeric=False)
+ assert_series_equal(result, expected)
+ with tm.assert_produces_warning(FutureWarning):
+ result = s2.convert_objects(convert_dates='coerce',
+ convert_numeric=True)
+ assert_series_equal(result, expected)
+
+ # preserver all-nans (if convert_dates='coerce')
+ s = Series(['foo', 'bar', 1, 1.0], dtype='O')
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates='coerce',
+ convert_numeric=False)
+ assert_series_equal(result, s)
+
+ # preserver if non-object
+ s = Series([1], dtype='float32')
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates='coerce',
+ convert_numeric=False)
+ assert_series_equal(result, s)
+
+ #r = s.copy()
+ #r[0] = np.nan
+ #result = r.convert_objects(convert_dates=True,convert_numeric=False)
+ #self.assertEqual(result.dtype, 'M8[ns]')
+
+ # dateutil parses some single letters into today's value as a date
+ for x in 'abcdefghijklmnopqrstuvwxyz':
+ s = Series([x])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates='coerce')
+ assert_series_equal(result, s)
+ s = Series([x.upper()])
+ with tm.assert_produces_warning(FutureWarning):
+ result = s.convert_objects(convert_dates='coerce')
+ assert_series_equal(result, s)
+
+ def test_convert_objects_preserve_bool(self):
+ s = Series([1, True, 3, 5], dtype=object)
+ with tm.assert_produces_warning(FutureWarning):
+ r = s.convert_objects(convert_numeric=True)
+ e = Series([1, 1, 3, 5], dtype='i8')
+ tm.assert_series_equal(r, e)
+
+ def test_convert_objects_preserve_all_bool(self):
+ s = Series([False, True, False, False], dtype=object)
+ with tm.assert_produces_warning(FutureWarning):
+ r = s.convert_objects(convert_numeric=True)
+ e = Series([False, True, False, False], dtype=bool)
+ tm.assert_series_equal(r, e)
+
+ # GH 10265
+ def test_convert(self):
# Tests: All to nans, coerce, true
# Test coercion returns correct type
s = Series(['a', 'b', 'c'])
- results = s.convert_objects(datetime=True, coerce=True)
+ results = s._convert(datetime=True, coerce=True)
expected = Series([lib.NaT] * 3)
assert_series_equal(results, expected)
- results = s.convert_objects(numeric=True, coerce=True)
+ results = s._convert(numeric=True, coerce=True)
expected = Series([np.nan] * 3)
assert_series_equal(results, expected)
expected = Series([lib.NaT] * 3, dtype=np.dtype('m8[ns]'))
- results = s.convert_objects(timedelta=True, coerce=True)
+ results = s._convert(timedelta=True, coerce=True)
assert_series_equal(results, expected)
dt = datetime(2001, 1, 1, 0, 0)
@@ -6471,83 +6588,83 @@ def test_convert_objects(self):
# Test coercion with mixed types
s = Series(['a', '3.1415', dt, td])
- results = s.convert_objects(datetime=True, coerce=True)
+ results = s._convert(datetime=True, coerce=True)
expected = Series([lib.NaT, lib.NaT, dt, lib.NaT])
assert_series_equal(results, expected)
- results = s.convert_objects(numeric=True, coerce=True)
+ results = s._convert(numeric=True, coerce=True)
expected = Series([nan, 3.1415, nan, nan])
assert_series_equal(results, expected)
- results = s.convert_objects(timedelta=True, coerce=True)
+ results = s._convert(timedelta=True, coerce=True)
expected = Series([lib.NaT, lib.NaT, lib.NaT, td],
dtype=np.dtype('m8[ns]'))
assert_series_equal(results, expected)
# Test standard conversion returns original
- results = s.convert_objects(datetime=True)
+ results = s._convert(datetime=True)
assert_series_equal(results, s)
- results = s.convert_objects(numeric=True)
+ results = s._convert(numeric=True)
expected = Series([nan, 3.1415, nan, nan])
assert_series_equal(results, expected)
- results = s.convert_objects(timedelta=True)
+ results = s._convert(timedelta=True)
assert_series_equal(results, s)
# test pass-through and non-conversion when other types selected
s = Series(['1.0','2.0','3.0'])
- results = s.convert_objects(datetime=True, numeric=True, timedelta=True)
+ results = s._convert(datetime=True, numeric=True, timedelta=True)
expected = Series([1.0,2.0,3.0])
assert_series_equal(results, expected)
- results = s.convert_objects(True,False,True)
+ results = s._convert(True,False,True)
assert_series_equal(results, s)
s = Series([datetime(2001, 1, 1, 0, 0),datetime(2001, 1, 1, 0, 0)],
dtype='O')
- results = s.convert_objects(datetime=True, numeric=True, timedelta=True)
+ results = s._convert(datetime=True, numeric=True, timedelta=True)
expected = Series([datetime(2001, 1, 1, 0, 0),datetime(2001, 1, 1, 0, 0)])
assert_series_equal(results, expected)
- results = s.convert_objects(datetime=False,numeric=True,timedelta=True)
+ results = s._convert(datetime=False,numeric=True,timedelta=True)
assert_series_equal(results, s)
td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0)
s = Series([td, td], dtype='O')
- results = s.convert_objects(datetime=True, numeric=True, timedelta=True)
+ results = s._convert(datetime=True, numeric=True, timedelta=True)
expected = Series([td, td])
assert_series_equal(results, expected)
- results = s.convert_objects(True,True,False)
+ results = s._convert(True,True,False)
assert_series_equal(results, s)
s = Series([1., 2, 3], index=['a', 'b', 'c'])
- result = s.convert_objects(numeric=True)
+ result = s._convert(numeric=True)
assert_series_equal(result, s)
# force numeric conversion
r = s.copy().astype('O')
r['a'] = '1'
- result = r.convert_objects(numeric=True)
+ result = r._convert(numeric=True)
assert_series_equal(result, s)
r = s.copy().astype('O')
r['a'] = '1.'
- result = r.convert_objects(numeric=True)
+ result = r._convert(numeric=True)
assert_series_equal(result, s)
r = s.copy().astype('O')
r['a'] = 'garbled'
- result = r.convert_objects(numeric=True)
+ result = r._convert(numeric=True)
expected = s.copy()
expected['a'] = nan
assert_series_equal(result, expected)
# GH 4119, not converting a mixed type (e.g.floats and object)
s = Series([1, 'na', 3, 4])
- result = s.convert_objects(datetime=True, numeric=True)
+ result = s._convert(datetime=True, numeric=True)
expected = Series([1, nan, 3, 4])
assert_series_equal(result, expected)
s = Series([1, '', 3, 4])
- result = s.convert_objects(datetime=True, numeric=True)
+ result = s._convert(datetime=True, numeric=True)
assert_series_equal(result, expected)
# dates
@@ -6556,95 +6673,64 @@ def test_convert_objects(self):
s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime(
2001, 1, 3, 0, 0), 'foo', 1.0, 1, Timestamp('20010104'), '20010105'], dtype='O')
- result = s.convert_objects(datetime=True)
+ result = s._convert(datetime=True)
expected = Series(
[Timestamp('20010101'), Timestamp('20010102'), Timestamp('20010103')], dtype='M8[ns]')
assert_series_equal(result, expected)
- result = s.convert_objects(datetime=True, coerce=True)
+ result = s._convert(datetime=True, coerce=True)
assert_series_equal(result, expected)
expected = Series(
[Timestamp(
'20010101'), Timestamp('20010102'), Timestamp('20010103'),
lib.NaT, lib.NaT, lib.NaT, Timestamp('20010104'), Timestamp('20010105')], dtype='M8[ns]')
- result = s2.convert_objects(datetime=True,
+ result = s2._convert(datetime=True,
numeric=False,
timedelta=False,
coerce=True)
assert_series_equal(result, expected)
- result = s2.convert_objects(datetime=True, coerce=True)
+ result = s2._convert(datetime=True, coerce=True)
assert_series_equal(result, expected)
s = Series(['foo', 'bar', 1, 1.0], dtype='O')
- result = s.convert_objects(datetime=True, coerce=True)
+ result = s._convert(datetime=True, coerce=True)
expected = Series([lib.NaT]*4)
assert_series_equal(result, expected)
# preserver if non-object
s = Series([1], dtype='float32')
- result = s.convert_objects(datetime=True, coerce=True)
+ result = s._convert(datetime=True, coerce=True)
assert_series_equal(result, s)
#r = s.copy()
#r[0] = np.nan
- #result = r.convert_objects(convert_dates=True,convert_numeric=False)
+ #result = r._convert(convert_dates=True,convert_numeric=False)
#self.assertEqual(result.dtype, 'M8[ns]')
# dateutil parses some single letters into today's value as a date
expected = Series([lib.NaT])
for x in 'abcdefghijklmnopqrstuvwxyz':
s = Series([x])
- result = s.convert_objects(datetime=True, coerce=True)
+ result = s._convert(datetime=True, coerce=True)
assert_series_equal(result, expected)
s = Series([x.upper()])
- result = s.convert_objects(datetime=True, coerce=True)
+ result = s._convert(datetime=True, coerce=True)
assert_series_equal(result, expected)
- # GH 10601
- # Remove test after deprecation to convert_objects is final
- def test_convert_objects_old_style_deprecation(self):
- s = Series(['foo', 'bar', 1, 1.0], dtype='O')
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', FutureWarning)
- new_style = s.convert_objects(datetime=True, coerce=True)
- old_style = s.convert_objects(convert_dates='coerce')
- self.assertEqual(len(w), 2)
- assert_series_equal(new_style, old_style)
-
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', FutureWarning)
- new_style = s.convert_objects(numeric=True, coerce=True)
- old_style = s.convert_objects(convert_numeric='coerce')
- self.assertEqual(len(w), 2)
- assert_series_equal(new_style, old_style)
-
- dt = datetime(2001, 1, 1, 0, 0)
- td = dt - datetime(2000, 1, 1, 0, 0)
- s = Series(['a', '3.1415', dt, td])
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', FutureWarning)
- new_style = s.convert_objects(timedelta=True, coerce=True)
- old_style = s.convert_objects(convert_timedeltas='coerce')
- self.assertEqual(len(w), 2)
- assert_series_equal(new_style, old_style)
-
- def test_convert_objects_no_arg_warning(self):
+ def test_convert_no_arg_error(self):
s = Series(['1.0','2'])
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', DeprecationWarning)
- s.convert_objects()
- self.assertEqual(len(w), 1)
+ self.assertRaises(ValueError, s._convert)
- def test_convert_objects_preserve_bool(self):
+ def test_convert_preserve_bool(self):
s = Series([1, True, 3, 5], dtype=object)
- r = s.convert_objects(datetime=True, numeric=True)
+ r = s._convert(datetime=True, numeric=True)
e = Series([1, 1, 3, 5], dtype='i8')
tm.assert_series_equal(r, e)
- def test_convert_objects_preserve_all_bool(self):
+ def test_convert_preserve_all_bool(self):
s = Series([False, True, False, False], dtype=object)
- r = s.convert_objects(datetime=True, numeric=True)
+ r = s._convert(datetime=True, numeric=True)
e = Series([False, True, False, False], dtype=bool)
tm.assert_series_equal(r, e)
diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py
index fb334cf9912f3..427c96a839c26 100644
--- a/pandas/tests/test_util.py
+++ b/pandas/tests/test_util.py
@@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-
-import warnings
-
import nose
-import sys
-import pandas.util
from pandas.util.decorators import deprecate_kwarg
import pandas.util.testing as tm
+
+
class TestDecorators(tm.TestCase):
def setUp(self):
@deprecate_kwarg('old', 'new')
@@ -75,7 +73,6 @@ def test_rands_array():
assert(arr.shape == (10, 10))
assert(len(arr[1, 1]) == 7)
-
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 55464a7f1d23e..98d6f5e8eb797 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -1079,7 +1079,7 @@ def _compute_plot_data(self):
label = 'None'
data = data.to_frame(name=label)
- numeric_data = data.convert_objects(datetime=True)._get_numeric_data()
+ numeric_data = data._convert(datetime=True)._get_numeric_data()
try:
is_empty = numeric_data.empty
@@ -1972,8 +1972,7 @@ def __init__(self, data, bins=10, bottom=0, **kwargs):
def _args_adjust(self):
if com.is_integer(self.bins):
# create common bin edge
- values = (self.data.convert_objects(datetime=True)
- ._get_numeric_data())
+ values = (self.data._convert(datetime=True)._get_numeric_data())
values = np.ravel(values)
values = values[~com.isnull(values)]
diff --git a/pandas/tools/tests/test_util.py b/pandas/tools/tests/test_util.py
index 1adf47e946a96..72ce7d8659157 100644
--- a/pandas/tools/tests/test_util.py
+++ b/pandas/tools/tests/test_util.py
@@ -2,14 +2,15 @@
import locale
import codecs
import nose
+from nose.tools import assert_raises, assert_true
import numpy as np
from numpy.testing import assert_equal
+import pandas as pd
from pandas import date_range, Index
import pandas.util.testing as tm
-from pandas.tools.util import cartesian_product
-
+from pandas.tools.util import cartesian_product, to_numeric
CURRENT_LOCALE = locale.getlocale()
LOCALE_OVERRIDE = os.environ.get('LOCALE_OVERRIDE', None)
@@ -89,6 +90,54 @@ def test_set_locale(self):
self.assertEqual(current_locale, CURRENT_LOCALE)
+class TestToNumeric(tm.TestCase):
+ def test_series(self):
+ s = pd.Series(['1', '-3.14', '7'])
+ res = to_numeric(s)
+ expected = pd.Series([1, -3.14, 7])
+ tm.assert_series_equal(res, expected)
+
+ s = pd.Series(['1', '-3.14', 7])
+ res = to_numeric(s)
+ tm.assert_series_equal(res, expected)
+
+ def test_error(self):
+ s = pd.Series([1, -3.14, 'apple'])
+ assert_raises(ValueError, to_numeric, s, errors='raise')
+
+ res = to_numeric(s, errors='ignore')
+ expected = pd.Series([1, -3.14, 'apple'])
+ tm.assert_series_equal(res, expected)
+
+ res = to_numeric(s, errors='coerce')
+ expected = pd.Series([1, -3.14, np.nan])
+ tm.assert_series_equal(res, expected)
+
+
+ def test_list(self):
+ s = ['1', '-3.14', '7']
+ res = to_numeric(s)
+ expected = np.array([1, -3.14, 7])
+ tm.assert_numpy_array_equal(res, expected)
+
+ def test_numeric(self):
+ s = pd.Series([1, -3.14, 7], dtype='O')
+ res = to_numeric(s)
+ expected = pd.Series([1, -3.14, 7])
+ tm.assert_series_equal(res, expected)
+
+ s = pd.Series([1, -3.14, 7])
+ res = to_numeric(s)
+ tm.assert_series_equal(res, expected)
+
+ def test_all_nan(self):
+ s = pd.Series(['a','b','c'])
+ res = to_numeric(s, errors='coerce')
+ expected = pd.Series([np.nan, np.nan, np.nan])
+ tm.assert_series_equal(res, expected)
+
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)
+
diff --git a/pandas/tools/util.py b/pandas/tools/util.py
index 0bb6b4b7f7892..925c23255b5f5 100644
--- a/pandas/tools/util.py
+++ b/pandas/tools/util.py
@@ -1,9 +1,9 @@
-import operator
-import warnings
+import numpy as np
+import pandas.lib as lib
+
+import pandas as pd
from pandas.compat import reduce
from pandas.core.index import Index
-import numpy as np
-from pandas import algos
from pandas.core import common as com
@@ -48,3 +48,57 @@ def compose(*funcs):
"""Compose 2 or more callables"""
assert len(funcs) > 1, 'At least 2 callables must be passed to compose'
return reduce(_compose2, funcs)
+
+
+def to_numeric(arg, errors='raise'):
+ """
+ Convert argument to a numeric type.
+
+ Parameters
+ ----------
+ arg : list, tuple or array of objects, or Series
+ errors : {'ignore', 'raise', 'coerce'}, default 'raise'
+ - If 'raise', then invalid parsing will raise an exception
+ - If 'coerce', then invalid parsing will be set as NaN
+ - If 'ignore', then invalid parsing will return the input
+
+ Returns
+ -------
+ ret : numeric if parsing succeeded.
+ Return type depends on input. Series if Series, otherwise ndarray
+
+ Examples
+ --------
+ Take separate series and convert to numeric, coercing when told to
+
+ >>> import pandas as pd
+ >>> s = pd.Series(['1.0', '2', -3])
+ >>> pd.to_numeric(s)
+ >>> s = pd.Series(['apple', '1.0', '2', -3])
+ >>> pd.to_numeric(s, errors='ignore')
+ >>> pd.to_numeric(s, errors='coerce')
+ """
+
+ index = name = None
+ if isinstance(arg, pd.Series):
+ index, name = arg.index, arg.name
+ elif isinstance(arg, (list, tuple)):
+ arg = np.array(arg, dtype='O')
+
+ conv = arg
+ arg = com._ensure_object(arg)
+
+ coerce_numeric = False if errors in ('ignore', 'raise') else True
+
+ try:
+ conv = lib.maybe_convert_numeric(arg,
+ set(),
+ coerce_numeric=coerce_numeric)
+ except:
+ if errors == 'raise':
+ raise
+
+ if index is not None:
+ return pd.Series(conv, index=index, name=name)
+ else:
+ return conv
| Restores the v0.16 behavior of convert_objects and moves the new
version of _convert
Adds to_numeric for directly converting numeric data
closes #11116
closes #11133
| https://api.github.com/repos/pandas-dev/pandas/pulls/11173 | 2015-09-22T21:28:43Z | 2015-10-02T14:13:52Z | 2015-10-02T14:13:52Z | 2016-02-16T16:29:59Z |
ENH: make Series.ptp ignore NaN values (GH11163) | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 0b2bb0b5a475c..9f943fa68e639 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -527,6 +527,7 @@ Other enhancements
- ``pd.read_csv`` is now able to infer compression type for files read from AWS S3 storage (:issue:`11070`, :issue:`11074`).
+
.. _whatsnew_0170.api:
.. _whatsnew_0170.api_breaking:
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 3d10566e47075..67c3ef39a8cb5 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -60,6 +60,7 @@ API changes
- ``Series.sort_index()`` now correctly handles the ``inplace`` option (:issue:`11402`)
- ``DataFrame.itertuples()`` now returns ``namedtuple`` objects, when possible. (:issue:`11269`)
+- ``Series.ptp`` will now ignore missing values by default (:issue:`11163`)
.. _whatsnew_0171.deprecations:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 605c95bfb0ba2..4cc1cac65243c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4701,6 +4701,17 @@ def stat_func(self, axis=None, skipna=None, level=None,
want the *index* of the minimum, use ``idxmin``. This is the
equivalent of the ``numpy.ndarray`` method ``argmin``.""", nanops.nanmin)
+ if cls.__name__ == 'Series':
+ def nanptp(values, axis=0, skipna=True):
+ nmax = nanops.nanmax(values, axis, skipna)
+ nmin = nanops.nanmin(values, axis, skipna)
+ return nmax - nmin
+
+ cls.ptp = _make_stat_function('ptp', """
+Returns the difference between the maximum value and the minimum
+value in the object. This is the equivalent of the ``numpy.ndarray``
+method ``ptp``.""", nanptp)
+
def _make_logical_function(name, desc, f):
@Substitution(outname=name, desc=desc)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 5106225cdd3c9..9b498bb969cbc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1277,9 +1277,6 @@ def multi(values, qs):
return self._maybe_box(lambda values: multi(values, q), dropna=True)
- def ptp(self, axis=None, out=None):
- return _values_from_object(self).ptp(axis, out)
-
def corr(self, other, method='pearson',
min_periods=None):
"""
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 1c8cbac60e7c7..f8f065f3371ab 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -5949,6 +5949,31 @@ def test_ptp(self):
ser = Series(arr)
self.assertEqual(np.ptp(ser), np.ptp(arr))
+ # GH11163
+ s = Series([3, 5, np.nan, -3, 10])
+ self.assertEqual(s.ptp(), 13)
+ self.assertTrue(pd.isnull(s.ptp(skipna=False)))
+
+ mi = pd.MultiIndex.from_product([['a','b'], [1,2,3]])
+ s = pd.Series([1, np.nan, 7, 3, 5, np.nan], index=mi)
+
+ expected = pd.Series([6, 2], index=['a', 'b'], dtype=np.float64)
+ self.assert_series_equal(s.ptp(level=0), expected)
+
+ expected = pd.Series([np.nan, np.nan], index=['a', 'b'])
+ self.assert_series_equal(s.ptp(level=0, skipna=False), expected)
+
+ with self.assertRaises(ValueError):
+ s.ptp(axis=1)
+
+ s = pd.Series(['a', 'b', 'c', 'd', 'e'])
+ with self.assertRaises(TypeError):
+ s.ptp()
+
+ with self.assertRaises(NotImplementedError):
+ s.ptp(numeric_only=True)
+
+
def test_asof(self):
# array or list or dates
N = 50
| Closes [GH11163](https://github.com/pydata/pandas/issues/11163).
`Series.ptp` will now ignore missing values when calculating the peak to peak difference.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11172 | 2015-09-22T20:31:53Z | 2015-11-14T15:04:01Z | 2015-11-14T15:04:01Z | 2015-11-14T23:16:58Z |
Added density of a categorical #10949 | diff --git a/doc/source/api.rst b/doc/source/api.rst
index bfd1c92d14acd..28d7fee0f158f 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -643,6 +643,7 @@ following usable methods and properties:
Series.cat.categories
Series.cat.ordered
Series.cat.codes
+ Series.cat.density
.. autosummary::
:toctree: generated/
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 74ace42eb7e22..03ac7711687e0 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -21,6 +21,7 @@ Enhancements
.. _whatsnew_0171.enhancements.other:
- Improve the error message in :func:`pandas.io.gbq.to_gbq` when a streaming insert fails (:issue:`11285`)
+- Added density property to Categorical (:issue:`10949`)
Other Enhancements
^^^^^^^^^^^^^^^^^^
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index 9decd5e212cbf..3a498626b50ae 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -1753,6 +1753,11 @@ def codes(self):
from pandas import Series
return Series(self.categorical.codes, index=self.index)
+ @property
+ def density(self):
+ """The cardinality ratio of this categorical."""
+ return np.divide(float(len(self.categorical.categories)), len(self.categorical))
+
def _delegate_method(self, name, *args, **kwargs):
from pandas import Series
method = getattr(self.categorical, name)
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index e97010e1cb552..5cf7bb1bacf07 100755
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -3602,7 +3602,7 @@ def test_cat_tab_completition(self):
ok_for_cat = ['categories','codes','ordered','set_categories',
'add_categories', 'remove_categories', 'rename_categories',
'reorder_categories', 'remove_unused_categories',
- 'as_ordered', 'as_unordered']
+ 'as_ordered', 'as_unordered', 'density']
def get_dir(s):
results = [ r for r in s.cat.__dir__() if not r.startswith('_') ]
return list(sorted(set(results)))
@@ -3678,6 +3678,12 @@ def test_concat_categorical(self):
tm.assert_frame_equal(df_expected, df_concat)
+ def test_density(self):
+ s1 = Series(list('aabbcccc')).astype('category')
+ self.assertEqual(0.375, s1.cat.density)
+
+ s2 = Series([]).astype('category')
+ self.assertTrue(np.isnan(s2.cat.density))
if __name__ == '__main__':
| Not sure if this is the correct approach to the problem
closes #10949.
Assuming it is I will go ahead and add some documentation for this enhancement. Let me know if you have any feedback.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11171 | 2015-09-22T18:48:51Z | 2015-10-20T17:49:06Z | null | 2015-10-20T17:49:06Z |
BF: for version comparison first arg should be the LooseVersion | diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 657789fe8ce9b..d44ce24cbefbc 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -1478,8 +1478,8 @@ def setUpClass(cls):
_skip_if_no_openpyxl()
import openpyxl
ver = openpyxl.__version__
- if not (ver >= LooseVersion('2.0.0') and ver < LooseVersion('2.2.0')):
- raise nose.SkipTest("openpyxl >= 2.2")
+ if not (LooseVersion(ver) >= LooseVersion('2.0.0') and LooseVersion(ver) < LooseVersion('2.2.0')):
+ raise nose.SkipTest("openpyxl %s >= 2.2" % str(ver))
cls.setUpClass = setUpClass
return cls
@@ -1593,8 +1593,8 @@ def setUpClass(cls):
_skip_if_no_openpyxl()
import openpyxl
ver = openpyxl.__version__
- if ver < LooseVersion('2.2.0'):
- raise nose.SkipTest("openpyxl < 2.2")
+ if LooseVersion(ver) < LooseVersion('2.2.0'):
+ raise nose.SkipTest("openpyxl %s < 2.2" % str(ver))
cls.setUpClass = setUpClass
return cls
| also enhanced skip test msg a bit
| https://api.github.com/repos/pandas-dev/pandas/pulls/11168 | 2015-09-22T16:25:27Z | 2015-09-24T01:20:47Z | 2015-09-24T01:20:47Z | 2015-09-24T01:20:51Z |
DOC: Stating to install NumPY | diff --git a/doc/source/groupby.rst b/doc/source/groupby.rst
index b5a382ce24342..21c6063d0725b 100644
--- a/doc/source/groupby.rst
+++ b/doc/source/groupby.rst
@@ -379,6 +379,7 @@ Or for an object grouped on multiple columns:
Aggregation
-----------
+Note the Aggregation section requires the installation of NumPY.
Once the GroupBy object has been created, several methods are available to
perform a computation on the grouped data.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11165 | 2015-09-22T06:05:44Z | 2015-09-22T07:46:46Z | null | 2015-09-22T07:46:46Z | |
DOC: minor doc formatting fixes | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9d40cf3921b98..b513b767693bf 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -597,7 +597,7 @@ def iterrows(self):
Notes
-----
- 1. Because ``iterrows` returns a Series for each row,
+ 1. Because ``iterrows`` returns a Series for each row,
it does **not** preserve dtypes across the rows (dtypes are
preserved across columns for DataFrames). For example,
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 4afaae0fd25df..03b2ea5597ab6 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -333,7 +333,8 @@ def values(self):
[a, a, b, c]
Categories (3, object): [a, b, c]
- # this is converted to UTC
+ Timezone aware datetime data is converted to UTC:
+
>>> pd.Series(pd.date_range('20130101',periods=3,tz='US/Eastern')).values
array(['2013-01-01T00:00:00.000000000-0500',
'2013-01-02T00:00:00.000000000-0500',
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 3337a978961c4..cd2297d6018ca 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -3674,10 +3674,10 @@ def box(self, by=None, **kwds):
.. versionadded:: 0.17.0
Parameters
- ---------
+ ----------
by : string or sequence
Column in the DataFrame to group by.
- **kwds : optional
+ \*\*kwds : optional
Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`.
Returns
| Removes some warnings
| https://api.github.com/repos/pandas-dev/pandas/pulls/11161 | 2015-09-21T12:22:23Z | 2015-09-21T12:22:28Z | 2015-09-21T12:22:27Z | 2015-09-21T12:22:28Z |
PERF: Series.dropna with non-nan dtype blocks | diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py
index 37969a6949157..a40ed3f1d6482 100644
--- a/asv_bench/benchmarks/series_methods.py
+++ b/asv_bench/benchmarks/series_methods.py
@@ -71,3 +71,23 @@ def setup(self):
def time_series_nsmallest2(self):
self.s2.nsmallest(3, take_last=True)
self.s2.nsmallest(3, take_last=False)
+
+
+class series_dropna_int64(object):
+ goal_time = 0.2
+
+ def setup(self):
+ self.s = Series(np.random.randint(1, 10, 1000000))
+
+ def time_series_dropna_int64(self):
+ self.s.dropna()
+
+class series_dropna_datetime(object):
+ goal_time = 0.2
+
+ def setup(self):
+ self.s = Series(pd.date_range('2000-01-01', freq='S', periods=1000000))
+ self.s[np.random.randint(1, 1000000, 100)] = pd.NaT
+
+ def time_series_dropna_datetime(self):
+ self.s.dropna()
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 25b22230e5f3d..5b2b128186bf5 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -53,6 +53,7 @@ Performance Improvements
~~~~~~~~~~~~~~~~~~~~~~~~
- Checking monotonic-ness before sorting on an index (:issue:`11080`)
+- ``Series.dropna`` performance improvement when its dtype can't contain ``NaN`` (:issue:`11159`)
.. _whatsnew_0171.bug_fixes:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index f4e3374626011..2fc90ef8596f1 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2501,11 +2501,19 @@ def dropna(self, axis=0, inplace=False, **kwargs):
'argument "{0}"'.format(list(kwargs.keys())[0]))
axis = self._get_axis_number(axis or 0)
- result = remove_na(self)
- if inplace:
- self._update_inplace(result)
+
+ if self._can_hold_na:
+ result = remove_na(self)
+ if inplace:
+ self._update_inplace(result)
+ else:
+ return result
else:
- return result
+ if inplace:
+ # do nothing
+ pass
+ else:
+ return self.copy()
valid = lambda self, inplace=False, **kwargs: self.dropna(inplace=inplace,
**kwargs)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 9c86c3f894c67..f33adc1cd08b7 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -5117,7 +5117,6 @@ def test_dropna_empty(self):
# invalid axis
self.assertRaises(ValueError, s.dropna, axis=1)
-
def test_datetime64_tz_dropna(self):
# DatetimeBlock
s = Series([Timestamp('2011-01-01 10:00'), pd.NaT,
@@ -5140,6 +5139,18 @@ def test_datetime64_tz_dropna(self):
self.assertEqual(result.dtype, 'datetime64[ns, Asia/Tokyo]')
self.assert_series_equal(result, expected)
+ def test_dropna_no_nan(self):
+ for s in [Series([1, 2, 3], name='x'),
+ Series([False, True, False], name='x')]:
+
+ result = s.dropna()
+ self.assert_series_equal(result, s)
+ self.assertFalse(result is s)
+
+ s2 = s.copy()
+ s2.dropna(inplace=True)
+ self.assert_series_equal(s2, s)
+
def test_axis_alias(self):
s = Series([1, 2, np.nan])
assert_series_equal(s.dropna(axis='rows'), s.dropna(axis='index'))
| Minor improvement when `dropna` actually does nothing. If OK for 0.17, I'll add a release note.
```
import numpy as np
import pandas as pd
s = pd.Series(np.random.randint(0, 1000, 50000000))
# before
%timeit s.dropna()
#1 loops, best of 3: 1.58 s per loop
# after
%timeit s.dropna()
#1 loops, best of 3: 568 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11159 | 2015-09-21T00:17:25Z | 2015-10-18T13:46:13Z | 2015-10-18T13:46:13Z | 2015-11-07T03:42:03Z |
PERF: nested dict DataFrame construction | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index f8efa8ec23300..22ab5c0236dca 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1032,6 +1032,7 @@ Performance Improvements
- Improved performance of ``to_datetime`` when specified format string is ISO8601 (:issue:`10178`)
- 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`)
- Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`)
+- Regression from 0.16.1 in constructing ``DataFrame`` from nested dictionary (:issue:`11084`)
.. _whatsnew_0170.bug_fixes:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9d40cf3921b98..86c382efa8a64 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -52,6 +52,8 @@
from pandas.tseries.period import PeriodIndex
from pandas.tseries.index import DatetimeIndex
+from pandas.tseries.tdi import TimedeltaIndex
+
import pandas.core.algorithms as algos
import pandas.core.base as base
@@ -5400,8 +5402,13 @@ def _homogenize(data, index, dtype=None):
v = v.reindex(index, copy=False)
else:
if isinstance(v, dict):
- v = _dict_compat(v)
- oindex = index.astype('O')
+ if oindex is None:
+ oindex = index.astype('O')
+
+ if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
+ v = _dict_compat(v)
+ else:
+ v = dict(v)
v = lib.fast_multiget(v, oindex.values, default=NA)
v = _sanitize_array(v, index, dtype=dtype, copy=False,
raise_cast_failure=False)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 533f8df1d4599..c963222cf4ad9 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -34,7 +34,7 @@
from pandas import (DataFrame, Index, Series, Panel, notnull, isnull,
MultiIndex, DatetimeIndex, Timestamp, date_range,
read_csv, timedelta_range, Timedelta, CategoricalIndex,
- option_context)
+ option_context, period_range)
from pandas.core.dtypes import DatetimeTZDtype
import pandas as pd
from pandas.parser import CParserError
@@ -3061,6 +3061,27 @@ def create_data(constructor):
assert_frame_equal(result_timedelta, expected)
assert_frame_equal(result_Timedelta, expected)
+ def test_nested_dict_frame_constructor(self):
+ rng = period_range('1/1/2000', periods=5)
+ df = DataFrame(randn(10, 5), columns=rng)
+
+ data = {}
+ for col in df.columns:
+ for row in df.index:
+ data.setdefault(col, {})[row] = df.get_value(row, col)
+
+ result = DataFrame(data, columns=rng)
+ tm.assert_frame_equal(result, df)
+
+ data = {}
+ for col in df.columns:
+ for row in df.index:
+ data.setdefault(row, {})[col] = df.get_value(row, col)
+
+ result = DataFrame(data, index=rng).T
+ tm.assert_frame_equal(result, df)
+
+
def _check_basic_constructor(self, empty):
"mat: 2d matrix with shpae (3, 2) to input. empty - makes sized objects"
mat = empty((2, 3), dtype=float)
diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py
index 951bb803ef793..c6fb54ceec644 100644
--- a/pandas/tseries/tests/test_period.py
+++ b/pandas/tseries/tests/test_period.py
@@ -2075,26 +2075,6 @@ def test_period_set_index_reindex(self):
df = df.set_index(idx2)
self.assertTrue(df.index.equals(idx2))
- def test_nested_dict_frame_constructor(self):
- rng = period_range('1/1/2000', periods=5)
- df = DataFrame(randn(10, 5), columns=rng)
-
- data = {}
- for col in df.columns:
- for row in df.index:
- data.setdefault(col, {})[row] = df.get_value(row, col)
-
- result = DataFrame(data, columns=rng)
- tm.assert_frame_equal(result, df)
-
- data = {}
- for col in df.columns:
- for row in df.index:
- data.setdefault(row, {})[col] = df.get_value(row, col)
-
- result = DataFrame(data, index=rng).T
- tm.assert_frame_equal(result, df)
-
def test_frame_to_time_stamp(self):
K = 5
index = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
| Part of #11084
http://pydata.github.io/pandas/#frame_ctor.frame_ctor_nested_dict_int64.time_frame_ctor_nested_dict_int64
```
before after ratio
[d28fd70 ] [48c588 ]
- 325.06ms 72.25ms 0.22 frame_ctor.frame_ctor_nested_dict.time_frame_ctor_nested_dict
- 364.35ms 106.67ms 0.29 frame_ctor.frame_ctor_nested_dict_int64.time_frame_ctor_nested_dict_int64
```
Two changes to get back to the old performance:
- skip attempting to box `Timedeltas`/`Timestamps` if not a `DatetimeIndex`/`TimedeltaIndex`
- only convert index to object once
| https://api.github.com/repos/pandas-dev/pandas/pulls/11158 | 2015-09-21T00:13:11Z | 2015-09-21T14:17:23Z | 2015-09-21T14:17:23Z | 2015-09-24T02:16:41Z |
DEPR: deprecate SparsePanel | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index f8efa8ec23300..c2c7ca2410068 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -964,6 +964,7 @@ Deprecations
``DataFrame.add(other, fill_value=0)`` and ``DataFrame.mul(other, fill_value=1.)``
(:issue:`10735`).
- ``TimeSeries`` deprecated in favor of ``Series`` (note that this has been alias since 0.13.0), (:issue:`10890`)
+- ``SparsePanel`` deprecated and will be removed in a future version (:issue:``)
- ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`)
- Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`)
- ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 05a2ff6840d62..4afaae0fd25df 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2566,7 +2566,7 @@ def last_valid_index(self):
def asof(self, where):
"""
- Return last good (non-NaN) value in TimeSeries if value is NaN for
+ Return last good (non-NaN) value in Series if value is NaN for
requested date.
If there is no good value, NaN is returned.
@@ -2624,7 +2624,7 @@ def to_timestamp(self, freq=None, how='start', copy=True):
Returns
-------
- ts : TimeSeries with DatetimeIndex
+ ts : Series with DatetimeIndex
"""
new_values = self._values
if copy:
@@ -2636,7 +2636,7 @@ def to_timestamp(self, freq=None, how='start', copy=True):
def to_period(self, freq=None, copy=True):
"""
- Convert TimeSeries from DatetimeIndex to PeriodIndex with desired
+ Convert Series from DatetimeIndex to PeriodIndex with desired
frequency (inferred from index if not passed)
Parameters
@@ -2645,7 +2645,7 @@ def to_period(self, freq=None, copy=True):
Returns
-------
- ts : TimeSeries with PeriodIndex
+ ts : Series with PeriodIndex
"""
new_values = self._values
if copy:
diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py
index 34256acfb0e60..f57339fea0a7f 100644
--- a/pandas/sparse/panel.py
+++ b/pandas/sparse/panel.py
@@ -5,6 +5,7 @@
# pylint: disable=E1101,E1103,W0231
+import warnings
from pandas.compat import range, lrange, zip
from pandas import compat
import numpy as np
@@ -69,6 +70,10 @@ def __init__(self, frames=None, items=None, major_axis=None, minor_axis=None,
default_fill_value=np.nan, default_kind='block',
copy=False):
+ # deprecation #11157
+ warnings.warn("SparsePanel is deprecated and will be removed in a future version",
+ FutureWarning, stacklevel=2)
+
if frames is None:
frames = {}
diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py
index 3c42467c20838..a86942718091c 100644
--- a/pandas/sparse/tests/test_sparse.py
+++ b/pandas/sparse/tests/test_sparse.py
@@ -1793,6 +1793,11 @@ def test_constructor(self):
"input must be a dict, a 'list' was passed"):
SparsePanel(['a', 'b', 'c'])
+ # deprecation GH11157
+ def test_deprecation(self):
+ with tm.assert_produces_warning(FutureWarning):
+ SparsePanel()
+
# GH 9272
def test_constructor_empty(self):
sp = SparsePanel()
| does not fit the current implementation; in theory a `Panel` could actually do this, but very little support (or issues related).
| https://api.github.com/repos/pandas-dev/pandas/pulls/11157 | 2015-09-20T21:13:13Z | 2015-09-20T23:19:08Z | 2015-09-20T23:19:08Z | 2015-09-20T23:19:08Z |
BLD: use python-dateutil in conda recipe | diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml
index 95c4aa084230d..e3495bc5bd04a 100644
--- a/conda.recipe/meta.yaml
+++ b/conda.recipe/meta.yaml
@@ -16,12 +16,12 @@ requirements:
- libpython # [py2k and win]
- setuptools
- pytz
- - dateutil
+ - python-dateutil
run:
- python
- numpy
- - dateutil
+ - python-dateutil
- pytz
test:
| https://api.github.com/repos/pandas-dev/pandas/pulls/11156 | 2015-09-20T21:12:11Z | 2015-09-20T23:18:11Z | 2015-09-20T23:18:11Z | 2015-09-20T23:18:11Z | |
BUG/API: GH11086 where freq is not inferred if both freq is None | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 2be7194af34b0..96a95bc03711d 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -916,7 +916,7 @@ Other API Changes
- When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column
was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`)
- some numeric reduction operators would return ``ValueError``, rather than ``TypeError`` on object types that includes strings and numbers (:issue:`11131`)
-
+- ``DatetimeIndex.union`` does not infer ``freq`` if ``self`` and the input have ``None`` as ``freq`` (:issue:`11086`)
- ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`)
=============================== ===============================================================
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 5fdc0ce86a0b4..ac2358cb3d231 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -51,7 +51,7 @@
_default_encoding = 'UTF-8'
def _ensure_decoded(s):
- """ if we have bytes, decode them to unicde """
+ """ if we have bytes, decode them to unicode """
if isinstance(s, np.bytes_):
s = s.decode('UTF-8')
return s
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index c2dc625bd6ece..8f6b924ebd850 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -895,7 +895,8 @@ def union(self, other):
result = Index.union(this, other)
if isinstance(result, DatetimeIndex):
result.tz = this.tz
- if result.freq is None:
+ if (result.freq is None and
+ (this.freq is not None or other.freq is not None)):
result.offset = to_offset(result.inferred_freq)
return result
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index a02edf32cfcb0..0883eb72a73fe 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -2551,6 +2551,15 @@ def test_intersection_bug_1708(self):
result = index_1 & index_2
self.assertEqual(len(result), 0)
+ def test_union_freq_both_none(self):
+ #GH11086
+ expected = bdate_range('20150101', periods=10)
+ expected.freq = None
+
+ result = expected.union(expected)
+ tm.assert_index_equal(result, expected)
+ self.assertIsNone(result.freq)
+
# GH 10699
def test_datetime64_with_DateOffset(self):
for klass, assert_func in zip([Series, DatetimeIndex],
| closes #11086, and a typo
| https://api.github.com/repos/pandas-dev/pandas/pulls/11155 | 2015-09-20T16:39:58Z | 2015-09-21T02:35:53Z | 2015-09-21T02:35:53Z | 2015-09-21T02:35:57Z |
ENH: add merge indicator to DataFrame.merge | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 50fecf9b2886c..9d40cf3921b98 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4265,12 +4265,12 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
@Appender(_merge_doc, indents=2)
def merge(self, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=False,
- suffixes=('_x', '_y'), copy=True):
+ suffixes=('_x', '_y'), copy=True, indicator=False):
from pandas.tools.merge import merge
return merge(self, right, how=how, on=on,
left_on=left_on, right_on=right_on,
left_index=left_index, right_index=right_index, sort=sort,
- suffixes=suffixes, copy=copy)
+ suffixes=suffixes, copy=copy, indicator=indicator)
def round(self, decimals=0, out=None):
"""
diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py
index 24b5feb21f5ac..929a72cfd4adc 100644
--- a/pandas/tools/tests/test_merge.py
+++ b/pandas/tools/tests/test_merge.py
@@ -951,25 +951,27 @@ def test_indicator(self):
df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b'], 'col_conflict':[1,2]})
df1_copy = df1.copy()
- df2 = pd.DataFrame({'col1':[1,2,3,4,5],'col_right':[2,2,2,2,2],
+ df2 = pd.DataFrame({'col1':[1,2,3,4,5],'col_right':[2,2,2,2,2],
'col_conflict':[1,2,3,4,5]})
df2_copy = df2.copy()
-
- df_result = pd.DataFrame({'col1':[0,1,2,3,4,5],
+
+ df_result = pd.DataFrame({'col1':[0,1,2,3,4,5],
'col_conflict_x':[1,2,np.nan,np.nan,np.nan,np.nan],
- 'col_left':['a','b', np.nan,np.nan,np.nan,np.nan],
- 'col_conflict_y':[np.nan,1,2,3,4,5],
+ 'col_left':['a','b', np.nan,np.nan,np.nan,np.nan],
+ 'col_conflict_y':[np.nan,1,2,3,4,5],
'col_right':[np.nan, 2,2,2,2,2]},
dtype='float64')
df_result['_merge'] = pd.Categorical(['left_only','both','right_only',
'right_only','right_only','right_only']
, categories=['left_only', 'right_only', 'both'])
- df_result = df_result[['col1', 'col_conflict_x', 'col_left',
+ df_result = df_result[['col1', 'col_conflict_x', 'col_left',
'col_conflict_y', 'col_right', '_merge' ]]
test = pd.merge(df1, df2, on='col1', how='outer', indicator=True)
assert_frame_equal(test, df_result)
+ test = df1.merge(df2, on='col1', how='outer', indicator=True)
+ assert_frame_equal(test, df_result)
# No side effects
assert_frame_equal(df1, df1_copy)
@@ -981,49 +983,65 @@ def test_indicator(self):
test_custom_name = pd.merge(df1, df2, on='col1', how='outer', indicator='custom_name')
assert_frame_equal(test_custom_name, df_result_custom_name)
+ test_custom_name = df1.merge(df2, on='col1', how='outer', indicator='custom_name')
+ assert_frame_equal(test_custom_name, df_result_custom_name)
# Check only accepts strings and booleans
with tm.assertRaises(ValueError):
pd.merge(df1, df2, on='col1', how='outer', indicator=5)
+ with tm.assertRaises(ValueError):
+ df1.merge(df2, on='col1', how='outer', indicator=5)
# Check result integrity
-
+
test2 = pd.merge(df1, df2, on='col1', how='left', indicator=True)
self.assertTrue((test2._merge != 'right_only').all())
+ test2 = df1.merge(df2, on='col1', how='left', indicator=True)
+ self.assertTrue((test2._merge != 'right_only').all())
test3 = pd.merge(df1, df2, on='col1', how='right', indicator=True)
self.assertTrue((test3._merge != 'left_only').all())
+ test3 = df1.merge(df2, on='col1', how='right', indicator=True)
+ self.assertTrue((test3._merge != 'left_only').all())
test4 = pd.merge(df1, df2, on='col1', how='inner', indicator=True)
self.assertTrue((test4._merge == 'both').all())
+ test4 = df1.merge(df2, on='col1', how='inner', indicator=True)
+ self.assertTrue((test4._merge == 'both').all())
# Check if working name in df
for i in ['_right_indicator', '_left_indicator', '_merge']:
df_badcolumn = pd.DataFrame({'col1':[1,2], i:[2,2]})
-
+
with tm.assertRaises(ValueError):
pd.merge(df1, df_badcolumn, on='col1', how='outer', indicator=True)
+ with tm.assertRaises(ValueError):
+ df1.merge(df_badcolumn, on='col1', how='outer', indicator=True)
# Check for name conflict with custom name
df_badcolumn = pd.DataFrame({'col1':[1,2], 'custom_column_name':[2,2]})
-
+
with tm.assertRaises(ValueError):
pd.merge(df1, df_badcolumn, on='col1', how='outer', indicator='custom_column_name')
+ with tm.assertRaises(ValueError):
+ df1.merge(df_badcolumn, on='col1', how='outer', indicator='custom_column_name')
# Merge on multiple columns
df3 = pd.DataFrame({'col1':[0,1], 'col2':['a','b']})
df4 = pd.DataFrame({'col1':[1,1,3], 'col2':['b','x','y']})
- hand_coded_result = pd.DataFrame({'col1':[0,1,1,3.0],
+ hand_coded_result = pd.DataFrame({'col1':[0,1,1,3.0],
'col2':['a','b','x','y']})
hand_coded_result['_merge'] = pd.Categorical(
['left_only','both','right_only','right_only']
, categories=['left_only', 'right_only', 'both'])
-
+
test5 = pd.merge(df3, df4, on=['col1', 'col2'], how='outer', indicator=True)
assert_frame_equal(test5, hand_coded_result)
-
+ test5 = df3.merge(df4, on=['col1', 'col2'], how='outer', indicator=True)
+ assert_frame_equal(test5, hand_coded_result)
+
def _check_merge(x, y):
for how in ['inner', 'left', 'outer']:
| Follow-up to https://github.com/pydata/pandas/pull/10054
xref #8790
Adds new `indicator` keyword to `DataFrame.merge` as well
| https://api.github.com/repos/pandas-dev/pandas/pulls/11154 | 2015-09-20T13:38:25Z | 2015-09-20T19:07:28Z | 2015-09-20T19:07:28Z | 2015-09-20T19:10:54Z |
(WIP) BUG: DatetimeTZBlock.fillna raises TypeError | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 2be7194af34b0..27c8a66575747 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1157,3 +1157,4 @@ Bug Fixes
- Bug in ``Index`` dtype may not applied properly (:issue:`11017`)
- Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`)
- Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`)
+- Bug in ``.fillna`` against may raise ``TypeError`` when data contains datetime dtype (:issue:`7095`, :issue:`11153`)
diff --git a/pandas/core/dtypes.py b/pandas/core/dtypes.py
index 68d72fdd80554..ce345738d9efc 100644
--- a/pandas/core/dtypes.py
+++ b/pandas/core/dtypes.py
@@ -181,7 +181,7 @@ def construct_from_string(cls, string):
def __unicode__(self):
# format the tz
- return "datetime64[{unit}, {tz}]".format(unit=self.unit,tz=self.tz)
+ return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz)
@property
def name(self):
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 94eccad8e0185..97b54d4ef6ebe 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1947,20 +1947,42 @@ def _try_fill(self, value):
def fillna(self, value, limit=None,
inplace=False, downcast=None):
- # straight putmask here
- values = self.values if inplace else self.values.copy()
mask = isnull(self.values)
value = self._try_fill(value)
+
if limit is not None:
if self.ndim > 2:
raise NotImplementedError("number of dimensions for 'fillna' "
"is currently limited to 2")
mask[mask.cumsum(self.ndim-1)>limit]=False
- np.putmask(values, mask, value)
- return [self if inplace else
- self.make_block(values,
- fastpath=True)]
+ if mask.any():
+ try:
+ return self._fillna_mask(mask, value, inplace=inplace)
+ except TypeError:
+ pass
+ # _fillna_mask raises TypeError when it fails
+ # cannot perform inplace op because of object coercion
+ values = self.get_values(dtype=object)
+ np.putmask(values, mask, value)
+ return [self.make_block(values, fastpath=True)]
+ else:
+ return [self if inplace else self.copy()]
+
+ def _fillna_mask(self, mask, value, inplace=False):
+ if getattr(value, 'tzinfo', None) is None:
+ # Series comes to this path
+ values = self.values
+ if not inplace:
+ values = values.copy()
+ try:
+ np.putmask(values, mask, value)
+ return [self if inplace else
+ self.make_block(values, fastpath=True)]
+ except (ValueError, TypeError):
+ # scalar causes ValueError, and array causes TypeError
+ pass
+ raise TypeError
def to_native_types(self, slicer=None, na_rep=None, date_format=None,
quoting=None, **kwargs):
@@ -2033,6 +2055,29 @@ def get_values(self, dtype=None):
.reshape(self.values.shape)
return self.values
+ def _fillna_mask(self, mask, value, inplace=False):
+ # cannot perform inplace op for internal DatetimeIndex
+ my_tz = tslib.get_timezone(self.values.tz)
+ value_tz = tslib.get_timezone(getattr(value, 'tzinfo', None))
+
+ if (my_tz == value_tz or self.dtype == getattr(value, 'dtype', None)):
+ if my_tz == value_tz:
+ # hack for PY2.6 / numpy 1.7.1.
+ # Other versions can directly use self.values.putmask
+ # --------------------------------------
+ try:
+ value = value.asm8
+ except AttributeError:
+ value = tslib.Timestamp(value).asm8
+ ### ------------------------------------
+
+ try:
+ values = self.values.putmask(mask, value)
+ return [self.make_block(values, fastpath=True)]
+ except ValueError:
+ pass
+ raise TypeError
+
def _slice(self, slicer):
""" return a slice of my values """
if isinstance(slicer, tuple):
diff --git a/pandas/tests/test_dtypes.py b/pandas/tests/test_dtypes.py
index 54a49de582e56..e6df9c894c219 100644
--- a/pandas/tests/test_dtypes.py
+++ b/pandas/tests/test_dtypes.py
@@ -137,6 +137,20 @@ def test_basic(self):
self.assertFalse(is_datetimetz(np.dtype('float64')))
self.assertFalse(is_datetimetz(1.0))
+ def test_dst(self):
+
+ dr1 = date_range('2013-01-01', periods=3, tz='US/Eastern')
+ s1 = Series(dr1, name='A')
+ self.assertTrue(is_datetimetz(s1))
+
+ dr2 = date_range('2013-08-01', periods=3, tz='US/Eastern')
+ s2 = Series(dr2, name='A')
+ self.assertTrue(is_datetimetz(s2))
+ self.assertEqual(s1.dtype, s2.dtype)
+
+
+
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index c1185f9455284..533f8df1d4599 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -8740,6 +8740,34 @@ def test_fillna_dtype_conversion(self):
result = df.fillna(v)
assert_frame_equal(result, expected)
+ def test_fillna_datetime_columns(self):
+ # GH 7095
+ df = pd.DataFrame({'A': [-1, -2, np.nan],
+ 'B': date_range('20130101', periods=3),
+ 'C': ['foo', 'bar', None],
+ 'D': ['foo2', 'bar2', None]},
+ index=date_range('20130110', periods=3))
+ result = df.fillna('?')
+ expected = pd.DataFrame({'A': [-1, -2, '?'],
+ 'B': date_range('20130101', periods=3),
+ 'C': ['foo', 'bar', '?'],
+ 'D': ['foo2', 'bar2', '?']},
+ index=date_range('20130110', periods=3))
+ self.assert_frame_equal(result, expected)
+
+ df = pd.DataFrame({'A': [-1, -2, np.nan],
+ 'B': [pd.Timestamp('2013-01-01'), pd.Timestamp('2013-01-02'), pd.NaT],
+ 'C': ['foo', 'bar', None],
+ 'D': ['foo2', 'bar2', None]},
+ index=date_range('20130110', periods=3))
+ result = df.fillna('?')
+ expected = pd.DataFrame({'A': [-1, -2, '?'],
+ 'B': [pd.Timestamp('2013-01-01'), pd.Timestamp('2013-01-02'), '?'],
+ 'C': ['foo', 'bar', '?'],
+ 'D': ['foo2', 'bar2', '?']},
+ index=date_range('20130110', periods=3))
+ self.assert_frame_equal(result, expected)
+
def test_ffill(self):
self.tsframe['A'][:5] = nan
self.tsframe['A'][-5:] = nan
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 2060b31511ead..a6d7e63656d68 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -3937,6 +3937,89 @@ def test_datetime64_fillna(self):
result = s.fillna(method='backfill')
assert_series_equal(result, expected)
+ def test_datetime64_tz_fillna(self):
+ for tz in ['US/Eastern', 'Asia/Tokyo']:
+ # DatetimeBlock
+ s = Series([Timestamp('2011-01-01 10:00'), pd.NaT,
+ Timestamp('2011-01-03 10:00'), pd.NaT])
+ result = s.fillna(pd.Timestamp('2011-01-02 10:00'))
+ expected = Series([Timestamp('2011-01-01 10:00'), Timestamp('2011-01-02 10:00'),
+ Timestamp('2011-01-03 10:00'), Timestamp('2011-01-02 10:00')])
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna(pd.Timestamp('2011-01-02 10:00', tz=tz))
+ expected = Series([Timestamp('2011-01-01 10:00'),
+ Timestamp('2011-01-02 10:00', tz=tz),
+ Timestamp('2011-01-03 10:00'),
+ Timestamp('2011-01-02 10:00', tz=tz)])
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna('AAA')
+ expected = Series([Timestamp('2011-01-01 10:00'), 'AAA',
+ Timestamp('2011-01-03 10:00'), 'AAA'], dtype=object)
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna({1: pd.Timestamp('2011-01-02 10:00', tz=tz),
+ 3: pd.Timestamp('2011-01-04 10:00')})
+ expected = Series([Timestamp('2011-01-01 10:00'),
+ Timestamp('2011-01-02 10:00', tz=tz),
+ Timestamp('2011-01-03 10:00'),
+ Timestamp('2011-01-04 10:00')])
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna({1: pd.Timestamp('2011-01-02 10:00'),
+ 3: pd.Timestamp('2011-01-04 10:00')})
+ expected = Series([Timestamp('2011-01-01 10:00'), Timestamp('2011-01-02 10:00'),
+ Timestamp('2011-01-03 10:00'), Timestamp('2011-01-04 10:00')])
+ self.assert_series_equal(expected, result)
+
+ # DatetimeBlockTZ
+ idx = pd.DatetimeIndex(['2011-01-01 10:00', pd.NaT,
+ '2011-01-03 10:00', pd.NaT], tz=tz)
+ s = pd.Series(idx)
+ result = s.fillna(pd.Timestamp('2011-01-02 10:00'))
+ expected = Series([Timestamp('2011-01-01 10:00', tz=tz),
+ Timestamp('2011-01-02 10:00'),
+ Timestamp('2011-01-03 10:00', tz=tz),
+ Timestamp('2011-01-02 10:00')])
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna(pd.Timestamp('2011-01-02 10:00', tz=tz))
+ idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-02 10:00',
+ '2011-01-03 10:00', '2011-01-02 10:00'],
+ tz=tz)
+ expected = Series(idx)
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna(pd.Timestamp('2011-01-02 10:00', tz=tz).to_pydatetime())
+ idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-02 10:00',
+ '2011-01-03 10:00', '2011-01-02 10:00'],
+ tz=tz)
+ expected = Series(idx)
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna('AAA')
+ expected = Series([Timestamp('2011-01-01 10:00', tz=tz), 'AAA',
+ Timestamp('2011-01-03 10:00', tz=tz), 'AAA'],
+ dtype=object)
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna({1: pd.Timestamp('2011-01-02 10:00', tz=tz),
+ 3: pd.Timestamp('2011-01-04 10:00')})
+ expected = Series([Timestamp('2011-01-01 10:00', tz=tz),
+ Timestamp('2011-01-02 10:00', tz=tz),
+ Timestamp('2011-01-03 10:00', tz=tz),
+ Timestamp('2011-01-04 10:00')])
+ self.assert_series_equal(expected, result)
+
+ result = s.fillna({1: pd.Timestamp('2011-01-02 10:00', tz=tz),
+ 3: pd.Timestamp('2011-01-04 10:00', tz=tz)})
+ expected = Series([Timestamp('2011-01-01 10:00', tz=tz),
+ Timestamp('2011-01-02 10:00', tz=tz),
+ Timestamp('2011-01-03 10:00', tz=tz),
+ Timestamp('2011-01-04 10:00', tz=tz)])
+ self.assert_series_equal(expected, result)
+
def test_fillna_int(self):
s = Series(np.random.randint(-100, 100, 50))
s.fillna(method='ffill', inplace=True)
@@ -5022,6 +5105,29 @@ def test_dropna_empty(self):
# invalid axis
self.assertRaises(ValueError, s.dropna, axis=1)
+
+ def test_datetime64_tz_dropna(self):
+ # DatetimeBlock
+ s = Series([Timestamp('2011-01-01 10:00'), pd.NaT,
+ Timestamp('2011-01-03 10:00'), pd.NaT])
+ result = s.dropna()
+ expected = Series([Timestamp('2011-01-01 10:00'),
+ Timestamp('2011-01-03 10:00')], index=[0, 2])
+ self.assert_series_equal(result, expected)
+
+ # DatetimeBlockTZ
+ idx = pd.DatetimeIndex(['2011-01-01 10:00', pd.NaT,
+ '2011-01-03 10:00', pd.NaT],
+ tz='Asia/Tokyo')
+ s = pd.Series(idx)
+ self.assertEqual(s.dtype, 'datetime64[ns, Asia/Tokyo]')
+ result = s.dropna()
+ expected = Series([Timestamp('2011-01-01 10:00', tz='Asia/Tokyo'),
+ Timestamp('2011-01-03 10:00', tz='Asia/Tokyo')],
+ index=[0, 2])
+ self.assertEqual(result.dtype, 'datetime64[ns, Asia/Tokyo]')
+ self.assert_series_equal(result, expected)
+
def test_axis_alias(self):
s = Series([1, 2, np.nan])
assert_series_equal(s.dropna(axis='rows'), s.dropna(axis='index'))
| ```
import pandas as pd
idx = pd.DatetimeIndex(['2011-01-01', pd.NaT, '2011-01-03'], tz='Asia/Tokyo')
s = pd.Series(idx)
s
#0 2011-01-01 00:00:00+09:00
#1 NaT
#2 2011-01-03 00:00:00+09:00
# dtype: datetime64[ns, Asia/Tokyo]
# NG, the result must be DatetimeTZBlock
s.fillna(pd.Timestamp('2011-01-02', tz='Asia/Tokyo'))
# TypeError: putmask() argument 1 must be numpy.ndarray, not DatetimeIndex
# NG, it should be object dtype, as the same as when Series creation with mixed tz
s.fillna(pd.Timestamp('2011-01-02'))
# TypeError: putmask() argument 1 must be numpy.ndarray, not DatetimeIndex
```
Also, found existing `DatetimeBlock` doesn't handle tz properly. Closes #7095.
```
idx = pd.DatetimeIndex(['2011-01-01', pd.NaT, '2011-01-03'])
s = pd.Series(idx)
# OK, result must be DatetimeBlock
s.fillna(pd.Timestamp('2011-01-02'))
#0 2011-01-01
#1 2011-01-02
#2 2011-01-03
# dtype: datetime64[ns]
# NG, it should be object dtype, as the same as when Series creation with mixed tz
s.fillna(pd.Timestamp('2011-01-02', tz='Asia/Tokyo'))
#0 2011-01-01 00:00:00
#1 2011-01-01 15:00:00
#2 2011-01-03 00:00:00
# dtype: datetime64[ns]
# NG, unable to fill different dtypes
s.fillna('AAA')
# ValueError: Error parsing datetime string "AAA" at position 0
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11153 | 2015-09-19T23:01:47Z | 2015-09-20T18:52:13Z | 2015-09-20T18:52:13Z | 2015-09-26T00:27:01Z |
PERF: improves performance in groupby.size | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 8e44480c0c09b..20c1140bbd80e 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1378,12 +1378,9 @@ def size(self):
Compute group sizes
"""
- # TODO: better impl
- labels, _, ngroups = self.group_info
- bin_counts = algos.value_counts(labels, sort=False)
- bin_counts = bin_counts.reindex(np.arange(ngroups))
- bin_counts.index = self.result_index
- return bin_counts
+ ids, _, ngroup = self.group_info
+ out = np.bincount(ids[ids != -1], minlength=ngroup)
+ return Series(out, index=self.result_index)
@cache_readonly
def _max_groupsize(self):
@@ -1845,24 +1842,6 @@ def groupings(self):
# for compat
return None
- def size(self):
- """
- Compute group sizes
-
- """
- index = self.result_index
- base = Series(np.zeros(len(index), dtype=np.int64), index=index)
- indices = self.indices
- for k, v in compat.iteritems(indices):
- indices[k] = len(v)
- bin_counts = Series(indices, dtype=np.int64)
- # make bin_counts.index to have same name to preserve it
- bin_counts.index.name = index.name
- result = base.add(bin_counts, fill_value=0)
- # addition with fill_value changes dtype to float64
- result = result.astype(np.int64)
- return result
-
#----------------------------------------------------------------------
# cython aggregation
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 0336ee2e9b50e..42d5af587a859 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2485,6 +2485,12 @@ def test_size(self):
for key, group in grouped:
self.assertEqual(result[key], len(group))
+ df = DataFrame(np.random.choice(20, (1000, 3)), columns=list('abc'))
+ for sort, key in cart_product((False, True), ('a', 'b', ['a', 'b'])):
+ left = df.groupby(key, sort=sort).size()
+ right = df.groupby(key, sort=sort)['c'].apply(lambda a: a.shape[0])
+ assert_series_equal(left, right, check_names=False)
+
def test_count(self):
from string import ascii_lowercase
n = 1 << 15
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py
index ec03d558e45b8..7052348e2e6a4 100644
--- a/pandas/tseries/tests/test_resample.py
+++ b/pandas/tseries/tests/test_resample.py
@@ -941,6 +941,20 @@ def test_resample_group_info(self): # GH10914
assert_series_equal(left, right)
+ def test_resample_size(self):
+ n = 10000
+ dr = date_range('2015-09-19', periods=n, freq='T')
+ ts = Series(np.random.randn(n), index=np.random.choice(dr, n))
+
+ left = ts.resample('7T', how='size')
+ ix = date_range(start=left.index.min(), end=ts.index.max(), freq='7T')
+
+ bins = np.searchsorted(ix.values, ts.index.values, side='right')
+ val = np.bincount(bins, minlength=len(ix) + 1)[1:]
+
+ right = Series(val, index=ix)
+ assert_series_equal(left, right)
+
def test_resmaple_dst_anchor(self):
# 5172
dti = DatetimeIndex([datetime(2012, 11, 4, 23)], tz='US/Eastern')
| on master:
``` python
In [1]: n = 100000
In [2]: np.random.seed(2718281)
In [3]: dr = date_range('2015-09-19', periods=n, freq='T')
In [4]: ts = Series(np.random.choice(n, n), index=np.random.choice(dr, n))
In [5]: %timeit ts.resample('5T', how='size')
1 loops, best of 3: 538 ms per loop
```
on branch:
``` python
In [5]: %timeit ts.resample('5T', how='size')
10 loops, best of 3: 27.6 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11152 | 2015-09-19T22:57:21Z | 2015-09-20T18:54:14Z | 2015-09-20T18:54:14Z | 2015-09-20T19:03:47Z |
BUG: axis kw not propogating on pct_change | diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index cd3c3848523f0..c2f639e0099a8 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -91,6 +91,7 @@ Bug Fixes
- Bug in ``squeeze()`` with zero length arrays (:issue:`11230`, :issue:`8999`)
+- Bug in ``DataFrame.pct_change()`` was not propagating ``axis`` keyword on ``.fillna`` method (:issue:`11150`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c18f4ec0a1f47..7abe8f1f35a24 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4565,7 +4565,7 @@ def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None,
if fill_method is None:
data = self
else:
- data = self.fillna(method=fill_method, limit=limit)
+ data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = (data.div(data.shift(periods=periods, freq=freq,
axis=axis, **kwargs)) - 1)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index dfbd21997568d..936df339479fc 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -11303,6 +11303,22 @@ def test_pct_change(self):
filled = self.tsframe.fillna(method='pad')
assert_frame_equal(rs, filled / filled.shift(freq='5D') - 1)
+ # GH 11150
+ def test_pct_change_frame(self):
+ pnl = DataFrame([np.arange(0, 40, 10), np.arange(0, 40, 10), np.arange(0, 40, 10)]).astype(np.float64)
+ pnl.iat[1,0] = np.nan
+ pnl.iat[1,1] = np.nan
+ pnl.iat[2,3] = 60
+
+ mask = pnl.isnull()
+
+ for axis in range(2):
+ expected = pnl.ffill(axis=axis)/pnl.ffill(axis=axis).shift(axis=axis) - 1
+ expected[mask] = np.nan
+ result = pnl.pct_change(axis=axis, fill_method='pad')
+
+ self.assert_frame_equal(result, expected)
+
def test_pct_change_shift_over_nas(self):
s = Series([1., 1.5, np.nan, 2.5, 3.])
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index d29673e96ecdd..706d5f70e7437 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -1858,6 +1858,7 @@ def test_pipe_panel(self):
with tm.assertRaises(ValueError):
result = wp.pipe((f, 'y'), x=1, y=1)
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| axis option was not correctly set on fillna in pct_change
| https://api.github.com/repos/pandas-dev/pandas/pulls/11150 | 2015-09-19T19:31:05Z | 2015-11-13T16:41:57Z | null | 2015-11-13T16:41:57Z |
API: multi-line, not inplace eval | diff --git a/doc/source/enhancingperf.rst b/doc/source/enhancingperf.rst
index 946256d585c49..9503675af8681 100644
--- a/doc/source/enhancingperf.rst
+++ b/doc/source/enhancingperf.rst
@@ -570,18 +570,51 @@ prefix the name of the :class:`~pandas.DataFrame` to the column(s) you're
interested in evaluating.
In addition, you can perform assignment of columns within an expression.
-This allows for *formulaic evaluation*. Only a single assignment is permitted.
-The assignment target can be a new column name or an existing column name, and
-it must be a valid Python identifier.
+This allows for *formulaic evaluation*. The assignment target can be a
+new column name or an existing column name, and it must be a valid Python
+identifier.
+
+.. versionadded:: 0.18.0
+
+The ``inplace`` keyword determines whether this assignment will performed
+on the original ``DataFrame`` or return a copy with the new column.
+
+.. warning::
+
+ For backwards compatability, ``inplace`` defaults to ``True`` if not
+ specified. This will change in a future version of pandas - if your
+ code depends on an inplace assignment you should update to explicitly
+ set ``inplace=True``
.. ipython:: python
df = pd.DataFrame(dict(a=range(5), b=range(5, 10)))
- df.eval('c = a + b')
- df.eval('d = a + b + c')
- df.eval('a = 1')
+ df.eval('c = a + b', inplace=True)
+ df.eval('d = a + b + c', inplace=True)
+ df.eval('a = 1', inplace=True)
df
+When ``inplace`` is set to ``False``, a copy of the ``DataFrame`` with the
+new or modified columns is returned and the original frame is unchanged.
+
+.. ipython:: python
+
+ df
+ df.eval('e = a - c', inplace=False)
+ df
+
+.. versionadded:: 0.18.0
+
+As a convenience, multiple assignments can be performed by using a
+multi-line string.
+
+.. ipython:: python
+
+ df.eval("""
+ c = a + b
+ d = a + b + c
+ a = 1""", inplace=False)
+
The equivalent in standard Python would be
.. ipython:: python
@@ -592,6 +625,23 @@ The equivalent in standard Python would be
df['a'] = 1
df
+.. versionadded:: 0.18.0
+
+The ``query`` method gained the ``inplace`` keyword which determines
+whether the query modifies the original frame.
+
+.. ipython:: python
+
+ df = pd.DataFrame(dict(a=range(5), b=range(5, 10)))
+ df.query('a > 2')
+ df.query('a > 2', inplace=True)
+ df
+
+.. warning::
+
+ Unlike with ``eval``, the default value for ``inplace`` for ``query``
+ is ``False``. This is consistent with prior versions of pandas.
+
Local Variables
~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v0.18.0.txt b/doc/source/whatsnew/v0.18.0.txt
index 94c2dddbe1ef0..5c21e04251f44 100644
--- a/doc/source/whatsnew/v0.18.0.txt
+++ b/doc/source/whatsnew/v0.18.0.txt
@@ -295,15 +295,60 @@ Other API Changes
- ``.memory_usage`` now includes values in the index, as does memory_usage in ``.info`` (:issue:`11597`)
+Changes to eval
+^^^^^^^^^^^^^^^
+In prior versions, new columns assignments in an ``eval`` expression resulted
+in an inplace change to the ``DataFrame``. (:issue:`9297`)
+.. ipython:: python
+ df = pd.DataFrame({'a': np.linspace(0, 10, 5), 'b': range(5)})
+ df.eval('c = a + b')
+ df
+In version 0.18.0, a new ``inplace`` keyword was added to choose whether the
+assignment should be done inplace or return a copy.
+.. ipython:: python
+ df
+ df.eval('d = c - b', inplace=False)
+ df
+ df.eval('d = c - b', inplace=True)
+ df
+.. warning::
+
+ For backwards compatability, ``inplace`` defaults to ``True`` if not specified.
+ This will change in a future version of pandas - if your code depends on an
+ inplace assignment you should update to explicitly set ``inplace=True``
+The ``inplace`` keyword parameter was also added the ``query`` method.
+.. ipython:: python
+
+ df.query('a > 5')
+ df.query('a > 5', inplace=True)
+ df
+
+.. warning::
+
+ Note that the default value for ``inplace`` in a ``query``
+ is ``False``, which is consistent with prior verions.
+
+``eval`` has also been updated to allow multi-line expressions for multiple
+assignments. These expressions will be evaluated one at a time in order. Only
+assginments are valid for multi-line expressions.
+
+.. ipython:: python
+
+ df
+ df.eval("""
+ e = d + a
+ f = e - 22
+ g = f / 2.0""", inplace=True)
+ df
.. _whatsnew_0180.deprecations:
@@ -410,7 +455,7 @@ Bug Fixes
- Bug in ``pd.read_clipboard`` and ``pd.to_clipboard`` functions not supporting Unicode; upgrade included ``pyperclip`` to v1.5.15 (:issue:`9263`)
-
+- Bug in ``DataFrame.query`` containing an assignment (:issue:`8664`)
diff --git a/pandas/computation/eval.py b/pandas/computation/eval.py
index e3096a85ca7d7..d2d16acc27fb6 100644
--- a/pandas/computation/eval.py
+++ b/pandas/computation/eval.py
@@ -3,11 +3,12 @@
"""Top level ``eval`` module.
"""
+import warnings
import tokenize
from pandas.core import common as com
from pandas.computation.expr import Expr, _parsers, tokenize_string
from pandas.computation.scope import _ensure_scope
-from pandas.compat import DeepChainMap, builtins
+from pandas.compat import string_types
from pandas.computation.engines import _engines
from distutils.version import LooseVersion
@@ -138,7 +139,7 @@ def _check_for_locals(expr, stack_level, parser):
def eval(expr, parser='pandas', engine='numexpr', truediv=True,
local_dict=None, global_dict=None, resolvers=(), level=0,
- target=None):
+ target=None, inplace=None):
"""Evaluate a Python expression as a string using various backends.
The following arithmetic operations are supported: ``+``, ``-``, ``*``,
@@ -196,6 +197,13 @@ def eval(expr, parser='pandas', engine='numexpr', truediv=True,
scope. Most users will **not** need to change this parameter.
target : a target object for assignment, optional, default is None
essentially this is a passed in resolver
+ inplace : bool, default True
+ If expression mutates, whether to modify object inplace or return
+ copy with mutation.
+
+ WARNING: inplace=None currently falls back to to True, but
+ in a future version, will default to False. Use inplace=True
+ explicitly rather than relying on the default.
Returns
-------
@@ -214,29 +222,78 @@ def eval(expr, parser='pandas', engine='numexpr', truediv=True,
pandas.DataFrame.query
pandas.DataFrame.eval
"""
- expr = _convert_expression(expr)
- _check_engine(engine)
- _check_parser(parser)
- _check_resolvers(resolvers)
- _check_for_locals(expr, level, parser)
-
- # get our (possibly passed-in) scope
- level += 1
- env = _ensure_scope(level, global_dict=global_dict,
- local_dict=local_dict, resolvers=resolvers,
- target=target)
-
- parsed_expr = Expr(expr, engine=engine, parser=parser, env=env,
- truediv=truediv)
-
- # construct the engine and evaluate the parsed expression
- eng = _engines[engine]
- eng_inst = eng(parsed_expr)
- ret = eng_inst.evaluate()
-
- # assign if needed
- if env.target is not None and parsed_expr.assigner is not None:
- env.target[parsed_expr.assigner] = ret
- return None
+ first_expr = True
+ if isinstance(expr, string_types):
+ exprs = [e for e in expr.splitlines() if e != '']
+ else:
+ exprs = [expr]
+ multi_line = len(exprs) > 1
+
+ if multi_line and target is None:
+ raise ValueError("multi-line expressions are only valid in the "
+ "context of data, use DataFrame.eval")
+
+ first_expr = True
+ for expr in exprs:
+ expr = _convert_expression(expr)
+ _check_engine(engine)
+ _check_parser(parser)
+ _check_resolvers(resolvers)
+ _check_for_locals(expr, level, parser)
+
+ # get our (possibly passed-in) scope
+ level += 1
+ env = _ensure_scope(level, global_dict=global_dict,
+ local_dict=local_dict, resolvers=resolvers,
+ target=target)
+
+ parsed_expr = Expr(expr, engine=engine, parser=parser, env=env,
+ truediv=truediv)
+
+ # construct the engine and evaluate the parsed expression
+ eng = _engines[engine]
+ eng_inst = eng(parsed_expr)
+ ret = eng_inst.evaluate()
+
+ if parsed_expr.assigner is None and multi_line:
+ raise ValueError("Multi-line expressions are only valid"
+ " if all expressions contain an assignment")
+
+ # assign if needed
+ if env.target is not None and parsed_expr.assigner is not None:
+ if inplace is None:
+ warnings.warn(
+ "eval expressions containing an assignment currently"
+ "default to operating inplace.\nThis will change in "
+ "a future version of pandas, use inplace=True to "
+ "avoid this warning.",
+ FutureWarning, stacklevel=3)
+ inplace = True
+
+ # if returning a copy, copy only on the first assignment
+ if not inplace and first_expr:
+ target = env.target.copy()
+ else:
+ target = env.target
+
+ target[parsed_expr.assigner] = ret
+
+ if not resolvers:
+ resolvers = ({parsed_expr.assigner: ret},)
+ else:
+ # existing resolver needs updated to handle
+ # case of mutating existing column in copy
+ for resolver in resolvers:
+ if parsed_expr.assigner in resolver:
+ resolver[parsed_expr.assigner] = ret
+ break
+ else:
+ resolvers += ({parsed_expr.assigner: ret},)
+
+ ret = None
+ first_expr = False
+
+ if not inplace and inplace is not None:
+ return target
return ret
diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py
index 7474c0d118612..3c529c26b453d 100644
--- a/pandas/computation/tests/test_eval.py
+++ b/pandas/computation/tests/test_eval.py
@@ -663,6 +663,13 @@ def test_identical(self):
tm.assert_numpy_array_equal(result, np.array([False]))
self.assertEqual(result.shape, (1, ))
+ def test_line_continuation(self):
+ # GH 11149
+ exp = """1 + 2 * \
+ 5 - 1 + 2 """
+ result = pd.eval(exp, engine=self.engine, parser=self.parser)
+ self.assertEqual(result, 12)
+
class TestEvalNumexprPython(TestEvalNumexprPandas):
@@ -1220,21 +1227,21 @@ def test_assignment_column(self):
expected = orig_df.copy()
expected['a'] = expected['a'] + expected['b']
df = orig_df.copy()
- df.eval('a = a + b')
+ df.eval('a = a + b', inplace=True)
assert_frame_equal(df, expected)
# single assignment - new variable
expected = orig_df.copy()
expected['c'] = expected['a'] + expected['b']
df = orig_df.copy()
- df.eval('c = a + b')
+ df.eval('c = a + b', inplace=True)
assert_frame_equal(df, expected)
# with a local name overlap
def f():
df = orig_df.copy()
- a = 1
- df.eval('a = 1 + b')
+ a = 1 # noqa
+ df.eval('a = 1 + b', inplace=True)
return df
df = f()
@@ -1245,9 +1252,9 @@ def f():
df = orig_df.copy()
def f():
- a = 1
+ a = 1 # noqa
old_a = df.a.copy()
- df.eval('a = a + b')
+ df.eval('a = a + b', inplace=True)
result = old_a + df.b
assert_series_equal(result, df.a, check_names=False)
self.assertTrue(result.name is None)
@@ -1256,12 +1263,13 @@ def f():
# multiple assignment
df = orig_df.copy()
- df.eval('c = a + b')
+ df.eval('c = a + b', inplace=True)
self.assertRaises(SyntaxError, df.eval, 'c = a = b')
# explicit targets
df = orig_df.copy()
- self.eval('c = df.a + df.b', local_dict={'df': df}, target=df)
+ self.eval('c = df.a + df.b', local_dict={'df': df},
+ target=df, inplace=True)
expected = orig_df.copy()
expected['c'] = expected['a'] + expected['b']
assert_frame_equal(df, expected)
@@ -1273,6 +1281,88 @@ def test_column_in(self):
expected = Series([True])
assert_series_equal(result, expected)
+ def assignment_not_inplace(self):
+ # GH 9297
+ tm.skip_if_no_ne('numexpr')
+ df = DataFrame(np.random.randn(5, 2), columns=list('ab'))
+
+ actual = df.eval('c = a + b', inplace=False) # noqa
+ expected = df.copy()
+ expected['c'] = expected['a'] + expected['b']
+ assert_frame_equal(df, expected)
+
+ # default for inplace will change
+ with tm.assert_produces_warnings(FutureWarning):
+ df.eval('c = a + b')
+
+ # but don't warn without assignment
+ with tm.assert_produces_warnings(None):
+ df.eval('a + b')
+
+ def test_multi_line_expression(self):
+ # GH 11149
+ tm.skip_if_no_ne('numexpr')
+ df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
+ expected = df.copy()
+
+ expected['c'] = expected['a'] + expected['b']
+ expected['d'] = expected['c'] + expected['b']
+ ans = df.eval("""
+ c = a + b
+ d = c + b""", inplace=True)
+ assert_frame_equal(expected, df)
+ self.assertIsNone(ans)
+
+ expected['a'] = expected['a'] - 1
+ expected['e'] = expected['a'] + 2
+ ans = df.eval("""
+ a = a - 1
+ e = a + 2""", inplace=True)
+ assert_frame_equal(expected, df)
+ self.assertIsNone(ans)
+
+ # multi-line not valid if not all assignments
+ with tm.assertRaises(ValueError):
+ df.eval("""
+ a = b + 2
+ b - 2""", inplace=False)
+
+ def test_multi_line_expression_not_inplace(self):
+ # GH 11149
+ tm.skip_if_no_ne('numexpr')
+ df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
+ expected = df.copy()
+
+ expected['c'] = expected['a'] + expected['b']
+ expected['d'] = expected['c'] + expected['b']
+ df = df.eval("""
+ c = a + b
+ d = c + b""", inplace=False)
+ assert_frame_equal(expected, df)
+
+ expected['a'] = expected['a'] - 1
+ expected['e'] = expected['a'] + 2
+ df = df.eval("""
+ a = a - 1
+ e = a + 2""", inplace=False)
+ assert_frame_equal(expected, df)
+
+ def test_assignment_in_query(self):
+ # GH 8664
+ df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
+ df_orig = df.copy()
+ with tm.assertRaises(ValueError):
+ df.query('a = 1')
+ assert_frame_equal(df, df_orig)
+
+ def query_inplace(self):
+ # GH 11149
+ df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
+ expected = df.copy()
+ expected = expected[expected['a'] == 2]
+ df.query('a == 2', inplace=True)
+ assert_frame_equal(expected, df)
+
def test_basic_period_index_boolean_expression(self):
df = mkdf(2, 2, data_gen_f=f, c_idx_type='p', r_idx_type='i')
@@ -1502,7 +1592,7 @@ def test_df_use_case(self):
'b': np.random.randn(10)})
df.eval("e = arctan2(sin(a), b)",
engine=self.engine,
- parser=self.parser)
+ parser=self.parser, inplace=True)
got = df.e
expect = np.arctan2(np.sin(df.a), df.b)
pd.util.testing.assert_almost_equal(got, expect)
@@ -1512,7 +1602,7 @@ def test_df_arithmetic_subexpression(self):
'b': np.random.randn(10)})
df.eval("e = sin(a + b)",
engine=self.engine,
- parser=self.parser)
+ parser=self.parser, inplace=True)
got = df.e
expect = np.sin(df.a + df.b)
pd.util.testing.assert_almost_equal(got, expect)
@@ -1522,7 +1612,7 @@ def check_result_type(self, dtype, expect_dtype):
self.assertEqual(df.a.dtype, dtype)
df.eval("b = sin(a)",
engine=self.engine,
- parser=self.parser)
+ parser=self.parser, inplace=True)
got = df.b
expect = np.sin(df.a)
self.assertEqual(expect.dtype, got.dtype)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b66c51bc4411e..6207ac5dc5c12 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2051,7 +2051,7 @@ def _getitem_frame(self, key):
raise ValueError('Must pass DataFrame with boolean values only')
return self.where(key)
- def query(self, expr, **kwargs):
+ def query(self, expr, inplace=False, **kwargs):
"""Query the columns of a frame with a boolean expression.
.. versionadded:: 0.13
@@ -2062,6 +2062,12 @@ def query(self, expr, **kwargs):
The query string to evaluate. You can refer to variables
in the environment by prefixing them with an '@' character like
``@a + b``.
+ inplace : bool
+ Whether the query should modify the data in place or return
+ a modified copy
+
+ .. versionadded:: 0.18.0
+
kwargs : dict
See the documentation for :func:`pandas.eval` for complete details
on the keyword arguments accepted by :meth:`DataFrame.query`.
@@ -2118,16 +2124,22 @@ def query(self, expr, **kwargs):
>>> df[df.a > df.b] # same result as the previous expression
"""
kwargs['level'] = kwargs.pop('level', 0) + 1
+ kwargs['target'] = None
res = self.eval(expr, **kwargs)
try:
- return self.loc[res]
+ new_data = self.loc[res]
except ValueError:
# when res is multi-dimensional loc raises, but this is sometimes a
# valid query
- return self[res]
+ new_data = self[res]
- def eval(self, expr, **kwargs):
+ if inplace:
+ self._update_inplace(new_data)
+ else:
+ return new_data
+
+ def eval(self, expr, inplace=None, **kwargs):
"""Evaluate an expression in the context of the calling DataFrame
instance.
@@ -2135,6 +2147,16 @@ def eval(self, expr, **kwargs):
----------
expr : string
The expression string to evaluate.
+ inplace : bool
+ If the expression contains an assignment, whether to return a new
+ DataFrame or mutate the existing.
+
+ WARNING: inplace=None currently falls back to to True, but
+ in a future version, will default to False. Use inplace=True
+ explicitly rather than relying on the default.
+
+ .. versionadded:: 0.18.0
+
kwargs : dict
See the documentation for :func:`~pandas.eval` for complete details
on the keyword arguments accepted by
@@ -2147,6 +2169,7 @@ def eval(self, expr, **kwargs):
See Also
--------
pandas.DataFrame.query
+ pandas.DataFrame.assign
pandas.eval
Notes
@@ -2168,9 +2191,10 @@ def eval(self, expr, **kwargs):
if resolvers is None:
index_resolvers = self._get_index_resolvers()
resolvers = dict(self.iteritems()), index_resolvers
- kwargs['target'] = self
+ if 'target' not in kwargs:
+ kwargs['target'] = self
kwargs['resolvers'] = kwargs.get('resolvers', ()) + resolvers
- return _eval(expr, **kwargs)
+ return _eval(expr, inplace=inplace, **kwargs)
def select_dtypes(self, include=None, exclude=None):
"""Return a subset of a DataFrame including/excluding columns based on
| closes #9297
closes #8664
This is just a proof of concept at this point - the idea is to allow multiple assignments within an eval block, and also include an `inplace` argument (currently default True to match old behavior, although maybe that should be changed) for chaining.
```
In [15]: df = pd.DataFrame({'a': np.linspace(0, 100), 'b': range(50)})
In [16]: df.eval("""
...: c = a * 2
...: d = c / 2.0
...: e = a + b + c""")
In [17]: df.head()
Out[17]:
a b c d e
0 0.000000 0 0.000000 0.000000 0.000000
1 2.040816 1 4.081633 2.040816 7.122449
2 4.081633 2 8.163265 4.081633 14.244898
3 6.122449 3 12.244898 6.122449 21.367347
4 8.163265 4 16.326531 8.163265 28.489796
In [18]: df.eval("""
...: f = e * 2
...: g = f * 1.5""", inplace=False).head()
Out[18]:
a b c d e f g
0 0.000000 0 0.000000 0.000000 0.000000 0.000000 0.000000
1 2.040816 1 4.081633 2.040816 7.122449 14.244898 21.367347
2 4.081633 2 8.163265 4.081633 14.244898 28.489796 42.734694
3 6.122449 3 12.244898 6.122449 21.367347 42.734694 64.102041
4 8.163265 4 16.326531 8.163265 28.489796 56.979592 85.469388
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11149 | 2015-09-19T18:45:31Z | 2016-01-04T02:17:23Z | null | 2016-01-15T01:02:47Z |
BUG: astype(str) on datetimelike index #10442 | diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 25b22230e5f3d..64d04df06851f 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -17,6 +17,7 @@ Highlights include:
Enhancements
~~~~~~~~~~~~
+- ``DatetimeIndex`` now supports conversion to strings with astype(str)(:issue:`10442`)
- Support for ``compression`` (gzip/bz2) in :method:`DataFrame.to_csv` (:issue:`7615`)
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 814a9ccc45582..868057c675594 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -756,6 +756,8 @@ def astype(self, dtype):
return self.asi8.copy()
elif dtype == _NS_DTYPE and self.tz is not None:
return self.tz_convert('UTC').tz_localize(None)
+ elif dtype == str:
+ return self._shallow_copy(values=self.format(), infer=True)
else: # pragma: no cover
raise ValueError('Cannot cast DatetimeIndex to dtype %s' % dtype)
diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py
index 24edc54582ec1..4d353eccba972 100644
--- a/pandas/tseries/tests/test_base.py
+++ b/pandas/tseries/tests/test_base.py
@@ -45,6 +45,32 @@ def test_ops_properties_basic(self):
self.assertEqual(s.day,10)
self.assertRaises(AttributeError, lambda : s.weekday)
+ def test_astype_str(self):
+ # test astype string - #10442
+ result = date_range('2012-01-01', periods=4, name='test_name').astype(str)
+ expected = Index(['2012-01-01', '2012-01-02', '2012-01-03','2012-01-04'],
+ name='test_name', dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ # test astype string with tz and name
+ result = date_range('2012-01-01', periods=3, name='test_name', tz='US/Eastern').astype(str)
+ expected = Index(['2012-01-01 00:00:00-05:00', '2012-01-02 00:00:00-05:00',
+ '2012-01-03 00:00:00-05:00'], name='test_name', dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ # test astype string with freqH and name
+ result = date_range('1/1/2011', periods=3, freq='H', name='test_name').astype(str)
+ expected = Index(['2011-01-01 00:00:00', '2011-01-01 01:00:00', '2011-01-01 02:00:00'],
+ name='test_name', dtype=object)
+ tm.assert_index_equal(result, expected)
+
+ # test astype string with freqH and timezone
+ result = date_range('3/6/2012 00:00', periods=2, freq='H',
+ tz='Europe/London', name='test_name').astype(str)
+ expected = Index(['2012-03-06 00:00:00+00:00', '2012-03-06 01:00:00+00:00'],
+ dtype=object, name='test_name')
+ tm.assert_index_equal(result, expected)
+
def test_asobject_tolist(self):
idx = pd.date_range(start='2013-01-01', periods=4, freq='M', name='idx')
expected_list = [pd.Timestamp('2013-01-31'), pd.Timestamp('2013-02-28'),
@@ -503,7 +529,6 @@ def test_infer_freq(self):
tm.assert_index_equal(idx, result)
self.assertEqual(result.freq, freq)
-
class TestTimedeltaIndexOps(Ops):
def setUp(self):
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index a80bdf970cccb..230016f00374f 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -2223,6 +2223,7 @@ def test_append_join_nondatetimeindex(self):
# it works
rng.join(idx, how='outer')
+
def test_astype(self):
rng = date_range('1/1/2000', periods=10)
@@ -2235,6 +2236,17 @@ def test_astype(self):
expected = date_range('1/1/2000', periods=10, tz='US/Eastern').tz_convert('UTC').tz_localize(None)
tm.assert_index_equal(result, expected)
+ # BUG#10442 : testing astype(str) is correct for Series/DatetimeIndex
+ result = pd.Series(pd.date_range('2012-01-01', periods=3)).astype(str)
+ expected = pd.Series(['2012-01-01', '2012-01-02', '2012-01-03'], dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ result = Series(pd.date_range('2012-01-01', periods=3, tz='US/Eastern')).astype(str)
+ expected = Series(['2012-01-01 00:00:00-05:00', '2012-01-02 00:00:00-05:00', '2012-01-03 00:00:00-05:00'],
+ dtype=object)
+ tm.assert_series_equal(result, expected)
+
+
def test_to_period_nofreq(self):
idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04'])
self.assertRaises(ValueError, idx.to_period)
| closes #10442
fix for the bug: Convert datetimelike index to strings with astype(str)
going to send pull request for test
| https://api.github.com/repos/pandas-dev/pandas/pulls/11148 | 2015-09-19T00:31:15Z | 2015-10-16T22:07:39Z | 2015-10-16T22:07:39Z | 2015-10-16T22:07:42Z |
PERF: improves performance in SeriesGroupBy.transform | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 2be7194af34b0..6ae67ab6eedb1 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1021,7 +1021,7 @@ Performance Improvements
- Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`)
- Added vbench benchmarks for alternative ExcelWriter engines and reading Excel files (:issue:`7171`)
- Performance improvements in ``Categorical.value_counts`` (:issue:`10804`)
-- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` (:issue:`10820`, :issue:`11077`)
+- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` and ``SeriesGroupby.transform`` (:issue:`10820`, :issue:`11077`)
- Performance improvements in ``DataFrame.drop_duplicates`` with integer dtypes (:issue:`10917`)
- 4x improvement in ``timedelta`` string parsing (:issue:`6755`, :issue:`10426`)
- 8x improvement in ``timedelta64`` and ``datetime64`` ops (:issue:`6755`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 8e44480c0c09b..35f5b7fadb9db 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -2512,13 +2512,19 @@ def _transform_fast(self, func):
if isinstance(func, compat.string_types):
func = getattr(self,func)
- values = func().values
- counts = self.size().fillna(0).values
- values = np.repeat(values, com._ensure_platform_int(counts))
- if any(counts == 0):
- values = self._try_cast(values, self._selected_obj)
+ ids, _, ngroup = self.grouper.group_info
+ mask = ids != -1
+
+ out = func().values[ids]
+ if not mask.all():
+ out = np.where(mask, out, np.nan)
+
+ obs = np.zeros(ngroup, dtype='bool')
+ obs[ids[mask]] = True
+ if not obs.all():
+ out = self._try_cast(out, self._selected_obj)
- return self._set_result_index_ordered(Series(values))
+ return Series(out, index=self.obj.index)
def filter(self, func, dropna=True, *args, **kwargs):
"""
| ```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
groupby_transform_series2 | 6.3464 | 167.3844 | 0.0379 |
groupby_transform_multi_key3 | 99.4797 | 1078.2626 | 0.0923 |
groupby_transform_multi_key1 | 10.9547 | 98.5500 | 0.1112 |
groupby_transform_multi_key2 | 9.0899 | 67.2680 | 0.1351 |
groupby_transform_series | 5.4360 | 30.5537 | 0.1779 |
groupby_transform_multi_key4 | 39.9816 | 187.1406 | 0.2136 |
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
Ratio < 1.0 means the target commit is faster then the baseline.
Seed used: 1234
Target [0470a10] : PERF: improves performance in SeriesGroupBy.transform
Base [7b9fe14] : revers import .pandas_vb_common
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11147 | 2015-09-18T23:07:27Z | 2015-09-20T18:53:34Z | 2015-09-20T18:53:34Z | 2015-09-20T19:03:42Z |
PERF: infer_datetime_format without padding #11142 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 2be7194af34b0..120be63edce72 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1031,6 +1031,7 @@ Performance Improvements
- 20x improvement in ``concat`` of Categoricals when categories are identical (:issue:`10587`)
- Improved performance of ``to_datetime`` when specified format string is ISO8601 (:issue:`10178`)
- 2x improvement of ``Series.value_counts`` for float dtype (:issue:`10821`)
+- Enable ``infer_datetime_format`` in ``to_datetime`` when date components do not have 0 padding (:issue:`11142`)
.. _whatsnew_0170.bug_fixes:
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index a02edf32cfcb0..c4eb0e0cddfc9 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -4615,6 +4615,24 @@ def test_guess_datetime_format_invalid_inputs(self):
for invalid_dt in invalid_dts:
self.assertTrue(tools._guess_datetime_format(invalid_dt) is None)
+ def test_guess_datetime_format_nopadding(self):
+ # GH 11142
+ dt_string_to_format = (
+ ('2011-1-1', '%Y-%m-%d'),
+ ('30-1-2011', '%d-%m-%Y'),
+ ('1/1/2011', '%m/%d/%Y'),
+ ('2011-1-1 00:00:00', '%Y-%m-%d %H:%M:%S'),
+ ('2011-1-1 0:0:0', '%Y-%m-%d %H:%M:%S'),
+ ('2011-1-3T00:00:0', '%Y-%m-%dT%H:%M:%S')
+ )
+
+ for dt_string, dt_format in dt_string_to_format:
+ self.assertEqual(
+ tools._guess_datetime_format(dt_string),
+ dt_format
+ )
+
+
def test_guess_datetime_format_for_array(self):
expected_format = '%Y-%m-%d %H:%M:%S.%f'
dt_string = datetime(2011, 12, 30, 0, 0, 0).strftime(expected_format)
diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py
index bd19b771f30ce..c38878fe398e4 100644
--- a/pandas/tseries/tools.py
+++ b/pandas/tseries/tools.py
@@ -86,20 +86,21 @@ def _guess_datetime_format(dt_str, dayfirst=False,
if not isinstance(dt_str, compat.string_types):
return None
- day_attribute_and_format = (('day',), '%d')
+ day_attribute_and_format = (('day',), '%d', 2)
+ # attr name, format, padding (if any)
datetime_attrs_to_format = [
- (('year', 'month', 'day'), '%Y%m%d'),
- (('year',), '%Y'),
- (('month',), '%B'),
- (('month',), '%b'),
- (('month',), '%m'),
+ (('year', 'month', 'day'), '%Y%m%d', 0),
+ (('year',), '%Y', 0),
+ (('month',), '%B', 0),
+ (('month',), '%b', 0),
+ (('month',), '%m', 2),
day_attribute_and_format,
- (('hour',), '%H'),
- (('minute',), '%M'),
- (('second',), '%S'),
- (('microsecond',), '%f'),
- (('second', 'microsecond'), '%S.%f'),
+ (('hour',), '%H', 2),
+ (('minute',), '%M', 2),
+ (('second',), '%S', 2),
+ (('microsecond',), '%f', 6),
+ (('second', 'microsecond'), '%S.%f', 0),
]
if dayfirst:
@@ -125,7 +126,7 @@ def _guess_datetime_format(dt_str, dayfirst=False,
format_guess = [None] * len(tokens)
found_attrs = set()
- for attrs, attr_format in datetime_attrs_to_format:
+ for attrs, attr_format, padding in datetime_attrs_to_format:
# If a given attribute has been placed in the format string, skip
# over other formats for that same underlying attribute (IE, month
# can be represented in multiple different ways)
@@ -134,9 +135,11 @@ def _guess_datetime_format(dt_str, dayfirst=False,
if all(getattr(parsed_datetime, attr) is not None for attr in attrs):
for i, token_format in enumerate(format_guess):
+ token_filled = tokens[i].zfill(padding)
if (token_format is None and
- tokens[i] == parsed_datetime.strftime(attr_format)):
+ token_filled == parsed_datetime.strftime(attr_format)):
format_guess[i] = attr_format
+ tokens[i] = token_filled
found_attrs.update(attrs)
break
@@ -163,6 +166,8 @@ def _guess_datetime_format(dt_str, dayfirst=False,
guessed_format = ''.join(output_format)
+ # rebuild string, capturing any inferred padding
+ dt_str = ''.join(tokens)
if parsed_datetime.strftime(guessed_format) == dt_str:
return guessed_format
| Closes #11142
| https://api.github.com/repos/pandas-dev/pandas/pulls/11146 | 2015-09-18T22:53:15Z | 2015-09-20T19:21:37Z | 2015-09-20T19:21:37Z | 2015-09-20T20:40:27Z |
COMPAT: Support for MPL 1.5 | diff --git a/ci/install_conda.sh b/ci/install_conda.sh
index c54f5494c12ee..8d99034a86109 100755
--- a/ci/install_conda.sh
+++ b/ci/install_conda.sh
@@ -72,6 +72,7 @@ bash miniconda.sh -b -p $HOME/miniconda || exit 1
conda config --set always_yes yes --set changeps1 no || exit 1
conda update -q conda || exit 1
+conda config --add channels conda-forge || exit 1
conda config --add channels http://conda.binstar.org/pandas || exit 1
conda config --set ssl_verify false || exit 1
diff --git a/ci/requirements-3.4.run b/ci/requirements-3.4.run
index 73209a4623a49..c984036203251 100644
--- a/ci/requirements-3.4.run
+++ b/ci/requirements-3.4.run
@@ -11,7 +11,6 @@ beautiful-soup
scipy
numexpr
pytables
-matplotlib=1.3.1
lxml
sqlalchemy
bottleneck
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 1a976bf0d921e..4ec5281b5f2ff 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -50,6 +50,7 @@ Highlights include:
- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>`
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>`
- Compatibility with Python 3.5 (:issue:`11097`)
+- Compatibility with matplotlib 1.5.0 (:issue:`11111`)
Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating.
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index ad9518116a066..27069ddfd9c49 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -74,13 +74,22 @@ def setUp(self):
'weight': random.normal(161, 32, size=n),
'category': random.randint(4, size=n)})
- if str(mpl.__version__) >= LooseVersion('1.4'):
+ self.mpl_le_1_2_1 = plotting._mpl_le_1_2_1()
+ self.mpl_ge_1_3_1 = plotting._mpl_ge_1_3_1()
+ self.mpl_ge_1_4_0 = plotting._mpl_ge_1_4_0()
+ self.mpl_ge_1_5_0 = plotting._mpl_ge_1_5_0()
+
+ if self.mpl_ge_1_4_0:
self.bp_n_objects = 7
else:
self.bp_n_objects = 8
+ if self.mpl_ge_1_5_0:
+ # 1.5 added PolyCollections to legend handler
+ # so we have twice as many items.
+ self.polycollection_factor = 2
+ else:
+ self.polycollection_factor = 1
- self.mpl_le_1_2_1 = str(mpl.__version__) <= LooseVersion('1.2.1')
- self.mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1')
def tearDown(self):
tm.close()
@@ -183,7 +192,7 @@ def _check_colors(self, collections, linecolors=None, facecolors=None,
"""
from matplotlib.lines import Line2D
- from matplotlib.collections import Collection
+ from matplotlib.collections import Collection, PolyCollection
conv = self.colorconverter
if linecolors is not None:
@@ -197,6 +206,8 @@ def _check_colors(self, collections, linecolors=None, facecolors=None,
result = patch.get_color()
# Line2D may contains string color expression
result = conv.to_rgba(result)
+ elif isinstance(patch, PolyCollection):
+ result = tuple(patch.get_edgecolor()[0])
else:
result = patch.get_edgecolor()
@@ -472,6 +483,21 @@ def is_grid_on():
obj.plot(kind=kind, grid=True, **kws)
self.assertTrue(is_grid_on())
+ def _maybe_unpack_cycler(self, rcParams, field='color'):
+ """
+ Compat layer for MPL 1.5 change to color cycle
+
+ Before: plt.rcParams['axes.color_cycle'] -> ['b', 'g', 'r'...]
+ After : plt.rcParams['axes.prop_cycle'] -> cycler(...)
+ """
+ if self.mpl_ge_1_5_0:
+ cyl = rcParams['axes.prop_cycle']
+ colors = [v[field] for v in cyl]
+ else:
+ colors = rcParams['axes.color_cycle']
+ return colors
+
+
@tm.mplskip
class TestSeriesPlots(TestPlotBase):
@@ -536,9 +562,13 @@ def test_plot_figsize_and_title(self):
def test_dont_modify_rcParams(self):
# GH 8242
- colors = self.plt.rcParams['axes.color_cycle']
+ if self.mpl_ge_1_5_0:
+ key = 'axes.prop_cycle'
+ else:
+ key = 'axes.color_cycle'
+ colors = self.plt.rcParams[key]
Series([1, 2, 3]).plot()
- self.assertEqual(colors, self.plt.rcParams['axes.color_cycle'])
+ self.assertEqual(colors, self.plt.rcParams[key])
def test_ts_line_lim(self):
ax = self.ts.plot()
@@ -770,8 +800,8 @@ def test_hist_legacy(self):
_check_plot_works(self.ts.hist)
_check_plot_works(self.ts.hist, grid=False)
_check_plot_works(self.ts.hist, figsize=(8, 10))
- _check_plot_works(self.ts.hist, by=self.ts.index.month)
- _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)
+ _check_plot_works(self.ts.hist, filterwarnings='ignore', by=self.ts.index.month)
+ _check_plot_works(self.ts.hist, filterwarnings='ignore', by=self.ts.index.month, bins=5)
fig, ax = self.plt.subplots(1, 1)
_check_plot_works(self.ts.hist, ax=ax)
@@ -805,25 +835,32 @@ def test_hist_layout(self):
def test_hist_layout_with_by(self):
df = self.hist_df
- axes = _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.gender, layout=(2, 1))
self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
- axes = _check_plot_works(df.height.hist, by=df.gender, layout=(3, -1))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.gender, layout=(3, -1))
self._check_axes_shape(axes, axes_num=2, layout=(3, 1))
- axes = _check_plot_works(df.height.hist, by=df.category, layout=(4, 1))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.category, layout=(4, 1))
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
- axes = _check_plot_works(df.height.hist, by=df.category, layout=(2, -1))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.category, layout=(2, -1))
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
- axes = _check_plot_works(df.height.hist, by=df.category, layout=(3, -1))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.category, layout=(3, -1))
self._check_axes_shape(axes, axes_num=4, layout=(3, 2))
- axes = _check_plot_works(df.height.hist, by=df.category, layout=(-1, 4))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.category, layout=(-1, 4))
self._check_axes_shape(axes, axes_num=4, layout=(1, 4))
- axes = _check_plot_works(df.height.hist, by=df.classroom, layout=(2, 2))
+ axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
+ by=df.classroom, layout=(2, 2))
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7))
@@ -1109,7 +1146,8 @@ def test_errorbar_plot(self):
s.plot(yerr=np.arange(11))
s_err = ['zzz']*10
- with tm.assertRaises(TypeError):
+ # in mpl 1.5+ this is a TypeError
+ with tm.assertRaises((ValueError, TypeError)):
s.plot(yerr=s_err)
def test_table(self):
@@ -1183,7 +1221,10 @@ def test_time_series_plot_color_kwargs(self):
def test_time_series_plot_color_with_empty_kwargs(self):
import matplotlib as mpl
- def_colors = mpl.rcParams['axes.color_cycle']
+ if self.mpl_ge_1_5_0:
+ def_colors = self._maybe_unpack_cycler(mpl.rcParams)
+ else:
+ def_colors = mpl.rcParams['axes.color_cycle']
index = date_range('1/1/2000', periods=12)
s = Series(np.arange(1, 13), index=index)
@@ -1213,14 +1254,16 @@ def setUp(self):
@slow
def test_plot(self):
df = self.tdf
- _check_plot_works(df.plot, grid=False)
- axes = _check_plot_works(df.plot, subplots=True)
+ _check_plot_works(df.plot, filterwarnings='ignore', grid=False)
+ axes = _check_plot_works(df.plot, filterwarnings='ignore', subplots=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
- axes = _check_plot_works(df.plot, subplots=True, layout=(-1, 2))
+ axes = _check_plot_works(df.plot, filterwarnings='ignore',
+ subplots=True, layout=(-1, 2))
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
- axes = _check_plot_works(df.plot, subplots=True, use_index=False)
+ axes = _check_plot_works(df.plot, filterwarnings='ignore',
+ subplots=True, use_index=False)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
df = DataFrame({'x': [1, 2], 'y': [3, 4]})
@@ -1229,13 +1272,14 @@ def test_plot(self):
df = DataFrame(np.random.rand(10, 3),
index=list(string.ascii_letters[:10]))
+
_check_plot_works(df.plot, use_index=True)
_check_plot_works(df.plot, sort_columns=False)
_check_plot_works(df.plot, yticks=[1, 5, 10])
_check_plot_works(df.plot, xticks=[1, 5, 10])
_check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
- _check_plot_works(df.plot, subplots=True, title='blah')
+ _check_plot_works(df.plot, filterwarnings='ignore', subplots=True, title='blah')
# We have to redo it here because _check_plot_works does two plots, once without an ax
# kwarg and once with an ax kwarg and the new sharex behaviour does not remove the
# visibility of the latter axis (as ax is present).
@@ -1292,7 +1336,11 @@ def test_plot(self):
fig, ax = self.plt.subplots()
axes = df.plot.bar(subplots=True, ax=ax)
self.assertEqual(len(axes), 1)
- self.assertIs(ax.get_axes(), axes[0])
+ if self.mpl_ge_1_5_0:
+ result = ax.axes
+ else:
+ result = ax.get_axes() # deprecated
+ self.assertIs(result, axes[0])
def test_color_and_style_arguments(self):
df = DataFrame({'x': [1, 2], 'y': [3, 4]})
@@ -1802,8 +1850,7 @@ def test_area_lim(self):
@slow
def test_bar_colors(self):
import matplotlib.pyplot as plt
-
- default_colors = plt.rcParams.get('axes.color_cycle')
+ default_colors = self._maybe_unpack_cycler(plt.rcParams)
df = DataFrame(randn(5, 5))
ax = df.plot.bar()
@@ -2025,6 +2072,19 @@ def test_plot_scatter_with_c(self):
float_array = np.array([0.0, 1.0])
df.plot.scatter(x='A', y='B', c=float_array, cmap='spring')
+ def test_scatter_colors(self):
+ df = DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]})
+ with tm.assertRaises(TypeError):
+ df.plot.scatter(x='a', y='b', c='c', color='green')
+
+ ax = df.plot.scatter(x='a', y='b', c='c')
+ tm.assert_numpy_array_equal(ax.collections[0].get_facecolor()[0],
+ (0, 0, 1, 1))
+
+ ax = df.plot.scatter(x='a', y='b', color='white')
+ tm.assert_numpy_array_equal(ax.collections[0].get_facecolor()[0],
+ (1, 1, 1, 1))
+
@slow
def test_plot_bar(self):
df = DataFrame(randn(6, 4),
@@ -2033,7 +2093,7 @@ def test_plot_bar(self):
_check_plot_works(df.plot.bar)
_check_plot_works(df.plot.bar, legend=False)
- _check_plot_works(df.plot.bar, subplots=True)
+ _check_plot_works(df.plot.bar, filterwarnings='ignore', subplots=True)
_check_plot_works(df.plot.bar, stacked=True)
df = DataFrame(randn(10, 15),
@@ -2250,7 +2310,7 @@ def test_boxplot_vertical(self):
self._check_text_labels(ax.get_yticklabels(), labels)
self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols))
- axes = _check_plot_works(df.plot.box, subplots=True,
+ axes = _check_plot_works(df.plot.box, filterwarnings='ignore', subplots=True,
vert=False, logx=True)
self._check_axes_shape(axes, axes_num=3, layout=(1, 3))
self._check_ax_scales(axes, xaxis='log')
@@ -2310,7 +2370,7 @@ def test_kde_df(self):
ax = df.plot(kind='kde', rot=20, fontsize=5)
self._check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5)
- axes = _check_plot_works(df.plot, kind='kde', subplots=True)
+ axes = _check_plot_works(df.plot, filterwarnings='ignore', kind='kde', subplots=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
axes = df.plot(kind='kde', logy=True, subplots=True)
@@ -2326,6 +2386,7 @@ def test_kde_missing_vals(self):
@slow
def test_hist_df(self):
+ from matplotlib.patches import Rectangle
if self.mpl_le_1_2_1:
raise nose.SkipTest("not supported in matplotlib <= 1.2.x")
@@ -2336,7 +2397,7 @@ def test_hist_df(self):
expected = [com.pprint_thing(c) for c in df.columns]
self._check_legend_labels(ax, labels=expected)
- axes = _check_plot_works(df.plot.hist, subplots=True, logy=True)
+ axes = _check_plot_works(df.plot.hist, filterwarnings='ignore', subplots=True, logy=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
self._check_ax_scales(axes, yaxis='log')
@@ -2346,11 +2407,14 @@ def test_hist_df(self):
ax = series.plot.hist(normed=True, cumulative=True, bins=4)
# height of last bin (index 5) must be 1.0
- self.assertAlmostEqual(ax.get_children()[5].get_height(), 1.0)
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+ self.assertAlmostEqual(rects[-1].get_height(), 1.0)
tm.close()
ax = series.plot.hist(cumulative=True, bins=4)
- self.assertAlmostEqual(ax.get_children()[5].get_height(), 100.0)
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+
+ self.assertAlmostEqual(rects[-2].get_height(), 100.0)
tm.close()
# if horizontal, yticklabels are rotated
@@ -2626,7 +2690,7 @@ def test_line_colors(self):
def test_line_colors_and_styles_subplots(self):
# GH 9894
from matplotlib import cm
- default_colors = self.plt.rcParams.get('axes.color_cycle')
+ default_colors = self._maybe_unpack_cycler(self.plt.rcParams)
df = DataFrame(randn(5, 5))
@@ -2698,7 +2762,8 @@ def test_area_colors(self):
handles, labels = ax.get_legend_handles_labels()
# legend is stored as Line2D, thus check linecolors
- self._check_colors(handles, linecolors=custom_colors)
+ linehandles = [x for x in handles if not isinstance(x, PolyCollection)]
+ self._check_colors(linehandles, linecolors=custom_colors)
for h in handles:
self.assertTrue(h.get_alpha() is None)
tm.close()
@@ -2710,12 +2775,13 @@ def test_area_colors(self):
self._check_colors(poly, facecolors=jet_colors)
handles, labels = ax.get_legend_handles_labels()
- self._check_colors(handles, linecolors=jet_colors)
+ linehandles = [x for x in handles if not isinstance(x, PolyCollection)]
+ self._check_colors(linehandles, linecolors=jet_colors)
for h in handles:
self.assertTrue(h.get_alpha() is None)
tm.close()
- # When stacked=True, alpha is set to 0.5
+ # When stacked=False, alpha is set to 0.5
ax = df.plot.area(colormap=cm.jet, stacked=False)
self._check_colors(ax.get_lines(), linecolors=jet_colors)
poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
@@ -2724,13 +2790,13 @@ def test_area_colors(self):
handles, labels = ax.get_legend_handles_labels()
# Line2D can't have alpha in its linecolor
- self._check_colors(handles, linecolors=jet_colors)
+ self._check_colors(handles[:len(jet_colors)], linecolors=jet_colors)
for h in handles:
self.assertEqual(h.get_alpha(), 0.5)
@slow
def test_hist_colors(self):
- default_colors = self.plt.rcParams.get('axes.color_cycle')
+ default_colors = self._maybe_unpack_cycler(self.plt.rcParams)
df = DataFrame(randn(5, 5))
ax = df.plot.hist()
@@ -2791,7 +2857,7 @@ def test_kde_colors_and_styles_subplots(self):
_skip_if_no_scipy_gaussian_kde()
from matplotlib import cm
- default_colors = self.plt.rcParams.get('axes.color_cycle')
+ default_colors = self._maybe_unpack_cycler(self.plt.rcParams)
df = DataFrame(randn(5, 5))
@@ -2853,7 +2919,7 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c='k', fliers_c='b'):
self._check_colors(bp['fliers'], linecolors=[fliers_c] * len(bp['fliers']))
self._check_colors(bp['caps'], linecolors=[caps_c] * len(bp['caps']))
- default_colors = self.plt.rcParams.get('axes.color_cycle')
+ default_colors = self._maybe_unpack_cycler(self.plt.rcParams)
df = DataFrame(randn(5, 5))
bp = df.plot.box(return_type='dict')
@@ -2900,12 +2966,17 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c='k', fliers_c='b'):
def test_default_color_cycle(self):
import matplotlib.pyplot as plt
- plt.rcParams['axes.color_cycle'] = list('rgbk')
+ colors = list('rgbk')
+ if self.mpl_ge_1_5_0:
+ import cycler
+ plt.rcParams['axes.prop_cycle'] = cycler.cycler('color', colors)
+ else:
+ plt.rcParams['axes.color_cycle'] = colors
df = DataFrame(randn(5, 3))
ax = df.plot()
- expected = plt.rcParams['axes.color_cycle'][:3]
+ expected = self._maybe_unpack_cycler(plt.rcParams)[:3]
self._check_colors(ax.get_lines(), linecolors=expected)
def test_unordered_ts(self):
@@ -3032,7 +3103,7 @@ def test_pie_df(self):
ax = _check_plot_works(df.plot.pie, y=2)
self._check_text_labels(ax.texts, df.index)
- axes = _check_plot_works(df.plot.pie, subplots=True)
+ axes = _check_plot_works(df.plot.pie, filterwarnings='ignore', subplots=True)
self.assertEqual(len(axes), len(df.columns))
for ax in axes:
self._check_text_labels(ax.texts, df.index)
@@ -3041,7 +3112,7 @@ def test_pie_df(self):
labels = ['A', 'B', 'C', 'D', 'E']
color_args = ['r', 'g', 'b', 'c', 'm']
- axes = _check_plot_works(df.plot.pie, subplots=True,
+ axes = _check_plot_works(df.plot.pie, filterwarnings='ignore', subplots=True,
labels=labels, colors=color_args)
self.assertEqual(len(axes), len(df.columns))
@@ -3095,7 +3166,8 @@ def test_errorbar_plot(self):
self._check_has_errorbars(ax, xerr=2, yerr=2)
ax = _check_plot_works(df.plot, xerr=0.2, yerr=0.2, kind=kind)
self._check_has_errorbars(ax, xerr=2, yerr=2)
- axes = _check_plot_works(df.plot, yerr=df_err, xerr=df_err, subplots=True, kind=kind)
+ axes = _check_plot_works(df.plot, filterwarnings='ignore', yerr=df_err,
+ xerr=df_err, subplots=True, kind=kind)
self._check_has_errorbars(axes, xerr=1, yerr=1)
ax = _check_plot_works((df+1).plot, yerr=df_err, xerr=df_err, kind='bar', log=True)
@@ -3125,7 +3197,7 @@ def test_errorbar_plot(self):
df.plot(yerr=np.random.randn(11))
df_err = DataFrame({'x': ['zzz']*12, 'y': ['zzz']*12})
- with tm.assertRaises(TypeError):
+ with tm.assertRaises((ValueError, TypeError)):
df.plot(yerr=df_err)
@slow
@@ -3184,7 +3256,8 @@ def test_errorbar_timeseries(self):
self._check_has_errorbars(ax, xerr=0, yerr=1)
ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
self._check_has_errorbars(ax, xerr=0, yerr=2)
- axes = _check_plot_works(tdf.plot, kind=kind, yerr=tdf_err, subplots=True)
+ axes = _check_plot_works(tdf.plot, filterwarnings='ignore', kind=kind,
+ yerr=tdf_err, subplots=True)
self._check_has_errorbars(axes, xerr=0, yerr=1)
def test_errorbar_asymmetrical(self):
@@ -3629,37 +3702,38 @@ def assert_is_valid_plot_return_object(objs):
''.format(objs.__class__.__name__))
-def _check_plot_works(f, *args, **kwargs):
+def _check_plot_works(f, filterwarnings='always', **kwargs):
import matplotlib.pyplot as plt
ret = None
-
- try:
+ with warnings.catch_warnings():
+ warnings.simplefilter(filterwarnings)
try:
- fig = kwargs['figure']
- except KeyError:
- fig = plt.gcf()
-
- plt.clf()
+ try:
+ fig = kwargs['figure']
+ except KeyError:
+ fig = plt.gcf()
- ax = kwargs.get('ax', fig.add_subplot(211))
- ret = f(*args, **kwargs)
+ plt.clf()
- assert_is_valid_plot_return_object(ret)
+ ax = kwargs.get('ax', fig.add_subplot(211))
+ ret = f(**kwargs)
- try:
- kwargs['ax'] = fig.add_subplot(212)
- ret = f(*args, **kwargs)
- except Exception:
- pass
- else:
assert_is_valid_plot_return_object(ret)
- with ensure_clean(return_filelike=True) as path:
- plt.savefig(path)
- finally:
- tm.close(fig)
+ try:
+ kwargs['ax'] = fig.add_subplot(212)
+ ret = f(**kwargs)
+ except Exception:
+ pass
+ else:
+ assert_is_valid_plot_return_object(ret)
+
+ with ensure_clean(return_filelike=True) as path:
+ plt.savefig(path)
+ finally:
+ tm.close(fig)
- return ret
+ return ret
def _generate_4_axes_via_gridspec():
import matplotlib.pyplot as plt
diff --git a/pandas/tests/test_graphics_others.py b/pandas/tests/test_graphics_others.py
index 641180c8010c0..b18cbae600b43 100644
--- a/pandas/tests/test_graphics_others.py
+++ b/pandas/tests/test_graphics_others.py
@@ -161,8 +161,8 @@ def test_plot_fails_when_ax_differs_from_figure(self):
@slow
def test_autocorrelation_plot(self):
from pandas.tools.plotting import autocorrelation_plot
- _check_plot_works(autocorrelation_plot, self.ts)
- _check_plot_works(autocorrelation_plot, self.ts.values)
+ _check_plot_works(autocorrelation_plot, series=self.ts)
+ _check_plot_works(autocorrelation_plot, series=self.ts.values)
ax = autocorrelation_plot(self.ts, label='Test')
self._check_legend_labels(ax, labels=['Test'])
@@ -170,13 +170,13 @@ def test_autocorrelation_plot(self):
@slow
def test_lag_plot(self):
from pandas.tools.plotting import lag_plot
- _check_plot_works(lag_plot, self.ts)
- _check_plot_works(lag_plot, self.ts, lag=5)
+ _check_plot_works(lag_plot, series=self.ts)
+ _check_plot_works(lag_plot, series=self.ts, lag=5)
@slow
def test_bootstrap_plot(self):
from pandas.tools.plotting import bootstrap_plot
- _check_plot_works(bootstrap_plot, self.ts, size=10)
+ _check_plot_works(bootstrap_plot, series=self.ts, size=10)
@tm.mplskip
@@ -210,7 +210,7 @@ def test_boxplot_legacy(self):
_check_plot_works(df.boxplot, column='one', by=['indic', 'indic2'])
_check_plot_works(df.boxplot, by='indic')
_check_plot_works(df.boxplot, by=['indic', 'indic2'])
- _check_plot_works(plotting.boxplot, df['one'], return_type='dict')
+ _check_plot_works(plotting.boxplot, data=df['one'], return_type='dict')
_check_plot_works(df.boxplot, notch=1, return_type='dict')
_check_plot_works(df.boxplot, by='indic', notch=1)
@@ -304,6 +304,7 @@ def test_boxplot_empty_column(self):
@slow
def test_hist_df_legacy(self):
+ from matplotlib.patches import Rectangle
_check_plot_works(self.hist_df.hist)
# make sure layout is handled
@@ -347,7 +348,8 @@ def test_hist_df_legacy(self):
# make sure kwargs to hist are handled
ax = ser.hist(normed=True, cumulative=True, bins=4)
# height of last bin (index 5) must be 1.0
- self.assertAlmostEqual(ax.get_children()[5].get_height(), 1.0)
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+ self.assertAlmostEqual(rects[-1].get_height(), 1.0)
tm.close()
ax = ser.hist(log=True)
@@ -413,9 +415,9 @@ def scat(**kwds):
def scat2(x, y, by=None, ax=None, figsize=None):
return plotting.scatter_plot(df, x, y, by, ax, figsize=None)
- _check_plot_works(scat2, 0, 1)
+ _check_plot_works(scat2, x=0, y=1)
grouper = Series(np.repeat([1, 2, 3, 4, 5], 20), df.index)
- _check_plot_works(scat2, 0, 1, by=grouper)
+ _check_plot_works(scat2, x=0, y=1, by=grouper)
def test_scatter_matrix_axis(self):
tm._skip_if_no_scipy()
@@ -424,7 +426,8 @@ def test_scatter_matrix_axis(self):
with tm.RNGContext(42):
df = DataFrame(randn(100, 3))
- axes = _check_plot_works(scatter_matrix, df, range_padding=.1)
+ axes = _check_plot_works(scatter_matrix, filterwarnings='always', frame=df,
+ range_padding=.1)
axes0_labels = axes[0][0].yaxis.get_majorticklabels()
# GH 5662
expected = ['-2', '-1', '0', '1', '2']
@@ -432,7 +435,8 @@ def test_scatter_matrix_axis(self):
self._check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0)
df[0] = ((df[0] - 2) / 3)
- axes = _check_plot_works(scatter_matrix, df, range_padding=.1)
+ axes = _check_plot_works(scatter_matrix, filterwarnings='always', frame=df,
+ range_padding=.1)
axes0_labels = axes[0][0].yaxis.get_majorticklabels()
expected = ['-1.2', '-1.0', '-0.8', '-0.6', '-0.4', '-0.2', '0.0']
self._check_text_labels(axes0_labels, expected)
@@ -445,17 +449,17 @@ def test_andrews_curves(self):
df = self.iris
- _check_plot_works(andrews_curves, df, 'Name')
+ _check_plot_works(andrews_curves, frame=df, class_column='Name')
rgba = ('#556270', '#4ECDC4', '#C7F464')
- ax = _check_plot_works(andrews_curves, df, 'Name', color=rgba)
+ ax = _check_plot_works(andrews_curves, frame=df, class_column='Name', color=rgba)
self._check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df['Name'][:10])
cnames = ['dodgerblue', 'aquamarine', 'seagreen']
- ax = _check_plot_works(andrews_curves, df, 'Name', color=cnames)
+ ax = _check_plot_works(andrews_curves, frame=df, class_column='Name', color=cnames)
self._check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df['Name'][:10])
- ax = _check_plot_works(andrews_curves, df, 'Name', colormap=cm.jet)
+ ax = _check_plot_works(andrews_curves, frame=df, class_column='Name', colormap=cm.jet)
cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique()))
self._check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df['Name'][:10])
@@ -478,23 +482,23 @@ def test_parallel_coordinates(self):
df = self.iris
- ax = _check_plot_works(parallel_coordinates, df, 'Name')
+ ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name')
nlines = len(ax.get_lines())
nxticks = len(ax.xaxis.get_ticklabels())
rgba = ('#556270', '#4ECDC4', '#C7F464')
- ax = _check_plot_works(parallel_coordinates, df, 'Name', color=rgba)
+ ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', color=rgba)
self._check_colors(ax.get_lines()[:10], linecolors=rgba, mapping=df['Name'][:10])
cnames = ['dodgerblue', 'aquamarine', 'seagreen']
- ax = _check_plot_works(parallel_coordinates, df, 'Name', color=cnames)
+ ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', color=cnames)
self._check_colors(ax.get_lines()[:10], linecolors=cnames, mapping=df['Name'][:10])
- ax = _check_plot_works(parallel_coordinates, df, 'Name', colormap=cm.jet)
+ ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', colormap=cm.jet)
cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique()))
self._check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df['Name'][:10])
- ax = _check_plot_works(parallel_coordinates, df, 'Name', axvlines=False)
+ ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name', axvlines=False)
assert len(ax.get_lines()) == (nlines - nxticks)
colors = ['b', 'g', 'r']
@@ -517,20 +521,20 @@ def test_radviz(self):
from matplotlib import cm
df = self.iris
- _check_plot_works(radviz, df, 'Name')
+ _check_plot_works(radviz, frame=df, class_column='Name')
rgba = ('#556270', '#4ECDC4', '#C7F464')
- ax = _check_plot_works(radviz, df, 'Name', color=rgba)
+ ax = _check_plot_works(radviz, frame=df, class_column='Name', color=rgba)
# skip Circle drawn as ticks
patches = [p for p in ax.patches[:20] if p.get_label() != '']
self._check_colors(patches[:10], facecolors=rgba, mapping=df['Name'][:10])
cnames = ['dodgerblue', 'aquamarine', 'seagreen']
- _check_plot_works(radviz, df, 'Name', color=cnames)
+ _check_plot_works(radviz, frame=df, class_column='Name', color=cnames)
patches = [p for p in ax.patches[:20] if p.get_label() != '']
self._check_colors(patches, facecolors=cnames, mapping=df['Name'][:10])
- _check_plot_works(radviz, df, 'Name', colormap=cm.jet)
+ _check_plot_works(radviz, frame=df, class_column='Name', colormap=cm.jet)
cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique()))
patches = [p for p in ax.patches[:20] if p.get_label() != '']
self._check_colors(patches, facecolors=cmaps, mapping=df['Name'][:10])
@@ -607,6 +611,8 @@ def test_grouped_plot_fignums(self):
@slow
def test_grouped_hist_legacy(self):
+ from matplotlib.patches import Rectangle
+
df = DataFrame(randn(500, 2), columns=['A', 'B'])
df['C'] = np.random.randint(0, 4, 500)
df['D'] = ['X'] * 500
@@ -633,7 +639,8 @@ def test_grouped_hist_legacy(self):
xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
# height of last bin (index 5) must be 1.0
for ax in axes.ravel():
- height = ax.get_children()[5].get_height()
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
+ height = rects[-1].get_height()
self.assertAlmostEqual(height, 1.0)
self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
ylabelsize=yf, yrot=yrot)
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index cd2297d6018ca..55464a7f1d23e 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -24,13 +24,13 @@
from pandas.compat import range, lrange, lmap, map, zip, string_types
import pandas.compat as compat
from pandas.util.decorators import Appender
-
try: # mpl optional
import pandas.tseries.converter as conv
conv.register() # needs to override so set_xlim works with str/number
except ImportError:
pass
+
# Extracted from https://gist.github.com/huyng/816622
# this is the rcParams set when setting display.with_mpl_style
# to True.
@@ -97,6 +97,48 @@
'ytick.minor.size': 0.0
}
+
+def _mpl_le_1_2_1():
+ try:
+ import matplotlib as mpl
+ return (str(mpl.__version__) <= LooseVersion('1.2.1') and
+ str(mpl.__version__)[0] != '0')
+ except ImportError:
+ return False
+
+def _mpl_ge_1_3_1():
+ try:
+ import matplotlib
+ # The or v[0] == '0' is because their versioneer is
+ # messed up on dev
+ return (matplotlib.__version__ >= LooseVersion('1.3.1')
+ or matplotlib.__version__[0] == '0')
+ except ImportError:
+ return False
+
+def _mpl_ge_1_4_0():
+ try:
+ import matplotlib
+ return (matplotlib.__version__ >= LooseVersion('1.4')
+ or matplotlib.__version__[0] == '0')
+ except ImportError:
+ return False
+
+def _mpl_ge_1_5_0():
+ try:
+ import matplotlib
+ return (matplotlib.__version__ >= LooseVersion('1.5')
+ or matplotlib.__version__[0] == '0')
+ except ImportError:
+ return False
+
+if _mpl_ge_1_5_0():
+ # Compat with mp 1.5, which uses cycler.
+ import cycler
+ colors = mpl_stylesheet.pop('axes.color_cycle')
+ mpl_stylesheet['axes.prop_cycle'] = cycler.cycler('color_cycle', colors)
+
+
def _get_standard_kind(kind):
return {'density': 'kde'}.get(kind, kind)
@@ -784,7 +826,6 @@ def _kind(self):
_layout_type = 'vertical'
_default_rot = 0
orientation = None
-
_pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog',
'mark_right', 'stacked']
_attr_defaults = {'logy': False, 'logx': False, 'loglog': False,
@@ -973,8 +1014,9 @@ def _maybe_right_yaxis(self, ax, axes_num):
else:
# otherwise, create twin axes
orig_ax, new_ax = ax, ax.twinx()
- new_ax._get_lines.color_cycle = orig_ax._get_lines.color_cycle
-
+ # TODO: use Matplotlib public API when available
+ new_ax._get_lines = orig_ax._get_lines
+ new_ax._get_patches_for_fill = orig_ax._get_patches_for_fill
orig_ax.right_ax, new_ax.left_ax = new_ax, orig_ax
if not self._has_plotted_object(orig_ax): # no data on left y
@@ -1197,6 +1239,14 @@ def plt(self):
import matplotlib.pyplot as plt
return plt
+ @staticmethod
+ def mpl_ge_1_3_1():
+ return _mpl_ge_1_3_1()
+
+ @staticmethod
+ def mpl_ge_1_5_0():
+ return _mpl_ge_1_5_0()
+
_need_to_set_index = False
def _get_xticks(self, convert_period=False):
@@ -1474,9 +1524,6 @@ def __init__(self, data, x, y, s=None, c=None, **kwargs):
self.c = c
def _make_plot(self):
- import matplotlib as mpl
- mpl_ge_1_3_1 = str(mpl.__version__) >= LooseVersion('1.3.1')
-
x, y, c, data = self.x, self.y, self.c, self.data
ax = self.axes[0]
@@ -1488,9 +1535,13 @@ def _make_plot(self):
# pandas uses colormap, matplotlib uses cmap.
cmap = self.colormap or 'Greys'
cmap = self.plt.cm.get_cmap(cmap)
-
- if c is None:
+ color = self.kwds.pop("color", None)
+ if c is not None and color is not None:
+ raise TypeError('Specify exactly one of `c` and `color`')
+ elif c is None and color is None:
c_values = self.plt.rcParams['patch.facecolor']
+ elif color is not None:
+ c_values = color
elif c_is_column:
c_values = self.data[c].values
else:
@@ -1505,7 +1556,7 @@ def _make_plot(self):
if cb:
img = ax.collections[0]
kws = dict(ax=ax)
- if mpl_ge_1_3_1:
+ if self.mpl_ge_1_3_1():
kws['label'] = c if c_is_column else ''
self.fig.colorbar(img, **kws)
@@ -1636,6 +1687,11 @@ def _ts_plot(cls, ax, x, data, style=None, **kwds):
# Set ax with freq info
_decorate_axes(ax, freq, kwds)
+ # digging deeper
+ if hasattr(ax, 'left_ax'):
+ _decorate_axes(ax.left_ax, freq, kwds)
+ if hasattr(ax, 'right_ax'):
+ _decorate_axes(ax.right_ax, freq, kwds)
ax._plot_data.append((data, cls._kind, kwds))
lines = cls._plot(ax, data.index, data.values, style=style, **kwds)
@@ -1743,6 +1799,8 @@ def _plot(cls, ax, x, y, style=None, column_num=None,
if not 'color' in kwds:
kwds['color'] = lines[0].get_color()
+ if cls.mpl_ge_1_5_0(): # mpl 1.5 added real support for poly legends
+ kwds.pop('label')
ax.fill_between(xdata, start, y_values, **kwds)
cls._update_stacker(ax, stacking_id, y)
return lines
diff --git a/pandas/tseries/tests/test_plotting.py b/pandas/tseries/tests/test_plotting.py
index d9b31c0a1d620..bcd1e400d3974 100644
--- a/pandas/tseries/tests/test_plotting.py
+++ b/pandas/tseries/tests/test_plotting.py
@@ -483,6 +483,7 @@ def test_gaps(self):
ts[5:25] = np.nan
ax = ts.plot()
lines = ax.get_lines()
+ tm._skip_if_mpl_1_5()
self.assertEqual(len(lines), 1)
l = lines[0]
data = l.get_xydata()
@@ -532,6 +533,9 @@ def test_gap_upsample(self):
self.assertEqual(len(ax.right_ax.get_lines()), 1)
l = lines[0]
data = l.get_xydata()
+
+ tm._skip_if_mpl_1_5()
+
tm.assertIsInstance(data, np.ma.core.MaskedArray)
mask = data.mask
self.assertTrue(mask[5:25, 1].all())
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 6d443c8fbc380..d70e6349ddef1 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -196,6 +196,14 @@ def setUpClass(cls):
return cls
+def _skip_if_mpl_1_5():
+ import matplotlib
+ v = matplotlib.__version__
+ if v > LooseVersion('1.4.3') or v[0] == '0':
+ import nose
+ raise nose.SkipTest("matplotlib 1.5")
+
+
def _skip_if_no_scipy():
try:
import scipy.stats
| closes https://github.com/pydata/pandas/issues/11111 (nice issue number)
Testing with tox locally I get 1 failure using either matplotlib 1.4 or 1.5. I may have messed up my tox config though. Still need to cleanup a bunch of stuff, I just threw in changes to get each test passing as I went.
release notes et. al coming tonight or tomorrow. Are we making any changes to the build matrix to run a matplotlib 1.5?
| https://api.github.com/repos/pandas-dev/pandas/pulls/11145 | 2015-09-18T19:55:26Z | 2015-09-22T11:29:59Z | 2015-09-22T11:29:59Z | 2016-11-03T12:38:24Z |
Openpyxl22 | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 5ad9af310225d..aea9a80f86735 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -2230,6 +2230,10 @@ Writing Excel Files to Memory
Pandas supports writing Excel files to buffer-like objects such as ``StringIO`` or
``BytesIO`` using :class:`~pandas.io.excel.ExcelWriter`.
+.. versionadded:: 0.17
+
+Added support for Openpyxl >= 2.2
+
.. code-block:: python
# Safe import for either Python 2.x or 3.x
@@ -2279,14 +2283,15 @@ config options <options>` ``io.excel.xlsx.writer`` and
files if `Xlsxwriter`_ is not available.
.. _XlsxWriter: http://xlsxwriter.readthedocs.org
-.. _openpyxl: http://packages.python.org/openpyxl/
+.. _openpyxl: http://openpyxl.readthedocs.org/
.. _xlwt: http://www.python-excel.org
To specify which writer you want to use, you can pass an engine keyword
argument to ``to_excel`` and to ``ExcelWriter``. The built-in engines are:
-- ``openpyxl``: This includes stable support for OpenPyxl 1.6.1 up to but
- not including 2.0.0, and experimental support for OpenPyxl 2.0.0 and later.
+- ``openpyxl``: This includes stable support for Openpyxl from 1.6.1. However,
+ it is advised to use version 2.2 and higher, especially when working with
+ styles.
- ``xlsxwriter``
- ``xlwt``
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index b113cbf057f39..5767af1ad3862 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -57,8 +57,10 @@ def get_writer(engine_name):
# make sure we make the intelligent choice for the user
if LooseVersion(openpyxl.__version__) < '2.0.0':
return _writers['openpyxl1']
+ elif LooseVersion(openpyxl.__version__) < '2.2.0':
+ return _writers['openpyxl20']
else:
- return _writers['openpyxl2']
+ return _writers['openpyxl22']
except ImportError:
# fall through to normal exception handling below
pass
@@ -760,11 +762,11 @@ class _OpenpyxlWriter(_Openpyxl1Writer):
register_writer(_OpenpyxlWriter)
-class _Openpyxl2Writer(_Openpyxl1Writer):
+class _Openpyxl20Writer(_Openpyxl1Writer):
"""
Note: Support for OpenPyxl v2 is currently EXPERIMENTAL (GH7565).
"""
- engine = 'openpyxl2'
+ engine = 'openpyxl20'
openpyxl_majorver = 2
def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
@@ -1172,8 +1174,76 @@ def _convert_to_protection(cls, protection_dict):
return Protection(**protection_dict)
-register_writer(_Openpyxl2Writer)
+register_writer(_Openpyxl20Writer)
+class _Openpyxl22Writer(_Openpyxl20Writer):
+ """
+ Note: Support for OpenPyxl v2.2 is currently EXPERIMENTAL (GH7565).
+ """
+ engine = 'openpyxl22'
+ openpyxl_majorver = 2
+
+ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
+ # Write the frame cells using openpyxl.
+ from openpyxl import styles
+
+ sheet_name = self._get_sheet_name(sheet_name)
+
+ _style_cache = {}
+
+ if sheet_name in self.sheets:
+ wks = self.sheets[sheet_name]
+ else:
+ wks = self.book.create_sheet()
+ wks.title = sheet_name
+ self.sheets[sheet_name] = wks
+
+ for cell in cells:
+ xcell = wks.cell(
+ row=startrow + cell.row + 1,
+ column=startcol + cell.col + 1
+ )
+ xcell.value = _conv_value(cell.val)
+
+ style_kwargs = {}
+ if cell.style:
+ key = str(cell.style)
+ style_kwargs = _style_cache.get(key)
+ if style_kwargs is None:
+ style_kwargs = self._convert_to_style_kwargs(cell.style)
+ _style_cache[key] = style_kwargs
+
+ if style_kwargs:
+ for k, v in style_kwargs.items():
+ setattr(xcell, k, v)
+
+ if cell.mergestart is not None and cell.mergeend is not None:
+
+ wks.merge_cells(
+ start_row=startrow + cell.row + 1,
+ start_column=startcol + cell.col + 1,
+ end_column=startcol + cell.mergeend + 1,
+ end_row=startrow + cell.mergeend + 1
+ )
+
+ # When cells are merged only the top-left cell is preserved
+ # The behaviour of the other cells in a merged range is undefined
+ if style_kwargs:
+ first_row = startrow + cell.row + 1
+ last_row = startrow + cell.mergestart + 1
+ first_col = startcol + cell.col + 1
+ last_col = startcol + cell.mergeend + 1
+
+ for row in range(first_row, last_row + 1):
+ for col in range(first_col, last_col + 1):
+ if row == first_row and col == first_col:
+ # Ignore first cell. It is already handled.
+ continue
+ xcell = wks.cell(column=col, row=row)
+ for k, v in style_kwargs.items():
+ setattr(xcell, k, v)
+
+register_writer(_Openpyxl22Writer)
class _XlwtWriter(ExcelWriter):
engine = 'xlwt'
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 0aee2af6ad166..657789fe8ce9b 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -19,7 +19,7 @@
from pandas.io.parsers import read_csv
from pandas.io.excel import (
ExcelFile, ExcelWriter, read_excel, _XlwtWriter, _Openpyxl1Writer,
- _Openpyxl2Writer, register_writer, _XlsxWriter
+ _Openpyxl20Writer, _Openpyxl22Writer, register_writer, _XlsxWriter
)
from pandas.io.common import URLError
from pandas.util.testing import ensure_clean, makeCustomDataframe as mkdf
@@ -1470,17 +1470,28 @@ def test_to_excel_styleconverter(self):
xlsx_style.alignment.vertical)
+def skip_openpyxl_gt21(cls):
+ """Skip a TestCase instance if openpyxl >= 2.2"""
+
+ @classmethod
+ def setUpClass(cls):
+ _skip_if_no_openpyxl()
+ import openpyxl
+ ver = openpyxl.__version__
+ if not (ver >= LooseVersion('2.0.0') and ver < LooseVersion('2.2.0')):
+ raise nose.SkipTest("openpyxl >= 2.2")
+
+ cls.setUpClass = setUpClass
+ return cls
+
@raise_on_incompat_version(2)
-class Openpyxl2Tests(ExcelWriterBase, tm.TestCase):
+@skip_openpyxl_gt21
+class Openpyxl20Tests(ExcelWriterBase, tm.TestCase):
ext = '.xlsx'
- engine_name = 'openpyxl2'
+ engine_name = 'openpyxl20'
check_skip = staticmethod(lambda *args, **kwargs: None)
def test_to_excel_styleconverter(self):
- _skip_if_no_openpyxl()
- if not openpyxl_compat.is_compat(major_ver=2):
- raise nose.SkipTest('incompatiable openpyxl version')
-
import openpyxl
from openpyxl import styles
@@ -1532,7 +1543,7 @@ def test_to_excel_styleconverter(self):
protection = styles.Protection(locked=True, hidden=False)
- kw = _Openpyxl2Writer._convert_to_style_kwargs(hstyle)
+ kw = _Openpyxl20Writer._convert_to_style_kwargs(hstyle)
self.assertEqual(kw['font'], font)
self.assertEqual(kw['border'], border)
self.assertEqual(kw['alignment'], alignment)
@@ -1542,7 +1553,116 @@ def test_to_excel_styleconverter(self):
def test_write_cells_merge_styled(self):
+ from pandas.core.format import ExcelCell
+ from openpyxl import styles
+
+ sheet_name='merge_styled'
+
+ sty_b1 = {'font': {'color': '00FF0000'}}
+ sty_a2 = {'font': {'color': '0000FF00'}}
+
+ initial_cells = [
+ ExcelCell(col=1, row=0, val=42, style=sty_b1),
+ ExcelCell(col=0, row=1, val=99, style=sty_a2),
+ ]
+
+ sty_merged = {'font': { 'color': '000000FF', 'bold': True }}
+ sty_kwargs = _Openpyxl20Writer._convert_to_style_kwargs(sty_merged)
+ openpyxl_sty_merged = styles.Style(**sty_kwargs)
+ merge_cells = [
+ ExcelCell(col=0, row=0, val='pandas',
+ mergestart=1, mergeend=1, style=sty_merged),
+ ]
+
+ with ensure_clean('.xlsx') as path:
+ writer = _Openpyxl20Writer(path)
+ writer.write_cells(initial_cells, sheet_name=sheet_name)
+ writer.write_cells(merge_cells, sheet_name=sheet_name)
+
+ wks = writer.sheets[sheet_name]
+ xcell_b1 = wks.cell('B1')
+ xcell_a2 = wks.cell('A2')
+ self.assertEqual(xcell_b1.style, openpyxl_sty_merged)
+ self.assertEqual(xcell_a2.style, openpyxl_sty_merged)
+
+def skip_openpyxl_lt22(cls):
+ """Skip a TestCase instance if openpyxl < 2.2"""
+
+ @classmethod
+ def setUpClass(cls):
_skip_if_no_openpyxl()
+ import openpyxl
+ ver = openpyxl.__version__
+ if ver < LooseVersion('2.2.0'):
+ raise nose.SkipTest("openpyxl < 2.2")
+
+ cls.setUpClass = setUpClass
+ return cls
+
+@raise_on_incompat_version(2)
+@skip_openpyxl_lt22
+class Openpyxl22Tests(ExcelWriterBase, tm.TestCase):
+ ext = '.xlsx'
+ engine_name = 'openpyxl22'
+ check_skip = staticmethod(lambda *args, **kwargs: None)
+
+ def test_to_excel_styleconverter(self):
+ import openpyxl
+ from openpyxl import styles
+
+ hstyle = {
+ "font": {
+ "color": '00FF0000',
+ "bold": True,
+ },
+ "borders": {
+ "top": "thin",
+ "right": "thin",
+ "bottom": "thin",
+ "left": "thin",
+ },
+ "alignment": {
+ "horizontal": "center",
+ "vertical": "top",
+ },
+ "fill": {
+ "patternType": 'solid',
+ 'fgColor': {
+ 'rgb': '006666FF',
+ 'tint': 0.3,
+ },
+ },
+ "number_format": {
+ "format_code": "0.00"
+ },
+ "protection": {
+ "locked": True,
+ "hidden": False,
+ },
+ }
+
+ font_color = styles.Color('00FF0000')
+ font = styles.Font(bold=True, color=font_color)
+ side = styles.Side(style=styles.borders.BORDER_THIN)
+ border = styles.Border(top=side, right=side, bottom=side, left=side)
+ alignment = styles.Alignment(horizontal='center', vertical='top')
+ fill_color = styles.Color(rgb='006666FF', tint=0.3)
+ fill = styles.PatternFill(patternType='solid', fgColor=fill_color)
+
+ number_format = '0.00'
+
+ protection = styles.Protection(locked=True, hidden=False)
+
+ kw = _Openpyxl22Writer._convert_to_style_kwargs(hstyle)
+ self.assertEqual(kw['font'], font)
+ self.assertEqual(kw['border'], border)
+ self.assertEqual(kw['alignment'], alignment)
+ self.assertEqual(kw['fill'], fill)
+ self.assertEqual(kw['number_format'], number_format)
+ self.assertEqual(kw['protection'], protection)
+
+
+ def test_write_cells_merge_styled(self):
if not openpyxl_compat.is_compat(major_ver=2):
raise nose.SkipTest('incompatiable openpyxl version')
@@ -1560,23 +1680,23 @@ def test_write_cells_merge_styled(self):
]
sty_merged = {'font': { 'color': '000000FF', 'bold': True }}
- sty_kwargs = _Openpyxl2Writer._convert_to_style_kwargs(sty_merged)
- openpyxl_sty_merged = styles.Style(**sty_kwargs)
+ sty_kwargs = _Openpyxl22Writer._convert_to_style_kwargs(sty_merged)
+ openpyxl_sty_merged = sty_kwargs['font']
merge_cells = [
ExcelCell(col=0, row=0, val='pandas',
mergestart=1, mergeend=1, style=sty_merged),
]
with ensure_clean('.xlsx') as path:
- writer = _Openpyxl2Writer(path)
+ writer = _Openpyxl22Writer(path)
writer.write_cells(initial_cells, sheet_name=sheet_name)
writer.write_cells(merge_cells, sheet_name=sheet_name)
wks = writer.sheets[sheet_name]
xcell_b1 = wks.cell('B1')
xcell_a2 = wks.cell('A2')
- self.assertEqual(xcell_b1.style, openpyxl_sty_merged)
- self.assertEqual(xcell_a2.style, openpyxl_sty_merged)
+ self.assertEqual(xcell_b1.font, openpyxl_sty_merged)
+ self.assertEqual(xcell_a2.font, openpyxl_sty_merged)
class XlwtTests(ExcelWriterBase, tm.TestCase):
@@ -1676,9 +1796,9 @@ def test_column_format(self):
cell = read_worksheet.cell('B2')
try:
- read_num_format = cell.style.number_format._format_code
+ read_num_format = cell.number_format
except:
- read_num_format = cell.style.number_format
+ read_num_format = cell.style.number_format._format_code
self.assertEqual(read_num_format, num_format)
diff --git a/tox.ini b/tox.ini
index b11a71f531524..9fbb15087c4d5 100644
--- a/tox.ini
+++ b/tox.ini
@@ -14,7 +14,6 @@ deps =
python-dateutil
beautifulsoup4
lxml
- openpyxl<2.0.0
xlsxwriter
xlrd
six
@@ -70,3 +69,24 @@ deps =
deps =
numpy==1.8.0
{[testenv]deps}
+
+[testenv:openpyxl1]
+usedevelop = True
+deps =
+ {[testenv]deps}
+ openpyxl<2.0.0
+commands = {envbindir}/nosetests {toxinidir}/pandas/io/tests/test_excel.py
+
+[testenv:openpyxl20]
+usedevelop = True
+deps =
+ {[testenv]deps}
+ openpyxl<2.2.0
+commands = {envbindir}/nosetests {posargs} {toxinidir}/pandas/io/tests/test_excel.py
+
+[testenv:openpyxl22]
+usedevelop = True
+deps =
+ {[testenv]deps}
+ openpyxl>=2.2.0
+commands = {envbindir}/nosetests {posargs} {toxinidir}/pandas/io/tests/test_excel.py
| closes #10125
I've added preliminary tests for openpyxl >= 2.2 styles. Unfortunately, I don't know how to get a whole test class to be skipped so tests will only run with either the Openpyxl20 or Openpyxl22 test class disabled, depending upon which version is installed. I hope this can be fixed fairly easily. Some code somewhere is still calling `openpyxl.styles.Style()` which needs changing. The aggregate Style object is an irrelevancy in client code.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11144 | 2015-09-18T17:29:52Z | 2015-09-22T14:12:37Z | null | 2017-11-28T11:37:59Z |
BUG: Issue in the gbq module when authenticating on remote servers #8489 | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 014daa3f68dbb..e04d2ae569d23 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -4059,6 +4059,7 @@ The key functions are:
.. autosummary::
:toctree: generated/
+ authorize
read_gbq
to_gbq
@@ -4066,6 +4067,22 @@ The key functions are:
.. _io.bigquery_reader:
+Authorization
+'''''''''''''
+
+Authorization is required in order to use the BigQuery API. You must call the
+:func:`~pandas.io.gbq.authorize` function to start the authorization process. In general,
+this is as simple as following the prompts in a browser. A code will be provided to complete
+the process. A credentials file will be saved to disk so that you only need to authorize once
+as long as the credentials have not been revoked. Additional information on the authentication
+can be found `here <https://cloud.google.com/bigquery/authentication?hl=en/>`__.
+
+To begin the authorization process, use the :func:`~pandas.io.gbq.authorize` function
+
+.. code-block:: python
+
+ gbq.authorize()
+
Querying
''''''''
@@ -4080,13 +4097,6 @@ into a DataFrame using the :func:`~pandas.io.gbq.read_gbq` function.
data_frame = pd.read_gbq('SELECT * FROM test_dataset.test_table', projectid)
-You will then be authenticated to the specified BigQuery account
-via Google's Oauth2 mechanism. In general, this is as simple as following the
-prompts in a browser window which will be opened for you. Should the browser not
-be available, or fail to launch, a code will be provided to complete the process
-manually. Additional information on the authentication mechanism can be found
-`here <https://developers.google.com/accounts/docs/OAuth2#clientside/>`__.
-
You can define which column from BigQuery to use as an index in the
destination DataFrame as well as a preferred column order as follows:
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 6d4b61bb97f22..7657b74a3bb78 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -23,6 +23,8 @@ Enhancements
.. _whatsnew_0171.enhancements.other:
- Improve the error message in :func:`pandas.io.gbq.to_gbq` when a streaming insert fails (:issue:`11285`)
+- Added :func:`pandas.io.gbq.authorize` to allow users to authenticate with Google BigQuery.
+ See the :ref:`docs <io.bigquery>` for more details (:issue:`11141`).
Other Enhancements
^^^^^^^^^^^^^^^^^^
@@ -97,3 +99,4 @@ Bug Fixes
- Fixed a bug that prevented the construction of an empty series of dtype
``datetime64[ns, tz]`` (:issue:`11245`).
- Bug in ``DataFrame.to_dict()`` produces a ``np.datetime64`` object instead of ``Timestamp`` when only datetime is present in data (:issue:`11327`)
+- Resolve the issue where authentication on remote servers fails silently when using the gbq module. (:issue:`11141`)
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index e7241036b94c4..d68466316586b 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -15,6 +15,8 @@
from pandas.util.decorators import deprecate
from pandas.compat import lzip, bytes_to_str
+CREDENTIALS_FILE = 'bigquery_credentials.dat'
+
def _check_google_client_version():
try:
@@ -109,7 +111,7 @@ class TableCreationError(PandasError, ValueError):
class GbqConnector(object):
- def __init__(self, project_id, reauth=False):
+ def __init__(self, project_id=None, reauth=False):
self.test_google_api_imports()
self.project_id = project_id
self.reauth = reauth
@@ -128,23 +130,44 @@ def test_google_api_imports(self):
except ImportError as e:
raise ImportError("Missing module required for Google BigQuery support: {0}".format(str(e)))
- def get_credentials(self):
+ def authorize(self):
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
- from oauth2client.tools import run_flow, argparser
_check_google_client_version()
+ storage = Storage(CREDENTIALS_FILE)
flow = OAuth2WebServerFlow(client_id='495642085510-k0tmvj2m941jhre2nbqka17vqpjfddtd.apps.googleusercontent.com',
client_secret='kOc9wMptUtxkcIFbtZCcrEAc',
scope='https://www.googleapis.com/auth/bigquery',
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
+ print('Please visit the following url to obtain an authorization code: {0}'.format(flow.step1_get_authorize_url()))
+
+ authorization_prompt_message = 'Enter authorization code and press enter: '
+
+ if compat.PY3:
+ code = eval(input(authorization_prompt_message))
+ else:
+ code = raw_input(authorization_prompt_message)
- storage = Storage('bigquery_credentials.dat')
+ code.strip()
+ storage.put(flow.step2_exchange(code))
credentials = storage.get()
- if credentials is None or credentials.invalid or self.reauth:
- credentials = run_flow(flow, storage, argparser.parse_args([]))
+ return credentials
+
+ def get_credentials(self):
+ from oauth2client.file import Storage
+
+ _check_google_client_version()
+
+ credentials = Storage(CREDENTIALS_FILE).get()
+
+ if self.reauth:
+ credentials = self.authorize()
+
+ if credentials is None or credentials.invalid:
+ raise AccessDenied("The credentials are missing or invalid. Please run gbq.authorize().")
return credentials
@@ -215,8 +238,8 @@ def run_query(self, query, verbose=True):
try:
query_reply = job_collection.insert(projectId=self.project_id, body=job_data).execute()
except AccessTokenRefreshError:
- raise AccessDenied("The credentials have been revoked or expired, please re-run the application "
- "to re-authorize")
+ raise AccessDenied("The credentials have been revoked or expired, please run gbq.authorize() "
+ "to re-authorize.")
except HttpError as ex:
self.process_http_error(ex)
@@ -518,6 +541,12 @@ def to_gbq(dataframe, destination_table, project_id, chunksize=10000,
connector.load_data(dataframe, dataset_id, table_id, chunksize, verbose)
+def authorize():
+ """ Allows users to create the credentials file required for BigQuery authorization """
+
+ GbqConnector(reauth=True)
+
+
def generate_bq_schema(df, default_type='STRING'):
# deprecation TimeSeries, #11121
@@ -526,6 +555,7 @@ def generate_bq_schema(df, default_type='STRING'):
return _generate_bq_schema(df, default_type=default_type)
+
def _generate_bq_schema(df, default_type='STRING'):
""" Given a passed df, generate the associated Google BigQuery schema.
@@ -554,6 +584,7 @@ def _generate_bq_schema(df, default_type='STRING'):
return {'fields': fields}
+
class _Table(GbqConnector):
def __init__(self, project_id, dataset_id, reauth=False):
diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py
index cc1e901d8f119..f3df2bfa0959b 100644
--- a/pandas/io/tests/test_gbq.py
+++ b/pandas/io/tests/test_gbq.py
@@ -29,7 +29,7 @@
_SETUPTOOLS_INSTALLED = False
-def _test_imports():
+def validate_imports():
global _GOOGLE_API_CLIENT_INSTALLED, _GOOGLE_API_CLIENT_VALID_VERSION, \
_HTTPLIB2_INSTALLED, _SETUPTOOLS_INSTALLED
@@ -83,13 +83,22 @@ def _test_imports():
raise ImportError("pandas requires httplib2 for Google BigQuery support")
-def test_requirements():
+def validate_requirements():
try:
- _test_imports()
+ validate_imports()
except (ImportError, NotImplementedError) as import_exception:
raise nose.SkipTest(import_exception)
+def validate_authorization():
+ try:
+ gbq.GbqConnector(PROJECT_ID)
+ except gbq.AccessDenied:
+ gbq.authorize()
+ except ImportError as import_exception:
+ raise nose.SkipTest(import_exception)
+
+
def clean_gbq_environment():
dataset = gbq._Dataset(PROJECT_ID)
@@ -126,12 +135,20 @@ def test_generate_bq_schema_deprecated():
gbq.generate_bq_schema(df)
class TestGBQConnectorIntegration(tm.TestCase):
- def setUp(self):
- test_requirements()
+
+ @classmethod
+ def setUpClass(cls):
+ # - GLOBAL CLASS FIXTURES -
+ # put here any instruction you want to execute only *ONCE* *BEFORE* executing *ALL* tests
+ # described below.
if not PROJECT_ID:
raise nose.SkipTest("Cannot run integration tests without a project id")
+ validate_requirements()
+ validate_authorization()
+
+ def setUp(self):
self.sut = gbq.GbqConnector(PROJECT_ID)
def test_should_be_able_to_make_a_connector(self):
@@ -157,7 +174,7 @@ def test_should_be_able_to_get_results_from_query(self):
class TestReadGBQUnitTests(tm.TestCase):
def setUp(self):
- test_requirements()
+ validate_requirements()
def test_should_return_bigquery_integers_as_python_floats(self):
result = gbq._parse_entry(1, 'INTEGER')
@@ -201,6 +218,7 @@ def test_that_parse_data_works_properly(self):
class TestReadGBQIntegration(tm.TestCase):
+
@classmethod
def setUpClass(cls):
# - GLOBAL CLASS FIXTURES -
@@ -210,7 +228,7 @@ def setUpClass(cls):
if not PROJECT_ID:
raise nose.SkipTest("Cannot run integration tests without a project id")
- test_requirements()
+ validate_requirements()
def setUp(self):
# - PER-TEST FIXTURES -
@@ -373,7 +391,8 @@ def setUpClass(cls):
if not PROJECT_ID:
raise nose.SkipTest("Cannot run integration tests without a project id")
- test_requirements()
+ validate_requirements()
+ validate_authorization()
clean_gbq_environment()
gbq._Dataset(PROJECT_ID).create(DATASET_ID + "1")
| Resolve issue where gbq authentication on remote servers fails silently.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11141 | 2015-09-18T02:10:10Z | 2015-10-16T23:29:05Z | null | 2015-10-16T23:33:49Z |
BUG: remove midrule in latex output with header=False | diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 736554672a089..d27616ae12649 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -42,3 +42,5 @@ Performance Improvements
Bug Fixes
~~~~~~~~~
+
+- Bug in ``DataFrame.to_latex()`` produces an extra rule when ``header=False`` (:issue:`7124`)
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 5f12abb543513..c1dbc6d939171 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -668,7 +668,7 @@ def write(buf, frame, column_format, strcols, longtable=False):
nlevels = frame.columns.nlevels
for i, row in enumerate(zip(*strcols)):
- if i == nlevels:
+ if i == nlevels and self.header:
buf.write('\\midrule\n') # End of header
if longtable:
buf.write('\\endhead\n')
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index b5220c8cb2706..f451a16da3021 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -2749,6 +2749,30 @@ def test_to_latex_escape_special_chars(self):
"""
self.assertEqual(observed, expected)
+ def test_to_latex_no_header(self):
+ # GH 7124
+ df = DataFrame({'a': [1, 2],
+ 'b': ['b1', 'b2']})
+ withindex_result = df.to_latex(header=False)
+ withindex_expected = r"""\begin{tabular}{lrl}
+\toprule
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\bottomrule
+\end{tabular}
+"""
+ self.assertEqual(withindex_result, withindex_expected)
+
+ withoutindex_result = df.to_latex(index=False, header=False)
+ withoutindex_expected = r"""\begin{tabular}{rl}
+\toprule
+ 1 & b1 \\
+ 2 & b2 \\
+\bottomrule
+\end{tabular}
+"""
+ self.assertEqual(withoutindex_result, withoutindex_expected)
+
def test_to_csv_quotechar(self):
df = DataFrame({'col' : [1,2]})
expected = """\
| This bug fix addresses issue #7124. If `to_latex` is called with option `header=False`, the output should not contain a `\midrule` which is used to separate the column headers from the data.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11140 | 2015-09-18T01:56:09Z | 2015-10-09T13:21:28Z | null | 2015-10-09T13:21:28Z |
TST: Verify fix for buffer overflow in read_csv with engine='c' | diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 6b7132aea3280..c9ae2f6029530 100755
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -2293,6 +2293,13 @@ def test_chunk_begins_with_newline_whitespace(self):
result = self.read_csv(StringIO(data), header=None)
self.assertEqual(len(result), 2)
+ # GH 9735
+ chunk1 = 'a' * (1024 * 256 - 2) + '\na'
+ chunk2 = '\n a'
+ result = pd.read_csv(StringIO(chunk1 + chunk2), header=None)
+ expected = pd.DataFrame(['a' * (1024 * 256 - 2), 'a', ' a'])
+ tm.assert_frame_equal(result, expected)
+
def test_empty_with_index(self):
# GH 10184
data = 'x,y'
| Tests for the bug in GH #9735, which was previously fixed in GH #10023.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11138 | 2015-09-17T19:55:56Z | 2015-09-17T23:45:20Z | 2015-09-17T23:45:20Z | 2015-09-18T09:14:24Z |
DEPR: Series.is_timeseries | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 070d3bff42c92..2be7194af34b0 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -964,6 +964,7 @@ Deprecations
``DataFrame.add(other, fill_value=0)`` and ``DataFrame.mul(other, fill_value=1.)``
(:issue:`10735`).
- ``TimeSeries`` deprecated in favor of ``Series`` (note that this has been alias since 0.13.0), (:issue:`10890`)
+- ``Series.is_time_series`` deprecated in favor of ``Series.index.is_all_dates`` (:issue:`11135`)
- Legacy offsets (like ``'A@JAN'``) listed in :ref:`here <timeseries.legacyaliases>` are deprecated (note that this has been alias since 0.8.0), (:issue:`10878`)
- ``WidePanel`` deprecated in favor of ``Panel``, ``LongPanel`` in favor of ``DataFrame`` (note these have been aliases since < 0.11.0), (:issue:`10892`)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 7f2573ce5bdde..05a2ff6840d62 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -251,7 +251,11 @@ def _can_hold_na(self):
@property
def is_time_series(self):
- return self._subtyp in ['time_series', 'sparse_time_series']
+ msg = "is_time_series is deprecated. Please use Series.index.is_all_dates"
+ warnings.warn(msg, FutureWarning, stacklevel=2)
+ # return self._subtyp in ['time_series', 'sparse_time_series']
+ return self.index.is_all_dates
+
_index = None
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 7fb89b30cec97..2060b31511ead 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -703,11 +703,15 @@ def test_TimeSeries_deprecation(self):
def test_constructor(self):
# Recognize TimeSeries
- self.assertTrue(self.ts.is_time_series)
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertTrue(self.ts.is_time_series)
+ self.assertTrue(self.ts.index.is_all_dates)
# Pass in Series
derived = Series(self.ts)
- self.assertTrue(derived.is_time_series)
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertTrue(derived.is_time_series)
+ self.assertTrue(derived.index.is_all_dates)
self.assertTrue(tm.equalContents(derived.index, self.ts.index))
# Ensure new index is not created
@@ -718,9 +722,12 @@ def test_constructor(self):
self.assertEqual(mixed.dtype, np.object_)
self.assertIs(mixed[1], np.NaN)
- self.assertFalse(self.empty.is_time_series)
- self.assertFalse(Series({}).is_time_series)
-
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertFalse(self.empty.is_time_series)
+ self.assertFalse(self.empty.index.is_all_dates)
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertFalse(Series({}).is_time_series)
+ self.assertFalse(Series({}).index.is_all_dates)
self.assertRaises(Exception, Series, np.random.randn(3, 3),
index=np.arange(3))
@@ -7693,12 +7700,16 @@ def test_set_index_makes_timeseries(self):
s = Series(lrange(10))
s.index = idx
- self.assertTrue(s.is_time_series == True)
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertTrue(s.is_time_series == True)
+ self.assertTrue(s.index.is_all_dates == True)
def test_timeseries_coercion(self):
idx = tm.makeDateIndex(10000)
ser = Series(np.random.randn(len(idx)), idx.astype(object))
- self.assertTrue(ser.is_time_series)
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertTrue(ser.is_time_series)
+ self.assertTrue(ser.index.is_all_dates)
self.assertIsInstance(ser.index, DatetimeIndex)
def test_replace(self):
| Follow-up for #10890. Deprecate `Series.is_timeseries`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11135 | 2015-09-17T14:35:38Z | 2015-09-17T15:36:06Z | 2015-09-17T15:36:06Z | 2015-09-17T15:36:08Z |
BUG: nested construction with timedelta #11129 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 0b4acdc3e89bb..4d020c4fc768f 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1154,3 +1154,4 @@ Bug Fixes
- Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`)
- Bug in ``Index`` dtype may not applied properly (:issue:`11017`)
- Bug in ``io.gbq`` when testing for minimum google api client version (:issue:`10652`)
+- Bug in ``DataFrame`` construction from nested ``dict`` with ``timedelta`` keys (:issue:`11129`)
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 8ffffae6bd160..0d9baad9f5d5e 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1851,9 +1851,9 @@ def _maybe_box(indexer, values, obj, key):
def _maybe_box_datetimelike(value):
# turn a datetime like into a Timestamp/timedelta as needed
- if isinstance(value, np.datetime64):
+ if isinstance(value, (np.datetime64, datetime)):
value = tslib.Timestamp(value)
- elif isinstance(value, np.timedelta64):
+ elif isinstance(value, (np.timedelta64, timedelta)):
value = tslib.Timedelta(value)
return value
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 24de36d95794c..f46918dd88f47 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3037,6 +3037,29 @@ def create_data(constructor):
assert_frame_equal(result_datetime, expected)
assert_frame_equal(result_Timestamp, expected)
+ def test_constructor_dict_timedelta64_index(self):
+ # GH 10160
+ td_as_int = [1, 2, 3, 4]
+
+ def create_data(constructor):
+ return dict((i, {constructor(s): 2*i}) for i, s in enumerate(td_as_int))
+
+ data_timedelta64 = create_data(lambda x: np.timedelta64(x, 'D'))
+ data_timedelta = create_data(lambda x: timedelta(days=x))
+ data_Timedelta = create_data(lambda x: Timedelta(x, 'D'))
+
+ expected = DataFrame([{0: 0, 1: None, 2: None, 3: None},
+ {0: None, 1: 2, 2: None, 3: None},
+ {0: None, 1: None, 2: 4, 3: None},
+ {0: None, 1: None, 2: None, 3: 6}],
+ index=[Timedelta(td, 'D') for td in td_as_int])
+
+ result_timedelta64 = DataFrame(data_timedelta64)
+ result_timedelta = DataFrame(data_timedelta)
+ result_Timedelta = DataFrame(data_Timedelta)
+ assert_frame_equal(result_timedelta64, expected)
+ assert_frame_equal(result_timedelta, expected)
+ assert_frame_equal(result_Timedelta, expected)
def _check_basic_constructor(self, empty):
"mat: 2d matrix with shpae (3, 2) to input. empty - makes sized objects"
diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py
index 69dc70698ca28..45b98b0f85b1c 100644
--- a/pandas/tseries/tests/test_timedeltas.py
+++ b/pandas/tseries/tests/test_timedeltas.py
@@ -885,6 +885,24 @@ def test_pickle(self):
v_p = self.round_trip_pickle(v)
self.assertEqual(v,v_p)
+ def test_timedelta_hash_equality(self):
+ #GH 11129
+ v = Timedelta(1, 'D')
+ td = timedelta(days=1)
+ self.assertEqual(hash(v), hash(td))
+
+ d = {td: 2}
+ self.assertEqual(d[v], 2)
+
+ tds = timedelta_range('1 second', periods=20)
+ self.assertTrue(
+ all(hash(td) == hash(td.to_pytimedelta()) for td in tds))
+
+ # python timedeltas drop ns resolution
+ ns_td = Timedelta(1, 'ns')
+ self.assertNotEqual(hash(ns_td), hash(ns_td.to_pytimedelta()))
+
+
class TestTimedeltaIndex(tm.TestCase):
_multiprocess_can_split_ = True
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index def3764c1113c..7b3e404f7504c 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -2061,7 +2061,10 @@ cdef class _Timedelta(timedelta):
int64_t _sign, _d, _h, _m, _s, _ms, _us, _ns
def __hash__(_Timedelta self):
- return hash(self.value)
+ if self._has_ns():
+ return hash(self.value)
+ else:
+ return timedelta.__hash__(self)
def __richcmp__(_Timedelta self, object other, int op):
cdef:
@@ -2110,63 +2113,63 @@ cdef class _Timedelta(timedelta):
cdef float64_t frac
if self.is_populated:
- return
+ return
# put frac in seconds
- frac = float(ivalue)/1e9
+ frac = float(ivalue)/1e9
if frac < 0:
- self._sign = -1
-
- # even fraction
- if int(-frac/86400) != -frac/86400.0:
- self._d = int(-frac/86400.0+1)
- frac += 86400*self._d
- else:
- frac = -frac
+ self._sign = -1
+
+ # even fraction
+ if int(-frac/86400) != -frac/86400.0:
+ self._d = int(-frac/86400.0+1)
+ frac += 86400*self._d
+ else:
+ frac = -frac
else:
- self._sign = 1
- self._d = 0
+ self._sign = 1
+ self._d = 0
if frac >= 86400:
- self._d += int(frac / 86400)
- frac -= self._d * 86400
+ self._d += int(frac / 86400)
+ frac -= self._d * 86400
if frac >= 3600:
- self._h = int(frac / 3600)
- frac -= self._h * 3600
+ self._h = int(frac / 3600)
+ frac -= self._h * 3600
else:
- self._h = 0
+ self._h = 0
if frac >= 60:
- self._m = int(frac / 60)
- frac -= self._m * 60
+ self._m = int(frac / 60)
+ frac -= self._m * 60
else:
- self._m = 0
+ self._m = 0
if frac >= 0:
- self._s = int(frac)
- frac -= self._s
+ self._s = int(frac)
+ frac -= self._s
else:
- self._s = 0
+ self._s = 0
if frac != 0:
- # reset so we don't lose precision
- sfrac = int((self._h*3600 + self._m*60 + self._s)*1e9)
- if self._sign < 0:
- ifrac = ivalue + self._d*DAY_NS - sfrac
- else:
- ifrac = ivalue - (self._d*DAY_NS + sfrac)
-
- self._ms = int(ifrac/1e6)
- ifrac -= self._ms*1000*1000
- self._us = int(ifrac/1e3)
- ifrac -= self._us*1000
- self._ns = ifrac
+ # reset so we don't lose precision
+ sfrac = int((self._h*3600 + self._m*60 + self._s)*1e9)
+ if self._sign < 0:
+ ifrac = ivalue + self._d*DAY_NS - sfrac
+ else:
+ ifrac = ivalue - (self._d*DAY_NS + sfrac)
+
+ self._ms = int(ifrac/1e6)
+ ifrac -= self._ms*1000*1000
+ self._us = int(ifrac/1e3)
+ ifrac -= self._us*1000
+ self._ns = ifrac
else:
- self._ms = 0
- self._us = 0
- self._ns = 0
+ self._ms = 0
+ self._us = 0
+ self._ns = 0
self.is_populated = 1
@@ -2177,6 +2180,9 @@ cdef class _Timedelta(timedelta):
"""
return timedelta(microseconds=int(self.value)/1000)
+ cpdef bint _has_ns(self):
+ return self.value % 1000 != 0
+
# components named tuple
Components = collections.namedtuple('Components',['days','hours','minutes','seconds','milliseconds','microseconds','nanoseconds'])
@@ -2433,7 +2439,7 @@ class Timedelta(_Timedelta):
"""
self._ensure_components()
return self._ns
-
+
def total_seconds(self):
"""
Total duration of timedelta in seconds (to ns precision)
| Closes #11129
Per discussion in issue this adds similar hash equality to `_Timedelta` / `datetime.timedelta`
that exists for `_Timestamp` / `datetime.datime`.
I tried inlining `_Timedelta._ensure_components` and it actually hurt performance a bit, so I left it
as a plain `def` but did build a seperate `_has_ns` check for hashing.
Adds a little overhead to hashing:
```
In [1]: tds = pd.timedelta_range('1 day', periods=100000)
# PR
In [2]: %timeit [hash(td) for td in tds]
1 loops, best of 3: 810 ms per loop
# Master
In [2]: %timeit [hash(td) for td in tds]
1 loops, best of 3: 765 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11134 | 2015-09-17T01:34:38Z | 2015-09-17T11:45:05Z | 2015-09-17T11:45:05Z | 2015-09-17T22:31:12Z |
API: convert_objects, xref #11116, instead of warning, raise a ValueError | diff --git a/pandas/core/common.py b/pandas/core/common.py
index 9189b0d89de4f..5784f7966d1f6 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -2,6 +2,7 @@
Misc tools for implementing data structures
"""
+import warnings
import re
import collections
import numbers
@@ -1868,7 +1869,12 @@ def _possibly_convert_objects(values,
conversion_count = sum((datetime, numeric, timedelta))
if conversion_count == 0:
- import warnings
+
+ if coerce:
+ raise ValueError("coerce=True was provided, with no options for conversions."
+ "excatly one of 'datetime', 'numeric' or "
+ "'timedelta' must be True when when coerce=True.")
+
warnings.warn('Must explicitly pass type for conversion. Defaulting to '
'pre-0.17 behavior where datetime=True, numeric=True, '
'timedelta=True and coerce=False', DeprecationWarning)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6aec297c31d2b..152e4ce465a8e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2564,24 +2564,11 @@ def convert_objects(self, datetime=False, numeric=False,
converted : same as input object
"""
- # Deprecation code to handle usage change
- issue_warning = False
- if datetime == 'coerce':
- datetime = coerce = True
- numeric = timedelta = False
- issue_warning = True
- elif numeric == 'coerce':
- numeric = coerce = True
- datetime = timedelta = False
- issue_warning = True
- elif timedelta == 'coerce':
- timedelta = coerce = True
- datetime = numeric = False
- issue_warning = True
- if issue_warning:
- warnings.warn("The use of 'coerce' as an input is deprecated. "
- "Instead set coerce=True.",
- FutureWarning)
+ # passing 'coerce' is deprecated, but we don't want to accidently
+ # force conversions
+ if datetime == 'coerce' or numeric == 'coerce' or timedelta == 'coerce':
+ raise ValueError("The use of 'coerce' as an input is deprecated. "
+ "Instead set coerce=True.")
return self._constructor(
self._data.convert(datetime=datetime,
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 7fb89b30cec97..7b7cdc9b7a19d 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -6492,29 +6492,34 @@ def test_convert_objects(self):
# Remove test after deprecation to convert_objects is final
def test_convert_objects_old_style_deprecation(self):
s = Series(['foo', 'bar', 1, 1.0], dtype='O')
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', FutureWarning)
- new_style = s.convert_objects(datetime=True, coerce=True)
- old_style = s.convert_objects(convert_dates='coerce')
- self.assertEqual(len(w), 2)
- assert_series_equal(new_style, old_style)
-
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', FutureWarning)
- new_style = s.convert_objects(numeric=True, coerce=True)
- old_style = s.convert_objects(convert_numeric='coerce')
- self.assertEqual(len(w), 2)
- assert_series_equal(new_style, old_style)
+ def f():
+ with tm.assert_produces_warning(FutureWarning):
+ s.convert_objects(convert_dates='coerce')
+ self.assertRaises(ValueError, f)
+ def f():
+ with tm.assert_produces_warning(FutureWarning):
+ s.convert_objects(convert_numeric='coerce')
+ self.assertRaises(ValueError, f)
dt = datetime(2001, 1, 1, 0, 0)
td = dt - datetime(2000, 1, 1, 0, 0)
s = Series(['a', '3.1415', dt, td])
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter('always', FutureWarning)
- new_style = s.convert_objects(timedelta=True, coerce=True)
- old_style = s.convert_objects(convert_timedeltas='coerce')
- self.assertEqual(len(w), 2)
- assert_series_equal(new_style, old_style)
+
+ def f():
+ with tm.assert_produces_warning(FutureWarning):
+ s.convert_objects(convert_timedeltas='coerce')
+ self.assertRaises(ValueError, f)
+
+ # back-compat xref GH 11116
+ data = """foo,bar
+2015-09-14,True
+2015-09-15,
+"""
+ df = pd.read_csv(StringIO(data),sep=',')
+
+ # we want to be vocal about the changes
+ self.assertRaises(ValueError, lambda : df.convert_objects(coerce=True))
+ self.assertRaises(ValueError, lambda : df.convert_objects('coerce'))
def test_convert_objects_no_arg_warning(self):
s = Series(['1.0','2'])
| closes #11116
This is a lot more noisy that the current impl. It pretty much raises on the old-style input if it had `coerce` in it. This is correct as the actual behavior of `coerce` has changed (in that it now it much more strict).
errror on old-style input
- raise a ValueError for df.convert_objects('coerce')
- raise a ValueError for df.convert_objects(convert_dates='coerce') (and convert_numeric,convert_timedelta)
```
In [1]: data = """foo,bar
...: 2015-09-14,True
...: 2015-09-15,
...: """
In [2]: df = pd.read_csv(StringIO(data),sep=',')
In [3]: df
Out[3]:
foo bar
0 2015-09-14 True
1 2015-09-15 NaN
```
```
In [4]: df.convert_objects('coerce')
ValueError: The use of 'coerce' as an input is deprecated. Instead set coerce=True.
In [5]: df.convert_objects(coerce=True)
ValueError: coerce=True was provided, with no options for conversions.excatly one of 'datetime', 'numeric' or 'timedelta' must be True when when coerce=True.
In [8]: df.convert_objects(convert_dates='coerce')
/Users/jreback/miniconda/bin/ipython:1: FutureWarning: the 'convert_dates' keyword is deprecated, use 'datetime' instead
ValueError: The use of 'coerce' as an input is deprecated. Instead set coerce=True.
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11133 | 2015-09-17T01:34:35Z | 2015-09-22T21:33:35Z | null | 2015-09-22T21:33:35Z |
ERR: make sure raising TypeError on invalid nanops reductions xref #10472 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 3d625c0299db5..622324155b551 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -915,6 +915,7 @@ Other API Changes
- ``groupby`` using ``Categorical`` follows the same rule as ``Categorical.unique`` described above (:issue:`10508`)
- When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column
was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`)
+- some numeric reduction operators would return ``ValueError``, rather than ``TypeError`` on object types that includes strings and numbers (:issue:`11131`)
- ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`)
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 8602fdc26d6f6..1561c0aefbb9b 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -43,7 +43,16 @@ def _f(*args, **kwargs):
raise TypeError('reduction operation {0!r} not allowed for '
'this dtype'.format(f.__name__.replace('nan',
'')))
- return f(*args, **kwargs)
+ try:
+ return f(*args, **kwargs)
+ except ValueError as e:
+ # we want to transform an object array
+ # ValueError message to the more typical TypeError
+ # e.g. this is normally a disallowed function on
+ # object arrays that contain strings
+ if is_object_dtype(args[0]):
+ raise TypeError(e)
+ raise
return _f
@@ -93,7 +102,17 @@ def f(values, axis=None, skipna=True, **kwds):
else:
result = alt(values, axis=axis, skipna=skipna, **kwds)
except Exception:
- result = alt(values, axis=axis, skipna=skipna, **kwds)
+ try:
+ result = alt(values, axis=axis, skipna=skipna, **kwds)
+ except ValueError as e:
+ # we want to transform an object array
+ # ValueError message to the more typical TypeError
+ # e.g. this is normally a disallowed function on
+ # object arrays that contain strings
+
+ if is_object_dtype(values):
+ raise TypeError(e)
+ raise
return result
@@ -372,7 +391,6 @@ def nanvar(values, axis=None, skipna=True, ddof=1):
values = values.copy()
np.putmask(values, mask, 0)
-
# xref GH10242
# Compute variance via two-pass algorithm, which is stable against
# cancellation errors and relatively accurate for small numbers of
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 24de36d95794c..01ad4992dd785 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -12792,7 +12792,7 @@ def test_numeric_only_flag(self):
# df1 has all numbers, df2 has a letter inside
self.assertRaises(TypeError, lambda : getattr(df1, meth)(axis=1, numeric_only=False))
- self.assertRaises(ValueError, lambda : getattr(df2, meth)(axis=1, numeric_only=False))
+ self.assertRaises(TypeError, lambda : getattr(df2, meth)(axis=1, numeric_only=False))
def test_sem(self):
alt = lambda x: np.std(x, ddof=1)/np.sqrt(len(x))
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index d25009171afdf..7fb89b30cec97 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2912,6 +2912,10 @@ def testit():
exp = alternate(s)
self.assertEqual(res, exp)
+ # check on string data
+ if name not in ['sum','min','max']:
+ self.assertRaises(TypeError, f, Series(list('abc')))
+
# Invalid axis.
self.assertRaises(ValueError, f, self.series, axis=1)
| xref #https://github.com/blaze/dask/issues/693
| https://api.github.com/repos/pandas-dev/pandas/pulls/11131 | 2015-09-16T23:46:48Z | 2015-09-17T00:28:58Z | 2015-09-17T00:28:58Z | 2015-09-17T00:28:58Z |
BLD: install build deps when building | diff --git a/ci/install_conda.sh b/ci/install_conda.sh
index 1db1e7fa6f571..c54f5494c12ee 100755
--- a/ci/install_conda.sh
+++ b/ci/install_conda.sh
@@ -78,21 +78,13 @@ conda config --set ssl_verify false || exit 1
# Useful for debugging any issues with conda
conda info -a || exit 1
-REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.txt"
-conda create -n pandas python=$TRAVIS_PYTHON_VERSION || exit 1
-conda install -n pandas --file=${REQ} || exit 1
-
-conda install -n pandas pip setuptools nose || exit 1
-conda remove -n pandas pandas
+# build deps
+REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.build"
+time conda create -n pandas python=$TRAVIS_PYTHON_VERSION nose || exit 1
+time conda install -n pandas --file=${REQ} || exit 1
source activate pandas
-# we may have additional pip installs
-REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.pip"
-if [ -e ${REQ} ]; then
- pip install -r $REQ
-fi
-
# set the compiler cache to work
if [ "$IRON_TOKEN" ]; then
export PATH=/usr/lib/ccache:/usr/lib64/ccache:$PATH
@@ -104,15 +96,33 @@ if [ "$IRON_TOKEN" ]; then
fi
if [ "$BUILD_TEST" ]; then
+
+ # build testing
pip uninstall --yes cython
pip install cython==0.15.1
( python setup.py build_ext --inplace && python setup.py develop ) || true
+
else
- python setup.py build_ext --inplace && python setup.py develop
-fi
-for package in beautifulsoup4; do
- pip uninstall --yes $package
-done
+ # build but don't install
+ time python setup.py build_ext --inplace || exit 1
+
+ # we may have run installations
+ REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.run"
+ time conda install -n pandas --file=${REQ} || exit 1
+
+ # we may have additional pip installs
+ REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.pip"
+ if [ -e ${REQ} ]; then
+ pip install -r $REQ
+ fi
+
+ # remove any installed pandas package
+ conda remove pandas
+
+ # install our pandas
+ python setup.py develop || exit 1
+
+fi
true
diff --git a/ci/install_pydata.sh b/ci/install_pydata.sh
index f2ab5af34dc64..667b57897be7e 100755
--- a/ci/install_pydata.sh
+++ b/ci/install_pydata.sh
@@ -90,7 +90,8 @@ fi
# Force virtualenv to accept system_site_packages
rm -f $VIRTUAL_ENV/lib/python$TRAVIS_PYTHON_VERSION/no-global-site-packages.txt
-time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.txt
+# build deps
+time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.build
# Need to enable for locale testing. The location of the locale file(s) is
# distro specific. For example, on Arch Linux all of the locales are in a
@@ -147,6 +148,9 @@ else
python setup.py develop
fi
+# install the run libs
+time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.run
+
# restore cython (if not numpy building)
if [ -z "$NUMPY_BUILD" ]; then
time pip install $PIP_ARGS $(cat ci/requirements-${wheel_box}.txt | grep -i cython)
diff --git a/ci/requirements-2.6.build b/ci/requirements-2.6.build
new file mode 100644
index 0000000000000..f8cbd8cef3fef
--- /dev/null
+++ b/ci/requirements-2.6.build
@@ -0,0 +1,4 @@
+numpy=1.7.0
+cython=0.19.1
+dateutil=1.5
+pytz=2013b
diff --git a/ci/requirements-2.6.txt b/ci/requirements-2.6.run
similarity index 93%
rename from ci/requirements-2.6.txt
rename to ci/requirements-2.6.run
index 9b338cee26801..d8ed2a4262cfc 100644
--- a/ci/requirements-2.6.txt
+++ b/ci/requirements-2.6.run
@@ -1,5 +1,4 @@
numpy=1.7.0
-cython=0.19.1
dateutil=1.5
pytz=2013b
scipy=0.11.0
diff --git a/ci/requirements-2.7.build b/ci/requirements-2.7.build
new file mode 100644
index 0000000000000..df543aaf40f69
--- /dev/null
+++ b/ci/requirements-2.7.build
@@ -0,0 +1,4 @@
+dateutil=2.1
+pytz=2013b
+numpy=1.7.1
+cython=0.19.1
diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.run
similarity index 91%
rename from ci/requirements-2.7.txt
rename to ci/requirements-2.7.run
index 2764e740886da..a740966684ab2 100644
--- a/ci/requirements-2.7.txt
+++ b/ci/requirements-2.7.run
@@ -1,8 +1,7 @@
dateutil=2.1
pytz=2013b
+numpy=1.7.1
xlwt=0.7.5
-numpy=1.7.0
-cython=0.19.1
numexpr=2.2.2
pytables=3.0.0
matplotlib=1.3.1
@@ -12,7 +11,6 @@ sqlalchemy=0.9.6
lxml=3.2.1
scipy
xlsxwriter=0.4.6
-statsmodels
boto=2.36.0
bottleneck=0.8.0
psycopg2=2.5.2
@@ -20,3 +18,4 @@ patsy
pymysql=0.6.3
html5lib=1.0b2
beautiful-soup=4.2.1
+statsmodels
diff --git a/ci/requirements-2.7_32.txt b/ci/requirements-2.7_32.txt
deleted file mode 100644
index 2e241b1ce45bf..0000000000000
--- a/ci/requirements-2.7_32.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-python-dateutil
-pytz
-xlwt
-numpy
-cython
-numexpr
-pytables
-matplotlib
-openpyxl
-xlrd
-scipy
diff --git a/ci/requirements-2.7_64.txt b/ci/requirements-2.7_64.txt
deleted file mode 100644
index 2e241b1ce45bf..0000000000000
--- a/ci/requirements-2.7_64.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-python-dateutil
-pytz
-xlwt
-numpy
-cython
-numexpr
-pytables
-matplotlib
-openpyxl
-xlrd
-scipy
diff --git a/ci/requirements-2.7_BUILD_TEST.txt b/ci/requirements-2.7_BUILD_TEST.build
similarity index 84%
rename from ci/requirements-2.7_BUILD_TEST.txt
rename to ci/requirements-2.7_BUILD_TEST.build
index b273ca043c4a2..faf1e3559f7f1 100644
--- a/ci/requirements-2.7_BUILD_TEST.txt
+++ b/ci/requirements-2.7_BUILD_TEST.build
@@ -2,4 +2,3 @@ dateutil
pytz
numpy
cython
-nose
diff --git a/ci/requirements-2.7_LOCALE.build b/ci/requirements-2.7_LOCALE.build
new file mode 100644
index 0000000000000..ada6686f599ca
--- /dev/null
+++ b/ci/requirements-2.7_LOCALE.build
@@ -0,0 +1,4 @@
+python-dateutil
+pytz=2013b
+numpy=1.7.1
+cython=0.19.1
diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.run
similarity index 94%
rename from ci/requirements-2.7_LOCALE.txt
rename to ci/requirements-2.7_LOCALE.run
index fc7aceb0dffbb..9bb37ee10f8db 100644
--- a/ci/requirements-2.7_LOCALE.txt
+++ b/ci/requirements-2.7_LOCALE.run
@@ -1,11 +1,10 @@
python-dateutil
pytz=2013b
+numpy=1.7.1
xlwt=0.7.5
openpyxl=1.6.2
xlsxwriter=0.4.6
xlrd=0.9.2
-numpy=1.7.1
-cython=0.19.1
bottleneck=0.8.0
matplotlib=1.2.1
patsy=0.1.0
diff --git a/ci/requirements-2.7_NUMPY_DEV_1_8_x.txt b/ci/requirements-2.7_NUMPY_DEV_1_8_x.txt
deleted file mode 100644
index 90fa8f11c1cfd..0000000000000
--- a/ci/requirements-2.7_NUMPY_DEV_1_8_x.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-python-dateutil
-pytz==2013b
-cython==0.19.1
diff --git a/ci/requirements-2.7_NUMPY_DEV_master.txt b/ci/requirements-2.7_NUMPY_DEV_master.build
similarity index 100%
rename from ci/requirements-2.7_NUMPY_DEV_master.txt
rename to ci/requirements-2.7_NUMPY_DEV_master.build
diff --git a/ci/requirements-2.7_NUMPY_DEV_master.run b/ci/requirements-2.7_NUMPY_DEV_master.run
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/ci/requirements-2.7_SLOW.build b/ci/requirements-2.7_SLOW.build
new file mode 100644
index 0000000000000..9558cf00ddf5c
--- /dev/null
+++ b/ci/requirements-2.7_SLOW.build
@@ -0,0 +1,4 @@
+python-dateutil
+pytz
+numpy
+cython
diff --git a/ci/requirements-2.7_SLOW.txt b/ci/requirements-2.7_SLOW.run
similarity index 96%
rename from ci/requirements-2.7_SLOW.txt
rename to ci/requirements-2.7_SLOW.run
index 563ce3e1190e6..b6c9250dd775e 100644
--- a/ci/requirements-2.7_SLOW.txt
+++ b/ci/requirements-2.7_SLOW.run
@@ -1,7 +1,6 @@
python-dateutil
pytz
numpy
-cython
matplotlib
scipy
patsy
diff --git a/ci/requirements-3.3.build b/ci/requirements-3.3.build
new file mode 100644
index 0000000000000..8dc9b2102596a
--- /dev/null
+++ b/ci/requirements-3.3.build
@@ -0,0 +1,4 @@
+python-dateutil
+pytz=2013b
+numpy=1.8.0
+cython=0.19.1
diff --git a/ci/requirements-3.3.txt b/ci/requirements-3.3.run
similarity index 93%
rename from ci/requirements-3.3.txt
rename to ci/requirements-3.3.run
index cb8c3f7c10127..09d07c1c51f94 100644
--- a/ci/requirements-3.3.txt
+++ b/ci/requirements-3.3.run
@@ -1,11 +1,10 @@
python-dateutil
pytz=2013b
+numpy=1.8.0
openpyxl=1.6.2
xlsxwriter=0.4.6
xlrd=0.9.2
html5lib=1.0b2
-numpy=1.8.0
-cython=0.19.1
numexpr
pytables
bottleneck=0.8.0
diff --git a/ci/requirements-3.4.build b/ci/requirements-3.4.build
new file mode 100644
index 0000000000000..9558cf00ddf5c
--- /dev/null
+++ b/ci/requirements-3.4.build
@@ -0,0 +1,4 @@
+python-dateutil
+pytz
+numpy
+cython
diff --git a/ci/requirements-3.4_SLOW.txt b/ci/requirements-3.4.run
similarity index 91%
rename from ci/requirements-3.4_SLOW.txt
rename to ci/requirements-3.4.run
index ecc31dad78d07..73209a4623a49 100644
--- a/ci/requirements-3.4_SLOW.txt
+++ b/ci/requirements-3.4.run
@@ -1,5 +1,6 @@
python-dateutil
pytz
+numpy
openpyxl
xlsxwriter
xlrd
@@ -7,8 +8,6 @@ xlwt
html5lib
patsy
beautiful-soup
-numpy
-cython
scipy
numexpr
pytables
@@ -16,5 +15,5 @@ matplotlib=1.3.1
lxml
sqlalchemy
bottleneck
-pymysql
+pymysql=0.6.3
psycopg2
diff --git a/ci/requirements-3.4_32.txt b/ci/requirements-3.4_32.txt
deleted file mode 100644
index f2a364ed64311..0000000000000
--- a/ci/requirements-3.4_32.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-python-dateutil
-pytz
-openpyxl
-xlrd
-numpy
-cython
-scipy
-numexpr
-pytables
-matplotlib
diff --git a/ci/requirements-3.4_64.txt b/ci/requirements-3.4_64.txt
deleted file mode 100644
index f2a364ed64311..0000000000000
--- a/ci/requirements-3.4_64.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-python-dateutil
-pytz
-openpyxl
-xlrd
-numpy
-cython
-scipy
-numexpr
-pytables
-matplotlib
diff --git a/ci/requirements-3.4_SLOW.build b/ci/requirements-3.4_SLOW.build
new file mode 100644
index 0000000000000..9558cf00ddf5c
--- /dev/null
+++ b/ci/requirements-3.4_SLOW.build
@@ -0,0 +1,4 @@
+python-dateutil
+pytz
+numpy
+cython
diff --git a/ci/requirements-3.4.txt b/ci/requirements-3.4_SLOW.run
similarity index 87%
rename from ci/requirements-3.4.txt
rename to ci/requirements-3.4_SLOW.run
index fd0a5bc53dd7e..4c60fb883954f 100644
--- a/ci/requirements-3.4.txt
+++ b/ci/requirements-3.4_SLOW.run
@@ -1,5 +1,6 @@
python-dateutil
pytz
+numpy
openpyxl
xlsxwriter
xlrd
@@ -7,8 +8,6 @@ xlwt
html5lib
patsy
beautiful-soup
-numpy
-cython
scipy
numexpr
pytables
@@ -16,5 +15,6 @@ matplotlib
lxml
sqlalchemy
bottleneck
-pymysql==0.6.3
+pymysql
psycopg2
+statsmodels
diff --git a/ci/requirements-3.5.build b/ci/requirements-3.5.build
new file mode 100644
index 0000000000000..9558cf00ddf5c
--- /dev/null
+++ b/ci/requirements-3.5.build
@@ -0,0 +1,4 @@
+python-dateutil
+pytz
+numpy
+cython
diff --git a/ci/requirements-3.5.txt b/ci/requirements-3.5.run
similarity index 97%
rename from ci/requirements-3.5.txt
rename to ci/requirements-3.5.run
index 7af2c473bceca..f06cac7b8b9c7 100644
--- a/ci/requirements-3.5.txt
+++ b/ci/requirements-3.5.run
@@ -1,12 +1,11 @@
python-dateutil
pytz
+numpy
openpyxl
xlsxwriter
xlrd
xlwt
patsy
-numpy
-cython
scipy
numexpr
pytables
| closes #11122
dependency resolution in the `pandas` channel is a bit challenging as the current script tries to install all deps up front before building. But `statsmodels` requires pandas, so a current version is installed (e.g. the rc), and several of the deps are changed.
So fixed, but installing only the build deps, compiling, then install in the run deps.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11127 | 2015-09-16T21:02:57Z | 2015-09-16T23:01:46Z | 2015-09-16T23:01:46Z | 2015-09-16T23:01:46Z |
BUG: Fix computation of invalid NaN indexes for interpolate. | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 0b4acdc3e89bb..3d625c0299db5 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -383,7 +383,7 @@ Other enhancements
- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`)
-- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`)
+- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218`, :issue:`10420`, :issue:`11115`)
.. ipython:: python
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 8ffffae6bd160..9189b0d89de4f 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1582,13 +1582,10 @@ def interpolate_1d(xvalues, yvalues, method='linear', limit=None,
method = 'values'
def _interp_limit(invalid, fw_limit, bw_limit):
- "Get idx of values that won't be forward-filled b/c they exceed the limit."
- all_nans = np.where(invalid)[0]
- if all_nans.size == 0: # no nans anyway
- return []
- violate = [invalid[max(0, x - bw_limit):x + fw_limit + 1] for x in all_nans]
- violate = np.array([x.all() & (x.size > bw_limit + fw_limit) for x in violate])
- return all_nans[violate] + fw_limit - bw_limit
+ "Get idx of values that won't be filled b/c they exceed the limits."
+ for x in np.where(invalid)[0]:
+ if invalid[max(0, x - fw_limit):x + bw_limit + 1].all():
+ yield x
valid_limit_directions = ['forward', 'backward', 'both']
limit_direction = limit_direction.lower()
@@ -1624,7 +1621,7 @@ def _interp_limit(invalid, fw_limit, bw_limit):
if limit_direction == 'backward':
violate_limit = sorted(end_nans | set(_interp_limit(invalid, 0, limit)))
if limit_direction == 'both':
- violate_limit = _interp_limit(invalid, limit, limit)
+ violate_limit = sorted(_interp_limit(invalid, limit, limit))
xvalues = getattr(xvalues, 'values', xvalues)
yvalues = getattr(yvalues, 'values', yvalues)
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 19989116b26df..3a26be2ca1032 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -878,7 +878,6 @@ def test_interp_limit_forward(self):
def test_interp_limit_bad_direction(self):
s = Series([1, 3, np.nan, np.nan, np.nan, 11])
- expected = Series([1., 3., 5., 7., 9., 11.])
self.assertRaises(ValueError, s.interpolate,
method='linear', limit=2,
@@ -930,6 +929,25 @@ def test_interp_limit_to_ends(self):
method='linear', limit=2, limit_direction='both')
assert_series_equal(result, expected)
+ def test_interp_limit_before_ends(self):
+ # These test are for issue #11115 -- limit ends properly.
+ s = Series([np.nan, np.nan, 5, 7, np.nan, np.nan])
+
+ expected = Series([np.nan, np.nan, 5., 7., 7., np.nan])
+ result = s.interpolate(
+ method='linear', limit=1, limit_direction='forward')
+ assert_series_equal(result, expected)
+
+ expected = Series([np.nan, 5., 5., 7., np.nan, np.nan])
+ result = s.interpolate(
+ method='linear', limit=1, limit_direction='backward')
+ assert_series_equal(result, expected)
+
+ expected = Series([np.nan, 5., 5., 7., 7., np.nan])
+ result = s.interpolate(
+ method='linear', limit=1, limit_direction='both')
+ assert_series_equal(result, expected)
+
def test_interp_all_good(self):
# scipy
tm._skip_if_no_scipy()
| Fixes issue #11115.
This change fixes up a couple edge cases for the computation of invalid NaN indexes for interpolation limits.
I've also added a test explicitly for the reported bug (and similar behaviors at the opposite end of the series) in #11115.
/cc @jreback
| https://api.github.com/repos/pandas-dev/pandas/pulls/11124 | 2015-09-16T18:03:12Z | 2015-09-16T23:04:10Z | 2015-09-16T23:04:10Z | 2015-09-16T23:04:13Z |
ENH: Add ability to create datasets using the gbq module | diff --git a/doc/source/api.rst b/doc/source/api.rst
index b1fe77c298d71..3445f9263101e 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -110,10 +110,7 @@ Google BigQuery
read_gbq
to_gbq
- generate_bq_schema
- create_table
- delete_table
- table_exists
+
.. currentmodule:: pandas
diff --git a/doc/source/io.rst b/doc/source/io.rst
index 6affbedad3ae2..ce8064b302c3b 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -4005,14 +4005,10 @@ The key functions are:
.. currentmodule:: pandas.io.gbq
.. autosummary::
- :toctree: generated/
+ :toctree: generated/
- read_gbq
- to_gbq
- generate_bq_schema
- create_table
- delete_table
- table_exists
+ read_gbq
+ to_gbq
.. currentmodule:: pandas
@@ -4078,8 +4074,7 @@ Assume we want to write a DataFrame ``df`` into a BigQuery table using :func:`~p
.. note::
- If the destination table does not exist, a new table will be created. The
- destination dataset id must already exist in order for a new table to be created.
+ The destination table and destination dataset will automatically be created if they do not already exist.
The ``if_exists`` argument can be used to dictate whether to ``'fail'``, ``'replace'``
or ``'append'`` if the destination table already exists. The default value is ``'fail'``.
@@ -4146,19 +4141,13 @@ For example:
often as the service seems to be changing and evolving. BiqQuery is best for analyzing large
sets of data quickly, but it is not a direct replacement for a transactional database.
-
Creating BigQuery Tables
''''''''''''''''''''''''
-As of 0.17.0, the gbq module has a function :func:`~pandas.io.gbq.create_table` which allows users
-to create a table in BigQuery. The only requirement is that the dataset must already exist.
-The schema may be generated from a pandas DataFrame using the :func:`~pandas.io.gbq.generate_bq_schema` function below.
-
-For example:
-
-.. code-block:: python
+.. warning::
- gbq.create_table('my_dataset.my_table', schema, projectid)
+ As of 0.17, the function :func:`~pandas.io.gbq.generate_bq_schema` has been deprecated and will be
+ removed in a future version.
As of 0.15.2, the gbq module has a function :func:`~pandas.io.gbq.generate_bq_schema` which will
produce the dictionary representation schema of the specified pandas DataFrame.
@@ -4174,31 +4163,6 @@ produce the dictionary representation schema of the specified pandas DataFrame.
{'name': 'my_int64', 'type': 'INTEGER'},
{'name': 'my_string', 'type': 'STRING'}]}
-Deleting BigQuery Tables
-''''''''''''''''''''''''
-
-As of 0.17.0, the gbq module has a function :func:`~pandas.io.gbq.delete_table` which allows users to delete a table
-in Google BigQuery.
-
-For example:
-
-.. code-block:: python
-
- gbq.delete_table('my_dataset.my_table', projectid)
-
-The following function can be used to check whether a table exists prior to calling ``table_exists``:
-
-:func:`~pandas.io.gbq.table_exists`.
-
-The return value will be of type boolean.
-
-For example:
-
-.. code-block:: python
-
- In [12]: gbq.table_exists('my_dataset.my_table', projectid)
- Out[12]: True
-
.. note::
If you delete and re-create a BigQuery table with the same name, but different table schema,
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 3d4d113940dec..4df0f4a33d196 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -328,8 +328,8 @@ has been changed to make this keyword unnecessary - the change is shown below.
Google BigQuery Enhancements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Added ability to automatically create a table using the :func:`pandas.io.gbq.to_gbq` function if destination table does not exist. (:issue:`8325`).
+- Added ability to automatically create a dataset using the :func:`pandas.io.gbq.to_gbq` function if destination dataset does not exist. (:issue:`11121`).
- Added ability to replace an existing table and schema when calling the :func:`pandas.io.gbq.to_gbq` function via the ``if_exists`` argument. See the :ref:`docs <io.bigquery>` for more details (:issue:`8325`).
-- Added the following functions to the gbq module: :func:`pandas.io.gbq.table_exists`, :func:`pandas.io.gbq.create_table`, and :func:`pandas.io.gbq.delete_table`. See the :ref:`docs <io.bigquery>` for more details (:issue:`8325`).
- ``InvalidColumnOrder`` and ``InvalidPageToken`` in the gbq module will raise ``ValueError`` instead of ``IOError``.
.. _whatsnew_0170.enhancements.other:
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 37e7cb944814a..91eb11f5192af 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -1,7 +1,6 @@
from datetime import datetime
import json
import logging
-import sys
from time import sleep
import uuid
@@ -12,6 +11,7 @@
from pandas.core.api import DataFrame
from pandas.tools.merge import concat
from pandas.core.common import PandasError
+from pandas.util.decorators import deprecate
def _check_google_client_version():
@@ -41,6 +41,13 @@ class AccessDenied(PandasError, ValueError):
pass
+class DatasetCreationError(PandasError, ValueError):
+ """
+ Raised when the create dataset method fails
+ """
+ pass
+
+
class GenericGBQException(PandasError, ValueError):
"""
Raised when an unrecognized Google API Error occurs.
@@ -65,7 +72,6 @@ class InvalidPageToken(PandasError, ValueError):
pass
-
class InvalidSchema(PandasError, ValueError):
"""
Raised when the provided DataFrame does
@@ -85,7 +91,8 @@ class NotFoundException(PandasError, ValueError):
class StreamingInsertError(PandasError, ValueError):
"""
Raised when BigQuery reports a streaming insert error.
- For more information see `Streaming Data Into BigQuery <https://cloud.google.com/bigquery/streaming-data-into-bigquery>`__
+ For more information see `Streaming Data Into BigQuery
+ <https://cloud.google.com/bigquery/streaming-data-into-bigquery>`__
"""
@@ -137,7 +144,8 @@ def get_credentials(self):
return credentials
- def get_service(self, credentials):
+ @staticmethod
+ def get_service(credentials):
import httplib2
from apiclient.discovery import build
@@ -149,7 +157,8 @@ def get_service(self, credentials):
return bigquery_service
- def process_http_error(self, ex):
+ @staticmethod
+ def process_http_error(ex):
# See `BigQuery Troubleshooting Errors <https://cloud.google.com/bigquery/troubleshooting-errors>`__
status = json.loads(ex.content)['error']
@@ -164,7 +173,8 @@ def process_http_error(self, ex):
raise GenericGBQException(errors)
- def process_insert_errors(self, insert_errors, verbose):
+ @staticmethod
+ def process_insert_errors(insert_errors, verbose):
for insert_error in insert_errors:
row = insert_error['index']
errors = insert_error.get('errors', None)
@@ -201,7 +211,7 @@ def run_query(self, query, verbose=True):
query_reply = job_collection.insert(projectId=self.project_id, body=job_data).execute()
except AccessTokenRefreshError:
raise AccessDenied("The credentials have been revoked or expired, please re-run the application "
- "to re-authorize")
+ "to re-authorize")
except HttpError as ex:
self.process_http_error(ex)
@@ -231,7 +241,9 @@ def run_query(self, query, verbose=True):
page_token = query_reply.get('pageToken', None)
if not page_token and current_row < total_rows:
- raise InvalidPageToken("Required pageToken was missing. Recieved {0} of {1} rows".format(current_row, total_rows))
+ raise InvalidPageToken(
+ "Required pageToken was missing. Received {0} of {1} rows".format(current_row,
+ total_rows))
elif page_token in seen_page_tokens:
raise InvalidPageToken("A duplicate pageToken was returned")
@@ -302,21 +314,6 @@ def load_data(self, dataframe, dataset_id, table_id, chunksize, verbose):
if verbose:
print("\n")
- def table_exists(self, dataset_id, table_id):
- from apiclient.errors import HttpError
-
- try:
- self.service.tables().get(
- projectId=self.project_id,
- datasetId=dataset_id,
- tableId=table_id).execute()
- return True
- except HttpError as ex:
- if ex.resp.status == 404:
- return False
- else:
- self.process_http_error(ex)
-
def verify_schema(self, dataset_id, table_id, schema):
from apiclient.errors import HttpError
@@ -330,40 +327,6 @@ def verify_schema(self, dataset_id, table_id, schema):
except HttpError as ex:
self.process_http_error(ex)
- def create_table(self, dataset_id, table_id, schema):
- from apiclient.errors import HttpError
-
- body = {
- 'schema': schema,
- 'tableReference': {
- 'tableId': table_id,
- 'projectId': self.project_id,
- 'datasetId': dataset_id
- }
- }
-
- try:
- self.service.tables().insert(
- projectId=self.project_id,
- datasetId=dataset_id,
- body=body
- ).execute()
- except HttpError as ex:
- self.process_http_error(ex)
-
- def delete_table(self, dataset_id, table_id):
- from apiclient.errors import HttpError
-
- try:
- self.service.tables().delete(
- datasetId=dataset_id,
- projectId=self.project_id,
- tableId=table_id
- ).execute()
-
- except HttpError as ex:
- self.process_http_error(ex)
-
def delete_and_recreate_table(self, dataset_id, table_id, table_schema, verbose):
delay = 0
@@ -376,9 +339,9 @@ def delete_and_recreate_table(self, dataset_id, table_id, table_schema, verbose)
print('The existing table has a different schema. Please wait 2 minutes. See Google BigQuery issue #191')
delay = 120
- self.delete_table(dataset_id, table_id)
- self.create_table(dataset_id, table_id, table_schema)
-
+ table = _Table(self.project_id, dataset_id)
+ table.delete(table_id)
+ table.create(table_id, table_schema)
sleep(delay)
@@ -530,10 +493,12 @@ def to_gbq(dataframe, destination_table, project_id, chunksize=10000,
connector = GbqConnector(project_id, reauth=reauth)
dataset_id, table_id = destination_table.rsplit('.', 1)
- table_schema = generate_bq_schema(dataframe)
+ table = _Table(project_id, dataset_id, reauth=reauth)
+
+ table_schema = _generate_bq_schema(dataframe)
# If table exists, check if_exists parameter
- if connector.table_exists(dataset_id, table_id):
+ if table.exists(table_id):
if if_exists == 'fail':
raise TableCreationError("Could not create the table because it already exists. "
"Change the if_exists parameter to append or replace data.")
@@ -543,12 +508,12 @@ def to_gbq(dataframe, destination_table, project_id, chunksize=10000,
if not connector.verify_schema(dataset_id, table_id, table_schema):
raise InvalidSchema("The schema of the destination table does not match")
else:
- connector.create_table(dataset_id, table_id, table_schema)
+ table.create(table_id, table_schema)
connector.load_data(dataframe, dataset_id, table_id, chunksize, verbose)
-def generate_bq_schema(df, default_type='STRING'):
+def _generate_bq_schema(df, default_type='STRING'):
""" Given a passed df, generate the associated Google BigQuery schema.
Parameters
@@ -576,75 +541,257 @@ def generate_bq_schema(df, default_type='STRING'):
return {'fields': fields}
+generate_bq_schema = deprecate('generate_bq_schema', _generate_bq_schema)
-def table_exists(table, project_id):
- """ Check if a table exists in Google BigQuery given a table and project id
- .. versionadded:: 0.17.0
+class _Table(GbqConnector):
- Parameters
- ----------
- table : str
- Name of table to be verified, in the form 'dataset.tablename'
- project_id : str
- Google BigQuery Account project ID.
+ def __init__(self, project_id, dataset_id, reauth=False):
+ from apiclient.errors import HttpError
+ self.test_google_api_imports()
+ self.project_id = project_id
+ self.reauth = reauth
+ self.credentials = self.get_credentials()
+ self.service = self.get_service(self.credentials)
+ self.http_error = HttpError
+ self.dataset_id = dataset_id
- Returns
- -------
- boolean
- true if table exists, otherwise false
- """
+ def exists(self, table_id):
+ """ Check if a table exists in Google BigQuery
- if '.' not in table:
- raise NotFoundException("Invalid Table Name. Should be of the form 'datasetId.tableId' ")
+ .. versionadded:: 0.17.0
+
+ Parameters
+ ----------
+ table : str
+ Name of table to be verified
+
+ Returns
+ -------
+ boolean
+ true if table exists, otherwise false
+ """
+
+ try:
+ self.service.tables().get(
+ projectId=self.project_id,
+ datasetId=self.dataset_id,
+ tableId=table_id).execute()
+ return True
+ except self.http_error as ex:
+ if ex.resp.status == 404:
+ return False
+ else:
+ self.process_http_error(ex)
- connector = GbqConnector(project_id)
- dataset_id, table_id = table.rsplit('.', 1)
+ def create(self, table_id, schema):
+ """ Create a table in Google BigQuery given a table and schema
- return connector.table_exists(dataset_id, table_id)
+ .. versionadded:: 0.17.0
+ Parameters
+ ----------
+ table : str
+ Name of table to be written
+ schema : str
+ Use the generate_bq_schema to generate your table schema from a dataframe.
+ """
-def create_table(table, schema, project_id):
- """ Create a table in Google BigQuery given a table, schema and project id
+ if self.exists(table_id):
+ raise TableCreationError("The table could not be created because it already exists")
- .. versionadded:: 0.17.0
+ if not _Dataset(self.project_id).exists(self.dataset_id):
+ _Dataset(self.project_id).create(self.dataset_id)
- Parameters
- ----------
- table : str
- Name of table to be written, in the form 'dataset.tablename'
- schema : str
- Use the generate_bq_schema to generate your table schema from a dataframe.
- project_id : str
- Google BigQuery Account project ID.
- """
+ body = {
+ 'schema': schema,
+ 'tableReference': {
+ 'tableId': table_id,
+ 'projectId': self.project_id,
+ 'datasetId': self.dataset_id
+ }
+ }
+
+ try:
+ self.service.tables().insert(
+ projectId=self.project_id,
+ datasetId=self.dataset_id,
+ body=body).execute()
+ except self.http_error as ex:
+ self.process_http_error(ex)
- if table_exists(table, project_id):
- raise TableCreationError("The table could not be created because it already exists")
+ def delete(self, table_id):
+ """ Delete a table in Google BigQuery
- connector = GbqConnector(project_id)
- dataset_id, table_id = table.rsplit('.', 1)
+ .. versionadded:: 0.17.0
- return connector.create_table(dataset_id, table_id, schema)
+ Parameters
+ ----------
+ table : str
+ Name of table to be deleted
+ """
+ if not self.exists(table_id):
+ raise NotFoundException("Table does not exist")
-def delete_table(table, project_id):
- """ Delete a table in Google BigQuery given a table and project id
+ try:
+ self.service.tables().delete(
+ datasetId=self.dataset_id,
+ projectId=self.project_id,
+ tableId=table_id).execute()
+ except self.http_error as ex:
+ self.process_http_error(ex)
- .. versionadded:: 0.17.0
- Parameters
- ----------
- table : str
- Name of table to be written, in the form 'dataset.tablename'
- project_id : str
- Google BigQuery Account project ID.
- """
+class _Dataset(GbqConnector):
+
+ def __init__(self, project_id, reauth=False):
+ from apiclient.errors import HttpError
+ self.test_google_api_imports()
+ self.project_id = project_id
+ self.reauth = reauth
+ self.credentials = self.get_credentials()
+ self.service = self.get_service(self.credentials)
+ self.http_error = HttpError
+
+ def exists(self, dataset_id):
+ """ Check if a dataset exists in Google BigQuery
+
+ .. versionadded:: 0.17.0
+
+ Parameters
+ ----------
+ dataset_id : str
+ Name of dataset to be verified
+
+ Returns
+ -------
+ boolean
+ true if dataset exists, otherwise false
+ """
+
+ try:
+ self.service.datasets().get(
+ projectId=self.project_id,
+ datasetId=dataset_id).execute()
+ return True
+ except self.http_error as ex:
+ if ex.resp.status == 404:
+ return False
+ else:
+ self.process_http_error(ex)
+
+ def datasets(self):
+ """ Return a list of datasets in Google BigQuery
- if not table_exists(table, project_id):
- raise NotFoundException("Table does not exist")
+ .. versionadded:: 0.17.0
- connector = GbqConnector(project_id)
- dataset_id, table_id = table.rsplit('.', 1)
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ list
+ List of datasets under the specific project
+ """
+
+ try:
+ list_dataset_response = self.service.datasets().list(
+ projectId=self.project_id).execute().get('datasets', None)
+
+ if not list_dataset_response:
+ return []
+
+ dataset_list = list()
+
+ for row_num, raw_row in enumerate(list_dataset_response):
+ dataset_list.append(raw_row['datasetReference']['datasetId'])
+
+ return dataset_list
+ except self.http_error as ex:
+ self.process_http_error(ex)
+
+ def create(self, dataset_id):
+ """ Create a dataset in Google BigQuery
+
+ .. versionadded:: 0.17.0
+
+ Parameters
+ ----------
+ dataset : str
+ Name of dataset to be written
+ """
+
+ if self.exists(dataset_id):
+ raise DatasetCreationError("The dataset could not be created because it already exists")
+
+ body = {
+ 'datasetReference': {
+ 'projectId': self.project_id,
+ 'datasetId': dataset_id
+ }
+ }
+
+ try:
+ self.service.datasets().insert(
+ projectId=self.project_id,
+ body=body).execute()
+ except self.http_error as ex:
+ self.process_http_error(ex)
+
+ def delete(self, dataset_id):
+ """ Delete a dataset in Google BigQuery
+
+ .. versionadded:: 0.17.0
+
+ Parameters
+ ----------
+ dataset : str
+ Name of dataset to be deleted
+ """
+
+ if not self.exists(dataset_id):
+ raise NotFoundException("Dataset {0} does not exist".format(dataset_id))
+
+ try:
+ self.service.datasets().delete(
+ datasetId=dataset_id,
+ projectId=self.project_id).execute()
+
+ except self.http_error as ex:
+ self.process_http_error(ex)
+
+ def tables(self, dataset_id):
+ """ List tables in the specific dataset in Google BigQuery
+
+ .. versionadded:: 0.17.0
+
+ Parameters
+ ----------
+ dataset : str
+ Name of dataset to list tables for
+
+ Returns
+ -------
+ list
+ List of tables under the specific dataset
+ """
+
+ try:
+ list_table_response = self.service.tables().list(
+ projectId=self.project_id,
+ datasetId=dataset_id).execute().get('tables', None)
+
+ if not list_table_response:
+ return []
+
+ table_list = list()
+
+ for row_num, raw_row in enumerate(list_table_response):
+ table_list.append(raw_row['tableReference']['tableId'])
+
+ return table_list
+ except self.http_error as ex:
+ self.process_http_error(ex)
- return connector.delete_table(dataset_id, table_id)
diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py
index 990050b8ac544..2b3d226cd3e0b 100644
--- a/pandas/io/tests/test_gbq.py
+++ b/pandas/io/tests/test_gbq.py
@@ -1,12 +1,6 @@
-import ast
from datetime import datetime
-import json
import nose
-import os
import pytz
-import shutil
-import subprocess
-import sys
import platform
from time import sleep
@@ -22,6 +16,9 @@
import pandas.util.testing as tm
PROJECT_ID = None
+DATASET_ID = 'pydata_pandas_bq_testing'
+TABLE_ID = 'new_test'
+DESTINATION_TABLE = "{0}.{1}".format(DATASET_ID + "1", TABLE_ID)
VERSION = platform.python_version()
@@ -32,14 +29,6 @@
_SETUPTOOLS_INSTALLED = False
-def missing_bq():
- try:
- subprocess.call(['bq', 'ls'])
- return False
- except OSError:
- return True
-
-
def _test_imports():
if not compat.PY3:
@@ -102,14 +91,33 @@ def test_requirements():
raise nose.SkipTest(import_exception)
+def clean_gbq_environment():
+ dataset = gbq._Dataset(PROJECT_ID)
+
+ for i in range(1, 10):
+ if DATASET_ID + str(i) in dataset.datasets():
+ dataset_id = DATASET_ID + str(i)
+ table = gbq._Table(PROJECT_ID, dataset_id)
+ for j in range(1, 20):
+ if TABLE_ID + str(j) in dataset.tables(dataset_id):
+ table.delete(TABLE_ID + str(j))
+
+ dataset.delete(dataset_id)
+
+
def make_mixed_dataframe_v2(test_size):
# create df to test for all BQ datatypes except RECORD
- bools = np.random.randint(2, size=(1,test_size)).astype(bool)
+ bools = np.random.randint(2, size=(1, test_size)).astype(bool)
flts = np.random.randn(1, test_size)
- ints = np.random.randint(1, 10, size=(1,test_size))
- strs = np.random.randint(1, 10, size=(1,test_size)).astype(str)
+ ints = np.random.randint(1, 10, size=(1, test_size))
+ strs = np.random.randint(1, 10, size=(1, test_size)).astype(str)
times = [datetime.now(pytz.timezone('US/Arizona')) for t in xrange(test_size)]
- return DataFrame({'bools': bools[0], 'flts': flts[0], 'ints': ints[0], 'strs': strs[0], 'times': times[0]}, index=range(test_size))
+ return DataFrame({'bools': bools[0],
+ 'flts': flts[0],
+ 'ints': ints[0],
+ 'strs': strs[0],
+ 'times': times[0]},
+ index=range(test_size))
class TestGBQConnectorIntegration(tm.TestCase):
@@ -194,15 +202,10 @@ def setUpClass(cls):
# put here any instruction you want to execute only *ONCE* *BEFORE* executing *ALL* tests
# described below.
- test_requirements()
-
if not PROJECT_ID:
raise nose.SkipTest("Cannot run integration tests without a project id")
- if missing_bq():
- raise nose.SkipTest("Cannot run read_gbq tests without bq command line client")
-
- subprocess.call(['bq', 'mk', PROJECT_ID + ':pydata_pandas_bq_testing'])
+ test_requirements()
def setUp(self):
# - PER-TEST FIXTURES -
@@ -213,13 +216,12 @@ def setUp(self):
def tearDownClass(cls):
# - GLOBAL CLASS FIXTURES -
# put here any instruction you want to execute only *ONCE* *AFTER* executing all tests.
- subprocess.call(['bq', 'rm', '-f', PROJECT_ID + ':pydata_pandas_bq_testing'])
+ pass
def tearDown(self):
# - PER-TEST FIXTURES -
# put here any instructions you want to be run *AFTER* *EVERY* test is executed.
- if gbq.table_exists('pydata_pandas_bq_testing.new_test', PROJECT_ID):
- subprocess.call(['bq', 'rm', '-f', PROJECT_ID + ':pydata_pandas_bq_testing.new_test'])
+ pass
def test_should_properly_handle_valid_strings(self):
query = 'SELECT "PI" as VALID_STRING'
@@ -331,14 +333,17 @@ def test_bad_table_name(self):
gbq.read_gbq("SELECT * FROM [publicdata:samples.nope]", project_id=PROJECT_ID)
def test_download_dataset_larger_than_200k_rows(self):
+ test_size = 200005
# Test for known BigQuery bug in datasets larger than 100k rows
# http://stackoverflow.com/questions/19145587/bq-py-not-paging-results
- df = gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] GROUP EACH BY id ORDER BY id ASC LIMIT 200005", project_id=PROJECT_ID)
- self.assertEqual(len(df.drop_duplicates()), 200005)
+ df = gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] GROUP EACH BY id ORDER BY id ASC LIMIT {0}".format(test_size),
+ project_id=PROJECT_ID)
+ self.assertEqual(len(df.drop_duplicates()), test_size)
def test_zero_rows(self):
# Bug fix for https://github.com/pydata/pandas/issues/10273
- df = gbq.read_gbq("SELECT title, language FROM [publicdata:samples.wikipedia] where timestamp=-9999999", project_id=PROJECT_ID)
+ df = gbq.read_gbq("SELECT title, language FROM [publicdata:samples.wikipedia] where timestamp=-9999999",
+ project_id=PROJECT_ID)
expected_result = DataFrame(columns=['title', 'language'])
self.assert_frame_equal(df, expected_result)
@@ -352,122 +357,118 @@ class TestToGBQIntegration(tm.TestCase):
@classmethod
def setUpClass(cls):
# - GLOBAL CLASS FIXTURES -
- # put here any instruction you want to execute only *ONCE* *BEFORE* executing *ALL* tests
- # described below.
-
- test_requirements()
+ # put here any instruction you want to execute only *ONCE* *BEFORE* executing *ALL* tests
+ # described below.
if not PROJECT_ID:
raise nose.SkipTest("Cannot run integration tests without a project id")
- if missing_bq():
- raise nose.SkipTest("Cannot run to_gbq tests without bq command line client")
+ test_requirements()
+ clean_gbq_environment()
- subprocess.call(['bq', 'mk', PROJECT_ID + ':pydata_pandas_bq_testing'])
+ gbq._Dataset(PROJECT_ID).create(DATASET_ID + "1")
def setUp(self):
# - PER-TEST FIXTURES -
- # put here any instruction you want to be run *BEFORE* *EVERY* test is executed.
- pass
+ # put here any instruction you want to be run *BEFORE* *EVERY* test is executed.
+
+ self.dataset = gbq._Dataset(PROJECT_ID)
+ self.table = gbq._Table(PROJECT_ID, DATASET_ID + "1")
@classmethod
def tearDownClass(cls):
# - GLOBAL CLASS FIXTURES -
# put here any instruction you want to execute only *ONCE* *AFTER* executing all tests.
- for i in range(1, 8):
- if gbq.table_exists('pydata_pandas_bq_testing.new_test' + str(i), PROJECT_ID):
- subprocess.call(['bq', 'rm', '-f', PROJECT_ID + ':pydata_pandas_bq_testing.new_test' + str(i)])
-
- subprocess.call(['bq', 'rm', '-f', PROJECT_ID + ':pydata_pandas_bq_testing'])
+ clean_gbq_environment()
def tearDown(self):
# - PER-TEST FIXTURES -
- # put here any instructions you want to be run *AFTER* *EVERY* test is executed.
+ # put here any instructions you want to be run *AFTER* *EVERY* test is executed.
pass
def test_upload_data(self):
- table_name = 'new_test1'
+ destination_table = DESTINATION_TABLE + "1"
test_size = 1000001
df = make_mixed_dataframe_v2(test_size)
- gbq.to_gbq(df, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, chunksize=10000)
+ gbq.to_gbq(df, destination_table, PROJECT_ID, chunksize=10000)
sleep(60) # <- Curses Google!!!
- result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM pydata_pandas_bq_testing." + table_name, project_id=PROJECT_ID)
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table),
+ project_id=PROJECT_ID)
self.assertEqual(result['NUM_ROWS'][0], test_size)
def test_upload_data_if_table_exists_fail(self):
- table_name = 'new_test2'
+ destination_table = DESTINATION_TABLE + "2"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
-
- gbq.create_table('pydata_pandas_bq_testing.' + table_name, gbq.generate_bq_schema(df), PROJECT_ID)
+ self.table.create(TABLE_ID + "2", gbq._generate_bq_schema(df))
# Test the default value of if_exists is 'fail'
with tm.assertRaises(gbq.TableCreationError):
- gbq.to_gbq(df, "pydata_pandas_bq_testing." + table_name, PROJECT_ID)
+ gbq.to_gbq(df, destination_table, PROJECT_ID)
# Test the if_exists parameter with value 'fail'
with tm.assertRaises(gbq.TableCreationError):
- gbq.to_gbq(df, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, if_exists='fail')
+ gbq.to_gbq(df, destination_table, PROJECT_ID, if_exists='fail')
def test_upload_data_if_table_exists_append(self):
- table_name = 'new_test3'
+ destination_table = DESTINATION_TABLE + "3"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
df_different_schema = tm.makeMixedDataFrame()
# Initialize table with sample data
- gbq.to_gbq(df, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, chunksize=10000)
+ gbq.to_gbq(df, destination_table, PROJECT_ID, chunksize=10000)
# Test the if_exists parameter with value 'append'
- gbq.to_gbq(df, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, if_exists='append')
+ gbq.to_gbq(df, destination_table, PROJECT_ID, if_exists='append')
sleep(60) # <- Curses Google!!!
- result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM pydata_pandas_bq_testing." + table_name, project_id=PROJECT_ID)
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), project_id=PROJECT_ID)
self.assertEqual(result['NUM_ROWS'][0], test_size * 2)
# Try inserting with a different schema, confirm failure
with tm.assertRaises(gbq.InvalidSchema):
- gbq.to_gbq(df_different_schema, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, if_exists='append')
+ gbq.to_gbq(df_different_schema, destination_table, PROJECT_ID, if_exists='append')
def test_upload_data_if_table_exists_replace(self):
- table_name = 'new_test4'
+ destination_table = DESTINATION_TABLE + "4"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
df_different_schema = tm.makeMixedDataFrame()
# Initialize table with sample data
- gbq.to_gbq(df, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, chunksize=10000)
+ gbq.to_gbq(df, destination_table, PROJECT_ID, chunksize=10000)
# Test the if_exists parameter with the value 'replace'.
- gbq.to_gbq(df_different_schema, "pydata_pandas_bq_testing." + table_name, PROJECT_ID, if_exists='replace')
+ gbq.to_gbq(df_different_schema, destination_table, PROJECT_ID, if_exists='replace')
sleep(60) # <- Curses Google!!!
- result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM pydata_pandas_bq_testing." + table_name, project_id=PROJECT_ID)
+ result = gbq.read_gbq("SELECT COUNT(*) as NUM_ROWS FROM {0}".format(destination_table), project_id=PROJECT_ID)
self.assertEqual(result['NUM_ROWS'][0], 5)
def test_google_upload_errors_should_raise_exception(self):
- table_name = 'new_test5'
+ destination_table = DESTINATION_TABLE + "5"
test_timestamp = datetime.now(pytz.timezone('US/Arizona'))
bad_df = DataFrame({'bools': [False, False], 'flts': [0.0, 1.0], 'ints': [0, '1'], 'strs': ['a', 1],
'times': [test_timestamp, test_timestamp]}, index=range(2))
with tm.assertRaises(gbq.StreamingInsertError):
- gbq.to_gbq(bad_df, 'pydata_pandas_bq_testing.' + table_name, PROJECT_ID, verbose=True)
+ gbq.to_gbq(bad_df, destination_table, PROJECT_ID, verbose=True)
- def test_generate_bq_schema(self):
+ def test_generate_schema(self):
df = tm.makeMixedDataFrame()
- schema = gbq.generate_bq_schema(df)
+ schema = gbq._generate_bq_schema(df)
test_schema = {'fields': [{'name': 'A', 'type': 'FLOAT'},
{'name': 'B', 'type': 'FLOAT'},
@@ -476,40 +477,70 @@ def test_generate_bq_schema(self):
self.assertEqual(schema, test_schema)
- def test_create_bq_table(self):
- table_name = 'new_test6'
-
+ def test_create_table(self):
+ destination_table = TABLE_ID + "6"
test_schema = {'fields': [{'name': 'A', 'type': 'FLOAT'}, {'name': 'B', 'type': 'FLOAT'},
{'name': 'C', 'type': 'STRING'}, {'name': 'D', 'type': 'TIMESTAMP'}]}
-
- gbq.create_table('pydata_pandas_bq_testing.' + table_name, test_schema, PROJECT_ID)
-
- self.assertTrue(gbq.table_exists('pydata_pandas_bq_testing.' + table_name, PROJECT_ID), 'Expected table to exist')
+ self.table.create(destination_table, test_schema)
+ self.assertTrue(self.table.exists(destination_table), 'Expected table to exist')
def test_table_does_not_exist(self):
- table_name = 'new_test7'
- self.assertTrue(not gbq.table_exists('pydata_pandas_bq_testing.' + table_name, PROJECT_ID),
- 'Expected table not to exist')
-
- def test_delete_bq_table(self):
- table_name = 'new_test8'
+ self.assertTrue(not self.table.exists(TABLE_ID + "7"), 'Expected table not to exist')
+ def test_delete_table(self):
+ destination_table = TABLE_ID + "8"
test_schema = {'fields': [{'name': 'A', 'type': 'FLOAT'}, {'name': 'B', 'type': 'FLOAT'},
{'name': 'C', 'type': 'STRING'}, {'name': 'D', 'type': 'TIMESTAMP'}]}
+ self.table.create(destination_table, test_schema)
+ self.table.delete(destination_table)
+ self.assertTrue(not self.table.exists(destination_table), 'Expected table not to exist')
- gbq.create_table('pydata_pandas_bq_testing.' + table_name, test_schema, PROJECT_ID)
-
- gbq.delete_table('pydata_pandas_bq_testing.' + table_name, PROJECT_ID)
-
- self.assertTrue(not gbq.table_exists('pydata_pandas_bq_testing.' + table_name, PROJECT_ID),
- 'Expected table not to exist')
-
- def test_upload_data_dataset_not_found(self):
- test_size = 10
- df = make_mixed_dataframe_v2(test_size)
-
- with tm.assertRaises(gbq.GenericGBQException):
- gbq.create_table('pydata_pandas_bq_testing2.new_test', gbq.generate_bq_schema(df), PROJECT_ID)
+ def test_list_table(self):
+ destination_table = TABLE_ID + "9"
+ test_schema = {'fields': [{'name': 'A', 'type': 'FLOAT'}, {'name': 'B', 'type': 'FLOAT'},
+ {'name': 'C', 'type': 'STRING'}, {'name': 'D', 'type': 'TIMESTAMP'}]}
+ self.table.create(destination_table, test_schema)
+ self.assertTrue(destination_table in self.dataset.tables(DATASET_ID + "1"),
+ 'Expected table list to contain table {0}'.format(destination_table))
+
+ def test_list_dataset(self):
+ dataset_id = DATASET_ID + "1"
+ self.assertTrue(dataset_id in self.dataset.datasets(),
+ 'Expected dataset list to contain dataset {0}'.format(dataset_id))
+
+ def test_list_table_zero_results(self):
+ dataset_id = DATASET_ID + "2"
+ self.dataset.create(dataset_id)
+ table_list = gbq._Dataset(PROJECT_ID).tables(dataset_id)
+ self.assertEqual(len(table_list), 0, 'Expected gbq.list_table() to return 0')
+
+ def test_create_dataset(self):
+ dataset_id = DATASET_ID + "3"
+ self.dataset.create(dataset_id)
+ self.assertTrue(dataset_id in self.dataset.datasets(), 'Expected dataset to exist')
+
+ def test_delete_dataset(self):
+ dataset_id = DATASET_ID + "4"
+ self.dataset.create(dataset_id)
+ self.dataset.delete(dataset_id)
+ self.assertTrue(dataset_id not in self.dataset.datasets(), 'Expected dataset not to exist')
+
+ def test_dataset_exists(self):
+ dataset_id = DATASET_ID + "5"
+ self.dataset.create(dataset_id)
+ self.assertTrue(self.dataset.exists(dataset_id), 'Expected dataset to exist')
+
+ def create_table_data_dataset_does_not_exist(self):
+ dataset_id = DATASET_ID + "6"
+ table_id = TABLE_ID + "1"
+ table_with_new_dataset = gbq._Table(PROJECT_ID, dataset_id)
+ df = make_mixed_dataframe_v2(10)
+ table_with_new_dataset.create(table_id, gbq._generate_bq_schema(df))
+ self.assertTrue(self.dataset.exists(dataset_id), 'Expected dataset to exist')
+ self.assertTrue(table_with_new_dataset.exists(table_id), 'Expected dataset to exist')
+
+ def test_dataset_does_not_exist(self):
+ self.assertTrue(not self.dataset.exists(DATASET_ID + "_not_found"), 'Expected dataset not to exist')
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| Removed the `bq` command line module from `test_gbq.py`, as it doesn't support python 3. In order to do this, I had to create functions for `create_dataset()`, `delete_dataset()` and `dataset_exists()`.
This change is required for #11110
At the same time, I also implemented the following list functions: `list_dataset()` and `list_table()`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11121 | 2015-09-16T04:27:04Z | 2015-09-24T23:02:30Z | null | 2015-09-24T23:37:55Z |
BF: do not assume that expanduser would replace all ~ | diff --git a/pandas/io/tests/test_common.py b/pandas/io/tests/test_common.py
index 34e7c94b64bcb..03d1e4fb1f365 100644
--- a/pandas/io/tests/test_common.py
+++ b/pandas/io/tests/test_common.py
@@ -3,6 +3,7 @@
"""
from pandas.compat import StringIO
import os
+from os.path import isabs
import pandas.util.testing as tm
@@ -16,7 +17,7 @@ def test_expand_user(self):
expanded_name = common._expand_user(filename)
self.assertNotEqual(expanded_name, filename)
- self.assertNotIn('~', expanded_name)
+ self.assertTrue(isabs(expanded_name))
self.assertEqual(os.path.expanduser(filename), expanded_name)
def test_expand_user_normal_path(self):
@@ -24,14 +25,13 @@ def test_expand_user_normal_path(self):
expanded_name = common._expand_user(filename)
self.assertEqual(expanded_name, filename)
- self.assertNotIn('~', expanded_name)
self.assertEqual(os.path.expanduser(filename), expanded_name)
def test_get_filepath_or_buffer_with_path(self):
filename = '~/sometest'
filepath_or_buffer, _, _ = common.get_filepath_or_buffer(filename)
self.assertNotEqual(filepath_or_buffer, filename)
- self.assertNotIn('~', filepath_or_buffer)
+ self.assertTrue(isabs(filepath_or_buffer))
self.assertEqual(os.path.expanduser(filename), filepath_or_buffer)
def test_get_filepath_or_buffer_with_buffer(self):
| since it must not e.g. if there is ~ in some directory name along the path (awkward but possible/allowed).
Better to check either new path is absolute. Removed 1 test which had no value
| https://api.github.com/repos/pandas-dev/pandas/pulls/11120 | 2015-09-16T01:58:17Z | 2015-09-17T01:00:29Z | 2015-09-17T01:00:29Z | 2015-09-22T14:16:59Z |
COMPAT: compat for python 3.5, #11097 | diff --git a/.travis.yml b/.travis.yml
index 6460a9a726b48..4e46fb7ad85ca 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -43,13 +43,6 @@ matrix:
- CLIPBOARD_GUI=gtk2
- BUILD_TYPE=conda
- DOC_BUILD=true # if rst files were changed, build docs in parallel with tests
- - python: 3.3
- env:
- - JOB_NAME: "33_nslow"
- - NOSE_ARGS="not slow and not disabled"
- - FULL_DEPS=true
- - CLIPBOARD=xsel
- - BUILD_TYPE=conda
- python: 3.4
env:
- JOB_NAME: "34_nslow"
@@ -64,6 +57,13 @@ matrix:
- FULL_DEPS=true
- CLIPBOARD=xsel
- BUILD_TYPE=conda
+ - python: 3.3
+ env:
+ - JOB_NAME: "33_nslow"
+ - NOSE_ARGS="not slow and not disabled"
+ - FULL_DEPS=true
+ - CLIPBOARD=xsel
+ - BUILD_TYPE=conda
- python: 2.7
env:
- JOB_NAME: "27_slow"
@@ -104,10 +104,10 @@ matrix:
- BUILD_TYPE=pydata
- PANDAS_TESTING_MODE="deprecate"
allow_failures:
- - python: 3.5
+ - python: 3.3
env:
- - JOB_NAME: "35_nslow"
- - NOSE_ARGS="not slow and not network and not disabled"
+ - JOB_NAME: "33_nslow"
+ - NOSE_ARGS="not slow and not disabled"
- FULL_DEPS=true
- CLIPBOARD=xsel
- BUILD_TYPE=conda
diff --git a/ci/requirements-3.5.txt b/ci/requirements-3.5.txt
index 1e67cefa6c98e..7af2c473bceca 100644
--- a/ci/requirements-3.5.txt
+++ b/ci/requirements-3.5.txt
@@ -10,3 +10,15 @@ cython
scipy
numexpr
pytables
+html5lib
+lxml
+
+# currently causing some warnings
+#sqlalchemy
+#pymysql
+#psycopg2
+
+# not available from conda
+#beautiful-soup
+#bottleneck
+#matplotlib
diff --git a/doc/source/install.rst b/doc/source/install.rst
index 36a6c4038f8be..5c5f6bdcf0ddf 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -18,7 +18,7 @@ Instructions for installing from source,
Python version support
----------------------
-Officially Python 2.6, 2.7, 3.3, and 3.4.
+Officially Python 2.6, 2.7, 3.3, 3.4, and 3.5
Installing pandas
-----------------
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 2010939724c5e..4fa8ba06cf8d0 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -64,6 +64,7 @@ Highlights include:
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>`
- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>`
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>`
+- Compatibility with Python 3.5
See the :ref:`v0.17.0 Whatsnew <whatsnew_0170>` overview for an extensive list
of all enhancements and bugs that have been fixed in 0.17.0.
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 615bfc9e23253..ab0e7a481f031 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -49,6 +49,7 @@ Highlights include:
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>`
- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>`
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>`
+- Compatibility with Python 3.5 (:issue:`11097`)
Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating.
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index 2ac81f15a6d6c..bad7192047e19 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -36,9 +36,9 @@
import sys
import types
-PY3 = (sys.version_info[0] >= 3)
PY2 = sys.version_info[0] == 2
-
+PY3 = (sys.version_info[0] >= 3)
+PY35 = (sys.version_info >= (3, 5))
try:
import __builtin__ as builtins
diff --git a/pandas/computation/expr.py b/pandas/computation/expr.py
index 123051d802d7d..2ae6f29f74efc 100644
--- a/pandas/computation/expr.py
+++ b/pandas/computation/expr.py
@@ -516,7 +516,54 @@ def visit_Attribute(self, node, **kwargs):
raise ValueError("Invalid Attribute context {0}".format(ctx.__name__))
- def visit_Call(self, node, side=None, **kwargs):
+ def visit_Call_35(self, node, side=None, **kwargs):
+ """ in 3.5 the starargs attribute was changed to be more flexible, #11097 """
+
+ if isinstance(node.func, ast.Attribute):
+ res = self.visit_Attribute(node.func)
+ elif not isinstance(node.func, ast.Name):
+ raise TypeError("Only named functions are supported")
+ else:
+ try:
+ res = self.visit(node.func)
+ except UndefinedVariableError:
+ # Check if this is a supported function name
+ try:
+ res = FuncNode(node.func.id)
+ except ValueError:
+ # Raise original error
+ raise
+
+ if res is None:
+ raise ValueError("Invalid function call {0}".format(node.func.id))
+ if hasattr(res, 'value'):
+ res = res.value
+
+ if isinstance(res, FuncNode):
+
+ new_args = [ self.visit(arg) for arg in node.args ]
+
+ if node.keywords:
+ raise TypeError("Function \"{0}\" does not support keyword "
+ "arguments".format(res.name))
+
+ return res(*new_args, **kwargs)
+
+ else:
+
+ new_args = [ self.visit(arg).value for arg in node.args ]
+
+ for key in node.keywords:
+ if not isinstance(key, ast.keyword):
+ raise ValueError("keyword error in function call "
+ "'{0}'".format(node.func.id))
+
+ if key.arg:
+ kwargs.append(ast.keyword(keyword.arg, self.visit(keyword.value)))
+
+ return self.const_type(res(*new_args, **kwargs), self.env)
+
+ def visit_Call_legacy(self, node, side=None, **kwargs):
# this can happen with: datetime.datetime
if isinstance(node.func, ast.Attribute):
@@ -607,6 +654,13 @@ def visitor(x, y):
operands = node.values
return reduce(visitor, operands)
+# ast.Call signature changed on 3.5,
+# conditionally change which methods is named
+# visit_Call depending on Python version, #11097
+if compat.PY35:
+ BaseExprVisitor.visit_Call = BaseExprVisitor.visit_Call_35
+else:
+ BaseExprVisitor.visit_Call = BaseExprVisitor.visit_Call_legacy
_python_not_supported = frozenset(['Dict', 'BoolOp', 'In', 'NotIn'])
_numexpr_supported_calls = frozenset(_reductions + _mathops)
diff --git a/pandas/io/tests/__init__.py b/pandas/io/tests/__init__.py
index e6089154cd5e5..e69de29bb2d1d 100644
--- a/pandas/io/tests/__init__.py
+++ b/pandas/io/tests/__init__.py
@@ -1,4 +0,0 @@
-
-def setUp():
- import socket
- socket.setdefaulttimeout(5)
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py
index 96bac2c45340b..e39e71b474f58 100644
--- a/pandas/io/tests/test_data.py
+++ b/pandas/io/tests/test_data.py
@@ -27,6 +27,13 @@ def _skip_if_no_lxml():
except ImportError:
raise nose.SkipTest("no lxml")
+def _skip_if_no_bs():
+ try:
+ import bs4
+ import html5lib
+ except ImportError:
+ raise nose.SkipTest("no html5lib/bs4")
+
def assert_n_failed_equals_n_null_columns(wngs, obj, cls=SymbolWarning):
all_nan_cols = pd.Series(dict((k, pd.isnull(v).all()) for k, v in
@@ -288,6 +295,7 @@ class TestYahooOptions(tm.TestCase):
def setUpClass(cls):
super(TestYahooOptions, cls).setUpClass()
_skip_if_no_lxml()
+ _skip_if_no_bs()
# aapl has monthlies
cls.aapl = web.Options('aapl', 'yahoo')
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 5eef48c51d070..06338e576a2b1 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -2573,7 +2573,9 @@ def test_tuple_index(self):
idx = [(0., 1.), (2., 3.), (4., 5.)]
data = np.random.randn(30).reshape((3, 10))
DF = DataFrame(data, index=idx, columns=col)
- with tm.assert_produces_warning(expected_warning=PerformanceWarning):
+
+ expected_warning = Warning if compat.PY35 else PerformanceWarning
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
self._check_roundtrip(DF, tm.assert_frame_equal)
def test_index_types(self):
@@ -2585,23 +2587,25 @@ def test_index_types(self):
check_index_type=True,
check_series_type=True)
- with tm.assert_produces_warning(expected_warning=PerformanceWarning):
+ # nose has a deprecation warning in 3.5
+ expected_warning = Warning if compat.PY35 else PerformanceWarning
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
ser = Series(values, [0, 'y'])
self._check_roundtrip(ser, func)
- with tm.assert_produces_warning(expected_warning=PerformanceWarning):
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
ser = Series(values, [datetime.datetime.today(), 0])
self._check_roundtrip(ser, func)
- with tm.assert_produces_warning(expected_warning=PerformanceWarning):
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
ser = Series(values, ['y', 0])
self._check_roundtrip(ser, func)
- with tm.assert_produces_warning(expected_warning=PerformanceWarning):
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
ser = Series(values, [datetime.date.today(), 'a'])
self._check_roundtrip(ser, func)
- with tm.assert_produces_warning(expected_warning=PerformanceWarning):
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
ser = Series(values, [1.23, 'b'])
self._check_roundtrip(ser, func)
@@ -3377,7 +3381,8 @@ def test_retain_index_attributes2(self):
with ensure_clean_path(self.path) as path:
- with tm.assert_produces_warning(expected_warning=AttributeConflictWarning):
+ expected_warning = Warning if compat.PY35 else AttributeConflictWarning
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
df = DataFrame(dict(A = Series(lrange(3), index=date_range('2000-1-1',periods=3,freq='H'))))
df.to_hdf(path,'data',mode='w',append=True)
@@ -3391,7 +3396,7 @@ def test_retain_index_attributes2(self):
self.assertEqual(read_hdf(path,'data').index.name, 'foo')
- with tm.assert_produces_warning(expected_warning=AttributeConflictWarning):
+ with tm.assert_produces_warning(expected_warning=expected_warning, check_stacklevel=False):
idx2 = date_range('2001-1-1',periods=3,freq='H')
idx2.name = 'bar'
diff --git a/setup.py b/setup.py
index 370c49a754b95..2d1b9374f6c94 100755
--- a/setup.py
+++ b/setup.py
@@ -181,6 +181,7 @@ def build_extensions(self):
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
'Programming Language :: Cython',
'Topic :: Scientific/Engineering',
]
| closes #11097
- update install / compat docs for 3.5
- use visit_Call based on the version of python
- skip if html5lib is not installed in test_data
- bug in nose causes deprecation warning in some pytables tests
- remove superfluous socket timeout
| https://api.github.com/repos/pandas-dev/pandas/pulls/11114 | 2015-09-15T16:32:37Z | 2015-09-15T23:25:24Z | 2015-09-15T23:25:24Z | 2015-09-15T23:25:24Z |
COMPAT: Add Google BigQuery support for python 3 #11094 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 03cac12436898..c8ab9599cd92a 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -332,6 +332,7 @@ Google BigQuery Enhancements
- Added ability to replace an existing table and schema when calling the :func:`pandas.io.gbq.to_gbq` function via the ``if_exists`` argument. See the :ref:`docs <io.bigquery>` for more details (:issue:`8325`).
- ``InvalidColumnOrder`` and ``InvalidPageToken`` in the gbq module will raise ``ValueError`` instead of ``IOError``.
- The ``generate_bq_schema()`` function is now deprecated and will be removed in a future version (:issue:`11121`)
+- Update the gbq module to support Python 3 (:issue:`11094`).
.. _whatsnew_0170.enhancements.other:
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 22500f23f6e07..e9568db06f391 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -13,10 +13,9 @@
from pandas.tools.merge import concat
from pandas.core.common import PandasError
from pandas.util.decorators import deprecate
+from pandas.compat import lzip, bytes_to_str
def _check_google_client_version():
- if compat.PY3:
- raise NotImplementedError("Google's libraries do not support Python 3 yet")
try:
import pkg_resources
@@ -24,11 +23,16 @@ def _check_google_client_version():
except ImportError:
raise ImportError('Could not import pkg_resources (setuptools).')
+ if compat.PY3:
+ google_api_minimum_version = '1.4.1'
+ else:
+ google_api_minimum_version = '1.2.0'
+
_GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version
- if StrictVersion(_GOOGLE_API_CLIENT_VERSION) < StrictVersion('1.2.0'):
- raise ImportError("pandas requires google-api-python-client >= 1.2.0 for Google "
- "BigQuery support, current version " + _GOOGLE_API_CLIENT_VERSION)
+ if StrictVersion(_GOOGLE_API_CLIENT_VERSION) < StrictVersion(google_api_minimum_version):
+ raise ImportError("pandas requires google-api-python-client >= {0} for Google BigQuery support, "
+ "current version {1}".format(google_api_minimum_version, _GOOGLE_API_CLIENT_VERSION))
logger = logging.getLogger('pandas.io.gbq')
logger.setLevel(logging.ERROR)
@@ -161,7 +165,7 @@ def get_service(credentials):
def process_http_error(ex):
# See `BigQuery Troubleshooting Errors <https://cloud.google.com/bigquery/troubleshooting-errors>`__
- status = json.loads(ex.content)['error']
+ status = json.loads(bytes_to_str(ex.content))['error']
errors = status.get('errors', None)
if errors:
@@ -353,10 +357,10 @@ def _parse_data(schema, rows):
fields = schema['fields']
col_types = [field['type'] for field in fields]
- col_names = [field['name'].encode('ascii', 'ignore') for field in fields]
+ col_names = [str(field['name']) for field in fields]
col_dtypes = [dtype_map.get(field['type'], object) for field in fields]
page_array = np.zeros((len(rows),),
- dtype=zip(col_names, col_dtypes))
+ dtype=lzip(col_names, col_dtypes))
for row_num, raw_row in enumerate(rows):
entries = raw_row.get('f', [])
diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py
index b57530e926a2e..cc1e901d8f119 100644
--- a/pandas/io/tests/test_gbq.py
+++ b/pandas/io/tests/test_gbq.py
@@ -30,45 +30,44 @@
def _test_imports():
- if not compat.PY3:
+ global _GOOGLE_API_CLIENT_INSTALLED, _GOOGLE_API_CLIENT_VALID_VERSION, \
+ _HTTPLIB2_INSTALLED, _SETUPTOOLS_INSTALLED
- global _GOOGLE_API_CLIENT_INSTALLED, _GOOGLE_API_CLIENT_VALID_VERSION, \
- _HTTPLIB2_INSTALLED, _SETUPTOOLS_INSTALLED
-
- try:
- import pkg_resources
- _SETUPTOOLS_INSTALLED = True
- except ImportError:
- _SETUPTOOLS_INSTALLED = False
-
- if _SETUPTOOLS_INSTALLED:
- try:
- from apiclient.discovery import build
- from apiclient.errors import HttpError
+ try:
+ import pkg_resources
+ _SETUPTOOLS_INSTALLED = True
+ except ImportError:
+ _SETUPTOOLS_INSTALLED = False
- from oauth2client.client import OAuth2WebServerFlow
- from oauth2client.client import AccessTokenRefreshError
+ if compat.PY3:
+ google_api_minimum_version = '1.4.1'
+ else:
+ google_api_minimum_version = '1.2.0'
- from oauth2client.file import Storage
- from oauth2client.tools import run_flow
- _GOOGLE_API_CLIENT_INSTALLED=True
- _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version
+ if _SETUPTOOLS_INSTALLED:
+ try:
+ from apiclient.discovery import build
+ from apiclient.errors import HttpError
- if StrictVersion(_GOOGLE_API_CLIENT_VERSION) >= StrictVersion('1.2.0'):
- _GOOGLE_API_CLIENT_VALID_VERSION = True
+ from oauth2client.client import OAuth2WebServerFlow
+ from oauth2client.client import AccessTokenRefreshError
- except ImportError:
- _GOOGLE_API_CLIENT_INSTALLED = False
+ from oauth2client.file import Storage
+ from oauth2client.tools import run_flow
+ _GOOGLE_API_CLIENT_INSTALLED=True
+ _GOOGLE_API_CLIENT_VERSION = pkg_resources.get_distribution('google-api-python-client').version
+ if StrictVersion(_GOOGLE_API_CLIENT_VERSION) >= StrictVersion(google_api_minimum_version):
+ _GOOGLE_API_CLIENT_VALID_VERSION = True
- try:
- import httplib2
- _HTTPLIB2_INSTALLED = True
- except ImportError:
- _HTTPLIB2_INSTALLED = False
+ except ImportError:
+ _GOOGLE_API_CLIENT_INSTALLED = False
- if compat.PY3:
- raise NotImplementedError("Google's libraries do not support Python 3 yet")
+ try:
+ import httplib2
+ _HTTPLIB2_INSTALLED = True
+ except ImportError:
+ _HTTPLIB2_INSTALLED = False
if not _SETUPTOOLS_INSTALLED:
raise ImportError('Could not import pkg_resources (setuptools).')
@@ -77,8 +76,8 @@ def _test_imports():
raise ImportError('Could not import Google API Client.')
if not _GOOGLE_API_CLIENT_VALID_VERSION:
- raise ImportError("pandas requires google-api-python-client >= 1.2.0 for Google "
- "BigQuery support, current version " + _GOOGLE_API_CLIENT_VERSION)
+ raise ImportError("pandas requires google-api-python-client >= {0} for Google BigQuery support, "
+ "current version {1}".format(google_api_minimum_version, _GOOGLE_API_CLIENT_VERSION))
if not _HTTPLIB2_INSTALLED:
raise ImportError("pandas requires httplib2 for Google BigQuery support")
@@ -299,7 +298,12 @@ def test_unicode_string_conversion_and_normalization(self):
{'UNICODE_STRING': [u("\xe9\xfc")]}
)
- query = 'SELECT "\xc3\xa9\xc3\xbc" as UNICODE_STRING'
+ unicode_string = "\xc3\xa9\xc3\xbc"
+
+ if compat.PY3:
+ unicode_string = unicode_string.encode('latin-1').decode('utf8')
+
+ query = 'SELECT "{0}" as UNICODE_STRING'.format(unicode_string)
df = gbq.read_gbq(query, project_id=PROJECT_ID)
tm.assert_frame_equal(df, correct_test_datatype)
| closes #11094
Adds gbq support for python 3.4
| https://api.github.com/repos/pandas-dev/pandas/pulls/11110 | 2015-09-15T15:32:08Z | 2015-09-27T14:10:24Z | 2015-09-27T14:10:24Z | 2015-09-27T14:19:46Z |
DOC: fix ref to template for plot accessor | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 01634d7c02481..b1fe77c298d71 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -982,7 +982,7 @@ specific plotting methods of the form ``DataFrame.plot.<kind>``.
.. autosummary::
:toctree: generated/
- :template: autosummary/accessor_plot.rst
+ :template: autosummary/accessor_callable.rst
DataFrame.plot
| https://api.github.com/repos/pandas-dev/pandas/pulls/11104 | 2015-09-15T13:55:12Z | 2015-09-15T13:55:20Z | 2015-09-15T13:55:20Z | 2015-09-15T13:58:56Z | |
ENH: Data formatting with unicode length | diff --git a/doc/source/options.rst b/doc/source/options.rst
index fb57175f96eaa..46ff2b6e5c343 100644
--- a/doc/source/options.rst
+++ b/doc/source/options.rst
@@ -440,3 +440,56 @@ For instance:
pd.reset_option('^display\.')
To round floats on a case-by-case basis, you can also use :meth:`~pandas.Series.round` and :meth:`~pandas.DataFrame.round`.
+
+.. _options.east_asian_width:
+
+Unicode Formatting
+------------------
+
+.. warning::
+
+ Enabling this option will affect the performance for printing of DataFrame and Series (about 2 times slower).
+ Use only when it is actually required.
+
+Some East Asian countries use Unicode characters its width is corresponding to 2 alphabets.
+If DataFrame or Series contains these characters, default output cannot be aligned properly.
+
+.. ipython:: python
+
+ df = pd.DataFrame({u'国籍': ['UK', u'日本'], u'名前': ['Alice', u'しのぶ']})
+ df
+
+Enable ``display.unicode.east_asian_width`` allows pandas to check each character's "East Asian Width" property.
+These characters can be aligned properly by checking this property, but it takes longer time than standard ``len`` function.
+
+.. ipython:: python
+
+ pd.set_option('display.unicode.east_asian_width', True)
+ df
+
+In addition, Unicode contains characters which width is "Ambiguous". These character's width should be either 1 or 2 depending on terminal setting or encoding. Because this cannot be distinguished from Python, ``display.unicode.ambiguous_as_wide`` option is added to handle this.
+
+By default, "Ambiguous" character's width, "¡" (inverted exclamation) in below example, is regarded as 1.
+
+.. note::
+
+ This should be aligned properly in terminal which uses monospaced font.
+
+.. ipython:: python
+
+ df = pd.DataFrame({'a': ['xxx', u'¡¡'], 'b': ['yyy', u'¡¡']})
+ df
+
+Enabling ``display.unicode.ambiguous_as_wide`` lets pandas to regard these character's width as 2. Note that this option will be effective only when ``display.unicode.east_asian_width`` is enabled. Confirm starting position has been changed, but not aligned properly because the setting is mismatched with this environment.
+
+.. ipython:: python
+
+ pd.set_option('display.unicode.ambiguous_as_wide', True)
+ df
+
+.. ipython:: python
+ :suppress:
+
+ pd.set_option('display.unicode.east_asian_width', False)
+ pd.set_option('display.unicode.ambiguous_as_wide', False)
+
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 9990d2bd1c78d..59b69d22c3b62 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -49,6 +49,7 @@ Highlights include:
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>`
- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>`
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>`
+- Display format with plain text can optionally align with Unicode East Asian Width, see :ref:`here <whatsnew_0170.east_asian_width>`
- Compatibility with Python 3.5 (:issue:`11097`)
- Compatibility with matplotlib 1.5.0 (:issue:`11111`)
@@ -334,6 +335,36 @@ Google BigQuery Enhancements
- The ``generate_bq_schema()`` function is now deprecated and will be removed in a future version (:issue:`11121`)
- Update the gbq module to support Python 3 (:issue:`11094`).
+.. _whatsnew_0170.east_asian_width:
+
+Display Alignemnt with Unicode East Asian Width
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. warning::
+
+ Enabling this option will affect the performance for printing of DataFrame and Series (about 2 times slower).
+ Use only when it is actually required.
+
+Some East Asian countries use Unicode characters its width is corresponding to 2 alphabets. If DataFrame or Series contains these characters, default output cannot be aligned properly. The following options are added to enable precise handling for these characters.
+
+- ``display.unicode.east_asian_width``: Whether to use the Unicode East Asian Width to calculate the display text width. (:issue:`2612`)
+- ``display.unicode.ambiguous_as_wide``: Whether to handle Unicode characters belong to Ambiguous as Wide. (:issue:`11102`)
+
+.. ipython:: python
+
+ df = pd.DataFrame({u'国籍': ['UK', u'日本'], u'名前': ['Alice', u'しのぶ']})
+ df
+
+ pd.set_option('display.unicode.east_asian_width', True)
+ df
+
+For further details, see :ref:`here <options.east_asian_width>`
+
+.. ipython:: python
+ :suppress:
+
+ pd.set_option('display.unicode.east_asian_width', False)
+
.. _whatsnew_0170.enhancements.other:
Other enhancements
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index bad7192047e19..ba5114dd7d8ba 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -35,6 +35,7 @@
from itertools import product
import sys
import types
+from unicodedata import east_asian_width
PY2 = sys.version_info[0] == 2
PY3 = (sys.version_info[0] >= 3)
@@ -90,6 +91,7 @@ def lmap(*args, **kwargs):
def lfilter(*args, **kwargs):
return list(filter(*args, **kwargs))
+
else:
# Python 2
import re
@@ -176,6 +178,11 @@ class to receive bound method
# The license for this library can be found in LICENSES/SIX and the code can be
# found at https://bitbucket.org/gutworth/six
+# Definition of East Asian Width
+# http://unicode.org/reports/tr11/
+# Ambiguous width can be changed by option
+_EAW_MAP = {'Na': 1, 'N': 1, 'W': 2, 'F': 2, 'H': 1}
+
if PY3:
string_types = str,
integer_types = int,
@@ -188,6 +195,20 @@ def u(s):
def u_safe(s):
return s
+
+ def strlen(data, encoding=None):
+ # encoding is for compat with PY2
+ return len(data)
+
+ def east_asian_len(data, encoding=None, ambiguous_width=1):
+ """
+ Calculate display width considering unicode East Asian Width
+ """
+ if isinstance(data, text_type):
+ return sum([_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data])
+ else:
+ return len(data)
+
else:
string_types = basestring,
integer_types = (int, long)
@@ -204,6 +225,25 @@ def u_safe(s):
except:
return s
+ def strlen(data, encoding=None):
+ try:
+ data = data.decode(encoding)
+ except UnicodeError:
+ pass
+ return len(data)
+
+ def east_asian_len(data, encoding=None, ambiguous_width=1):
+ """
+ Calculate display width considering unicode East Asian Width
+ """
+ if isinstance(data, text_type):
+ try:
+ data = data.decode(encoding)
+ except UnicodeError:
+ pass
+ return sum([_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data])
+ else:
+ return len(data)
string_and_binary_types = string_types + (binary_type,)
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 2d403f904a446..2411925207696 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -2149,21 +2149,33 @@ def _count_not_none(*args):
-def adjoin(space, *lists):
+def adjoin(space, *lists, **kwargs):
"""
Glues together two sets of strings using the amount of space requested.
The idea is to prettify.
- """
+
+ ----------
+ space : int
+ number of spaces for padding
+ lists : str
+ list of str which being joined
+ strlen : callable
+ function used to calculate the length of each str. Needed for unicode
+ handling.
+ justfunc : callable
+ function used to justify str. Needed for unicode handling.
+ """
+ strlen = kwargs.pop('strlen', len)
+ justfunc = kwargs.pop('justfunc', _justify)
+
out_lines = []
newLists = []
- lengths = [max(map(len, x)) + space for x in lists[:-1]]
-
+ lengths = [max(map(strlen, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
-
maxLen = max(map(len, lists))
for i, lst in enumerate(lists):
- nl = [x.ljust(lengths[i]) for x in lst]
+ nl = justfunc(lst, lengths[i], mode='left')
nl.extend([' ' * lengths[i]] * (maxLen - len(lst)))
newLists.append(nl)
toJoin = zip(*newLists)
@@ -2171,6 +2183,16 @@ def adjoin(space, *lists):
out_lines.append(_join_unicode(lines))
return _join_unicode(out_lines, sep='\n')
+def _justify(texts, max_len, mode='right'):
+ """
+ Perform ljust, center, rjust against string or list-like
+ """
+ if mode == 'left':
+ return [x.ljust(max_len) for x in texts]
+ elif mode == 'center':
+ return [x.center(max_len) for x in texts]
+ else:
+ return [x.rjust(max_len) for x in texts]
def _join_unicode(lines, sep=''):
try:
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index 03eaa45582bef..751a530ce73cc 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -144,6 +144,17 @@
Deprecated.
"""
+pc_east_asian_width_doc = """
+: boolean
+ Whether to use the Unicode East Asian Width to calculate the display text width
+ Enabling this may affect to the performance (default: False)
+"""
+pc_ambiguous_as_wide_doc = """
+: boolean
+ Whether to handle Unicode characters belong to Ambiguous as Wide (width=2)
+ (default: False)
+"""
+
pc_line_width_deprecation_warning = """\
line_width has been deprecated, use display.width instead (currently both are
identical)
@@ -282,6 +293,10 @@ def mpl_style_cb(key):
pc_line_width_doc)
cf.register_option('memory_usage', True, pc_memory_usage_doc,
validator=is_instance_factory([type(None), bool]))
+ cf.register_option('unicode.east_asian_width', False,
+ pc_east_asian_width_doc, validator=is_bool)
+ cf.register_option('unicode.ambiguous_as_wide', False,
+ pc_east_asian_width_doc, validator=is_bool)
cf.deprecate_option('display.line_width',
msg=pc_line_width_deprecation_warning,
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 0c1a3dbadbd86..5f12abb543513 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -138,6 +138,7 @@ def __init__(self, series, buf=None, length=True, header=True,
float_format = get_option("display.float_format")
self.float_format = float_format
self.dtype = dtype
+ self.adj = _get_adjustment()
self._chk_truncate()
@@ -221,22 +222,24 @@ def to_string(self):
fmt_index, have_header = self._get_formatted_index()
fmt_values = self._get_formatted_values()
- maxlen = max(len(x) for x in fmt_index) # max index len
+ maxlen = max(self.adj.len(x) for x in fmt_index) # max index len
pad_space = min(maxlen, 60)
if self.truncate_v:
n_header_rows = 0
row_num = self.tr_row_num
- width = len(fmt_values[row_num-1])
+ width = self.adj.len(fmt_values[row_num-1])
if width > 3:
dot_str = '...'
else:
dot_str = '..'
- dot_str = dot_str.center(width)
+ # Series uses mode=center because it has single value columns
+ # DataFrame uses mode=left
+ dot_str = self.adj.justify([dot_str], width, mode='center')[0]
fmt_values.insert(row_num + n_header_rows, dot_str)
fmt_index.insert(row_num + 1, '')
- result = adjoin(3, *[fmt_index[1:], fmt_values])
+ result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values])
if self.header and have_header:
result = fmt_index[0] + '\n' + result
@@ -247,19 +250,54 @@ def to_string(self):
return compat.text_type(u('').join(result))
-def _strlen_func():
- if compat.PY3: # pragma: no cover
- _strlen = len
- else:
- encoding = get_option("display.encoding")
+class TextAdjustment(object):
+
+ def __init__(self):
+ self.encoding = get_option("display.encoding")
+
+ def len(self, text):
+ return compat.strlen(text, encoding=self.encoding)
+
+ def justify(self, texts, max_len, mode='right'):
+ return com._justify(texts, max_len, mode=mode)
+
+ def adjoin(self, space, *lists, **kwargs):
+ return com.adjoin(space, *lists, strlen=self.len,
+ justfunc=self.justify, **kwargs)
+
+
+class EastAsianTextAdjustment(TextAdjustment):
+
+ def __init__(self):
+ super(EastAsianTextAdjustment, self).__init__()
+ if get_option("display.unicode.ambiguous_as_wide"):
+ self.ambiguous_width = 2
+ else:
+ self.ambiguous_width = 1
+
+ def len(self, text):
+ return compat.east_asian_len(text, encoding=self.encoding,
+ ambiguous_width=self.ambiguous_width)
+
+ def justify(self, texts, max_len, mode='right'):
+ # re-calculate padding space per str considering East Asian Width
+ def _get_pad(t):
+ return max_len - self.len(t) + len(t)
+
+ if mode == 'left':
+ return [x.ljust(_get_pad(x)) for x in texts]
+ elif mode == 'center':
+ return [x.center(_get_pad(x)) for x in texts]
+ else:
+ return [x.rjust(_get_pad(x)) for x in texts]
- def _strlen(x):
- try:
- return len(x.decode(encoding))
- except UnicodeError:
- return len(x)
- return _strlen
+def _get_adjustment():
+ use_east_asian_width = get_option("display.unicode.east_asian_width")
+ if use_east_asian_width:
+ return EastAsianTextAdjustment()
+ else:
+ return TextAdjustment()
class TableFormatter(object):
@@ -338,6 +376,7 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
self.columns = frame.columns
self._chk_truncate()
+ self.adj = _get_adjustment()
def _chk_truncate(self):
'''
@@ -414,7 +453,6 @@ def _to_str_columns(self):
"""
Render a DataFrame to a list of columns (as lists of strings).
"""
- _strlen = _strlen_func()
frame = self.tr_frame
# may include levels names also
@@ -427,27 +465,23 @@ def _to_str_columns(self):
for i, c in enumerate(frame):
cheader = str_columns[i]
max_colwidth = max(self.col_space or 0,
- *(_strlen(x) for x in cheader))
-
+ *(self.adj.len(x) for x in cheader))
fmt_values = self._format_col(i)
-
fmt_values = _make_fixed_width(fmt_values, self.justify,
- minimum=max_colwidth)
+ minimum=max_colwidth,
+ adj=self.adj)
- max_len = max(np.max([_strlen(x) for x in fmt_values]),
+ max_len = max(np.max([self.adj.len(x) for x in fmt_values]),
max_colwidth)
- if self.justify == 'left':
- cheader = [x.ljust(max_len) for x in cheader]
- else:
- cheader = [x.rjust(max_len) for x in cheader]
-
+ cheader = self.adj.justify(cheader, max_len, mode=self.justify)
stringified.append(cheader + fmt_values)
else:
stringified = []
for i, c in enumerate(frame):
fmt_values = self._format_col(i)
fmt_values = _make_fixed_width(fmt_values, self.justify,
- minimum=(self.col_space or 0))
+ minimum=(self.col_space or 0),
+ adj=self.adj)
stringified.append(fmt_values)
@@ -461,13 +495,13 @@ def _to_str_columns(self):
if truncate_h:
col_num = self.tr_col_num
- col_width = len(strcols[self.tr_size_col][0]) # infer from column header
+ col_width = self.adj.len(strcols[self.tr_size_col][0]) # infer from column header
strcols.insert(self.tr_col_num + 1, ['...'.center(col_width)] * (len(str_index)))
if truncate_v:
n_header_rows = len(str_index) - len(frame)
row_num = self.tr_row_num
for ix, col in enumerate(strcols):
- cwidth = len(strcols[ix][row_num]) # infer from above row
+ cwidth = self.adj.len(strcols[ix][row_num]) # infer from above row
is_dot_col = False
if truncate_h:
is_dot_col = ix == col_num + 1
@@ -477,13 +511,13 @@ def _to_str_columns(self):
my_str = '..'
if ix == 0:
- dot_str = my_str.ljust(cwidth)
+ dot_mode = 'left'
elif is_dot_col:
- cwidth = len(strcols[self.tr_size_col][0])
- dot_str = my_str.center(cwidth)
+ cwidth = self.adj.len(strcols[self.tr_size_col][0])
+ dot_mode = 'center'
else:
- dot_str = my_str.rjust(cwidth)
-
+ dot_mode = 'right'
+ dot_str = self.adj.justify([my_str], cwidth, mode=dot_mode)[0]
strcols[ix].insert(row_num + n_header_rows, dot_str)
return strcols
@@ -492,6 +526,7 @@ def to_string(self):
Render a DataFrame to a console-friendly tabular output.
"""
from pandas import Series
+
frame = self.frame
if len(frame.columns) == 0 or len(frame.index) == 0:
@@ -503,11 +538,11 @@ def to_string(self):
else:
strcols = self._to_str_columns()
if self.line_width is None: # no need to wrap around just print the whole frame
- text = adjoin(1, *strcols)
+ text = self.adj.adjoin(1, *strcols)
elif not isinstance(self.max_cols, int) or self.max_cols > 0: # need to wrap around
text = self._join_multiline(*strcols)
else: # max_cols == 0. Try to fit frame to terminal
- text = adjoin(1, *strcols).split('\n')
+ text = self.adj.adjoin(1, *strcols).split('\n')
row_lens = Series(text).apply(len)
max_len_col_ix = np.argmax(row_lens)
max_len = row_lens[max_len_col_ix]
@@ -535,7 +570,7 @@ def to_string(self):
# and then generate string representation
self._chk_truncate()
strcols = self._to_str_columns()
- text = adjoin(1, *strcols)
+ text = self.adj.adjoin(1, *strcols)
self.buf.writelines(text)
@@ -549,9 +584,9 @@ def _join_multiline(self, *strcols):
strcols = list(strcols)
if self.index:
idx = strcols.pop(0)
- lwidth -= np.array([len(x) for x in idx]).max() + adjoin_width
+ lwidth -= np.array([self.adj.len(x) for x in idx]).max() + adjoin_width
- col_widths = [np.array([len(x) for x in col]).max()
+ col_widths = [np.array([self.adj.len(x) for x in col]).max()
if len(col) > 0 else 0
for col in strcols]
col_bins = _binify(col_widths, lwidth)
@@ -572,8 +607,7 @@ def _join_multiline(self, *strcols):
row.append([' \\'] + [' '] * (nrows - 1))
else:
row.append([' '] * nrows)
-
- str_lst.append(adjoin(adjoin_width, *row))
+ str_lst.append(self.adj.adjoin(adjoin_width, *row))
st = ed
return '\n\n'.join(str_lst)
@@ -776,11 +810,12 @@ def _get_formatted_index(self, frame):
formatter=fmt)
else:
fmt_index = [index.format(name=show_index_names, formatter=fmt)]
- fmt_index = [tuple(_make_fixed_width(
- list(x), justify='left', minimum=(self.col_space or 0)))
- for x in fmt_index]
+ fmt_index = [tuple(_make_fixed_width(list(x), justify='left',
+ minimum=(self.col_space or 0),
+ adj=self.adj))
+ for x in fmt_index]
- adjoined = adjoin(1, *fmt_index).split('\n')
+ adjoined = self.adj.adjoin(1, *fmt_index).split('\n')
# empty space for columns
if show_col_names:
@@ -2222,13 +2257,16 @@ def _formatter(x):
return _formatter
-def _make_fixed_width(strings, justify='right', minimum=None):
+def _make_fixed_width(strings, justify='right', minimum=None,
+ adj=None):
+
if len(strings) == 0 or justify == 'all':
return strings
- _strlen = _strlen_func()
+ if adj is None:
+ adj = _get_adjustment()
- max_len = np.max([_strlen(x) for x in strings])
+ max_len = np.max([adj.len(x) for x in strings])
if minimum is not None:
max_len = max(minimum, max_len)
@@ -2237,22 +2275,14 @@ def _make_fixed_width(strings, justify='right', minimum=None):
if conf_max is not None and max_len > conf_max:
max_len = conf_max
- if justify == 'left':
- justfunc = lambda self, x: self.ljust(x)
- else:
- justfunc = lambda self, x: self.rjust(x)
-
def just(x):
- eff_len = max_len
-
if conf_max is not None:
- if (conf_max > 3) & (_strlen(x) > max_len):
- x = x[:eff_len - 3] + '...'
-
- return justfunc(x, eff_len)
-
- result = [just(x) for x in strings]
+ if (conf_max > 3) & (adj.len(x) > max_len):
+ x = x[:max_len - 3] + '...'
+ return x
+ strings = [just(x) for x in strings]
+ result = adj.justify(strings, max_len, mode=justify)
return result
diff --git a/pandas/core/index.py b/pandas/core/index.py
index d64a20fc9563c..1daa0e1b52d02 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -488,7 +488,7 @@ def _format_data(self):
"""
Return the formatted data as a unicode string
"""
- from pandas.core.format import get_console_size
+ from pandas.core.format import get_console_size, _get_adjustment
display_width, _ = get_console_size()
if display_width is None:
display_width = get_option('display.width') or 80
@@ -502,14 +502,19 @@ def _format_data(self):
formatter = self._formatter_func
# do we want to justify (only do so for non-objects)
- is_justify = not (self.inferred_type == 'string' or self.inferred_type == 'categorical' and is_object_dtype(self.categories))
+ is_justify = not (self.inferred_type in ('string', 'unicode') or
+ (self.inferred_type == 'categorical' and
+ is_object_dtype(self.categories)))
# are we a truncated display
is_truncated = n > max_seq_items
+ # adj can optionaly handle unicode eastern asian width
+ adj = _get_adjustment()
+
def _extend_line(s, line, value, display_width, next_line_prefix):
- if len(line.rstrip()) + len(value.rstrip()) >= display_width:
+ if adj.len(line.rstrip()) + adj.len(value.rstrip()) >= display_width:
s += line.rstrip()
line = next_line_prefix
line += value
@@ -517,7 +522,7 @@ def _extend_line(s, line, value, display_width, next_line_prefix):
def best_len(values):
if values:
- return max([len(x) for x in values])
+ return max([adj.len(x) for x in values])
else:
return 0
@@ -556,8 +561,10 @@ def best_len(values):
word = head[i] + sep + ' '
summary, line = _extend_line(summary, line, word,
display_width, space2)
+
if is_truncated:
- summary += line + space2 + '...'
+ # remove trailing space of last line
+ summary += line.rstrip() + space2 + '...'
line = space2
for i in range(len(tail)-1):
@@ -4501,8 +4508,11 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False,
start=int(names),
sentinel=sentinel)
+
if adjoin:
- return com.adjoin(space, *result_levels).split('\n')
+ from pandas.core.format import _get_adjustment
+ adj = _get_adjustment()
+ return adj.adjoin(space, *result_levels).split('\n')
else:
return result_levels
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 9173c0a87f6c2..e97010e1cb552 100755
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -2,7 +2,7 @@
# pylint: disable=E1101,E1103,W0232
from datetime import datetime
-from pandas.compat import range, lrange, u
+from pandas.compat import range, lrange, u, PY3
import os
import pickle
import re
@@ -534,6 +534,33 @@ def test_print_none_width(self):
with option_context("display.width", None):
self.assertEqual(exp, repr(a))
+ def test_unicode_print(self):
+ if PY3:
+ _rep = repr
+ else:
+ _rep = unicode
+
+ c = pd.Categorical(['aaaaa', 'bb', 'cccc'] * 20)
+ expected = u"""[aaaaa, bb, cccc, aaaaa, bb, ..., bb, cccc, aaaaa, bb, cccc]
+Length: 60
+Categories (3, object): [aaaaa, bb, cccc]"""
+ self.assertEqual(_rep(c), expected)
+
+ c = pd.Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20)
+ expected = u"""[ああああ, いいいいい, ううううううう, ああああ, いいいいい, ..., いいいいい, ううううううう, ああああ, いいいいい, ううううううう]
+Length: 60
+Categories (3, object): [ああああ, いいいいい, ううううううう]"""
+ self.assertEqual(_rep(c), expected)
+
+ # unicode option should not affect to Categorical, as it doesn't care the repr width
+ with option_context('display.unicode.east_asian_width', True):
+
+ c = pd.Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20)
+ expected = u"""[ああああ, いいいいい, ううううううう, ああああ, いいいいい, ..., いいいいい, ううううううう, ああああ, いいいいい, ううううううう]
+Length: 60
+Categories (3, object): [ああああ, いいいいい, ううううううう]"""
+ self.assertEqual(_rep(c), expected)
+
def test_periodindex(self):
idx1 = PeriodIndex(['2014-01', '2014-01', '2014-02', '2014-02',
'2014-03', '2014-03'], freq='M')
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index c488d22da7dfe..003fd134cf210 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -14,6 +14,7 @@
from pandas.core.common import notnull, isnull, array_equivalent
import pandas.core.common as com
import pandas.core.convert as convert
+import pandas.core.format as fmt
import pandas.util.testing as tm
import pandas.core.config as cf
@@ -332,6 +333,99 @@ def test_adjoin():
assert(adjoined == expected)
+
+class TestFormattBase(tm.TestCase):
+
+ def test_adjoin(self):
+ data = [['a', 'b', 'c'],
+ ['dd', 'ee', 'ff'],
+ ['ggg', 'hhh', 'iii']]
+ expected = 'a dd ggg\nb ee hhh\nc ff iii'
+
+ adjoined = com.adjoin(2, *data)
+
+ self.assertEqual(adjoined, expected)
+
+ def test_adjoin_unicode(self):
+ data = [[u'あ', 'b', 'c'],
+ ['dd', u'ええ', 'ff'],
+ ['ggg', 'hhh', u'いいい']]
+ expected = u'あ dd ggg\nb ええ hhh\nc ff いいい'
+ adjoined = com.adjoin(2, *data)
+ self.assertEqual(adjoined, expected)
+
+ adj = fmt.EastAsianTextAdjustment()
+
+ expected = u"""あ dd ggg
+b ええ hhh
+c ff いいい"""
+ adjoined = adj.adjoin(2, *data)
+ self.assertEqual(adjoined, expected)
+ cols = adjoined.split('\n')
+ self.assertEqual(adj.len(cols[0]), 13)
+ self.assertEqual(adj.len(cols[1]), 13)
+ self.assertEqual(adj.len(cols[2]), 16)
+
+ expected = u"""あ dd ggg
+b ええ hhh
+c ff いいい"""
+ adjoined = adj.adjoin(7, *data)
+ self.assertEqual(adjoined, expected)
+ cols = adjoined.split('\n')
+ self.assertEqual(adj.len(cols[0]), 23)
+ self.assertEqual(adj.len(cols[1]), 23)
+ self.assertEqual(adj.len(cols[2]), 26)
+
+ def test_justify(self):
+ adj = fmt.EastAsianTextAdjustment()
+
+ def just(x, *args, **kwargs):
+ # wrapper to test single str
+ return adj.justify([x], *args, **kwargs)[0]
+
+ self.assertEqual(just('abc', 5, mode='left'), 'abc ')
+ self.assertEqual(just('abc', 5, mode='center'), ' abc ')
+ self.assertEqual(just('abc', 5, mode='right'), ' abc')
+ self.assertEqual(just(u'abc', 5, mode='left'), 'abc ')
+ self.assertEqual(just(u'abc', 5, mode='center'), ' abc ')
+ self.assertEqual(just(u'abc', 5, mode='right'), ' abc')
+
+ self.assertEqual(just(u'パンダ', 5, mode='left'), u'パンダ')
+ self.assertEqual(just(u'パンダ', 5, mode='center'), u'パンダ')
+ self.assertEqual(just(u'パンダ', 5, mode='right'), u'パンダ')
+
+ self.assertEqual(just(u'パンダ', 10, mode='left'), u'パンダ ')
+ self.assertEqual(just(u'パンダ', 10, mode='center'), u' パンダ ')
+ self.assertEqual(just(u'パンダ', 10, mode='right'), u' パンダ')
+
+ def test_east_asian_len(self):
+ adj = fmt.EastAsianTextAdjustment()
+
+ self.assertEqual(adj.len('abc'), 3)
+ self.assertEqual(adj.len(u'abc'), 3)
+
+ self.assertEqual(adj.len(u'パンダ'), 6)
+ self.assertEqual(adj.len(u'パンダ'), 5)
+ self.assertEqual(adj.len(u'パンダpanda'), 11)
+ self.assertEqual(adj.len(u'パンダpanda'), 10)
+
+
+ def test_ambiguous_width(self):
+ adj = fmt.EastAsianTextAdjustment()
+ self.assertEqual(adj.len(u'¡¡ab'), 4)
+
+ with cf.option_context('display.unicode.ambiguous_as_wide', True):
+ adj = fmt.EastAsianTextAdjustment()
+ self.assertEqual(adj.len(u'¡¡ab'), 6)
+
+ data = [[u'あ', 'b', 'c'],
+ ['dd', u'ええ', 'ff'],
+ ['ggg', u'¡¡ab', u'いいい']]
+ expected = u'あ dd ggg \nb ええ ¡¡ab\nc ff いいい'
+ adjoined = adj.adjoin(2, *data)
+ self.assertEqual(adjoined, expected)
+
+
def test_iterpairs():
data = [1, 2, 3, 4]
expected = [(1, 2),
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index 58c365029a694..b5220c8cb2706 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -162,10 +162,10 @@ def test_repr_truncation(self):
r = repr(df)
r = r[r.find('\n') + 1:]
- _strlen = fmt._strlen_func()
+ adj = fmt._get_adjustment()
for line, value in lzip(r.split('\n'), df['B']):
- if _strlen(value) + 1 > max_len:
+ if adj.len(value) + 1 > max_len:
self.assertIn('...', line)
else:
self.assertNotIn('...', line)
@@ -438,6 +438,209 @@ def test_to_string_with_formatters_unicode(self):
self.assertEqual(result, u(' c/\u03c3\n') +
'0 1\n1 2\n2 3')
+ def test_east_asian_unicode_frame(self):
+ if PY3:
+ _rep = repr
+ else:
+ _rep = unicode
+
+ # not alighned properly because of east asian width
+
+ # mid col
+ df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'],
+ 'b': [1, 222, 33333, 4]},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" a b\na あ 1\n"
+ u"bb いいい 222\nc う 33333\n"
+ u"ddd ええええええ 4")
+ self.assertEqual(_rep(df), expected)
+
+ # last col
+ df = DataFrame({'a': [1, 222, 33333, 4],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" a b\na 1 あ\n"
+ u"bb 222 いいい\nc 33333 う\n"
+ u"ddd 4 ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # all col
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" a b\na あああああ あ\n"
+ u"bb い いいい\nc う う\n"
+ u"ddd えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # column name
+ df = DataFrame({u'あああああ': [1, 222, 33333, 4],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" b あああああ\na あ 1\n"
+ u"bb いいい 222\nc う 33333\n"
+ u"ddd ええええええ 4")
+ self.assertEqual(_rep(df), expected)
+
+ # index
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=[u'あああ', u'いいいいいい', u'うう', u'え'])
+ expected = (u" a b\nあああ あああああ あ\n"
+ u"いいいいいい い いいい\nうう う う\n"
+ u"え えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # index name
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=pd.Index([u'あ', u'い', u'うう', u'え'], name=u'おおおお'))
+ expected = (u" a b\nおおおお \nあ あああああ あ\n"
+ u"い い いいい\nうう う う\nえ えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # all
+ df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'],
+ u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']},
+ index=pd.Index([u'あ', u'いいい', u'うう', u'え'], name=u'お'))
+ expected = (u" あああ いいいいい\nお \nあ あああ あ\n"
+ u"いいい い いいい\nうう う う\nえ えええええ ええ")
+ self.assertEqual(_rep(df), expected)
+
+ # MultiIndex
+ idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'),
+ (u'おおお', u'かかかか'), (u'き', u'くく')])
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=idx)
+ expected = (u" a b\nあ いい あああああ あ\n"
+ u"う え い いいい\nおおお かかかか う う\n"
+ u"き くく えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # truncate
+ with option_context('display.max_rows', 3, 'display.max_columns', 3):
+ df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ'],
+ 'c': [u'お', u'か', u'ききき', u'くくくくくく'],
+ u'ああああ': [u'さ', u'し', u'す', u'せ']},
+ columns=['a', 'b', 'c', u'ああああ'])
+
+ expected = (u" a ... ああああ\n0 あああああ ... さ\n"
+ u".. ... ... ...\n3 えええ ... せ\n"
+ u"\n[4 rows x 4 columns]")
+ self.assertEqual(_rep(df), expected)
+
+ df.index = [u'あああ', u'いいいい', u'う', 'aaa']
+ expected = (u" a ... ああああ\nあああ あああああ ... さ\n"
+ u".. ... ... ...\naaa えええ ... せ\n"
+ u"\n[4 rows x 4 columns]")
+ self.assertEqual(_rep(df), expected)
+
+ # Emable Unicode option -----------------------------------------
+ with option_context('display.unicode.east_asian_width', True):
+
+ # mid col
+ df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'],
+ 'b': [1, 222, 33333, 4]},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" a b\na あ 1\n"
+ u"bb いいい 222\nc う 33333\n"
+ u"ddd ええええええ 4")
+ self.assertEqual(_rep(df), expected)
+
+ # last col
+ df = DataFrame({'a': [1, 222, 33333, 4],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" a b\na 1 あ\n"
+ u"bb 222 いいい\nc 33333 う\n"
+ u"ddd 4 ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # all col
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" a b\na あああああ あ\n"
+ u"bb い いいい\nc う う\n"
+ u"ddd えええ ええええええ""")
+ self.assertEqual(_rep(df), expected)
+
+ # column name
+ df = DataFrame({u'あああああ': [1, 222, 33333, 4],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=['a', 'bb', 'c', 'ddd'])
+ expected = (u" b あああああ\na あ 1\n"
+ u"bb いいい 222\nc う 33333\n"
+ u"ddd ええええええ 4")
+ self.assertEqual(_rep(df), expected)
+
+ # index
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=[u'あああ', u'いいいいいい', u'うう', u'え'])
+ expected = (u" a b\nあああ あああああ あ\n"
+ u"いいいいいい い いいい\nうう う う\n"
+ u"え えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # index name
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']},
+ index=pd.Index([u'あ', u'い', u'うう', u'え'], name=u'おおおお'))
+ expected = (u" a b\nおおおお \n"
+ u"あ あああああ あ\nい い いいい\n"
+ u"うう う う\nえ えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # all
+ df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'],
+ u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']},
+ index=pd.Index([u'あ', u'いいい', u'うう', u'え'], name=u'お'))
+ expected = (u" あああ いいいいい\nお \n"
+ u"あ あああ あ\nいいい い いいい\n"
+ u"うう う う\nえ えええええ ええ")
+ self.assertEqual(_rep(df), expected)
+
+ # MultiIndex
+ idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'),
+ (u'おおお', u'かかかか'), (u'き', u'くく')])
+ df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=idx)
+ expected = (u" a b\nあ いい あああああ あ\n"
+ u"う え い いいい\nおおお かかかか う う\n"
+ u"き くく えええ ええええええ")
+ self.assertEqual(_rep(df), expected)
+
+ # truncate
+ with option_context('display.max_rows', 3, 'display.max_columns', 3):
+
+ df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'],
+ 'b': [u'あ', u'いいい', u'う', u'ええええええ'],
+ 'c': [u'お', u'か', u'ききき', u'くくくくくく'],
+ u'ああああ': [u'さ', u'し', u'す', u'せ']},
+ columns=['a', 'b', 'c', u'ああああ'])
+
+ expected = (u" a ... ああああ\n0 あああああ ... さ\n"
+ u".. ... ... ...\n3 えええ ... せ\n"
+ u"\n[4 rows x 4 columns]")
+ self.assertEqual(_rep(df), expected)
+
+ df.index = [u'あああ', u'いいいい', u'う', 'aaa']
+ expected = (u" a ... ああああ\nあああ あああああ ... さ\n"
+ u"... ... ... ...\naaa えええ ... せ\n"
+ u"\n[4 rows x 4 columns]")
+ self.assertEqual(_rep(df), expected)
+
+ # ambiguous unicode
+ df = DataFrame({u'あああああ': [1, 222, 33333, 4],
+ 'b': [u'あ', u'いいい', u'¡¡', u'ええええええ']},
+ index=['a', 'bb', 'c', '¡¡¡'])
+ expected = (u" b あああああ\na あ 1\n"
+ u"bb いいい 222\nc ¡¡ 33333\n"
+ u"¡¡¡ ええええええ 4")
+ self.assertEqual(_rep(df), expected)
+
def test_to_string_buffer_all_unicode(self):
buf = StringIO()
@@ -895,10 +1098,6 @@ def test_to_html_regression_GH6098(self):
# it works
df.pivot_table(index=[u('clé1')], columns=[u('clé2')])._repr_html_()
-
-
-
-
def test_to_html_truncate(self):
raise nose.SkipTest("unreliable on travis")
index = pd.DatetimeIndex(start='20010101',freq='D',periods=20)
@@ -2888,6 +3087,148 @@ def test_unicode_name_in_footer(self):
sf = fmt.SeriesFormatter(s, name=u('\u05e2\u05d1\u05e8\u05d9\u05ea'))
sf._get_footer() # should not raise exception
+ def test_east_asian_unicode_series(self):
+ if PY3:
+ _rep = repr
+ else:
+ _rep = unicode
+ # not alighned properly because of east asian width
+
+ # unicode index
+ s = Series(['a', 'bb', 'CCC', 'D'],
+ index=[u'あ', u'いい', u'ううう', u'ええええ'])
+ expected = (u"あ a\nいい bb\nううう CCC\n"
+ u"ええええ D\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # unicode values
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=['a', 'bb', 'c', 'ddd'])
+ expected = (u"a あ\nbb いい\nc ううう\n"
+ u"ddd ええええ\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # both
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
+ index=[u'ああ', u'いいいい', u'う', u'えええ'])
+ expected = (u"ああ あ\nいいいい いい\nう ううう\n"
+ u"えええ ええええ\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # unicode footer
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
+ index=[u'ああ', u'いいいい', u'う', u'えええ'],
+ name=u'おおおおおおお')
+ expected = (u"ああ あ\nいいいい いい\nう ううう\n"
+ u"えええ ええええ\nName: おおおおおおお, dtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # MultiIndex
+ idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'),
+ (u'おおお', u'かかかか'), (u'き', u'くく')])
+ s = Series([1, 22, 3333, 44444], index=idx)
+ expected = (u"あ いい 1\nう え 22\nおおお かかかか 3333\n"
+ u"き くく 44444\ndtype: int64")
+ self.assertEqual(_rep(s), expected)
+
+ # object dtype, shorter than unicode repr
+ s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ'])
+ expected = (u"1 1\nAB 22\nNaN 3333\n"
+ u"あああ 44444\ndtype: int64")
+ self.assertEqual(_rep(s), expected)
+
+ # object dtype, longer than unicode repr
+ s = Series([1, 22, 3333, 44444],
+ index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ'])
+ expected = (u"1 1\nAB 22\n"
+ u"2011-01-01 00:00:00 3333\nあああ 44444\ndtype: int64")
+ self.assertEqual(_rep(s), expected)
+
+ # truncate
+ with option_context('display.max_rows', 3):
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
+ name=u'おおおおおおお')
+
+ expected = (u"0 あ\n ... \n"
+ u"3 ええええ\nName: おおおおおおお, dtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ s.index = [u'ああ', u'いいいい', u'う', u'えええ']
+ expected = (u"ああ あ\n ... \n"
+ u"えええ ええええ\nName: おおおおおおお, dtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # Emable Unicode option -----------------------------------------
+ with option_context('display.unicode.east_asian_width', True):
+
+ # unicode index
+ s = Series(['a', 'bb', 'CCC', 'D'],
+ index=[u'あ', u'いい', u'ううう', u'ええええ'])
+ expected = (u"あ a\nいい bb\nううう CCC\n"
+ u"ええええ D\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # unicode values
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=['a', 'bb', 'c', 'ddd'])
+ expected = (u"a あ\nbb いい\nc ううう\n"
+ u"ddd ええええ\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # both
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
+ index=[u'ああ', u'いいいい', u'う', u'えええ'])
+ expected = (u"ああ あ\nいいいい いい\nう ううう\n"
+ u"えええ ええええ\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # unicode footer
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
+ index=[u'ああ', u'いいいい', u'う', u'えええ'],
+ name=u'おおおおおおお')
+ expected = (u"ああ あ\nいいいい いい\nう ううう\n"
+ u"えええ ええええ\nName: おおおおおおお, dtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # MultiIndex
+ idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'),
+ (u'おおお', u'かかかか'), (u'き', u'くく')])
+ s = Series([1, 22, 3333, 44444], index=idx)
+ expected = (u"あ いい 1\nう え 22\nおおお かかかか 3333\n"
+ u"き くく 44444\ndtype: int64")
+ self.assertEqual(_rep(s), expected)
+
+ # object dtype, shorter than unicode repr
+ s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ'])
+ expected = (u"1 1\nAB 22\nNaN 3333\n"
+ u"あああ 44444\ndtype: int64")
+ self.assertEqual(_rep(s), expected)
+
+ # object dtype, longer than unicode repr
+ s = Series([1, 22, 3333, 44444],
+ index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ'])
+ expected = (u"1 1\nAB 22\n"
+ u"2011-01-01 00:00:00 3333\nあああ 44444\ndtype: int64")
+ self.assertEqual(_rep(s), expected)
+
+ # truncate
+ with option_context('display.max_rows', 3):
+ s = Series([u'あ', u'いい', u'ううう', u'ええええ'],
+ name=u'おおおおおおお')
+ expected = (u"0 あ\n ... \n"
+ u"3 ええええ\nName: おおおおおおお, dtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ s.index = [u'ああ', u'いいいい', u'う', u'えええ']
+ expected = (u"ああ あ\n ... \n"
+ u"えええ ええええ\nName: おおおおおおお, dtype: object")
+ self.assertEqual(_rep(s), expected)
+
+ # ambiguous unicode
+ s = Series([u'¡¡', u'い¡¡', u'ううう', u'ええええ'],
+ index=[u'ああ', u'¡¡¡¡いい', u'¡¡', u'えええ'])
+ expected = (u"ああ ¡¡\n¡¡¡¡いい い¡¡\n¡¡ ううう\n"
+ u"えええ ええええ\ndtype: object")
+ self.assertEqual(_rep(s), expected)
+
def test_float_trim_zeros(self):
vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10,
2.03954217305e+10, 5.59897817305e+10]
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 75daabe2dab67..81ebc7efdbdd9 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -2,7 +2,7 @@
# pylint: disable=E1101,E1103,W0232
from datetime import datetime, timedelta, time
-from pandas.compat import range, lrange, lzip, u, zip
+from pandas.compat import range, lrange, lzip, u, zip, PY3
import operator
import re
import nose
@@ -1842,6 +1842,137 @@ def test_conversion_preserves_name(self):
self.assertEqual(i.name, pd.to_datetime(i).name)
self.assertEqual(i.name, pd.to_timedelta(i).name)
+ def test_string_index_repr(self):
+ # py3/py2 repr can differ because of "u" prefix
+ # which also affects to displayed element size
+
+ # short
+ idx = pd.Index(['a', 'bb', 'ccc'])
+ if PY3:
+ expected = u"""Index(['a', 'bb', 'ccc'], dtype='object')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'a', u'bb', u'ccc'], dtype='object')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # multiple lines
+ idx = pd.Index(['a', 'bb', 'ccc'] * 10)
+ if PY3:
+ expected = u"""Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc',
+ 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc',
+ 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
+ dtype='object')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a',
+ u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb',
+ u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'],
+ dtype='object')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # truncated
+ idx = pd.Index(['a', 'bb', 'ccc'] * 100)
+ if PY3:
+ expected = u"""Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
+ ...
+ 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
+ dtype='object', length=300)"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a',
+ ...
+ u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'],
+ dtype='object', length=300)"""
+ self.assertEqual(unicode(idx), expected)
+
+ # short
+ idx = pd.Index([u'あ', u'いい', u'ううう'])
+ if PY3:
+ expected = u"""Index(['あ', 'いい', 'ううう'], dtype='object')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'あ', u'いい', u'ううう'], dtype='object')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # multiple lines
+ idx = pd.Index([u'あ', u'いい', u'ううう'] * 10)
+ if PY3:
+ expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
+ dtype='object')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'],
+ dtype='object')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # truncated
+ idx = pd.Index([u'あ', u'いい', u'ううう'] * 100)
+ if PY3:
+ expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
+ ...
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
+ dtype='object', length=300)"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ ...
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'],
+ dtype='object', length=300)"""
+ self.assertEqual(unicode(idx), expected)
+
+ # Emable Unicode option -----------------------------------------
+ with cf.option_context('display.unicode.east_asian_width', True):
+
+ # short
+ idx = pd.Index([u'あ', u'いい', u'ううう'])
+ if PY3:
+ expected = u"""Index(['あ', 'いい', 'ううう'], dtype='object')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'あ', u'いい', u'ううう'], dtype='object')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # multiple lines
+ idx = pd.Index([u'あ', u'いい', u'ううう'] * 10)
+ if PY3:
+ expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう'],
+ dtype='object')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'],
+ dtype='object')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # truncated
+ idx = pd.Index([u'あ', u'いい', u'ううう'] * 100)
+ if PY3:
+ expected = u"""Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ',
+ ...
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
+ 'ううう'],
+ dtype='object', length=300)"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""Index([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ',
+ ...
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう'],
+ dtype='object', length=300)"""
+ self.assertEqual(unicode(idx), expected)
+
+
class TestCategoricalIndex(Base, tm.TestCase):
_holder = CategoricalIndex
@@ -2211,6 +2342,180 @@ def test_equals(self):
self.assertFalse(CategoricalIndex(list('aabca') + [np.nan],categories=['c','a','b']).equals(list('aabca')))
self.assertTrue(CategoricalIndex(list('aabca') + [np.nan],categories=['c','a','b']).equals(list('aabca') + [np.nan]))
+ def test_string_categorical_index_repr(self):
+ # short
+ idx = pd.CategoricalIndex(['a', 'bb', 'ccc'])
+ if PY3:
+ expected = u"""CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'a', u'bb', u'ccc'], categories=[u'a', u'bb', u'ccc'], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # multiple lines
+ idx = pd.CategoricalIndex(['a', 'bb', 'ccc'] * 10)
+ if PY3:
+ expected = u"""CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
+ 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb',
+ 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
+ categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb',
+ u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a',
+ u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc',
+ u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'],
+ categories=[u'a', u'bb', u'ccc'], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # truncated
+ idx = pd.CategoricalIndex(['a', 'bb', 'ccc'] * 100)
+ if PY3:
+ expected = u"""CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
+ ...
+ 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
+ categories=['a', 'bb', 'ccc'], ordered=False, dtype='category', length=300)"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb',
+ u'ccc', u'a',
+ ...
+ u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a',
+ u'bb', u'ccc'],
+ categories=[u'a', u'bb', u'ccc'], ordered=False, dtype='category', length=300)"""
+ self.assertEqual(unicode(idx), expected)
+
+ # larger categories
+ idx = pd.CategoricalIndex(list('abcdefghijklmmo'))
+ if PY3:
+ expected = u"""CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
+ 'm', 'm', 'o'],
+ categories=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', ...], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j',
+ u'k', u'l', u'm', u'm', u'o'],
+ categories=[u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', ...], ordered=False, dtype='category')"""
+
+ self.assertEqual(unicode(idx), expected)
+
+ # short
+ idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'])
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう'], categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # multiple lines
+ idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 10)
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
+ 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう',
+ u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう'],
+ categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # truncated
+ idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 100)
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
+ ...
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ',
+ ...
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう'],
+ categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category', length=300)"""
+ self.assertEqual(unicode(idx), expected)
+
+ # larger categories
+ idx = pd.CategoricalIndex(list(u'あいうえおかきくけこさしすせそ'))
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し',
+ 'す', 'せ', 'そ'],
+ categories=['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', ...], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', u'け', u'こ',
+ u'さ', u'し', u'す', u'せ', u'そ'],
+ categories=[u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', ...], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # Emable Unicode option -----------------------------------------
+ with cf.option_context('display.unicode.east_asian_width', True):
+
+ # short
+ idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'])
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう'], categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # multiple lines
+ idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 10)
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ', u'いい', u'ううう'],
+ categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
+ # truncated
+ idx = pd.CategoricalIndex([u'あ', u'いい', u'ううう'] * 100)
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
+ 'ううう', 'あ',
+ ...
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
+ 'あ', 'いい', 'ううう'],
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'いい', u'ううう', u'あ', u'いい', u'ううう', u'あ',
+ u'いい', u'ううう', u'あ',
+ ...
+ u'ううう', u'あ', u'いい', u'ううう', u'あ', u'いい',
+ u'ううう', u'あ', u'いい', u'ううう'],
+ categories=[u'あ', u'いい', u'ううう'], ordered=False, dtype='category', length=300)"""
+ self.assertEqual(unicode(idx), expected)
+
+ # larger categories
+ idx = pd.CategoricalIndex(list(u'あいうえおかきくけこさしすせそ'))
+ if PY3:
+ expected = u"""CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ',
+ 'さ', 'し', 'す', 'せ', 'そ'],
+ categories=['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', ...], ordered=False, dtype='category')"""
+ self.assertEqual(repr(idx), expected)
+ else:
+ expected = u"""CategoricalIndex([u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く',
+ u'け', u'こ', u'さ', u'し', u'す', u'せ', u'そ'],
+ categories=[u'あ', u'い', u'う', u'え', u'お', u'か', u'き', u'く', ...], ordered=False, dtype='category')"""
+ self.assertEqual(unicode(idx), expected)
+
class Numeric(Base):
| Closes #2612. Added `display.unicode.east_asian_width` options, which calculate text width considering East Asian Width. Enabling this option affects to a performance as width must be calculated per characters.
#### Current results (captured)

- [x] Basic impl and test
- [x] Series / DataFrame truncation
- [x] Perf test
- [x] Doc / Release note
| https://api.github.com/repos/pandas-dev/pandas/pulls/11102 | 2015-09-15T12:38:20Z | 2015-10-03T14:41:03Z | 2015-10-03T14:41:03Z | 2015-10-03T22:24:44Z |
ENH Add user defined function support to read_gbq | diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 37e7cb944814a..15566486573c8 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -181,7 +181,7 @@ def process_insert_errors(self, insert_errors, verbose):
raise StreamingInsertError
- def run_query(self, query, verbose=True):
+ def run_query(self, query, verbose=True, udf_uris=[]):
from apiclient.errors import HttpError
from oauth2client.client import AccessTokenRefreshError
@@ -197,6 +197,12 @@ def run_query(self, query, verbose=True):
}
}
+ if len(udf_uris) > 0:
+ udf_resources = job_data['configuration']['query']['userDefinedFunctionResources'] = []
+ for uri in udf_uris:
+ uri_resource = {'resourceUri': uri}
+ udf_resources.append(uri_resource)
+
try:
query_reply = job_collection.insert(projectId=self.project_id, body=job_data).execute()
except AccessTokenRefreshError:
@@ -418,7 +424,7 @@ def _parse_entry(field_value, field_type):
return field_value
-def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False, verbose=True):
+def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False, verbose=True, udf_uris=[]):
"""Load data from Google BigQuery.
THIS IS AN EXPERIMENTAL LIBRARY
@@ -446,6 +452,10 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=Fals
verbose : boolean (default True)
Verbose output
+ udf_uris : list(str) (optional)
+ List of Google Cloud Storage URIs for user defined functions (UDFs)
+ used in your query.
+
Returns
-------
df: DataFrame
@@ -457,7 +467,7 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=Fals
raise TypeError("Missing required parameter: project_id")
connector = GbqConnector(project_id, reauth=reauth)
- schema, pages = connector.run_query(query, verbose=verbose)
+ schema, pages = connector.run_query(query, verbose=verbose, udf_uris=udf_uris)
dataframe_list = []
while len(pages) > 0:
page = pages.pop()
| Added support for BigQuery's new user defined function (UDF) feature. See https://cloud.google.com/bigquery/user-defined-functions#api for details.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11099 | 2015-09-15T02:29:11Z | 2015-10-11T15:43:28Z | null | 2015-10-11T15:43:28Z |
DOC: Fixed outdated doc-string, added missing default values, added missing optional parameters for some io classes | diff --git a/pandas/io/data.py b/pandas/io/data.py
index 1a4c45628a256..310b165101bdf 100644
--- a/pandas/io/data.py
+++ b/pandas/io/data.py
@@ -53,12 +53,17 @@ def DataReader(name, data_source=None, start=None, end=None,
name : str or list of strs
the name of the dataset. Some data sources (yahoo, google, fred) will
accept a list of names.
- data_source: str
+ data_source: str, default: None
the data source ("yahoo", "google", "fred", or "ff")
- start : {datetime, None}
+ start : datetime, default: None
left boundary for range (defaults to 1/1/2010)
- end : {datetime, None}
+ end : datetime, default: None
right boundary for range (defaults to today)
+ retry_count : int, default 3
+ Number of times to retry query request.
+ pause : numeric, default 0.001
+ Time, in seconds, to pause between consecutive queries of chunks. If
+ single value given for symbol, represents the pause between retries.
Examples
----------
@@ -398,28 +403,28 @@ def get_data_yahoo(symbols=None, start=None, end=None, retry_count=3,
Parameters
----------
- symbols : string, array-like object (list, tuple, Series), or DataFrame
+ symbols : string, array-like object (list, tuple, Series), or DataFrame, default: None
Single stock symbol (ticker), array-like object of symbols or
- DataFrame with index containing stock symbols.
+ DataFrame with index containing stock symbols
start : string, (defaults to '1/1/2010')
Starting date, timestamp. Parses many different kind of date
representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980')
end : string, (defaults to today)
Ending date, timestamp. Same format as starting date.
- retry_count : int, default 3
+ retry_count : int, default: 3
Number of times to retry query request.
- pause : int, default 0
+ pause : numeric, default: 0.001
Time, in seconds, to pause between consecutive queries of chunks. If
single value given for symbol, represents the pause between retries.
- adjust_price : bool, default False
+ adjust_price : bool, default: False
If True, adjusts all prices in hist_data ('Open', 'High', 'Low',
'Close') based on 'Adj Close' price. Adds 'Adj_Ratio' column and drops
'Adj Close'.
- ret_index : bool, default False
+ ret_index : bool, default: False
If True, includes a simple return index 'Ret_Index' in hist_data.
- chunksize : int, default 25
+ chunksize : int, default: 25
Number of symbols to download consecutively before intiating pause.
- interval : string, default 'd'
+ interval : string, default: 'd'
Time interval code, valid values are 'd' for daily, 'w' for weekly,
'm' for monthly and 'v' for dividend.
@@ -451,13 +456,15 @@ def get_data_google(symbols=None, start=None, end=None, retry_count=3,
representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980')
end : string, (defaults to today)
Ending date, timestamp. Same format as starting date.
- retry_count : int, default 3
+ retry_count : int, default: 3
Number of times to retry query request.
- pause : int, default 0
+ pause : numeric, default: 0.001
Time, in seconds, to pause between consecutive queries of chunks. If
single value given for symbol, represents the pause between retries.
- chunksize : int, default 25
+ chunksize : int, default: 25
Number of symbols to download consecutively before intiating pause.
+ ret_index : bool, default: False
+ If True, includes a simple return index 'Ret_Index' in hist_data.
Returns
-------
@@ -903,10 +910,10 @@ def get_near_stock_price(self, above_below=2, call=True, put=False,
The number of strike prices above and below the stock price that
should be taken
- call : bool
+ call : bool, default: True
Tells the function whether or not it should be using calls
- put : bool
+ put : bool, default: False
Tells the function weather or not it should be using puts
month : number, int, optional(default=None)
diff --git a/pandas/io/ga.py b/pandas/io/ga.py
index 57de5c6f5abb4..b6b4081e3650f 100644
--- a/pandas/io/ga.py
+++ b/pandas/io/ga.py
@@ -30,10 +30,9 @@
dimensions : list of str
Un-prefixed dimension variable names
start_date : str/date/datetime
-end_date : str/date/datetime, optional
- Defaults to today
-segment : list of str, optional
-filters : list of str, optional
+end_date : str/date/datetime, optional, default is None but internally set as today
+segment : list of str, optional, default: None
+filters : list of str, optional, default: None
start_index : int, default 1
max_results : int, default 10000
If >10000, must specify chunksize or ValueError will be raised"""
@@ -58,21 +57,21 @@
Sort output by index or list of columns
chunksize : int, optional
If max_results >10000, specifies the number of rows per iteration
-index_col : str/list of str/dict, optional
+index_col : str/list of str/dict, optional, default: None
If unspecified then dimension variables are set as index
-parse_dates : bool/list/dict, default True
-keep_date_col : boolean, default False
-date_parser : optional
-na_values : optional
-converters : optional
+parse_dates : bool/list/dict, default: True
+keep_date_col : boolean, default: False
+date_parser : optional, default: None
+na_values : optional, default: None
+converters : optional, default: None
dayfirst : bool, default False
Informs date parsing
-account_name : str, optional
-account_id : str, optional
-property_name : str, optional
-property_id : str, optional
-profile_name : str, optional
-profile_id : str, optional
+account_name : str, optional, default: None
+account_id : str, optional, default: None
+property_name : str, optional, default: None
+property_id : str, optional, default: None
+profile_name : str, optional, default: None
+profile_id : str, optional, default: None
%%(extras)s
Returns
-------
@@ -192,8 +191,8 @@ def get_account(self, name=None, id=None, **kwargs):
Parameters
----------
- name : str, optional
- id : str, optional
+ name : str, optional, default: None
+ id : str, optional, default: None
"""
accounts = self.service.management().accounts().list().execute()
return _get_match(accounts, name, id, **kwargs)
@@ -205,9 +204,9 @@ def get_web_property(self, account_id=None, name=None, id=None, **kwargs):
Parameters
----------
- account_id : str, optional
- name : str, optional
- id : str, optional
+ account_id : str, optional, default: None
+ name : str, optional, default: None
+ id : str, optional, default: None
"""
prop_store = self.service.management().webproperties()
kwds = {}
@@ -225,10 +224,10 @@ def get_profile(self, account_id=None, web_property_id=None, name=None,
Parameters
----------
- account_id : str, optional
- web_property_id : str, optional
- name : str, optional
- id : str, optional
+ account_id : str, optional, default: None
+ web_property_id : str, optional, default: None
+ name : str, optional, default: None
+ id : str, optional, default: None
"""
profile_store = self.service.management().profiles()
kwds = {}
diff --git a/pandas/io/json.py b/pandas/io/json.py
index d6310d81ab87f..f368f0e6cf28e 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -110,12 +110,12 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
Parameters
----------
- filepath_or_buffer : a valid JSON string or file-like
+ path_or_buf : a valid JSON string or file-like, default: None
The string could be a URL. Valid URL schemes include http, ftp, s3, and
file. For file URLs, a host is expected. For instance, a local file
could be ``file://localhost/path/to/table.json``
- orient
+ orient
* `Series`
@@ -162,13 +162,13 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
* it is ``'date'``
- keep_default_dates : boolean, default True.
+ keep_default_dates : boolean, default True
If parsing dates, then parse the default datelike columns
numpy : boolean, default False
Direct decoding to numpy arrays. Supports numeric data only, but
non-numeric column and index labels are supported. Note also that the
JSON ordering MUST be the same for each term if numpy=True.
- precise_float : boolean, default False.
+ precise_float : boolean, default False
Set to enable usage of higher precision (strtod) function when
decoding string to double values. Default (False) is to use fast but
less precise builtin functionality
@@ -582,6 +582,8 @@ def nested_to_record(ds, prefix="", level=0):
Parameters
----------
ds : dict or list of dicts
+ prefix: the prefix, optional, default: ""
+ level: the number of levels in the jason string, optional, default: 0
Returns
-------
@@ -646,7 +648,7 @@ def json_normalize(data, record_path=None, meta=None,
record_path : string or list of strings, default None
Path in each object to list of records. If not passed, data will be
assumed to be an array of records
- meta : list of paths (string or list of strings)
+ meta : list of paths (string or list of strings), default None
Fields to use as metadata for each record in resulting table
record_prefix : string, default None
If True, prefix records with dotted (?) path, e.g. foo.bar.field if
| Some doc-strings are outdated, in a sense that there are missing newly added optional parameters and default values.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11098 | 2015-09-14T23:54:06Z | 2015-09-17T17:27:23Z | 2015-09-17T17:27:23Z | 2015-09-17T17:34:49Z |
ERR/API: Raise NotImplementedError when method is not implemented (issue: 7692) | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 1a976bf0d921e..4ea4f0a5ab307 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1107,7 +1107,7 @@ Bug Fixes
- Bug causes memory leak in time-series line and area plot (:issue:`9003`)
- Bug when setting a ``Panel`` sliced along the major or minor axes when the right-hand side is a ``DataFrame`` (:issue:`11014`)
-
+- Bug that returns ``None`` and does not raise `NotImplementedError` when operator functions of ``Panel`` are not implemented (:issue:`7692`)
- Bug in line and kde plot cannot accept multiple colors when ``subplots=True`` (:issue:`9894`)
- Bug in ``DataFrame.plot`` raises ``ValueError`` when color name is specified by multiple characters (:issue:`10387`)
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index 1293b4034b84e..08ef82835830c 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -679,6 +679,10 @@ def _combine(self, other, func, axis=0):
return self._combine_frame(other, func, axis=axis)
elif np.isscalar(other):
return self._combine_const(other, func)
+ else:
+ raise NotImplementedError(str(type(other)) +
+ ' is not supported in combine operation with ' +
+ str(type(self)))
def _combine_const(self, other, func):
new_values = func(self.values, other)
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 7c67ded16139c..bd27d11ef14c1 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -7,6 +7,7 @@
import nose
import numpy as np
+import pandas as pd
from pandas import Series, DataFrame, Index, isnull, notnull, pivot, MultiIndex
from pandas.core.datetools import bday
@@ -354,6 +355,16 @@ def test_combinePanel(self):
def test_neg(self):
self.assert_panel_equal(-self.panel, self.panel * -1)
+ # issue 7692
+ def test_raise_when_not_implemented(self):
+ p = Panel(np.arange(3*4*5).reshape(3,4,5), items=['ItemA','ItemB','ItemC'],
+ major_axis=pd.date_range('20130101',periods=4),minor_axis=list('ABCDE'))
+ d = p.sum(axis=1).ix[0]
+ ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'div', 'mod', 'pow']
+ for op in ops:
+ with self.assertRaises(NotImplementedError):
+ getattr(p,op)(d, axis=0)
+
def test_select(self):
p = self.panel
| Fixed #7692
| https://api.github.com/repos/pandas-dev/pandas/pulls/11095 | 2015-09-14T20:27:25Z | 2015-09-21T15:32:17Z | null | 2015-09-21T15:33:55Z |
TST: More thorough test to check correctness of to_html_unicode | diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index 6c92bb7095d8b..d6abb00e55e7b 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -521,11 +521,12 @@ def test_to_html_with_empty_string_label(self):
self.assertTrue("rowspan" not in res)
def test_to_html_unicode(self):
- # it works!
df = DataFrame({u('\u03c3'): np.arange(10.)})
- df.to_html()
+ expected = u'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>\u03c3</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9</td>\n </tr>\n </tbody>\n</table>'
+ self.assertEqual(df.to_html(), expected)
df = DataFrame({'A': [u('\u03c3')]})
- df.to_html()
+ expected = u'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>\u03c3</td>\n </tr>\n </tbody>\n</table>'
+ self.assertEqual(df.to_html(), expected)
def test_to_html_escaped(self):
a = 'str<ing1 &'
| The current test for `test_to_html_unicode` only checks for whether the function works but does not check for its correctness.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11093 | 2015-09-14T15:25:50Z | 2015-09-16T23:02:08Z | 2015-09-16T23:02:08Z | 2015-09-16T23:02:45Z |
DOC: Update "enhancing perf" doc based on #10953 | diff --git a/doc/source/enhancingperf.rst b/doc/source/enhancingperf.rst
index 855a459f48cf4..028e6d064a561 100644
--- a/doc/source/enhancingperf.rst
+++ b/doc/source/enhancingperf.rst
@@ -449,12 +449,15 @@ These operations are supported by :func:`pandas.eval`:
- Attribute access, e.g., ``df.a``
- Subscript expressions, e.g., ``df[0]``
- Simple variable evaluation, e.g., ``pd.eval('df')`` (this is not very useful)
+- Math functions, `sin`, `cos`, `exp`, `log`, `expm1`, `log1p`,
+ `sqrt`, `sinh`, `cosh`, `tanh`, `arcsin`, `arccos`, `arctan`, `arccosh`,
+ `arcsinh`, `arctanh`, `abs` and `arctan2`.
This Python syntax is **not** allowed:
* Expressions
- - Function calls
+ - Function calls other than math functions.
- ``is``/``is not`` operations
- ``if`` expressions
- ``lambda`` expressions
| Updated ["enhancing performance"](http://pandas.pydata.org/pandas-docs/stable/enhancingperf.html#enhancingperf-eval) doc based on #10953.
CC @sklam
| https://api.github.com/repos/pandas-dev/pandas/pulls/11092 | 2015-09-14T12:21:30Z | 2015-09-14T13:10:48Z | 2015-09-14T13:10:48Z | 2015-09-14T13:10:51Z |
TST: Fix skipped unit tests in test_ga. Install python-gflags using p… | diff --git a/ci/requirements-2.7.pip b/ci/requirements-2.7.pip
index ff1978a8d45ed..644457d69b37f 100644
--- a/ci/requirements-2.7.pip
+++ b/ci/requirements-2.7.pip
@@ -1,3 +1,4 @@
blosc
httplib2
google-api-python-client == 1.2
+python-gflags == 2.0
diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt
index d6a1e2d362330..2764e740886da 100644
--- a/ci/requirements-2.7.txt
+++ b/ci/requirements-2.7.txt
@@ -20,4 +20,3 @@ patsy
pymysql=0.6.3
html5lib=1.0b2
beautiful-soup=4.2.1
-python-gflags=2.0
diff --git a/ci/requirements-2.7_SLOW.txt b/ci/requirements-2.7_SLOW.txt
index 1a56434c62f86..563ce3e1190e6 100644
--- a/ci/requirements-2.7_SLOW.txt
+++ b/ci/requirements-2.7_SLOW.txt
@@ -20,4 +20,3 @@ psycopg2
pymysql
html5lib
beautiful-soup
-python-gflags
diff --git a/pandas/io/tests/test_ga.py b/pandas/io/tests/test_ga.py
index cc26411e8d364..13d31b43ac39a 100644
--- a/pandas/io/tests/test_ga.py
+++ b/pandas/io/tests/test_ga.py
@@ -3,11 +3,14 @@
import nose
import pandas as pd
-from pandas import DataFrame
+from pandas import compat
from pandas.util.testing import network, assert_frame_equal, with_connectivity_check
from numpy.testing.decorators import slow
import pandas.util.testing as tm
+if compat.PY3:
+ raise nose.SkipTest("python-gflags does not support Python 3 yet")
+
try:
import httplib2
import pandas.io.ga as ga
@@ -17,6 +20,7 @@
except ImportError:
raise nose.SkipTest("need httplib2 and auth libs")
+
class TestGoogle(tm.TestCase):
_multiprocess_can_split_ = True
@@ -29,8 +33,7 @@ def test_remove_token_store(self):
reset_default_token_store()
self.assertFalse(os.path.exists(auth.DEFAULT_TOKEN_FILE))
- @slow
- @network
+ @with_connectivity_check("http://www.google.com")
def test_getdata(self):
try:
end_date = datetime.now()
@@ -45,18 +48,19 @@ def test_getdata(self):
start_date=start_date,
end_date=end_date,
dimensions=['date', 'hour'],
- parse_dates={'ts': ['date', 'hour']})
-
- assert isinstance(df, DataFrame)
- assert isinstance(df.index, pd.DatetimeIndex)
- assert len(df) > 1
- assert 'date' not in df
- assert 'hour' not in df
- assert df.index.name == 'ts'
- assert 'avgTimeOnSite' in df
- assert 'visitors' in df
- assert 'newVisits' in df
- assert 'pageviewsPerVisit' in df
+ parse_dates={'ts': ['date', 'hour']},
+ index_col=0)
+
+ self.assertIsInstance(df, pd.DataFrame)
+ self.assertIsInstance(df.index, pd.DatetimeIndex)
+ self.assertGreater(len(df), 1)
+ self.assertTrue('date' not in df)
+ self.assertTrue('hour' not in df)
+ self.assertEqual(df.index.name, 'ts')
+ self.assertTrue('avgTimeOnSite' in df)
+ self.assertTrue('visitors' in df)
+ self.assertTrue('newVisits' in df)
+ self.assertTrue('pageviewsPerVisit' in df)
df2 = read_ga(
metrics=['avgTimeOnSite', 'visitors', 'newVisits',
@@ -64,14 +68,14 @@ def test_getdata(self):
start_date=start_date,
end_date=end_date,
dimensions=['date', 'hour'],
- parse_dates={'ts': ['date', 'hour']})
+ parse_dates={'ts': ['date', 'hour']},
+ index_col=0)
assert_frame_equal(df, df2)
except AuthenticationConfigError:
raise nose.SkipTest("authentication error")
- @slow
@with_connectivity_check("http://www.google.com")
def test_iterator(self):
try:
@@ -81,20 +85,21 @@ def test_iterator(self):
metrics='visitors',
start_date='2005-1-1',
dimensions='date',
- max_results=10, chunksize=5)
+ max_results=10, chunksize=5,
+ index_col=0)
df1 = next(it)
df2 = next(it)
for df in [df1, df2]:
- assert isinstance(df, DataFrame)
- assert isinstance(df.index, pd.DatetimeIndex)
- assert len(df) == 5
- assert 'date' not in df
- assert df.index.name == 'date'
- assert 'visitors' in df
+ self.assertIsInstance(df, pd.DataFrame)
+ self.assertIsInstance(df.index, pd.DatetimeIndex)
+ self.assertEqual(len(df), 5)
+ self.assertTrue('date' not in df)
+ self.assertEqual(df.index.name, 'date')
+ self.assertTrue('visitors' in df)
- assert (df2.index > df1.index).all()
+ self.assertTrue((df2.index > df1.index).all())
except AuthenticationConfigError:
raise nose.SkipTest("authentication error")
@@ -102,30 +107,28 @@ def test_iterator(self):
def test_v2_advanced_segment_format(self):
advanced_segment_id = 1234567
query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id)
- assert query['segment'] == 'gaid::' + str(advanced_segment_id), "An integer value should be formatted as an advanced segment."
+ self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "An integer value should be formatted as an advanced segment.")
def test_v2_dynamic_segment_format(self):
dynamic_segment_id = 'medium==referral'
query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=dynamic_segment_id)
- assert query['segment'] == 'dynamic::ga:' + str(dynamic_segment_id), "A string value with more than just letters and numbers should be formatted as a dynamic segment."
+ self.assertEqual(query['segment'], 'dynamic::ga:' + str(dynamic_segment_id), "A string value with more than just letters and numbers should be formatted as a dynamic segment.")
def test_v3_advanced_segment_common_format(self):
advanced_segment_id = 'aZwqR234'
query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id)
- assert query['segment'] == 'gaid::' + str(advanced_segment_id), "A string value with just letters and numbers should be formatted as an advanced segment."
+ self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "A string value with just letters and numbers should be formatted as an advanced segment.")
def test_v3_advanced_segment_weird_format(self):
advanced_segment_id = '_aZwqR234-s1'
query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id)
- assert query['segment'] == 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and hyphens should be formatted as an advanced segment."
+ self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and hyphens should be formatted as an advanced segment.")
def test_v3_advanced_segment_with_underscore_format(self):
advanced_segment_id = 'aZwqR234_s1'
query = ga.format_query('google_profile_id', ['visits'], '2013-09-01', segment=advanced_segment_id)
- assert query['segment'] == 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and underscores should be formatted as an advanced segment."
-
+ self.assertEqual(query['segment'], 'gaid::' + str(advanced_segment_id), "A string value with just letters, numbers, and underscores should be formatted as an advanced segment.")
- @slow
@with_connectivity_check("http://www.google.com")
def test_segment(self):
try:
@@ -142,20 +145,21 @@ def test_segment(self):
end_date=end_date,
segment=-2,
dimensions=['date', 'hour'],
- parse_dates={'ts': ['date', 'hour']})
-
- assert isinstance(df, DataFrame)
- assert isinstance(df.index, pd.DatetimeIndex)
- assert len(df) > 1
- assert 'date' not in df
- assert 'hour' not in df
- assert df.index.name == 'ts'
- assert 'avgTimeOnSite' in df
- assert 'visitors' in df
- assert 'newVisits' in df
- assert 'pageviewsPerVisit' in df
-
- #dynamic
+ parse_dates={'ts': ['date', 'hour']},
+ index_col=0)
+
+ self.assertIsInstance(df, pd.DataFrame)
+ self.assertIsInstance(df.index, pd.DatetimeIndex)
+ self.assertGreater(len(df), 1)
+ self.assertTrue('date' not in df)
+ self.assertTrue('hour' not in df)
+ self.assertEqual(df.index.name, 'ts')
+ self.assertTrue('avgTimeOnSite' in df)
+ self.assertTrue('visitors' in df)
+ self.assertTrue('newVisits' in df)
+ self.assertTrue('pageviewsPerVisit' in df)
+
+ # dynamic
df = read_ga(
metrics=['avgTimeOnSite', 'visitors', 'newVisits',
'pageviewsPerVisit'],
@@ -163,18 +167,19 @@ def test_segment(self):
end_date=end_date,
segment="source=~twitter",
dimensions=['date', 'hour'],
- parse_dates={'ts': ['date', 'hour']})
+ parse_dates={'ts': ['date', 'hour']},
+ index_col=0)
- assert isinstance(df, DataFrame)
+ assert isinstance(df, pd.DataFrame)
assert isinstance(df.index, pd.DatetimeIndex)
- assert len(df) > 1
- assert 'date' not in df
- assert 'hour' not in df
- assert df.index.name == 'ts'
- assert 'avgTimeOnSite' in df
- assert 'visitors' in df
- assert 'newVisits' in df
- assert 'pageviewsPerVisit' in df
+ self.assertGreater(len(df), 1)
+ self.assertTrue('date' not in df)
+ self.assertTrue('hour' not in df)
+ self.assertEqual(df.index.name, 'ts')
+ self.assertTrue('avgTimeOnSite' in df)
+ self.assertTrue('visitors' in df)
+ self.assertTrue('newVisits' in df)
+ self.assertTrue('pageviewsPerVisit' in df)
except AuthenticationConfigError:
raise nose.SkipTest("authentication error")
| closes #11090
This commit should resolve the following error in the travis build log.
```
-------------------------------------------------------------
#15 nose.failure.Failure.runTest: need httplib2 and auth libs
-------------------------------------------------------------
```
Valid Google credentials are required to run the ga unit tests.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11091 | 2015-09-13T20:15:02Z | 2015-09-14T19:51:21Z | 2015-09-14T19:51:21Z | 2015-09-14T20:23:13Z |
TST: make sure to close stata readers | diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index 29f0422c58ac8..8505150932c90 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -98,19 +98,19 @@ def test_read_empty_dta(self):
def test_data_method(self):
# Minimal testing of legacy data method
- reader_114 = StataReader(self.dta1_114)
- with warnings.catch_warnings(record=True) as w:
- parsed_114_data = reader_114.data()
+ with StataReader(self.dta1_114) as rdr:
+ with warnings.catch_warnings(record=True) as w:
+ parsed_114_data = rdr.data()
- reader_114 = StataReader(self.dta1_114)
- parsed_114_read = reader_114.read()
+ with StataReader(self.dta1_114) as rdr:
+ parsed_114_read = rdr.read()
tm.assert_frame_equal(parsed_114_data, parsed_114_read)
def test_read_dta1(self):
- reader_114 = StataReader(self.dta1_114)
- parsed_114 = reader_114.read()
- reader_117 = StataReader(self.dta1_117)
- parsed_117 = reader_117.read()
+
+ parsed_114 = self.read_dta(self.dta1_114)
+ parsed_117 = self.read_dta(self.dta1_117)
+
# Pandas uses np.nan as missing value.
# Thus, all columns will be of type float, regardless of their name.
expected = DataFrame([(np.nan, np.nan, np.nan, np.nan, np.nan)],
@@ -264,19 +264,18 @@ def test_read_dta18(self):
for col in parsed_118.columns:
tm.assert_almost_equal(parsed_118[col], expected[col])
- rdr = StataReader(self.dta22_118)
- vl = rdr.variable_labels()
- vl_expected = {u'Unicode_Cities_Strl': u'Here are some strls with Ünicode chars',
- u'Longs': u'long data',
- u'Things': u'Here are some things',
- u'Bytes': u'byte data',
- u'Ints': u'int data',
- u'Cities': u'Here are some cities',
- u'Floats': u'float data'}
- tm.assert_dict_equal(vl, vl_expected)
-
- self.assertEqual(rdr.data_label, u'This is a Ünicode data label')
+ with StataReader(self.dta22_118) as rdr:
+ vl = rdr.variable_labels()
+ vl_expected = {u'Unicode_Cities_Strl': u'Here are some strls with Ünicode chars',
+ u'Longs': u'long data',
+ u'Things': u'Here are some things',
+ u'Bytes': u'byte data',
+ u'Ints': u'int data',
+ u'Cities': u'Here are some cities',
+ u'Floats': u'float data'}
+ tm.assert_dict_equal(vl, vl_expected)
+ self.assertEqual(rdr.data_label, u'This is a Ünicode data label')
def test_read_write_dta5(self):
original = DataFrame([(np.nan, np.nan, np.nan, np.nan, np.nan)],
@@ -610,8 +609,10 @@ def test_bool_uint(self):
tm.assert_frame_equal(written_and_read_again, expected)
def test_variable_labels(self):
- sr_115 = StataReader(self.dta16_115).variable_labels()
- sr_117 = StataReader(self.dta16_117).variable_labels()
+ with StataReader(self.dta16_115) as rdr:
+ sr_115 = rdr.variable_labels()
+ with StataReader(self.dta16_117) as rdr:
+ sr_117 = rdr.variable_labels()
keys = ('var1', 'var2', 'var3')
labels = ('label1', 'label2', 'label3')
for k,v in compat.iteritems(sr_115):
@@ -652,7 +653,8 @@ def test_missing_value_generator(self):
df = DataFrame([[0.0]],columns=['float_'])
with tm.ensure_clean() as path:
df.to_stata(path)
- valid_range = StataReader(path).VALID_RANGE
+ with StataReader(path) as rdr:
+ valid_range = rdr.VALID_RANGE
expected_values = ['.' + chr(97 + i) for i in range(26)]
expected_values.insert(0, '.')
for t in types:
| https://api.github.com/repos/pandas-dev/pandas/pulls/11088 | 2015-09-13T15:27:25Z | 2015-09-13T18:27:40Z | 2015-09-13T18:27:40Z | 2015-09-13T18:27:40Z | |
DOC: Comparison with SAS | diff --git a/doc/source/comparison_with_sas.rst b/doc/source/comparison_with_sas.rst
new file mode 100644
index 0000000000000..fd42c97c9cbc0
--- /dev/null
+++ b/doc/source/comparison_with_sas.rst
@@ -0,0 +1,607 @@
+.. currentmodule:: pandas
+.. _compare_with_sas:
+
+Comparison with SAS
+********************
+For potential users coming from `SAS <https://en.wikipedia.org/wiki/SAS_(software)>`__
+this page is meant to demonstrate how different SAS operations would be
+performed in pandas.
+
+If you're new to pandas, you might want to first read through :ref:`10 Minutes to pandas<10min>`
+to familiarize yourself with the library.
+
+As is customary, we import pandas and numpy as follows:
+
+.. ipython:: python
+
+ import pandas as pd
+ import numpy as np
+
+
+.. note::
+
+ Throughout this tutorial, the pandas ``DataFrame`` will be displayed by calling
+ ``df.head()``, which displays the first N (default 5) rows of the ``DataFrame``.
+ This is often used in interactive work (e.g. `Jupyter notebook
+ <https://jupyter.org/>`_ or terminal) - the equivalent in SAS would be:
+
+ .. code-block:: none
+
+ proc print data=df(obs=5);
+ run;
+
+Data Structures
+---------------
+
+General Terminology Translation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. csv-table::
+ :header: "pandas", "SAS"
+ :widths: 20, 20
+
+ ``DataFrame``, data set
+ column, variable
+ row, observation
+ groupby, BY-group
+ ``NaN``, ``.``
+
+
+``DataFrame`` / ``Series``
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A ``DataFrame`` in pandas is analogous to a SAS data set - a two-dimensional
+data source with labeled columns that can be of different types. As will be
+shown in this document, almost any operation that can be applied to a data set
+using SAS's ``DATA`` step, can also be accomplished in pandas.
+
+A ``Series`` is the data structure that represents one column of a
+``DataFrame``. SAS doesn't have a separate data structure for a single column,
+but in general, working with a ``Series`` is analogous to referencing a column
+in the ``DATA`` step.
+
+``Index``
+~~~~~~~~~
+
+Every ``DataFrame`` and ``Series`` has an ``Index`` - which are labels on the
+*rows* of the data. SAS does not have an exactly analogous concept. A data set's
+row are essentially unlabeled, other than an implicit integer index that can be
+accessed during the ``DATA`` step (``_N_``).
+
+In pandas, if no index is specified, an integer index is also used by default
+(first row = 0, second row = 1, and so on). While using a labeled ``Index`` or
+``MultiIndex`` can enable sophisticated analyses and is ultimately an important
+part of pandas to understand, for this comparison we will essentially ignore the
+``Index`` and just treat the ``DataFrame`` as a collection of columns. Please
+see the :ref:`indexing documentation<indexing>` for much more on how to use an
+``Index`` effectively.
+
+
+Data Input / Output
+-------------------
+
+Constructing a DataFrame from Values
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A SAS data set can be built from specified values by
+placing the data after a ``datalines`` statement and
+specifying the column names.
+
+.. code-block:: none
+
+ data df;
+ input x y;
+ datalines;
+ 1 2
+ 3 4
+ 5 6
+ ;
+ run;
+
+A pandas ``DataFrame`` can be constructed in many different ways,
+but for a small number of values, it is often convenient to specify it as
+a python dictionary, where the keys are the column names
+and the values are the data.
+
+.. ipython:: python
+
+ df = pd.DataFrame({
+ 'x': [1, 3, 5],
+ 'y': [2, 4, 6]})
+ df
+
+
+Reading External Data
+~~~~~~~~~~~~~~~~~~~~~
+
+Like SAS, pandas provides utilities for reading in data from
+many formats. The ``tips`` dataset, found within the pandas
+tests (`csv <https://raw.github.com/pydata/pandas/master/pandas/tests/data/tips.csv>`_)
+will be used in many of the following examples.
+
+SAS provides ``PROC IMPORT`` to read csv data into a data set.
+
+.. code-block:: none
+
+ proc import datafile='tips.csv' dbms=csv out=tips replace;
+ getnames=yes;
+ run;
+
+The pandas method is :func:`read_csv`, which works similarly.
+
+.. ipython:: python
+
+ url = 'https://raw.github.com/pydata/pandas/master/pandas/tests/data/tips.csv'
+ tips = pd.read_csv(url)
+ tips.head()
+
+
+Like ``PROC IMPORT``, ``read_csv`` can take a number of parameters to specify
+how the data should be parsed. For example, if the data was instead tab delimited,
+and did not have column names, the pandas command would be:
+
+.. code-block:: python
+
+ tips = pd.read_csv('tips.csv', sep='\t', header=False)
+
+ # alternatively, read_table is an alias to read_csv with tab delimiter
+ tips = pd.read_table('tips.csv', header=False)
+
+In addition to text/csv, pandas supports a variety of other data formats
+such as Excel, HDF5, and SQL databases. These are all read via a ``pd.read_*``
+function. See the :ref:`IO documentation<io>` for more details.
+
+Exporting Data
+~~~~~~~~~~~~~~
+
+The inverse of ``PROC IMPORT`` in SAS is ``PROC EXPORT``
+
+.. code-block:: none
+
+ proc export data=tips outfile='tips2.csv' dbms=csv;
+ run;
+
+Similarly in pandas, the opposite of ``read_csv`` is :meth:`~DataFrame.to_csv`,
+and other data formats follow a similar api.
+
+.. code-block:: python
+
+ tips.to_csv('tips2.csv')
+
+
+Data Operations
+---------------
+
+Operations on Columns
+~~~~~~~~~~~~~~~~~~~~~
+
+In the ``DATA`` step, arbitrary math expressions can
+be used on new or existing columns.
+
+.. code-block:: none
+
+ data tips;
+ set tips;
+ total_bill = total_bill - 2;
+ new_bill = total_bill / 2;
+ run;
+
+pandas provides similar vectorized operations by
+specifying the individual ``Series`` in the ``DataFrame``.
+New columns can be assigned in the same way.
+
+.. ipython:: python
+
+ tips['total_bill'] = tips['total_bill'] - 2
+ tips['new_bill'] = tips['total_bill'] / 2.0
+ tips.head()
+
+.. ipython:: python
+ :suppress:
+
+ tips = tips.drop('new_bill', axis=1)
+
+Filtering
+~~~~~~~~~
+
+Filtering in SAS is done with an ``if`` or ``where`` statement, on one
+or more columns.
+
+.. code-block:: none
+
+ data tips;
+ set tips;
+ if total_bill > 10;
+ run;
+
+ data tips;
+ set tips;
+ where total_bill > 10;
+ /* equivalent in this case - where happens before the
+ DATA step begins and can also be used in PROC statements */
+ run;
+
+DataFrames can be filtered in multiple ways; the most intuitive of which is using
+:ref:`boolean indexing <indexing.boolean>`
+
+.. ipython:: python
+
+ tips[tips['total_bill'] > 10].head()
+
+If/Then Logic
+~~~~~~~~~~~~~
+
+In SAS, if/then logic can be used to create new columns.
+
+.. code-block:: none
+
+ data tips;
+ set tips;
+ format bucket $4.;
+
+ if total_bill < 10 then bucket = 'low';
+ else bucket = 'high';
+ run;
+
+The same operation in pandas can be accomplished using
+the ``where`` method from ``numpy``.
+
+.. ipython:: python
+
+ tips['bucket'] = np.where(tips['total_bill'] < 10, 'low', 'high')
+ tips.head()
+
+.. ipython:: python
+ :suppress:
+
+ tips = tips.drop('bucket', axis=1)
+
+Date Functionality
+~~~~~~~~~~~~~~~~~~
+
+SAS provides a variety of functions to do operations on
+date/datetime columns.
+
+.. code-block:: none
+
+ data tips;
+ set tips;
+ format date1 date2 date1_plusmonth mmddyy10.;
+ date1 = mdy(1, 15, 2013);
+ date2 = mdy(2, 15, 2015);
+ date1_year = year(date1);
+ date2_month = month(date2);
+ * shift date to begninning of next interval;
+ date1_next = intnx('MONTH', date1, 1);
+ * count intervals between dates;
+ months_between = intck('MONTH', date1, date2);
+ run;
+
+The equivalent pandas operations are shown below. In addition to these
+functions pandas supports other Time Series features
+not available in Base SAS (such as resampling and and custom offets) -
+see the :ref:`timeseries documentation<timeseries>` for more details.
+
+.. ipython:: python
+
+ tips['date1'] = pd.Timestamp('2013-01-15')
+ tips['date2'] = pd.Timestamp('2015-02-15')
+ tips['date1_year'] = tips['date1'].dt.year
+ tips['date2_month'] = tips['date2'].dt.month
+ tips['date1_next'] = tips['date1'] + pd.offsets.MonthBegin()
+ tips['months_between'] = (tips['date2'].dt.to_period('M') -
+ tips['date1'].dt.to_period('M'))
+
+ tips[['date1','date2','date1_year','date2_month',
+ 'date1_next','months_between']].head()
+
+.. ipython:: python
+ :suppress:
+
+ tips = tips.drop(['date1','date2','date1_year',
+ 'date2_month','date1_next','months_between'], axis=1)
+
+Selection of Columns
+~~~~~~~~~~~~~~~~~~~~
+
+SAS provides keywords in the ``DATA`` step to select,
+drop, and rename columns.
+
+.. code-block:: none
+
+ data tips;
+ set tips;
+ keep sex total_bill tip;
+ run;
+
+ data tips;
+ set tips;
+ drop sex;
+ run;
+
+ data tips;
+ set tips;
+ rename total_bill=total_bill_2;
+ run;
+
+The same operations are expressed in pandas below.
+
+.. ipython:: python
+
+ # keep
+ tips[['sex', 'total_bill', 'tip']].head()
+
+ # drop
+ tips.drop('sex', axis=1).head()
+
+ # rename
+ tips.rename(columns={'total_bill':'total_bill_2'}).head()
+
+
+Sorting by Values
+~~~~~~~~~~~~~~~~~
+
+Sorting in SAS is accomplished via ``PROC SORT``
+
+.. code-block:: none
+
+ proc sort data=tips;
+ by sex total_bill;
+ run;
+
+pandas objects have a :meth:`~DataFrame.sort_values` method, which
+takes a list of columnns to sort by.
+
+.. ipython:: python
+
+ tips = tips.sort_values(['sex', 'total_bill'])
+ tips.head()
+
+Merging
+-------
+
+The following tables will be used in the merge examples
+
+.. ipython:: python
+
+ df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'],
+ 'value': np.random.randn(4)})
+ df1
+ df2 = pd.DataFrame({'key': ['B', 'D', 'D', 'E'],
+ 'value': np.random.randn(4)})
+ df2
+
+In SAS, data must be explicitly sorted before merging. Different
+types of joins are accomplished using the ``in=`` dummy
+variables to track whether a match was found in one or both
+input frames.
+
+.. code-block:: none
+
+ proc sort data=df1;
+ by key;
+ run;
+
+ proc sort data=df2;
+ by key;
+ run;
+
+ data left_join inner_join right_join outer_join;
+ merge df1(in=a) df2(in=b);
+
+ if a and b then output inner_join;
+ if a then output left_join;
+ if b then output right_join;
+ if a or b then output outer_join;
+ run;
+
+pandas DataFrames have a :meth:`~DataFrame.merge` method, which provides
+similar functionality. Note that the data does not have
+to be sorted ahead of time, and different join
+types are accomplished via the ``how`` keyword.
+
+.. ipython:: python
+
+ inner_join = df1.merge(df2, on=['key'], how='inner')
+ inner_join
+
+ left_join = df1.merge(df2, on=['key'], how='left')
+ left_join
+
+ right_join = df1.merge(df2, on=['key'], how='right')
+ right_join
+
+ outer_join = df1.merge(df2, on=['key'], how='outer')
+ outer_join
+
+
+Missing Data
+------------
+
+Like SAS, pandas has a representation for missing data - which is the
+special float value ``NaN`` (not a number). Many of the semantics
+are the same, for example missing data propagates through numeric
+operations, and is ignored by default for aggregations.
+
+.. ipython:: python
+
+ outer_join
+ outer_join['value_x'] + outer_join['value_y']
+ outer_join['value_x'].sum()
+
+One difference is that missing data cannot be compared to its sentinel value.
+For example, in SAS you could do this to filter missing values.
+
+.. code-block:: none
+
+ data outer_join_nulls;
+ set outer_join;
+ if value_x = .;
+ run;
+
+ data outer_join_no_nulls;
+ set outer_join;
+ if value_x ^= .;
+ run;
+
+Which doesn't work in in pandas. Instead, the ``pd.isnull`` or ``pd.notnull`` functions
+should be used for comparisons.
+
+.. ipython:: python
+
+ outer_join[pd.isnull(outer_join['value_x'])]
+ outer_join[pd.notnull(outer_join['value_x'])]
+
+pandas also provides a variety of methods to work with missing data - some of
+which would be challenging to express in SAS. For example, there are methods to
+drop all rows with any missing values, replacing missing values with a specified
+value, like the mean, or forward filling from previous rows. See the
+:ref:`missing data documentation<missing_data>` for more.
+
+.. ipython:: python
+
+ outer_join.dropna()
+ outer_join.fillna(method='ffill')
+ outer_join['value_x'].fillna(outer_join['value_x'].mean())
+
+
+GroupBy
+-------
+
+Aggregation
+~~~~~~~~~~~
+
+SAS's PROC SUMMARY can be used to group by one or
+more key variables and compute aggregations on
+numeric columns.
+
+.. code-block:: none
+
+ proc summary data=tips nway;
+ class sex smoker;
+ var total_bill tip;
+ output out=tips_summed sum=;
+ run;
+
+pandas provides a flexible ``groupby`` mechanism that
+allows similar aggregations. See the :ref:`groupby documentation<groupby>`
+for more details and examples.
+
+.. ipython:: python
+
+ tips_summed = tips.groupby(['sex', 'smoker'])['total_bill', 'tip'].sum()
+ tips_summed.head()
+
+
+Transformation
+~~~~~~~~~~~~~~
+
+In SAS, if the group aggregations need to be used with
+the original frame, it must be merged back together. For
+example, to subtract the mean for each observation by smoker group.
+
+.. code-block:: none
+
+ proc summary data=tips missing nway;
+ class smoker;
+ var total_bill;
+ output out=smoker_means mean(total_bill)=group_bill;
+ run;
+
+ proc sort data=tips;
+ by smoker;
+ run;
+
+ data tips;
+ merge tips(in=a) smoker_means(in=b);
+ by smoker;
+ adj_total_bill = total_bill - group_bill;
+ if a and b;
+ run;
+
+
+pandas ``groubpy`` provides a ``transform`` mechanism that allows
+these type of operations to be succinctly expressed in one
+operation.
+
+.. ipython:: python
+
+ gb = tips.groupby('smoker')['total_bill']
+ tips['adj_total_bill'] = tips['total_bill'] - gb.transform('mean')
+ tips.head()
+
+
+By Group Processing
+~~~~~~~~~~~~~~~~~~~
+
+In addition to aggregation, pandas ``groupby`` can be used to
+replicate most other by group processing from SAS. For example,
+this ``DATA`` step reads the data by sex/smoker group and filters to
+the first entry for each.
+
+.. code-block:: none
+
+ proc sort data=tips;
+ by sex smoker;
+ run;
+
+ data tips_first;
+ set tips;
+ by sex smoker;
+ if FIRST.sex or FIRST.smoker then output;
+ run;
+
+In pandas this would be written as:
+
+.. ipython:: python
+
+ tips.groupby(['sex','smoker']).first()
+
+
+Other Considerations
+--------------------
+
+Disk vs Memory
+~~~~~~~~~~~~~~
+
+pandas operates exclusively in memory, where a SAS data set exists on disk.
+This means that the size of data able to be loaded in pandas is limited by your
+machine's memory, but also that the operations on that data may be faster.
+
+If out of core processing is needed, one possibility is the
+`dask.dataframe <http://dask.pydata.org/en/latest/dataframe.html>`_
+library (currently in development) which
+provides a subset of pandas functionality for an on-disk ``DataFrame``
+
+Data Interop
+~~~~~~~~~~~~
+
+pandas provides a :func:`read_sas` method that can read SAS data saved in
+the XPORT format. The ability to read SAS's binary format is planned for a
+future release.
+
+.. code-block:: none
+
+ libname xportout xport 'transport-file.xpt';
+ data xportout.tips;
+ set tips(rename=(total_bill=tbill));
+ * xport variable names limited to 6 characters;
+ run;
+
+.. code-block:: python
+
+ df = pd.read_sas('transport-file.xpt')
+
+XPORT is a relatively limited format and the parsing of it is not as
+optimized as some of the other pandas readers. An alternative way
+to interop data between SAS and pandas is to serialize to csv.
+
+.. code-block:: python
+
+ # version 0.17, 10M rows
+
+ In [8]: %time df = pd.read_sas('big.xpt')
+ Wall time: 14.6 s
+
+ In [9]: %time df = pd.read_csv('big.csv')
+ Wall time: 4.86 s
diff --git a/doc/source/index.rst.template b/doc/source/index.rst.template
index f4469482ec290..621bd33ba5a41 100644
--- a/doc/source/index.rst.template
+++ b/doc/source/index.rst.template
@@ -145,6 +145,7 @@ See the package overview for more detail about what's in the library.
ecosystem
comparison_with_r
comparison_with_sql
+ comparison_with_sas
{% endif -%}
{% if api -%}
api
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 6e74e2c68e44e..2010939724c5e 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -62,6 +62,7 @@ Highlights include:
- Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`)
- Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`)
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>`
+- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>`
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>`
See the :ref:`v0.17.0 Whatsnew <whatsnew_0170>` overview for an extensive list
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 3f6da20c4a422..cdc5ffb2fa556 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -47,6 +47,7 @@ Highlights include:
- Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`)
- Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`)
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>`
+- Documentation comparing SAS to *pandas*, see :ref:`here <compare_with_sas>`
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>`
Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating.
| closes #11075
xref #4052
There doesn't seem to be a straightforward way to syntax highlight the SAS code, so it will format as generic code blocks.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11087 | 2015-09-13T14:17:11Z | 2015-09-13T19:10:41Z | 2015-09-13T19:10:41Z | 2015-09-13T21:43:33Z |
BUG: Fixed bug in groupby.std changing target column when as_index=False | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 3b3bf8cffe41b..d03bbf7291ab8 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1067,6 +1067,7 @@ Bug Fixes
- Bug in ``algos.outer_join_indexer`` when ``right`` array is empty (:issue:`10618`)
- Bug in ``filter`` (regression from 0.16.0) and ``transform`` when grouping on multiple keys, one of which is datetime-like (:issue:`10114`)
+- Bug in ``groupby(as_index=False)`` with ``std`` accidentally modifying target column at the same time (:issue:`10355`)
- Bug in ``to_datetime`` and ``to_timedelta`` causing ``Index`` name to be lost (:issue:`10875`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index f34fd6e3d2575..c6717c16f3e0e 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -788,8 +788,9 @@ def std(self, ddof=1):
For multiple groupings, the result index will be a MultiIndex
"""
- # todo, implement at cython level?
- return np.sqrt(self.var(ddof=ddof))
+ self._set_selection_from_grouper()
+ f = lambda x: np.sqrt(x.var(ddof=ddof))
+ return self._python_agg_general(f)
def var(self, ddof=1):
"""
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 97b57690ccc49..83178970767a4 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -888,6 +888,20 @@ def _check_results(grouped):
lambda x: x.weekday()])
_check_results(by_mwkday)
+ # issue 10355
+ def test_std(self):
+ df = pd.DataFrame({
+ 'a' : [1,1,1,2,2,2,3,3,3],
+ 'b' : [1,2,3,4,5,6,7,8,9],
+ })
+ result = df.groupby('a',as_index=False).std()
+ expected = pd.DataFrame({
+ 'a' : [1, 2, 3],
+ 'b' : [1, 1, 1]
+ })
+ assert_frame_equal(result, expected)
+
+
def test_aggregate_item_by_item(self):
df = self.df.copy()
| Fixed #10355
| https://api.github.com/repos/pandas-dev/pandas/pulls/11085 | 2015-09-13T00:28:26Z | 2015-09-14T02:01:07Z | null | 2019-02-14T05:23:07Z |
DOC: fix plot submethods whatsnew example | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 914c18a66af61..3f6da20c4a422 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -150,7 +150,7 @@ The Series and DataFrame ``.plot()`` method allows for customizing :ref:`plot ty
To alleviate this issue, we have added a new, optional plotting interface, which exposes each kind of plot as a method of the ``.plot`` attribute. Instead of writing ``series.plot(kind=<kind>, ...)``, you can now also use ``series.plot.<kind>(...)``:
.. ipython::
- :verbatim:
+ :verbatim:
In [13]: df = pd.DataFrame(np.random.rand(10, 2), columns=['a', 'b'])
| This was not building properly.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11083 | 2015-09-12T23:25:09Z | 2015-09-12T23:35:09Z | 2015-09-12T23:35:09Z | 2015-09-13T00:23:54Z |
CI: support *.pip for installations | diff --git a/ci/install_conda.sh b/ci/install_conda.sh
index 01b89807d164c..1db1e7fa6f571 100755
--- a/ci/install_conda.sh
+++ b/ci/install_conda.sh
@@ -78,16 +78,20 @@ conda config --set ssl_verify false || exit 1
# Useful for debugging any issues with conda
conda info -a || exit 1
+REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.txt"
conda create -n pandas python=$TRAVIS_PYTHON_VERSION || exit 1
-conda install -n pandas --file=ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.txt || exit 1
+conda install -n pandas --file=${REQ} || exit 1
conda install -n pandas pip setuptools nose || exit 1
conda remove -n pandas pandas
source activate pandas
-pip install -U blosc # See https://github.com/pydata/pandas/pull/9783
-python -c 'import blosc; blosc.print_versions()'
+# we may have additional pip installs
+REQ="ci/requirements-${TRAVIS_PYTHON_VERSION}${JOB_TAG}.pip"
+if [ -e ${REQ} ]; then
+ pip install -r $REQ
+fi
# set the compiler cache to work
if [ "$IRON_TOKEN" ]; then
diff --git a/ci/requirements-2.6.pip b/ci/requirements-2.6.pip
new file mode 100644
index 0000000000000..cf8e6b8b3d3a6
--- /dev/null
+++ b/ci/requirements-2.6.pip
@@ -0,0 +1 @@
+blosc
diff --git a/ci/requirements-2.7.pip b/ci/requirements-2.7.pip
new file mode 100644
index 0000000000000..cf8e6b8b3d3a6
--- /dev/null
+++ b/ci/requirements-2.7.pip
@@ -0,0 +1 @@
+blosc
diff --git a/ci/requirements-2.7_LOCALE.pip b/ci/requirements-2.7_LOCALE.pip
new file mode 100644
index 0000000000000..cf8e6b8b3d3a6
--- /dev/null
+++ b/ci/requirements-2.7_LOCALE.pip
@@ -0,0 +1 @@
+blosc
diff --git a/ci/requirements-3.3.pip b/ci/requirements-3.3.pip
new file mode 100644
index 0000000000000..cf8e6b8b3d3a6
--- /dev/null
+++ b/ci/requirements-3.3.pip
@@ -0,0 +1 @@
+blosc
diff --git a/ci/requirements-3.4.pip b/ci/requirements-3.4.pip
new file mode 100644
index 0000000000000..cf8e6b8b3d3a6
--- /dev/null
+++ b/ci/requirements-3.4.pip
@@ -0,0 +1 @@
+blosc
diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py
index 88b3c94d3ea18..f0545e9949e24 100644
--- a/pandas/util/print_versions.py
+++ b/pandas/util/print_versions.py
@@ -72,6 +72,7 @@ def show_versions(as_json=False):
("patsy", lambda mod: mod.__version__),
("dateutil", lambda mod: mod.__version__),
("pytz", lambda mod: mod.VERSION),
+ ("blosc", lambda mod: mod.__version__),
("bottleneck", lambda mod: mod.__version__),
("tables", lambda mod: mod.__version__),
("numexpr", lambda mod: mod.__version__),
| https://api.github.com/repos/pandas-dev/pandas/pulls/11081 | 2015-09-12T22:46:57Z | 2015-09-12T23:36:12Z | 2015-09-12T23:36:12Z | 2015-09-12T23:36:12Z | |
BUG: Fix Series nunique groupby with object dtype | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 9d8532aa3649a..7fe92b580536a 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1014,7 +1014,7 @@ Performance Improvements
- Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`)
- Added vbench benchmarks for alternative ExcelWriter engines and reading Excel files (:issue:`7171`)
- Performance improvements in ``Categorical.value_counts`` (:issue:`10804`)
-- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` (:issue:`10820`)
+- Performance improvements in ``SeriesGroupBy.nunique`` and ``SeriesGroupBy.value_counts`` (:issue:`10820`, :issue:`11077`)
- Performance improvements in ``DataFrame.drop_duplicates`` with integer dtypes (:issue:`10917`)
- 4x improvement in ``timedelta`` string parsing (:issue:`6755`, :issue:`10426`)
- 8x improvement in ``timedelta64`` and ``datetime64`` ops (:issue:`6755`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index f34fd6e3d2575..8e44480c0c09b 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -2565,7 +2565,17 @@ def nunique(self, dropna=True):
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
- sorter = np.lexsort((val, ids))
+ try:
+ sorter = np.lexsort((val, ids))
+ except TypeError: # catches object dtypes
+ assert val.dtype == object, \
+ 'val.dtype must be object, got %s' % val.dtype
+ val, _ = algos.factorize(val, sort=False)
+ sorter = np.lexsort((val, ids))
+ isnull = lambda a: a == -1
+ else:
+ isnull = com.isnull
+
ids, val = ids[sorter], val[sorter]
# group boundries are where group ids change
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 97b57690ccc49..0336ee2e9b50e 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -5511,6 +5511,22 @@ def test_sort(x):
g.apply(test_sort)
+ def test_nunique_with_object(self):
+ # GH 11077
+ data = pd.DataFrame(
+ [[100, 1, 'Alice'],
+ [200, 2, 'Bob'],
+ [300, 3, 'Charlie'],
+ [-400, 4, 'Dan'],
+ [500, 5, 'Edith']],
+ columns=['amount', 'id', 'name']
+ )
+
+ result = data.groupby(['id', 'amount'])['name'].nunique()
+ index = MultiIndex.from_arrays([data.id, data.amount])
+ expected = pd.Series([1] * 5, name='name', index=index)
+ tm.assert_series_equal(result, expected)
+
def assert_fp_equal(a, b):
assert (np.abs(a - b) < 1e-12).all()
| closes #11077
| https://api.github.com/repos/pandas-dev/pandas/pulls/11079 | 2015-09-12T18:31:35Z | 2015-09-14T22:09:02Z | 2015-09-14T22:09:01Z | 2015-09-14T22:11:28Z |
updateing my fork | diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 9eab385a7a2a5..f78c6a1fc9235 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2700,7 +2700,7 @@ def plot_group(group, ax):
return fig
-def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
+def hist_frame(data, column=None, weights=None, by=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
sharey=False, figsize=None, layout=None, bins=10, **kwds):
"""
@@ -2711,6 +2711,8 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
data : DataFrame
column : string or sequence
If passed, will be used to limit data to a subset of columns
+ weights : string or sequence
+ If passed, will be used to weight the data
by : object, optional
If passed, then used to form histograms for separate groups
grid : boolean, default True
@@ -2742,7 +2744,7 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
"""
if by is not None:
- axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize,
+ axes = grouped_hist(data, column=column, weights=weights, by=by, ax=ax, grid=grid, figsize=figsize,
sharex=sharex, sharey=sharey, layout=layout, bins=bins,
xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot,
**kwds)
@@ -2846,7 +2848,7 @@ def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
return axes
-def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
+def grouped_hist(data, column=None, weights=weights, by=None, ax=None, bins=50, figsize=None,
layout=None, sharex=False, sharey=False, rot=90, grid=True,
xlabelsize=None, xrot=None, ylabelsize=None, yrot=None,
**kwargs):
@@ -2857,6 +2859,7 @@ def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
----------
data: Series/DataFrame
column: object, optional
+ weights: object, optional
by: object, optional
ax: axes, optional
bins: int, default 50
@@ -2872,12 +2875,14 @@ def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
-------
axes: collection of Matplotlib Axes
"""
- def plot_group(group, ax):
- ax.hist(group.dropna().values, bins=bins, **kwargs)
+ def plot_group(group, ax, weights=None):
+ if weights is not None:
+ weights=weights.dropna().values
+ ax.hist(group.dropna().values, weights=weights, bins=bins, **kwargs)
xrot = xrot or rot
- fig, axes = _grouped_plot(plot_group, data, column=column,
+ fig, axes = _grouped_plot(plot_group, data, column=column, weights=weights,
by=by, sharex=sharex, sharey=sharey, ax=ax,
figsize=figsize, layout=layout, rot=rot)
@@ -2964,7 +2969,7 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
return ret
-def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True,
+def _grouped_plot(plotf, data, column=None, weights=None, by=None, numeric_only=True,
figsize=None, sharex=True, sharey=True, layout=None,
rot=0, ax=None, **kwargs):
from pandas import DataFrame
@@ -2977,6 +2982,8 @@ def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True,
grouped = data.groupby(by)
if column is not None:
+ if weights is not None:
+ weights = grouped[weights]
grouped = grouped[column]
naxes = len(grouped)
@@ -2986,11 +2993,16 @@ def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True,
_axes = _flatten(axes)
+ weight = None
for i, (key, group) in enumerate(grouped):
ax = _axes[i]
+ if weights is not None:
+ weight = weights.get_group(key)
if numeric_only and isinstance(group, DataFrame):
group = group._get_numeric_data()
- plotf(group, ax, **kwargs)
+ if weight is not None:
+ weight = weight._get_numeric_data()
+ plotf(group, ax, weight, **kwargs)
ax.set_title(com.pprint_thing(key))
return fig, axes
| https://api.github.com/repos/pandas-dev/pandas/pulls/11078 | 2015-09-12T18:18:15Z | 2015-09-12T18:20:20Z | null | 2015-09-12T18:20:20Z | |
ENH Add check for inferred compression before `get_filepath_or_buffer` | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 615bfc9e23253..a6e6c9f2f2b3c 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -481,6 +481,8 @@ Other enhancements
- Read CSV files from AWS S3 incrementally, instead of first downloading the entire file. (Full file download still required for compressed files in Python 2.) (:issue:`11070`, :issue:`11073`)
+- ``pd.read_csv`` is now able to infer compression type for files read from AWS S3 storage (:issue:`11070`, :issue:`11074`).
+
.. _whatsnew_0170.api:
.. _whatsnew_0170.api_breaking:
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 7095a0fd60f2a..e13c402b454d1 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -217,6 +217,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
content_encoding = req.headers.get('Content-Encoding', None)
if content_encoding == 'gzip':
compression = 'gzip'
+ else:
+ compression = None
# cat on the compression to the tuple returned by the function
to_return = list(maybe_read_encoded_stream(req, encoding, compression)) + \
[compression]
@@ -237,7 +239,9 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
conn = boto.connect_s3(anon=True)
b = conn.get_bucket(parsed_url.netloc, validate=False)
- if compat.PY2 and compression == 'gzip':
+ if compat.PY2 and (compression == 'gzip' or
+ (compression == 'infer' and
+ filepath_or_buffer.endswith(".gz"))):
k = boto.s3.key.Key(b, parsed_url.path)
filepath_or_buffer = BytesIO(k.get_contents_as_string(
encoding=encoding))
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 736c08f72dee8..15e11193fd1b7 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -235,10 +235,25 @@ def _read(filepath_or_buffer, kwds):
if skipfooter is not None:
kwds['skip_footer'] = skipfooter
+ # If the input could be a filename, check for a recognizable compression extension.
+ # If we're reading from a URL, the `get_filepath_or_buffer` will use header info
+ # to determine compression, so use what it finds in that case.
+ inferred_compression = kwds.get('compression')
+ if inferred_compression == 'infer':
+ if isinstance(filepath_or_buffer, compat.string_types):
+ if filepath_or_buffer.endswith('.gz'):
+ inferred_compression = 'gzip'
+ elif filepath_or_buffer.endswith('.bz2'):
+ inferred_compression = 'bz2'
+ else:
+ inferred_compression = None
+ else:
+ inferred_compression = None
+
filepath_or_buffer, _, compression = get_filepath_or_buffer(filepath_or_buffer,
encoding,
compression=kwds.get('compression', None))
- kwds['compression'] = compression
+ kwds['compression'] = inferred_compression if compression == 'infer' else compression
if kwds.get('date_parser', None) is not None:
if isinstance(kwds['parse_dates'], bool):
@@ -301,7 +316,7 @@ def _read(filepath_or_buffer, kwds):
'verbose': False,
'encoding': None,
'squeeze': False,
- 'compression': 'infer',
+ 'compression': None,
'mangle_dupe_cols': True,
'tupleize_cols': False,
'infer_datetime_format': False,
@@ -1402,17 +1417,6 @@ def __init__(self, f, **kwds):
self.comment = kwds['comment']
self._comment_lines = []
- if self.compression == 'infer':
- if isinstance(f, compat.string_types):
- if f.endswith('.gz'):
- self.compression = 'gzip'
- elif f.endswith('.bz2'):
- self.compression = 'bz2'
- else:
- self.compression = None
- else:
- self.compression = None
-
if isinstance(f, compat.string_types):
f = com._get_handle(f, 'r', encoding=self.encoding,
compression=self.compression)
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 70a49e6bd6782..6b7132aea3280 100755
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -4341,6 +4341,15 @@ def test_parse_public_s3_bucket_python(self):
self.assertFalse(df.empty)
tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
+ @tm.network
+ def test_infer_s3_compression(self):
+ for ext in ['', '.gz', '.bz2']:
+ df = pd.read_csv('s3://pandas-test/tips.csv' + ext,
+ engine='python', compression='infer')
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
+
@tm.network
def test_parse_public_s3_bucket_nrows_python(self):
for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
diff --git a/pandas/parser.pyx b/pandas/parser.pyx
index 647e8e72414e9..8ac1f64f2d50e 100644
--- a/pandas/parser.pyx
+++ b/pandas/parser.pyx
@@ -541,17 +541,6 @@ cdef class TextReader:
self.parser.cb_io = NULL
self.parser.cb_cleanup = NULL
- if self.compression == 'infer':
- if isinstance(source, basestring):
- if source.endswith('.gz'):
- self.compression = 'gzip'
- elif source.endswith('.bz2'):
- self.compression = 'bz2'
- else:
- self.compression = None
- else:
- self.compression = None
-
if self.compression:
if self.compression == 'gzip':
import gzip
| When reading CSVs, if `compression='infer'`, check the input before calling `get_filepath_or_buffer` in the `_read` function. This way we can catch compresion extensions on S3 files. Partially resolves issue #11070 .
Checking for the file extension in the `_read` function should make the checks inside the parsers redundant. When I tried to remove them, however, I discovered that there's tests which assume the parsers can take an "infer" compression, so I left their checks.
I also discovered that the URL-reading code has a test which reads a URL ending in "gz" but which appears not to be gzip encoded, so this PR attempts to preserve its verdict in that case.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11074 | 2015-09-12T16:09:22Z | 2015-09-15T13:23:42Z | 2015-09-15T13:23:42Z | 2015-09-15T13:29:18Z |
ENH Enable streaming from S3 | diff --git a/asv_bench/benchmarks/io_bench.py b/asv_bench/benchmarks/io_bench.py
index a171641502d3c..0f15ab6e5e142 100644
--- a/asv_bench/benchmarks/io_bench.py
+++ b/asv_bench/benchmarks/io_bench.py
@@ -1,9 +1,10 @@
from .pandas_vb_common import *
-from pandas import concat, Timestamp
+from pandas import concat, Timestamp, compat
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
+import timeit
class frame_to_csv(object):
@@ -135,4 +136,36 @@ def setup(self):
self.df = DataFrame({'float1': randn(10000), 'float2': randn(10000), 'string1': (['foo'] * 10000), 'bool1': ([True] * 10000), 'int1': np.random.randint(0, 100000, size=10000), }, index=self.index)
def time_write_csv_standard(self):
- self.df.to_csv('__test__.csv')
\ No newline at end of file
+ self.df.to_csv('__test__.csv')
+
+
+class read_csv_from_s3(object):
+ # Make sure that we can read part of a file from S3 without
+ # needing to download the entire thing. Use the timeit.default_timer
+ # to measure wall time instead of CPU time -- we want to see
+ # how long it takes to download the data.
+ timer = timeit.default_timer
+ params = ([None, "gzip", "bz2"], ["python", "c"])
+ param_names = ["compression", "engine"]
+
+ def setup(self, compression, engine):
+ if compression == "bz2" and engine == "c" and compat.PY2:
+ # The Python 2 C parser can't read bz2 from open files.
+ raise NotImplementedError
+ try:
+ import boto
+ except ImportError:
+ # Skip these benchmarks if `boto` is not installed.
+ raise NotImplementedError
+
+ self.big_fname = "s3://pandas-test/large_random.csv"
+
+ def time_read_nrows(self, compression, engine):
+ # Read a small number of rows from a huge (100,000 x 50) table.
+ ext = ""
+ if compression == "gzip":
+ ext = ".gz"
+ elif compression == "bz2":
+ ext = ".bz2"
+ pd.read_csv(self.big_fname + ext, nrows=10,
+ compression=compression, engine=engine)
diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 9d8532aa3649a..5f9f7574a282b 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -479,6 +479,8 @@ Other enhancements
- In ``pd.read_csv``, recognize "s3n://" and "s3a://" URLs as designating S3 file storage (:issue:`11070`, :issue:`11071`).
+- Read CSV files from AWS S3 incrementally, instead of first downloading the entire file. (Full file download still required for compressed files in Python 2.) (:issue:`11070`, :issue:`11073`)
+
.. _whatsnew_0170.api:
.. _whatsnew_0170.api_breaking:
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 5ab5640ca12c0..7095a0fd60f2a 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -47,6 +47,77 @@ class DtypeWarning(Warning):
pass
+try:
+ from boto.s3 import key
+ class BotoFileLikeReader(key.Key):
+ """boto Key modified to be more file-like
+
+ This modification of the boto Key will read through a supplied
+ S3 key once, then stop. The unmodified boto Key object will repeatedly
+ cycle through a file in S3: after reaching the end of the file,
+ boto will close the file. Then the next call to `read` or `next` will
+ re-open the file and start reading from the beginning.
+
+ Also adds a `readline` function which will split the returned
+ values by the `\n` character.
+ """
+ def __init__(self, *args, **kwargs):
+ encoding = kwargs.pop("encoding", None) # Python 2 compat
+ super(BotoFileLikeReader, self).__init__(*args, **kwargs)
+ self.finished_read = False # Add a flag to mark the end of the read.
+ self.buffer = ""
+ self.lines = []
+ if encoding is None and compat.PY3:
+ encoding = "utf-8"
+ self.encoding = encoding
+ self.lines = []
+
+ def next(self):
+ return self.readline()
+
+ __next__ = next
+
+ def read(self, *args, **kwargs):
+ if self.finished_read:
+ return b'' if compat.PY3 else ''
+ return super(BotoFileLikeReader, self).read(*args, **kwargs)
+
+ def close(self, *args, **kwargs):
+ self.finished_read = True
+ return super(BotoFileLikeReader, self).close(*args, **kwargs)
+
+ def seekable(self):
+ """Needed for reading by bz2"""
+ return False
+
+ def readline(self):
+ """Split the contents of the Key by '\n' characters."""
+ if self.lines:
+ retval = self.lines[0]
+ self.lines = self.lines[1:]
+ return retval
+ if self.finished_read:
+ if self.buffer:
+ retval, self.buffer = self.buffer, ""
+ return retval
+ else:
+ raise StopIteration
+
+ if self.encoding:
+ self.buffer = "{}{}".format(self.buffer, self.read(8192).decode(self.encoding))
+ else:
+ self.buffer = "{}{}".format(self.buffer, self.read(8192))
+
+ split_buffer = self.buffer.split("\n")
+ self.lines.extend(split_buffer[:-1])
+ self.buffer = split_buffer[-1]
+
+ return self.readline()
+except ImportError:
+ # boto is only needed for reading from S3.
+ pass
+
+
def _is_url(url):
"""Check to see if a URL has a valid protocol.
@@ -166,10 +237,14 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
conn = boto.connect_s3(anon=True)
b = conn.get_bucket(parsed_url.netloc, validate=False)
- k = boto.s3.key.Key(b)
- k.key = parsed_url.path
- filepath_or_buffer = BytesIO(k.get_contents_as_string(
- encoding=encoding))
+ if compat.PY2 and compression == 'gzip':
+ k = boto.s3.key.Key(b, parsed_url.path)
+ filepath_or_buffer = BytesIO(k.get_contents_as_string(
+ encoding=encoding))
+ else:
+ k = BotoFileLikeReader(b, parsed_url.path, encoding=encoding)
+ k.open('r') # Expose read errors immediately
+ filepath_or_buffer = k
return filepath_or_buffer, None, compression
return _expand_user(filepath_or_buffer), None, compression
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 205140e02a8ea..70a49e6bd6782 100755
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -4241,16 +4241,22 @@ def setUp(self):
@tm.network
def test_parse_public_s3_bucket(self):
- import nose.tools as nt
- df = pd.read_csv('s3://nyqpug/tips.csv')
- nt.assert_true(isinstance(df, pd.DataFrame))
- nt.assert_false(df.empty)
- tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
+ for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
+ if comp == 'bz2' and compat.PY2:
+ # The Python 2 C parser can't read bz2 from S3.
+ self.assertRaises(ValueError, pd.read_csv,
+ 's3://pandas-test/tips.csv' + ext,
+ compression=comp)
+ else:
+ df = pd.read_csv('s3://pandas-test/tips.csv' + ext, compression=comp)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
# Read public file from bucket with not-public contents
df = pd.read_csv('s3://cant_get_it/tips.csv')
- nt.assert_true(isinstance(df, pd.DataFrame))
- nt.assert_false(df.empty)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
@tm.network
@@ -4269,6 +4275,81 @@ def test_parse_public_s3a_bucket(self):
self.assertFalse(df.empty)
tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df)
+ @tm.network
+ def test_parse_public_s3_bucket_nrows(self):
+ for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
+ if comp == 'bz2' and compat.PY2:
+ # The Python 2 C parser can't read bz2 from S3.
+ self.assertRaises(ValueError, pd.read_csv,
+ 's3://pandas-test/tips.csv' + ext,
+ compression=comp)
+ else:
+ df = pd.read_csv('s3://pandas-test/tips.csv' + ext, nrows=10, compression=comp)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df)
+
+ @tm.network
+ def test_parse_public_s3_bucket_chunked(self):
+ # Read with a chunksize
+ chunksize = 5
+ local_tips = pd.read_csv(tm.get_data_path('tips.csv'))
+ for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
+ if comp == 'bz2' and compat.PY2:
+ # The Python 2 C parser can't read bz2 from S3.
+ self.assertRaises(ValueError, pd.read_csv,
+ 's3://pandas-test/tips.csv' + ext,
+ compression=comp)
+ else:
+ df_reader = pd.read_csv('s3://pandas-test/tips.csv' + ext,
+ chunksize=chunksize, compression=comp)
+ self.assertEqual(df_reader.chunksize, chunksize)
+ for i_chunk in [0, 1, 2]:
+ # Read a couple of chunks and make sure we see them properly.
+ df = df_reader.get_chunk()
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ true_df = local_tips.iloc[chunksize * i_chunk: chunksize * (i_chunk + 1)]
+ true_df = true_df.reset_index().drop('index', axis=1) # Chunking doesn't preserve row numbering
+ tm.assert_frame_equal(true_df, df)
+
+ @tm.network
+ def test_parse_public_s3_bucket_chunked_python(self):
+ # Read with a chunksize using the Python parser
+ chunksize = 5
+ local_tips = pd.read_csv(tm.get_data_path('tips.csv'))
+ for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
+ df_reader = pd.read_csv('s3://pandas-test/tips.csv' + ext,
+ chunksize=chunksize, compression=comp,
+ engine='python')
+ self.assertEqual(df_reader.chunksize, chunksize)
+ for i_chunk in [0, 1, 2]:
+ # Read a couple of chunks and make sure we see them properly.
+ df = df_reader.get_chunk()
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ true_df = local_tips.iloc[chunksize * i_chunk: chunksize * (i_chunk + 1)]
+ true_df = true_df.reset_index().drop('index', axis=1) # Chunking doesn't preserve row numbering
+ tm.assert_frame_equal(true_df, df)
+
+ @tm.network
+ def test_parse_public_s3_bucket_python(self):
+ for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
+ df = pd.read_csv('s3://pandas-test/tips.csv' + ext, engine='python',
+ compression=comp)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
+
+ @tm.network
+ def test_parse_public_s3_bucket_nrows_python(self):
+ for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]:
+ df = pd.read_csv('s3://pandas-test/tips.csv' + ext, engine='python',
+ nrows=10, compression=comp)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df)
+
@tm.network
def test_s3_fails(self):
import boto
| File reading from AWS S3: Modify the `get_filepath_or_buffer` function such that it only opens the connection to S3, rather than reading the entire file at once. This allows partial reads (e.g. through the `nrows` argument) or chunked reading (e.g. through the `chunksize` argument) without needing to download the entire file first.
I wasn't sure what the best place was to put the `OnceThroughKey`. (Suggestions for better names welcome.) I don't like putting an entire class inside a function like that, but this keeps the `boto` dependency contained.
The `readline` function, and modifying `next` such that it returns lines, was necessary to allow the Python engine to read uncompressed CSVs.
The Python 2 standard library's `gzip` module needs a `seek` and `tell` function on its inputs, so I reverted to the old behavior there.
Partially addresses #11070 .
| https://api.github.com/repos/pandas-dev/pandas/pulls/11073 | 2015-09-12T13:51:09Z | 2015-09-14T22:24:49Z | 2015-09-14T22:24:49Z | 2015-09-14T22:32:55Z |
ENH Enable bzip2 streaming for Python 3 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 914c18a66af61..986af61414587 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -465,6 +465,8 @@ Other enhancements
- Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`)
+- ``pd.read_csv`` can now read bz2-compressed files incrementally, and the C parser can read bz2-compressed files from AWS S3 (:issue:`11070`, :issue:`11072`).
+
.. _whatsnew_0170.api:
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index f0c994ba17e27..736c08f72dee8 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1344,12 +1344,13 @@ def _wrap_compressed(f, compression, encoding=None):
elif compression == 'bz2':
import bz2
- # bz2 module can't take file objects, so have to run through decompress
- # manually
- data = bz2.decompress(f.read())
if compat.PY3:
- data = data.decode(encoding)
- f = StringIO(data)
+ f = bz2.open(f, 'rt', encoding=encoding)
+ else:
+ # Python 2's bz2 module can't take file objects, so have to
+ # run through decompress manually
+ data = bz2.decompress(f.read())
+ f = StringIO(data)
return f
else:
raise ValueError('do not recognize compression method %s'
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index ed261edad4f20..fabe4ce40b22f 100755
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -3836,6 +3836,14 @@ def test_decompression(self):
self.assertRaises(ValueError, self.read_csv,
path, compression='bz3')
+ with open(path, 'rb') as fin:
+ if compat.PY3:
+ result = self.read_csv(fin, compression='bz2')
+ tm.assert_frame_equal(result, expected)
+ else:
+ self.assertRaises(ValueError, self.read_csv,
+ fin, compression='bz2')
+
def test_decompression_regex_sep(self):
try:
import gzip
diff --git a/pandas/parser.pyx b/pandas/parser.pyx
index c2916f2c0cfb8..647e8e72414e9 100644
--- a/pandas/parser.pyx
+++ b/pandas/parser.pyx
@@ -561,10 +561,10 @@ cdef class TextReader:
source = gzip.GzipFile(fileobj=source)
elif self.compression == 'bz2':
import bz2
- if isinstance(source, basestring):
+ if isinstance(source, basestring) or PY3:
source = bz2.BZ2File(source, 'rb')
else:
- raise ValueError('Python cannot read bz2 from open file '
+ raise ValueError('Python 2 cannot read bz2 from open file '
'handle')
else:
raise ValueError('Unrecognized compression type: %s' %
| This is the one modification related to issue #11070 which affects non-S3 interactions with `read_csv`. The Python 3 standard library has an improved capability for handling bz2 compression, so a simple change will let `read_csv` stream bz2-compressed files.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11072 | 2015-09-12T13:32:12Z | 2015-09-13T14:52:53Z | 2015-09-13T14:52:53Z | 2015-09-14T20:12:22Z |
ENH Recognize 's3n' and 's3a' as an S3 address | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 3b3bf8cffe41b..b45c843d28eb8 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -467,6 +467,7 @@ Other enhancements
- ``pd.read_csv`` can now read bz2-compressed files incrementally, and the C parser can read bz2-compressed files from AWS S3 (:issue:`11070`, :issue:`11072`).
+- In ``pd.read_csv``, recognize "s3n://" and "s3a://" URLs as designating S3 file storage (:issue:`11070`, :issue:`11071`).
.. _whatsnew_0170.api:
diff --git a/pandas/io/common.py b/pandas/io/common.py
index c6ece61f05a01..5ab5640ca12c0 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -66,9 +66,9 @@ def _is_url(url):
def _is_s3_url(url):
- """Check for an s3 url"""
+ """Check for an s3, s3n, or s3a url"""
try:
- return parse_url(url).scheme == 's3'
+ return parse_url(url).scheme in ['s3', 's3n', 's3a']
except:
return False
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index fabe4ce40b22f..205140e02a8ea 100755
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -4253,6 +4253,22 @@ def test_parse_public_s3_bucket(self):
nt.assert_false(df.empty)
tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')), df)
+ @tm.network
+ def test_parse_public_s3n_bucket(self):
+ # Read from AWS s3 as "s3n" URL
+ df = pd.read_csv('s3n://pandas-test/tips.csv', nrows=10)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df)
+
+ @tm.network
+ def test_parse_public_s3a_bucket(self):
+ # Read from AWS s3 as "s3a" URL
+ df = pd.read_csv('s3a://pandas-test/tips.csv', nrows=10)
+ self.assertTrue(isinstance(df, pd.DataFrame))
+ self.assertFalse(df.empty)
+ tm.assert_frame_equal(pd.read_csv(tm.get_data_path('tips.csv')).iloc[:10], df)
+
@tm.network
def test_s3_fails(self):
import boto
| This PR allows `read_csv` to recognize that "s3n://" designates a valid AWS S3 address. Partially addresses issue #11070 .
| https://api.github.com/repos/pandas-dev/pandas/pulls/11071 | 2015-09-12T13:29:25Z | 2015-09-14T19:49:34Z | 2015-09-14T19:49:34Z | 2015-09-14T20:09:26Z |
DOC/CI: include api docs on travis | diff --git a/.travis.yml b/.travis.yml
index 4e46fb7ad85ca..bd3b3bad6b73f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -18,6 +18,7 @@ git:
matrix:
fast_finish: true
+ fail_fast: true
include:
- python: 2.6
env:
@@ -42,7 +43,6 @@ matrix:
- FULL_DEPS=true
- CLIPBOARD_GUI=gtk2
- BUILD_TYPE=conda
- - DOC_BUILD=true # if rst files were changed, build docs in parallel with tests
- python: 3.4
env:
- JOB_NAME: "34_nslow"
@@ -103,6 +103,12 @@ matrix:
- NUMPY_BUILD=master
- BUILD_TYPE=pydata
- PANDAS_TESTING_MODE="deprecate"
+ - python: 2.7
+ env:
+ - JOB_NAME: "doc_build"
+ - JOB_TAG=_DOC_BUILD
+ - BUILD_TYPE=conda
+ - DOC_BUILD=true # if rst files were changed, build docs in parallel with tests
allow_failures:
- python: 3.3
env:
@@ -150,6 +156,12 @@ matrix:
- FULL_DEPS=true
- BUILD_TYPE=pydata
- BUILD_TEST=true
+ - python: 2.7
+ env:
+ - JOB_NAME: "doc_build"
+ - JOB_TAG=_DOC_BUILD
+ - BUILD_TYPE=conda
+ - DOC_BUILD=true
before_install:
- echo "before_install"
@@ -178,7 +190,7 @@ before_script:
script:
- echo "script"
- - ci/run_build_docs.sh &
+ - ci/run_build_docs.sh
- ci/script.sh
# nothing here, or failed tests won't fail travis
diff --git a/ci/before_install.sh b/ci/before_install.sh
index e4376e1bf21c2..46f9507801330 100755
--- a/ci/before_install.sh
+++ b/ci/before_install.sh
@@ -11,3 +11,7 @@ echo "inside $0"
sudo apt-get update $APT_ARGS # run apt-get update for all versions
true # never fail because bad things happened here
+
+if [ x"$DOC_BUILD" == x"" ]; then
+ exit 1
+fi
diff --git a/ci/build_docs.sh b/ci/build_docs.sh
index a8488e202dbec..c0843593f85ff 100755
--- a/ci/build_docs.sh
+++ b/ci/build_docs.sh
@@ -14,23 +14,22 @@ fi
if [ x"$DOC_BUILD" != x"" ]; then
- # we're running network tests, let's build the docs in the meantime
echo "Will build docs"
- conda install -n pandas sphinx=1.1.3 pygments ipython=2.4 --yes
source activate pandas
+ conda install -n pandas -c r r rpy2 --yes
+
+ time sudo apt-get $APT_ARGS install dvipng
mv "$TRAVIS_BUILD_DIR"/doc /tmp
cd /tmp/doc
- rm /tmp/doc/source/api.rst # no R
- rm /tmp/doc/source/r_interface.rst # no R
-
echo ###############################
echo # Log file for the doc build #
echo ###############################
- echo -e "y\n" | ./make.py --no-api 2>&1
+ echo ./make.py
+ ./make.py
cd /tmp/doc/build/html
git config --global user.email "pandas-docs-bot@localhost.foo"
diff --git a/ci/requirements-2.7_DOC_BUILD.build b/ci/requirements-2.7_DOC_BUILD.build
new file mode 100644
index 0000000000000..faf1e3559f7f1
--- /dev/null
+++ b/ci/requirements-2.7_DOC_BUILD.build
@@ -0,0 +1,4 @@
+dateutil
+pytz
+numpy
+cython
diff --git a/ci/requirements-2.7_DOC_BUILD.run b/ci/requirements-2.7_DOC_BUILD.run
new file mode 100644
index 0000000000000..15634f7bb033b
--- /dev/null
+++ b/ci/requirements-2.7_DOC_BUILD.run
@@ -0,0 +1,16 @@
+sphinx=1.2.3
+ipython=3.2.1
+matplotlib
+scipy
+lxml
+beautiful-soup
+html5lib
+pytables
+openpyxl=1.8.5
+xlrd
+xlwt
+xlsxwriter
+sqlalchemy
+numexpr
+bottleneck
+statsmodels
diff --git a/ci/run_build_docs.sh b/ci/run_build_docs.sh
index c04c815297aa3..2909b9619552e 100755
--- a/ci/run_build_docs.sh
+++ b/ci/run_build_docs.sh
@@ -2,7 +2,7 @@
echo "inside $0"
-"$TRAVIS_BUILD_DIR"/ci/build_docs.sh 2>&1 > /tmp/doc.log &
+"$TRAVIS_BUILD_DIR"/ci/build_docs.sh 2>&1
# wait until subprocesses finish (build_docs.sh)
wait
diff --git a/ci/script.sh b/ci/script.sh
index 1126e8249646c..b2e02d27c970b 100755
--- a/ci/script.sh
+++ b/ci/script.sh
@@ -4,6 +4,11 @@ echo "inside $0"
source activate pandas
+# don't run the tests for the doc build
+if [ x"$DOC_BUILD" != x"" ]; then
+ exit 0
+fi
+
if [ -n "$LOCALE_OVERRIDE" ]; then
export LC_ALL="$LOCALE_OVERRIDE";
echo "Setting LC_ALL to $LOCALE_OVERRIDE"
diff --git a/doc/make.py b/doc/make.py
index 6b424ce2814d5..b6e2cc90b620d 100755
--- a/doc/make.py
+++ b/doc/make.py
@@ -104,7 +104,7 @@ def clean():
def html():
check_build()
- if os.system('sphinx-build -P -b html -d build/doctrees '
+ if os.system('sphinx-build -P -j 4 -b html -d build/doctrees '
'source build/html'):
raise SystemExit("Building HTML failed.")
try:
diff --git a/doc/source/api.rst b/doc/source/api.rst
index 60516fd02b116..ca6874ecbf24a 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -603,7 +603,7 @@ strings and apply several methods to it. These can be acccessed like
..
The following is needed to ensure the generated pages are created with the
- correct template (otherwise they would be created in the Series class page)
+ correct template (otherwise they would be created in the Series/Index class page)
..
.. autosummary::
@@ -613,6 +613,10 @@ strings and apply several methods to it. These can be acccessed like
Series.str
Series.cat
Series.dt
+ Index.str
+ CategoricalIndex.str
+ DatetimeIndex.str
+ TimedeltaIndex.str
.. _api.categorical:
diff --git a/doc/sphinxext/numpydoc/docscrape_sphinx.py b/doc/sphinxext/numpydoc/docscrape_sphinx.py
index ba93b2eab779d..5a582b4d03282 100755
--- a/doc/sphinxext/numpydoc/docscrape_sphinx.py
+++ b/doc/sphinxext/numpydoc/docscrape_sphinx.py
@@ -19,6 +19,7 @@ def __init__(self, docstring, config={}):
def load_config(self, config):
self.use_plots = config.get('use_plots', False)
self.class_members_toctree = config.get('class_members_toctree', True)
+ self.class_members_list = config.get('class_members_list', True)
# string conversion routines
def _str_header(self, name, symbol='`'):
@@ -95,7 +96,7 @@ def _str_member_list(self, name):
"""
out = []
- if self[name]:
+ if self[name] and self.class_members_list:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
@@ -114,11 +115,13 @@ def _str_member_list(self, name):
or inspect.isgetsetdescriptor(param_obj)):
param_obj = None
- if param_obj and (pydoc.getdoc(param_obj) or not desc):
- # Referenced object has a docstring
- autosum += [" %s%s" % (prefix, param)]
- else:
- others.append((param, param_type, desc))
+ # pandas HACK - do not exclude attributes wich are None
+ # if param_obj and (pydoc.getdoc(param_obj) or not desc):
+ # # Referenced object has a docstring
+ # autosum += [" %s%s" % (prefix, param)]
+ # else:
+ # others.append((param, param_type, desc))
+ autosum += [" %s%s" % (prefix, param)]
if autosum:
out += ['.. autosummary::']
diff --git a/doc/sphinxext/numpydoc/numpydoc.py b/doc/sphinxext/numpydoc/numpydoc.py
index 2bc2d1e91ed3f..0cccf72de3745 100755
--- a/doc/sphinxext/numpydoc/numpydoc.py
+++ b/doc/sphinxext/numpydoc/numpydoc.py
@@ -42,6 +42,10 @@ def mangle_docstrings(app, what, name, obj, options, lines,
class_members_toctree=app.config.numpydoc_class_members_toctree,
)
+ # PANDAS HACK (to remove the list of methods/attributes for Categorical)
+ if what == "class" and name.endswith(".Categorical"):
+ cfg['class_members_list'] = False
+
if what == 'module':
# Strip top title
title_re = re.compile(sixu('^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'),
| Continued in #12002
---
Closes #6100
Closes #3800
Just to check how this takes on travis
| https://api.github.com/repos/pandas-dev/pandas/pulls/11069 | 2015-09-12T10:14:21Z | 2015-11-20T18:44:08Z | null | 2016-01-08T23:59:46Z |
DOC: Re-organize whatsnew | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index c3b12f4e73b01..914c18a66af61 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -38,10 +38,12 @@ Highlights include:
- The sorting API has been revamped to remove some long-time inconsistencies, see :ref:`here <whatsnew_0170.api_breaking.sorting>`
- Support for a ``datetime64[ns]`` with timezones as a first-class dtype, see :ref:`here <whatsnew_0170.tz>`
- The default for ``to_datetime`` will now be to ``raise`` when presented with unparseable formats,
- previously this would return the original input, see :ref:`here <whatsnew_0170.api_breaking.to_datetime>`
+ previously this would return the original input. Also, date parse
+ functions now return consistent results. See :ref:`here <whatsnew_0170.api_breaking.to_datetime>`
- The default for ``dropna`` in ``HDFStore`` has changed to ``False``, to store by default all rows even
if they are all ``NaN``, see :ref:`here <whatsnew_0170.api_breaking.hdf_dropna>`
-- Support for ``Series.dt.strftime`` to generate formatted strings for datetime-likes, see :ref:`here <whatsnew_0170.strftime>`
+- Datetime accessor (``dt``) now supports ``Series.dt.strftime`` to generate formatted strings for datetime-likes, and ``Series.dt.total_seconds`` to generate each duration of the timedelta in seconds. See :ref:`here <whatsnew_0170.strftime>`
+- ``Period`` and ``PeriodIndex`` can handle multiplied freq like ``3D``, which corresponding to 3 days span. See :ref:`here <whatsnew_0170.periodfreq>`
- Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`)
- Development support for benchmarking with the `Air Speed Velocity library <https://github.com/spacetelescope/asv/>`_ (:issue:`8316`)
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>`
@@ -169,8 +171,11 @@ Each method signature only includes relevant arguments. Currently, these are lim
.. _whatsnew_0170.strftime:
-Support strftime for Datetimelikes
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Additional methods for ``dt`` accessor
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+strftime
+""""""""
We are now supporting a ``Series.dt.strftime`` method for datetime-likes to generate a formatted string (:issue:`10110`). Examples:
@@ -190,6 +195,18 @@ We are now supporting a ``Series.dt.strftime`` method for datetime-likes to gene
The string format is as the python standard library and details can be found `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_
+total_seconds
+"""""""""""""
+
+``pd.Series`` of type ``timedelta64`` has new method ``.dt.total_seconds()`` returning the duration of the timedelta in seconds (:issue:`10817`)
+
+.. ipython:: python
+
+ # TimedeltaIndex
+ s = pd.Series(pd.timedelta_range('1 minutes', periods=4))
+ s
+ s.dt.total_seconds()
+
.. _whatsnew_0170.periodfreq:
Period Frequency Enhancement
@@ -240,7 +257,7 @@ See the :ref:`docs <io.sas>` for more details.
.. _whatsnew_0170.matheval:
Support for Math Functions in .eval()
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:meth:`~pandas.eval` now supports calling math functions (:issue:`4893`)
@@ -307,7 +324,6 @@ has been changed to make this keyword unnecessary - the change is shown below.
Other enhancements
^^^^^^^^^^^^^^^^^^
-
- ``merge`` now accepts the argument ``indicator`` which adds a Categorical-type column (by default called ``_merge``) to the output object that takes on the values (:issue:`8790`)
=================================== ================
@@ -326,93 +342,52 @@ Other enhancements
For more, see the :ref:`updated docs <merging.indicator>`
-- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`)
-- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`)
-- Enable writing complex values to HDF stores when using table format (:issue:`10447`)
-- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`)
-- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`)
-
- .. ipython:: python
-
- ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13])
- ser.interpolate(limit=1, limit_direction='both')
-
-- Round DataFrame to variable number of decimal places (:issue:`10568`).
+- ``pd.merge`` will now allow duplicate column names if they are not merged upon (:issue:`10639`).
- .. ipython :: python
+- ``pd.pivot`` will now allow passing index as ``None`` (:issue:`3962`).
- df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'],
- index=['first', 'second', 'third'])
- df
- df.round(2)
- df.round({'A': 0, 'C': 2})
+- ``concat`` will now use existing Series names if provided (:issue:`10698`).
-- ``pd.read_sql`` and ``to_sql`` can accept database URI as ``con`` parameter (:issue:`10214`)
-- Enable ``pd.read_hdf`` to be used without specifying a key when the HDF file contains a single dataset (:issue:`10443`)
-- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`)
-- Enable serialization of lists and dicts to strings in ``ExcelWriter`` (:issue:`8188`)
-- Added functionality to use the ``base`` argument when resampling a ``TimeDeltaIndex`` (:issue:`10530`)
-- ``DatetimeIndex`` can be instantiated using strings contains ``NaT`` (:issue:`7599`)
-- The string parsing of ``to_datetime``, ``Timestamp`` and ``DatetimeIndex`` has been made consistent. (:issue:`7599`)
+ .. ipython:: python
- Prior to v0.17.0, ``Timestamp`` and ``to_datetime`` may parse year-only datetime-string incorrectly using today's date, otherwise ``DatetimeIndex``
- uses the beginning of the year. ``Timestamp`` and ``to_datetime`` may raise ``ValueError`` in some types of datetime-string which ``DatetimeIndex``
- can parse, such as a quarterly string.
+ foo = pd.Series([1,2], name='foo')
+ bar = pd.Series([1,2])
+ baz = pd.Series([4,5])
- Previous Behavior
+ Previous Behavior:
.. code-block:: python
- In [1]: Timestamp('2012Q2')
- Traceback
- ...
- ValueError: Unable to parse 2012Q2
-
- # Results in today's date.
- In [2]: Timestamp('2014')
- Out [2]: 2014-08-12 00:00:00
-
- v0.17.0 can parse them as below. It works on ``DatetimeIndex`` also.
+ In [1] pd.concat([foo, bar, baz], 1)
+ Out[1]:
+ 0 1 2
+ 0 1 1 4
+ 1 2 2 5
- New Behaviour
+ New Behavior:
.. ipython:: python
- Timestamp('2012Q2')
- Timestamp('2014')
- DatetimeIndex(['2012Q2', '2014'])
-
- .. note::
-
- If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``.
-
- .. ipython:: python
-
- import pandas.tseries.offsets as offsets
- Timestamp.now()
- Timestamp.now() + offsets.DateOffset(years=1)
-
-- ``to_datetime`` can now accept ``yearfirst`` keyword (:issue:`7599`)
-
-- ``pandas.tseries.offsets`` larger than the ``Day`` offset can now be used with with ``Series`` for addition/subtraction (:issue:`10699`). See the :ref:`Documentation <timeseries.offsetseries>` for more details.
-
-- ``pd.Series`` of type ``timedelta64`` has new method ``.dt.total_seconds()`` returning the duration of the timedelta in seconds (:issue:`10817`)
+ pd.concat([foo, bar, baz], 1)
-- ``pd.Timedelta.total_seconds()`` now returns Timedelta duration to ns precision (previously microsecond precision) (:issue:`10939`)
+- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`)
-- ``.as_blocks`` will now take a ``copy`` optional argument to return a copy of the data, default is to copy (no change in behavior from prior versions), (:issue:`9607`)
-- ``regex`` argument to ``DataFrame.filter`` now handles numeric column names instead of raising ``ValueError`` (:issue:`10384`).
-- ``pd.read_stata`` will now read Stata 118 type files. (:issue:`9882`)
+- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`)
-- ``pd.merge`` will now allow duplicate column names if they are not merged upon (:issue:`10639`).
+ .. ipython:: python
-- ``pd.pivot`` will now allow passing index as ``None`` (:issue:`3962`).
+ ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13])
+ ser.interpolate(limit=1, limit_direction='both')
-- ``read_sql_table`` will now allow reading from views (:issue:`10750`).
+- Round DataFrame to variable number of decimal places (:issue:`10568`).
-- ``msgpack`` submodule has been updated to 0.4.6 with backward compatibility (:issue:`10581`)
+ .. ipython :: python
-- ``DataFrame.to_dict`` now accepts the *index* option in ``orient`` keyword argument (:issue:`10844`).
+ df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'],
+ index=['first', 'second', 'third'])
+ df
+ df.round(2)
+ df.round({'A': 0, 'C': 2})
- ``drop_duplicates`` and ``duplicated`` now accept ``keep`` keyword to target first, last, and all duplicates. ``take_last`` keyword is deprecated, see :ref:`deprecations <whatsnew_0170.deprecations>` (:issue:`6511`, :issue:`8505`)
@@ -444,37 +419,50 @@ Other enhancements
``tolerance`` is also exposed by the lower level ``Index.get_indexer`` and ``Index.get_loc`` methods.
-- Support pickling of ``Period`` objects (:issue:`10439`)
+- Added functionality to use the ``base`` argument when resampling a ``TimeDeltaIndex`` (:issue:`10530`)
-- ``DataFrame.apply`` will return a Series of dicts if the passed function returns a dict and ``reduce=True`` (:issue:`8735`).
+- ``DatetimeIndex`` can be instantiated using strings contains ``NaT`` (:issue:`7599`)
+
+- ``to_datetime`` can now accept ``yearfirst`` keyword (:issue:`7599`)
+
+- ``pandas.tseries.offsets`` larger than the ``Day`` offset can now be used with with ``Series`` for addition/subtraction (:issue:`10699`). See the :ref:`Documentation <timeseries.offsetseries>` for more details.
+
+- ``pd.Timedelta.total_seconds()`` now returns Timedelta duration to ns precision (previously microsecond precision) (:issue:`10939`)
- ``PeriodIndex`` now supports arithmetic with ``np.ndarray`` (:issue:`10638`)
-- ``concat`` will now use existing Series names if provided (:issue:`10698`).
+- Support pickling of ``Period`` objects (:issue:`10439`)
- .. ipython:: python
+- ``.as_blocks`` will now take a ``copy`` optional argument to return a copy of the data, default is to copy (no change in behavior from prior versions), (:issue:`9607`)
- foo = pd.Series([1,2], name='foo')
- bar = pd.Series([1,2])
- baz = pd.Series([4,5])
+- ``regex`` argument to ``DataFrame.filter`` now handles numeric column names instead of raising ``ValueError`` (:issue:`10384`).
- Previous Behavior:
+- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`)
- .. code-block:: python
+- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`)
- In [1] pd.concat([foo, bar, baz], 1)
- Out[1]:
- 0 1 2
- 0 1 1 4
- 1 2 2 5
+- Enable serialization of lists and dicts to strings in ``ExcelWriter`` (:issue:`8188`)
- New Behavior:
+- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`)
- .. ipython:: python
+- ``pd.read_sql`` and ``to_sql`` can accept database URI as ``con`` parameter (:issue:`10214`)
- pd.concat([foo, bar, baz], 1)
+- ``read_sql_table`` will now allow reading from views (:issue:`10750`).
+
+- Enable writing complex values to HDF stores when using table format (:issue:`10447`)
+
+- Enable ``pd.read_hdf`` to be used without specifying a key when the HDF file contains a single dataset (:issue:`10443`)
+
+- ``pd.read_stata`` will now read Stata 118 type files. (:issue:`9882`)
+
+- ``msgpack`` submodule has been updated to 0.4.6 with backward compatibility (:issue:`10581`)
+
+- ``DataFrame.to_dict`` now accepts the *index* option in ``orient`` keyword argument (:issue:`10844`).
+
+- ``DataFrame.apply`` will return a Series of dicts if the passed function returns a dict and ``reduce=True`` (:issue:`8735`).
- Allow passing `kwargs` to the interpolation methods (:issue:`10378`).
+
- Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`)
@@ -547,9 +535,13 @@ Previous Replacement
Changes to to_datetime and to_timedelta
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-The default for ``pd.to_datetime`` error handling has changed to ``errors='raise'``. In prior versions it was ``errors='ignore'``.
-Furthermore, the ``coerce`` argument has been deprecated in favor of ``errors='coerce'``. This means that invalid parsing will raise rather that return the original
-input as in previous versions. (:issue:`10636`)
+Error handling
+""""""""""""""
+
+The default for ``pd.to_datetime`` error handling has changed to ``errors='raise'``.
+In prior versions it was ``errors='ignore'``. Furthermore, the ``coerce`` argument
+has been deprecated in favor of ``errors='coerce'``. This means that invalid parsing
+will raise rather that return the original input as in previous versions. (:issue:`10636`)
Previous Behavior:
@@ -573,7 +565,7 @@ Of course you can coerce this as well.
to_datetime(['2009-07-31', 'asd'], errors='coerce')
-To keep the previous behaviour, you can use ``errors='ignore'``:
+To keep the previous behavior, you can use ``errors='ignore'``:
.. ipython:: python
@@ -582,6 +574,48 @@ To keep the previous behaviour, you can use ``errors='ignore'``:
Furthermore, ``pd.to_timedelta`` has gained a similar API, of ``errors='raise'|'ignore'|'coerce'``, and the ``coerce`` keyword
has been deprecated in favor of ``errors='coerce'``.
+Consistent Parsing
+""""""""""""""""""
+
+The string parsing of ``to_datetime``, ``Timestamp`` and ``DatetimeIndex`` has
+been made consistent. (:issue:`7599`)
+
+Prior to v0.17.0, ``Timestamp`` and ``to_datetime`` may parse year-only datetime-string incorrectly using today's date, otherwise ``DatetimeIndex``
+uses the beginning of the year. ``Timestamp`` and ``to_datetime`` may raise ``ValueError`` in some types of datetime-string which ``DatetimeIndex``
+can parse, such as a quarterly string.
+
+Previous Behavior:
+
+.. code-block:: python
+
+ In [1]: Timestamp('2012Q2')
+ Traceback
+ ...
+ ValueError: Unable to parse 2012Q2
+
+ # Results in today's date.
+ In [2]: Timestamp('2014')
+ Out [2]: 2014-08-12 00:00:00
+
+v0.17.0 can parse them as below. It works on ``DatetimeIndex`` also.
+
+New Behavior:
+
+.. ipython:: python
+
+ Timestamp('2012Q2')
+ Timestamp('2014')
+ DatetimeIndex(['2012Q2', '2014'])
+
+.. note::
+
+ If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``.
+
+ .. ipython:: python
+
+ import pandas.tseries.offsets as offsets
+ Timestamp.now()
+ Timestamp.now() + offsets.DateOffset(years=1)
.. _whatsnew_0170.api_breaking.convert_objects:
@@ -656,7 +690,7 @@ Operator equal on ``Index`` should behavior similarly to ``Series`` (:issue:`994
Starting in v0.17.0, comparing ``Index`` objects of different lengths will raise
a ``ValueError``. This is to be consistent with the behavior of ``Series``.
-Previous behavior:
+Previous Behavior:
.. code-block:: python
@@ -669,7 +703,7 @@ Previous behavior:
In [4]: pd.Index([1, 2, 3]) == pd.Index([1, 2])
Out[4]: False
-New behavior:
+New Behavior:
.. code-block:: python
@@ -706,14 +740,14 @@ Boolean comparisons of a ``Series`` vs ``None`` will now be equivalent to compar
s.iloc[1] = None
s
-Previous behavior:
+Previous Behavior:
.. code-block:: python
In [5]: s==None
TypeError: Could not compare <type 'NoneType'> type with Series
-New behavior:
+New Behavior:
.. ipython:: python
@@ -742,7 +776,7 @@ HDFStore dropna behavior
The default behavior for HDFStore write functions with ``format='table'`` is now to keep rows that are all missing. Previously, the behavior was to drop rows that were all missing save the index. The previous behavior can be replicated using the ``dropna=True`` option. (:issue:`9382`)
-Previously:
+Previous Behavior:
.. ipython:: python
@@ -768,7 +802,7 @@ Previously:
2 2 NaN
-New behavior:
+New Behavior:
.. ipython:: python
:suppress:
| Reorganized release note for 0.17. There are some descriptions which looks the same level, but one in a highlights and the other is not.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11068 | 2015-09-12T09:05:48Z | 2015-09-12T09:22:34Z | 2015-09-12T09:22:34Z | 2015-09-12T10:45:07Z |
DOC: Missing Excel index images | diff --git a/doc/source/_static/new-excel-index.png b/doc/source/_static/new-excel-index.png
new file mode 100644
index 0000000000000..479237c3712d2
Binary files /dev/null and b/doc/source/_static/new-excel-index.png differ
diff --git a/doc/source/_static/old-excel-index.png b/doc/source/_static/old-excel-index.png
new file mode 100644
index 0000000000000..5281367a5ad9d
Binary files /dev/null and b/doc/source/_static/old-excel-index.png differ
| Adds missing static files that didn't get pushed in https://github.com/pydata/pandas/pull/10967
@jreback
| https://api.github.com/repos/pandas-dev/pandas/pulls/11067 | 2015-09-11T22:33:26Z | 2015-09-11T23:00:48Z | 2015-09-11T23:00:48Z | 2015-09-11T23:05:56Z |
BUG: matplotlib inset-axis #10407 | diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 9eab385a7a2a5..4fb46cf8e0ac6 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -3318,25 +3318,31 @@ def _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey):
if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1:
_remove_labels_from_axis(ax.xaxis)
- except IndexError:
+ except (IndexError, AttributeError):
# if gridspec is used, ax.rowNum and ax.colNum may different
# from layout shape. in this case, use last_row logic
for ax in axarr:
- if ax.is_last_row():
- continue
- if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1:
- _remove_labels_from_axis(ax.xaxis)
+ try:
+ if ax.is_last_row():
+ continue
+ if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1:
+ _remove_labels_from_axis(ax.xaxis)
+ except AttributeError:
+ pass
+
if ncols > 1:
for ax in axarr:
# only the first column should get y labels -> set all other to off
# as we only have labels in teh first column and we always have a subplot there,
# we can skip the layout test
- if ax.is_first_col():
- continue
- if sharey or len(ax.get_shared_y_axes().get_siblings(ax)) > 1:
- _remove_labels_from_axis(ax.yaxis)
-
+ try:
+ if ax.is_first_col():
+ continue
+ if sharey or len(ax.get_shared_y_axes().get_siblings(ax)) > 1:
+ _remove_labels_from_axis(ax.yaxis)
+ except AttributeError:
+ pass
def _flatten(axes):
| This is the issue: https://github.com/pydata/pandas/issues/10407
I just added a bunch of try-catch AttributeError around the offending code - it seemed to do the trick for me.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11065 | 2015-09-11T16:38:44Z | 2015-11-15T21:09:28Z | null | 2023-05-11T01:13:10Z |
Adds the option display.escape_notebook_repr_html | diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index 03eaa45582bef..08f3e68c28e2a 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -77,6 +77,12 @@
pandas objects (if it is available).
"""
+pc_esc_nb_repr_h_doc = """
+: boolean
+ When True, IPython notebook will use HTML-safe sequences for
+ <, >, and & when representing pandas objects.
+"""
+
pc_date_dayfirst_doc = """
: boolean
When True, prints and parses dates with the day first, eg 20/01/2005
@@ -255,6 +261,8 @@ def mpl_style_cb(key):
validator=is_text)
cf.register_option('notebook_repr_html', True, pc_nb_repr_h_doc,
validator=is_bool)
+ cf.register_option('escape_notebook_repr_html', True, pc_esc_nb_repr_h_doc,
+ validator=is_bool)
cf.register_option('date_dayfirst', False, pc_date_dayfirst_doc,
validator=is_bool)
cf.register_option('date_yearfirst', False, pc_date_yearfirst_doc,
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 77b8c4cf35aad..a4b6e8645fbf6 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -566,10 +566,11 @@ def _repr_html_(self):
max_rows = get_option("display.max_rows")
max_cols = get_option("display.max_columns")
show_dimensions = get_option("display.show_dimensions")
+ escape_html = get_option("display.escape_notebook_repr_html")
return self.to_html(max_rows=max_rows, max_cols=max_cols,
show_dimensions=show_dimensions,
- notebook=True)
+ notebook=True, escape=escape_html)
else:
return None
@@ -1459,7 +1460,7 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table
escape : boolean, default True
- Convert the characters <, >, and & to HTML-safe sequences.=
+ Convert the characters <, >, and & to HTML-safe sequences.
max_rows : int, optional
Maximum number of rows to show before truncating. If None, show
all.
| Adds the option `display.escape_notebook_repr_html` for controlling HTML escaping when rendering DataFrames in IPython notebooks. Unset, this argument does not change the default behaviour.
Fixes #11062
| https://api.github.com/repos/pandas-dev/pandas/pulls/11063 | 2015-09-11T14:59:20Z | 2015-11-02T12:08:44Z | null | 2017-01-30T20:55:09Z |
DOC: clean up 0.17 whatsnew | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 5d9e415b85acf..2c192ee33061b 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -21,9 +21,14 @@ users upgrade to this version.
After installing pandas-datareader, you can easily change your imports:
- .. code-block:: Python
+ .. code-block:: python
+
+ from pandas.io import data, wb
+
+ becomes
+
+ .. code-block:: python
- from pandas.io import data, wb # becomes
from pandas_datareader import data, wb
Highlights include:
@@ -53,44 +58,60 @@ Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsne
New features
~~~~~~~~~~~~
-- ``merge`` now accepts the argument ``indicator`` which adds a Categorical-type column (by default called ``_merge``) to the output object that takes on the values (:issue:`8790`)
+.. _whatsnew_0170.tz:
- =================================== ================
- Observation Origin ``_merge`` value
- =================================== ================
- Merge key only in ``'left'`` frame ``left_only``
- Merge key only in ``'right'`` frame ``right_only``
- Merge key in both frames ``both``
- =================================== ================
+Datetime with TZ
+^^^^^^^^^^^^^^^^
- .. ipython:: python
+We are adding an implementation that natively supports datetime with timezones. A ``Series`` or a ``DataFrame`` column previously
+*could* be assigned a datetime with timezones, and would work as an ``object`` dtype. This had performance issues with a large
+number rows. See the :ref:`docs <timeseries.timezone_series>` for more details. (:issue:`8260`, :issue:`10763`, :issue:`11034`).
- df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b']})
- df2 = pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]})
- pd.merge(df1, df2, on='col1', how='outer', indicator=True)
+The new implementation allows for having a single-timezone across all rows, with operations in a performant manner.
- For more, see the :ref:`updated docs <merging.indicator>`
+.. ipython:: python
-- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`)
-- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`)
-- Enable writing complex values to HDF stores when using table format (:issue:`10447`)
-- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`)
-- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`)
+ df = DataFrame({'A' : date_range('20130101',periods=3),
+ 'B' : date_range('20130101',periods=3,tz='US/Eastern'),
+ 'C' : date_range('20130101',periods=3,tz='CET')})
+ df
+ df.dtypes
- .. ipython:: python
+.. ipython:: python
- ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13])
- ser.interpolate(limit=1, limit_direction='both')
+ df.B
+ df.B.dt.tz_localize(None)
-- Round DataFrame to variable number of decimal places (:issue:`10568`).
+This uses a new-dtype representation as well, that is very similar in look-and-feel to its numpy cousin ``datetime64[ns]``
- .. ipython :: python
+.. ipython:: python
- df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'],
- index=['first', 'second', 'third'])
- df
- df.round(2)
- df.round({'A': 0, 'C': 2})
+ df['B'].dtype
+ type(df['B'].dtype)
+
+.. note::
+
+ There is a slightly different string repr for the underlying ``DatetimeIndex`` as a result of the dtype changes, but
+ functionally these are the same.
+
+ Previous Behavior:
+
+ .. code-block:: python
+
+ In [1]: pd.date_range('20130101',periods=3,tz='US/Eastern')
+ Out[1]: DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
+ '2013-01-03 00:00:00-05:00'],
+ dtype='datetime64[ns]', freq='D', tz='US/Eastern')
+
+ In [2]: pd.date_range('20130101',periods=3,tz='US/Eastern').dtype
+ Out[2]: dtype('<M8[ns]')
+
+ New Behavior:
+
+ .. ipython:: python
+
+ pd.date_range('20130101',periods=3,tz='US/Eastern')
+ pd.date_range('20130101',periods=3,tz='US/Eastern').dtype
.. _whatsnew_0170.gil:
@@ -286,6 +307,46 @@ has been changed to make this keyword unnecessary - the change is shown below.
Other enhancements
^^^^^^^^^^^^^^^^^^
+
+- ``merge`` now accepts the argument ``indicator`` which adds a Categorical-type column (by default called ``_merge``) to the output object that takes on the values (:issue:`8790`)
+
+ =================================== ================
+ Observation Origin ``_merge`` value
+ =================================== ================
+ Merge key only in ``'left'`` frame ``left_only``
+ Merge key only in ``'right'`` frame ``right_only``
+ Merge key in both frames ``both``
+ =================================== ================
+
+ .. ipython:: python
+
+ df1 = pd.DataFrame({'col1':[0,1], 'col_left':['a','b']})
+ df2 = pd.DataFrame({'col1':[1,2,2],'col_right':[2,2,2]})
+ pd.merge(df1, df2, on='col1', how='outer', indicator=True)
+
+ For more, see the :ref:`updated docs <merging.indicator>`
+
+- ``DataFrame`` has gained the ``nlargest`` and ``nsmallest`` methods (:issue:`10393`)
+- SQL io functions now accept a SQLAlchemy connectable. (:issue:`7877`)
+- Enable writing complex values to HDF stores when using table format (:issue:`10447`)
+- Enable reading gzip compressed files via URL, either by explicitly setting the compression parameter or by inferring from the presence of the HTTP Content-Encoding header in the response (:issue:`8685`)
+- Add a ``limit_direction`` keyword argument that works with ``limit`` to enable ``interpolate`` to fill ``NaN`` values forward, backward, or both (:issue:`9218` and :issue:`10420`)
+
+ .. ipython:: python
+
+ ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13])
+ ser.interpolate(limit=1, limit_direction='both')
+
+- Round DataFrame to variable number of decimal places (:issue:`10568`).
+
+ .. ipython :: python
+
+ df = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'],
+ index=['first', 'second', 'third'])
+ df
+ df.round(2)
+ df.round({'A': 0, 'C': 2})
+
- ``pd.read_sql`` and ``to_sql`` can accept database URI as ``con`` parameter (:issue:`10214`)
- Enable ``pd.read_hdf`` to be used without specifying a key when the HDF file contains a single dataset (:issue:`10443`)
- Enable writing Excel files in :ref:`memory <_io.excel_writing_buffer>` using StringIO/BytesIO (:issue:`7074`)
@@ -321,13 +382,15 @@ Other enhancements
Timestamp('2014')
DatetimeIndex(['2012Q2', '2014'])
- .. note:: If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``.
+ .. note::
- .. ipython:: python
+ If you want to perform calculations based on today's date, use ``Timestamp.now()`` and ``pandas.tseries.offsets``.
- import pandas.tseries.offsets as offsets
- Timestamp.now()
- Timestamp.now() + offsets.DateOffset(years=1)
+ .. ipython:: python
+
+ import pandas.tseries.offsets as offsets
+ Timestamp.now()
+ Timestamp.now() + offsets.DateOffset(years=1)
- ``to_datetime`` can now accept ``yearfirst`` keyword (:issue:`7599`)
@@ -411,6 +474,9 @@ Other enhancements
pd.concat([foo, bar, baz], 1)
+- Allow passing `kwargs` to the interpolation methods (:issue:`10378`).
+- Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`)
+
.. _whatsnew_0170.api:
@@ -516,60 +582,6 @@ To keep the previous behaviour, you can use ``errors='ignore'``:
Furthermore, ``pd.to_timedelta`` has gained a similar API, of ``errors='raise'|'ignore'|'coerce'``, and the ``coerce`` keyword
has been deprecated in favor of ``errors='coerce'``.
-.. _whatsnew_0170.tz:
-
-Datetime with TZ
-~~~~~~~~~~~~~~~~
-
-We are adding an implementation that natively supports datetime with timezones. A ``Series`` or a ``DataFrame`` column previously
-*could* be assigned a datetime with timezones, and would work as an ``object`` dtype. This had performance issues with a large
-number rows. See the :ref:`docs <timeseries.timezone_series>` for more details. (:issue:`8260`, :issue:`10763`, :issue:`11034`).
-
-The new implementation allows for having a single-timezone across all rows, with operations in a performant manner.
-
-.. ipython:: python
-
- df = DataFrame({'A' : date_range('20130101',periods=3),
- 'B' : date_range('20130101',periods=3,tz='US/Eastern'),
- 'C' : date_range('20130101',periods=3,tz='CET')})
- df
- df.dtypes
-
-.. ipython:: python
-
- df.B
- df.B.dt.tz_localize(None)
-
-This uses a new-dtype representation as well, that is very similar in look-and-feel to its numpy cousin ``datetime64[ns]``
-
-.. ipython:: python
-
- df['B'].dtype
- type(df['B'].dtype)
-
-.. note::
-
- There is a slightly different string repr for the underlying ``DatetimeIndex`` as a result of the dtype changes, but
- functionally these are the same.
-
- Previous Behavior:
-
- .. code-block:: python
-
- In [1]: pd.date_range('20130101',periods=3,tz='US/Eastern')
- Out[1]: DatetimeIndex(['2013-01-01 00:00:00-05:00', '2013-01-02 00:00:00-05:00',
- '2013-01-03 00:00:00-05:00'],
- dtype='datetime64[ns]', freq='D', tz='US/Eastern')
-
- In [2]: pd.date_range('20130101',periods=3,tz='US/Eastern').dtype
- Out[2]: dtype('<M8[ns]')
-
- New Behavior:
-
- .. ipython:: python
-
- pd.date_range('20130101',periods=3,tz='US/Eastern')
- pd.date_range('20130101',periods=3,tz='US/Eastern').dtype
.. _whatsnew_0170.api_breaking.convert_objects:
@@ -847,11 +859,10 @@ Other API Changes
- Line and kde plot with ``subplots=True`` now uses default colors, not all black. Specify ``color='k'`` to draw all lines in black (:issue:`9894`)
- Calling the ``.value_counts()`` method on a Series with ``categorical`` dtype now returns a Series with a ``CategoricalIndex`` (:issue:`10704`)
-- Allow passing `kwargs` to the interpolation methods (:issue:`10378`).
- The metadata properties of subclasses of pandas objects will now be serialized (:issue:`10553`).
- ``groupby`` using ``Categorical`` follows the same rule as ``Categorical.unique`` described above (:issue:`10508`)
-- Improved error message when concatenating an empty iterable of dataframes (:issue:`9157`)
-- When constructing ``DataFrame`` with an array of ``complex64`` dtype that meant the corresponding column was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`)
+- When constructing ``DataFrame`` with an array of ``complex64`` dtype previously meant the corresponding column
+ was automatically promoted to the ``complex128`` dtype. Pandas will now preserve the itemsize of the input for complex data (:issue:`10952`)
- ``NaT``'s methods now either raise ``ValueError``, or return ``np.nan`` or ``NaT`` (:issue:`9513`)
@@ -869,8 +880,6 @@ Other API Changes
Deprecations
^^^^^^^^^^^^
-.. note:: These indexing function have been deprecated in the documentation since 0.11.0.
-
- For ``Series`` the following indexing functions are deprecated (:issue:`10177`).
===================== =================================
@@ -891,6 +900,8 @@ Deprecations
``.icol(j)`` ``.iloc[:, j]``
===================== =================================
+.. note:: These indexing function have been deprecated in the documentation since 0.11.0.
+
- ``Categorical.name`` was deprecated to make ``Categorical`` more ``numpy.ndarray`` like. Use ``Series(cat, name="whatever")`` instead (:issue:`10482`).
- Setting missing values (NaN) in a ``Categorical``'s ``categories`` will issue a warning (:issue:`10748`). You can still have missing values in the ``values``.
- ``drop_duplicates`` and ``duplicated``'s ``take_last`` keyword was deprecated in favor of ``keep``. (:issue:`6511`, :issue:`8505`)
@@ -908,7 +919,6 @@ Deprecations
Removal of prior version deprecations/changes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`)
- Removal of ``na_last`` parameters from ``Series.order()`` and ``Series.sort()``, in favor of ``na_position``, xref (:issue:`5231`)
- Remove of ``percentile_width`` from ``.describe()``, in favor of ``percentiles``. (:issue:`7088`)
- Removal of ``colSpace`` parameter from ``DataFrame.to_string()``, in favor of ``col_space``, circa 0.8.0 version.
@@ -1089,3 +1099,4 @@ Bug Fixes
- Bug in ``Index`` arithmetic may result in incorrect class (:issue:`10638`)
- Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`)
- Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`)
+- Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`)
| Mainly some rearranging (eg the datetime tz was somewhere in the middle of the API changes, moved it to in front of the new features)
| https://api.github.com/repos/pandas-dev/pandas/pulls/11059 | 2015-09-11T09:20:20Z | 2015-09-11T11:14:04Z | 2015-09-11T11:14:04Z | 2015-09-11T11:14:09Z |
DOC: Updated doc-string using new doc-string design for DataFrameFormatter | diff --git a/pandas/core/format.py b/pandas/core/format.py
index 985b349273130..0c1a3dbadbd86 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -58,18 +58,13 @@
the print configuration (controlled by set_option), 'right' out
of the box."""
-force_unicode_docstring = """
- force_unicode : bool, default False
- Always return a unicode result. Deprecated in v0.10.0 as string
- formatting is now rendered to unicode by default."""
-
return_docstring = """
Returns
-------
formatted : string (or unicode, depending on data and options)"""
-docstring_to_string = common_docstring + justify_docstring + force_unicode_docstring + return_docstring
+docstring_to_string = common_docstring + justify_docstring + return_docstring
class CategoricalFormatter(object):
@@ -300,7 +295,7 @@ class DataFrameFormatter(TableFormatter):
"""
__doc__ = __doc__ if __doc__ else ''
- __doc__ += docstring_to_string
+ __doc__ += common_docstring + justify_docstring + return_docstring
def __init__(self, frame, buf=None, columns=None, col_space=None,
header=True, index=True, na_rep='NaN', formatters=None,
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 77b8c4cf35aad..0eeface27238f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1414,7 +1414,7 @@ def to_stata(
write_index=write_index)
writer.write_file()
- @Appender(fmt.common_docstring + fmt.justify_docstring + fmt.return_docstring, indents=1)
+ @Appender(fmt.docstring_to_string, indents=1)
def to_string(self, buf=None, columns=None, col_space=None,
header=True, index=True, na_rep='NaN', formatters=None,
float_format=None, sparsify=None, index_names=True,
@@ -1442,7 +1442,7 @@ def to_string(self, buf=None, columns=None, col_space=None,
result = formatter.buf.getvalue()
return result
- @Appender(fmt.common_docstring + fmt.justify_docstring + fmt.return_docstring, indents=1)
+ @Appender(fmt.docstring_to_string, indents=1)
def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
header=True, index=True, na_rep='NaN', formatters=None,
float_format=None, sparsify=None, index_names=True,
| `DataFrameFormatter` does not have this parameter: `force_unicode_docstring`. This change uses the doc-string re-design in #11011
| https://api.github.com/repos/pandas-dev/pandas/pulls/11057 | 2015-09-11T05:26:28Z | 2015-09-13T20:16:22Z | 2015-09-13T20:16:22Z | 2015-09-13T20:27:43Z |
BUG: Fixed bug in groupby(axis=1) with filter() throws IndexError, #11041 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 07f87ef9d8647..60214a40a446e 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -982,7 +982,7 @@ Bug Fixes
key (:issue:`10385`).
- Bug in ``groupby(sort=False)`` with datetime-like ``Categorical`` raises ``ValueError`` (:issue:`10505`)
-
+- Bug in ``groupby()`` with ``filter()`` throws ``IndexError`` (:issue:`11041`)
- Bug in ``test_categorical`` on big-endian builds (:issue:`10425`)
- Bug in ``Series.shift`` and ``DataFrame.shift`` not supporting categorical data (:issue:`9416`)
- Bug in ``Series.map`` using categorical ``Series`` raises ``AttributeError`` (:issue:`10324`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index a7796b76b7d35..bc04bcb833d4b 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1205,7 +1205,7 @@ def _apply_filter(self, indices, dropna):
else:
indices = np.sort(np.concatenate(indices))
if dropna:
- filtered = self._selected_obj.take(indices)
+ filtered = self._selected_obj.take(indices, axis = self.axis)
else:
mask = np.empty(len(self._selected_obj.index), dtype=bool)
mask.fill(False)
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 7a552fb53e139..a407e880916e3 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -494,7 +494,6 @@ def test_groupby_dict_mapping(self):
assert_series_equal(result, expected2)
def test_groupby_bounds_check(self):
- import pandas as pd
# groupby_X is code-generated, so if one variant
# does, the rest probably do to
a = np.array([1,2],dtype='object')
@@ -3979,7 +3978,6 @@ def test_groupby_datetime64_32_bit(self):
assert_series_equal(result,expected)
def test_groupby_categorical_unequal_len(self):
- import pandas as pd
#GH3011
series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4])
# The raises only happens with categorical, not with series of types category
@@ -4037,7 +4035,6 @@ def noddy(value, weight):
no_toes = df_grouped.apply(lambda x: noddy(x.value, x.weight ))
def test_groupby_with_empty(self):
- import pandas as pd
index = pd.DatetimeIndex(())
data = ()
series = pd.Series(data, index)
@@ -4376,7 +4373,6 @@ def test_cumcount_groupby_not_col(self):
assert_series_equal(expected, sg.cumcount())
def test_filter_series(self):
- import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.Series([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.Series([20, 22, 24], index=[2, 4, 5])
@@ -4395,7 +4391,6 @@ def test_filter_series(self):
expected_even.reindex(s.index))
def test_filter_single_column_df(self):
- import pandas as pd
df = pd.DataFrame([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.DataFrame([20, 22, 24], index=[2, 4, 5])
@@ -4414,7 +4409,6 @@ def test_filter_single_column_df(self):
expected_even.reindex(df.index))
def test_filter_multi_column_df(self):
- import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': [1, 1, 1, 1]})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
@@ -4423,7 +4417,6 @@ def test_filter_multi_column_df(self):
grouped.filter(lambda x: x['A'].sum() - x['B'].sum() > 10), expected)
def test_filter_mixed_df(self):
- import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
@@ -4433,7 +4426,6 @@ def test_filter_mixed_df(self):
grouped.filter(lambda x: x['A'].sum() > 10), expected)
def test_filter_out_all_groups(self):
- import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
@@ -4446,7 +4438,6 @@ def test_filter_out_all_groups(self):
grouped.filter(lambda x: x['A'].sum() > 1000), df.ix[[]])
def test_filter_out_no_groups(self):
- import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
@@ -4459,7 +4450,6 @@ def test_filter_out_no_groups(self):
assert_frame_equal(filtered, df)
def test_filter_condition_raises(self):
- import pandas as pd
def raise_if_sum_is_zero(x):
if x.sum() == 0:
raise ValueError
@@ -4471,6 +4461,14 @@ def raise_if_sum_is_zero(x):
self.assertRaises(TypeError,
lambda: grouped.filter(raise_if_sum_is_zero))
+ # issue 11041
+ def test_filter_with_axis_in_groupby(self):
+ index = pd.MultiIndex.from_product([range(10), [0, 1]])
+ data = pd.DataFrame(np.arange(100).reshape(-1, 20), columns=index)
+ result = data.groupby(level=0, axis=1).filter(lambda x: x.iloc[0, 0] > 10)
+ expected_index = pd.MultiIndex(levels=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1]], labels=[[6, 6, 7, 7, 8, 8, 9, 9], [0, 1, 0, 1, 0, 1, 0, 1]])
+ self.assert_numpy_array_equal(expected_index, result.columns)
+
def test_filter_bad_shapes(self):
df = DataFrame({'A': np.arange(8), 'B': list('aabbbbcc'), 'C': np.arange(8)})
s = df['B']
| Fixed #11041
| https://api.github.com/repos/pandas-dev/pandas/pulls/11055 | 2015-09-11T02:15:01Z | 2015-09-11T14:12:16Z | null | 2015-09-11T14:15:01Z |
DOC: Deleted redundant/repetitive import statement | diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 7a552fb53e139..9aad9a972daf5 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -494,7 +494,6 @@ def test_groupby_dict_mapping(self):
assert_series_equal(result, expected2)
def test_groupby_bounds_check(self):
- import pandas as pd
# groupby_X is code-generated, so if one variant
# does, the rest probably do to
a = np.array([1,2],dtype='object')
@@ -3979,7 +3978,6 @@ def test_groupby_datetime64_32_bit(self):
assert_series_equal(result,expected)
def test_groupby_categorical_unequal_len(self):
- import pandas as pd
#GH3011
series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4])
# The raises only happens with categorical, not with series of types category
@@ -4037,7 +4035,6 @@ def noddy(value, weight):
no_toes = df_grouped.apply(lambda x: noddy(x.value, x.weight ))
def test_groupby_with_empty(self):
- import pandas as pd
index = pd.DatetimeIndex(())
data = ()
series = pd.Series(data, index)
@@ -4376,7 +4373,6 @@ def test_cumcount_groupby_not_col(self):
assert_series_equal(expected, sg.cumcount())
def test_filter_series(self):
- import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.Series([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.Series([20, 22, 24], index=[2, 4, 5])
@@ -4395,7 +4391,6 @@ def test_filter_series(self):
expected_even.reindex(s.index))
def test_filter_single_column_df(self):
- import pandas as pd
df = pd.DataFrame([1, 3, 20, 5, 22, 24, 7])
expected_odd = pd.DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6])
expected_even = pd.DataFrame([20, 22, 24], index=[2, 4, 5])
@@ -4414,7 +4409,6 @@ def test_filter_single_column_df(self):
expected_even.reindex(df.index))
def test_filter_multi_column_df(self):
- import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': [1, 1, 1, 1]})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
@@ -4423,7 +4417,6 @@ def test_filter_multi_column_df(self):
grouped.filter(lambda x: x['A'].sum() - x['B'].sum() > 10), expected)
def test_filter_mixed_df(self):
- import pandas as pd
df = pd.DataFrame({'A': [1, 12, 12, 1], 'B': 'a b c d'.split()})
grouper = df['A'].apply(lambda x: x % 2)
grouped = df.groupby(grouper)
@@ -4433,7 +4426,6 @@ def test_filter_mixed_df(self):
grouped.filter(lambda x: x['A'].sum() > 10), expected)
def test_filter_out_all_groups(self):
- import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
@@ -4446,7 +4438,6 @@ def test_filter_out_all_groups(self):
grouped.filter(lambda x: x['A'].sum() > 1000), df.ix[[]])
def test_filter_out_no_groups(self):
- import pandas as pd
s = pd.Series([1, 3, 20, 5, 22, 24, 7])
grouper = s.apply(lambda x: x % 2)
grouped = s.groupby(grouper)
@@ -4459,7 +4450,6 @@ def test_filter_out_no_groups(self):
assert_frame_equal(filtered, df)
def test_filter_condition_raises(self):
- import pandas as pd
def raise_if_sum_is_zero(x):
if x.sum() == 0:
raise ValueError
| https://api.github.com/repos/pandas-dev/pandas/pulls/11054 | 2015-09-11T01:55:38Z | 2015-09-11T04:46:09Z | null | 2015-09-11T04:46:12Z | |
Add capability to handle Path/LocalPath objects | diff --git a/ci/requirements-2.7.pip b/ci/requirements-2.7.pip
index 644457d69b37f..9bc533110cea3 100644
--- a/ci/requirements-2.7.pip
+++ b/ci/requirements-2.7.pip
@@ -2,3 +2,5 @@ blosc
httplib2
google-api-python-client == 1.2
python-gflags == 2.0
+pathlib
+py
diff --git a/doc/source/conf.py b/doc/source/conf.py
index f2a033eb82d9c..23095b7f4d24b 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -299,8 +299,9 @@
intersphinx_mapping = {
'statsmodels': ('http://statsmodels.sourceforge.net/devel/', None),
'matplotlib': ('http://matplotlib.org/', None),
- 'python': ('http://docs.python.org/', None),
- 'numpy': ('http://docs.scipy.org/doc/numpy', None)
+ 'python': ('http://docs.python.org/3', None),
+ 'numpy': ('http://docs.scipy.org/doc/numpy', None),
+ 'py': ('http://pylib.readthedocs.org/en/latest/', None)
}
import glob
autosummary_generate = glob.glob("*.rst")
diff --git a/doc/source/io.rst b/doc/source/io.rst
index 9def8be621aed..44eb8e33e5ddf 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -79,9 +79,10 @@ for some advanced strategies
They can take a number of arguments:
- - ``filepath_or_buffer``: Either a string path to a file, URL
+ - ``filepath_or_buffer``: Either a path to a file (a :class:`python:str`,
+ :class:`python:pathlib.Path`, or :class:`py:py._path.local.LocalPath`), URL
(including http, ftp, and S3 locations), or any object with a ``read``
- method (such as an open file or ``StringIO``).
+ method (such as an open file or :class:`~python:io.StringIO`).
- ``sep`` or ``delimiter``: A delimiter / separator to split fields
on. With ``sep=None``, ``read_csv`` will try to infer the delimiter
automatically in some cases by "sniffing".
diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt
index 736554672a089..ae0004d9eba08 100755
--- a/doc/source/whatsnew/v0.17.1.txt
+++ b/doc/source/whatsnew/v0.17.1.txt
@@ -23,6 +23,10 @@ Enhancements
Other Enhancements
^^^^^^^^^^^^^^^^^^
+- :func:`~pandas.io.parsers.read_csv` and :func:`~pandas.io.parsers.read_table` now
+ also accept :class:`python:pathlib.Path`, or :class:`py:py._path.local.LocalPath`
+ for the ``filepath_or_buffer`` argument. (:issue:`11051`)
+
.. _whatsnew_0171.api:
API changes
diff --git a/pandas/io/common.py b/pandas/io/common.py
index b9cdd44e52555..98c93ded5d3e8 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -5,10 +5,24 @@
import zipfile
from contextlib import contextmanager, closing
-from pandas.compat import StringIO, string_types, BytesIO
+from pandas.compat import StringIO, BytesIO, string_types, text_type
from pandas import compat
+try:
+ import pathlib
+ _PATHLIB_INSTALLED = True
+except ImportError:
+ _PATHLIB_INSTALLED = False
+
+
+try:
+ from py.path import local as LocalPath
+ _PY_PATH_INSTALLED = True
+except:
+ _PY_PATH_INSTALLED = False
+
+
if compat.PY3:
from urllib.request import urlopen, pathname2url
_urlopen = urlopen
@@ -201,6 +215,25 @@ def _validate_header_arg(header):
"header=int or list-like of ints to specify "
"the row(s) making up the column names")
+def _stringify_path(filepath_or_buffer):
+ """Return the argument coerced to a string if it was a pathlib.Path
+ or a py.path.local
+
+ Parameters
+ ----------
+ filepath_or_buffer : object to be converted
+
+ Returns
+ -------
+ str_filepath_or_buffer : a the string version of the input path
+ """
+ if _PATHLIB_INSTALLED and isinstance(filepath_or_buffer, pathlib.Path):
+ return text_type(filepath_or_buffer)
+ if _PY_PATH_INSTALLED and isinstance(filepath_or_buffer, LocalPath):
+ return filepath_or_buffer.strpath
+ return filepath_or_buffer
+
+
def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
compression=None):
"""
@@ -209,7 +242,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
Parameters
----------
- filepath_or_buffer : a url, filepath, or buffer
+ filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),
+ or buffer
encoding : the encoding to use to decode py3 bytes, default is 'utf-8'
Returns
@@ -257,6 +291,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
filepath_or_buffer = k
return filepath_or_buffer, None, compression
+ # It is a pathlib.Path/py.path.local or string
+ filepath_or_buffer = _stringify_path(filepath_or_buffer)
return _expand_user(filepath_or_buffer), None, compression
diff --git a/pandas/io/tests/test_common.py b/pandas/io/tests/test_common.py
index 03d1e4fb1f365..003068a702246 100644
--- a/pandas/io/tests/test_common.py
+++ b/pandas/io/tests/test_common.py
@@ -5,10 +5,20 @@
import os
from os.path import isabs
+import nose
import pandas.util.testing as tm
from pandas.io import common
+try:
+ from pathlib import Path
+except ImportError:
+ pass
+
+try:
+ from py.path import local as LocalPath
+except ImportError:
+ pass
class TestCommonIOCapabilities(tm.TestCase):
@@ -27,6 +37,22 @@ def test_expand_user_normal_path(self):
self.assertEqual(expanded_name, filename)
self.assertEqual(os.path.expanduser(filename), expanded_name)
+ def test_stringify_path_pathlib(self):
+ tm._skip_if_no_pathlib()
+
+ rel_path = common._stringify_path(Path('.'))
+ self.assertEqual(rel_path, '.')
+ redundant_path = common._stringify_path(Path('foo//bar'))
+ self.assertEqual(redundant_path, 'foo/bar')
+
+ def test_stringify_path_localpath(self):
+ tm._skip_if_no_localpath()
+
+ path = 'foo/bar'
+ abs_path = os.path.abspath(path)
+ lpath = LocalPath(path)
+ self.assertEqual(common._stringify_path(lpath), abs_path)
+
def test_get_filepath_or_buffer_with_path(self):
filename = '~/sometest'
filepath_or_buffer, _, _ = common.get_filepath_or_buffer(filename)
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 362351c7c31c2..df3f1aaa815fa 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -255,6 +255,23 @@ def _skip_if_python26():
import nose
raise nose.SkipTest("skipping on python2.6")
+
+def _skip_if_no_pathlib():
+ try:
+ from pathlib import Path
+ except ImportError:
+ import nose
+ raise nose.SkipTest("pathlib not available")
+
+
+def _skip_if_no_localpath():
+ try:
+ from py.path import local as LocalPath
+ except ImportError:
+ import nose
+ raise nose.SkipTest("py.path not installed")
+
+
def _incompat_bottleneck_version(method):
""" skip if we have bottleneck installed
and its >= 1.0
| fixes #11033
| https://api.github.com/repos/pandas-dev/pandas/pulls/11051 | 2015-09-10T12:59:11Z | 2015-10-17T14:45:16Z | null | 2015-10-17T14:46:11Z |
BUG: GH10645 and GH10692 where operation on large Index would error | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 0b6f6522dfde0..1626ecbf98e80 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1033,7 +1033,7 @@ Bug Fixes
- Bug in ``Index.take`` may add unnecessary ``freq`` attribute (:issue:`10791`)
- Bug in ``merge`` with empty ``DataFrame`` may raise ``IndexError`` (:issue:`10824`)
- Bug in ``to_latex`` where unexpected keyword argument for some documented arguments (:issue:`10888`)
-
+- Bug in indexing of large ``DataFrame`` where ``IndexError`` is uncaught (:issue:`10645` and :issue:`10692`)
- Bug in ``read_csv`` when using the ``nrows`` or ``chunksize`` parameters if file contains only a header line (:issue:`9535`)
- Bug in serialization of ``category`` types in HDF5 in presence of alternate encodings. (:issue:`10366`)
- Bug in ``pd.DataFrame`` when constructing an empty DataFrame with a string dtype (:issue:`9428`)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 025b8c9d0e250..c60509f00ebac 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -4727,7 +4727,7 @@ def __contains__(self, key):
try:
self.get_loc(key)
return True
- except KeyError:
+ except LookupError:
return False
def __reduce__(self):
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 71bba3a9edea2..8b4528ef451ef 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1040,7 +1040,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
# if we are a label return me
try:
return labels.get_loc(obj)
- except KeyError:
+ except LookupError:
if isinstance(obj, tuple) and isinstance(labels, MultiIndex):
if is_setter and len(obj) == labels.nlevels:
return {'key': obj}
@@ -1125,7 +1125,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
else:
try:
return labels.get_loc(obj)
- except KeyError:
+ except LookupError:
# allow a not found key only if we are a setter
if not is_list_like_indexer(obj) and is_setter:
return {'key': obj}
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index c48807365913c..acffbd12d1c9a 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -4602,7 +4602,17 @@ def test_indexing_dtypes_on_empty(self):
assert_series_equal(df2.loc[:,'a'], df2.iloc[:,0])
assert_series_equal(df2.loc[:,'a'], df2.ix[:,0])
+ def test_large_dataframe_indexing(self):
+ #GH10692
+ result = DataFrame({'x': range(10**6)})
+ result.loc[len(result)] = len(result) + 1
+ expected = DataFrame({'x': range(10**6 + 1)})
+ assert_frame_equal(result, expected)
+ def test_large_mi_dataframe_indexing(self):
+ #GH10645
+ result = MultiIndex.from_arrays([range(10**6), range(10**6)])
+ assert(not (10**6, 0) in result)
class TestCategoricalIndex(tm.TestCase):
| closes #10645
closes #10692
replaces #10675
Do I need `@slow` for these tests?
| https://api.github.com/repos/pandas-dev/pandas/pulls/11049 | 2015-09-10T11:42:38Z | 2015-09-10T22:11:55Z | 2015-09-10T22:11:55Z | 2015-09-10T22:12:02Z |
DOC/CLN: typo and redundant code | diff --git a/doc/README.rst b/doc/README.rst
index 7f001192f5d73..06d95e6b9c44d 100644
--- a/doc/README.rst
+++ b/doc/README.rst
@@ -114,7 +114,7 @@ Often it will be necessary to rebuild the C extension after updating::
Building the documentation
^^^^^^^^^^^^^^^^^^^^^^^^^^
-So how do you build the docs? Navigate to your local the folder
+So how do you build the docs? Navigate to your local folder
``pandas/doc/`` directory in the console and run::
python make.py html
diff --git a/doc/source/gotchas.rst b/doc/source/gotchas.rst
index cf4a86d530180..fe7ab67b7f759 100644
--- a/doc/source/gotchas.rst
+++ b/doc/source/gotchas.rst
@@ -297,7 +297,7 @@ concise means of selecting data from a pandas object:
df
df.ix[['b', 'c', 'e']]
-This is, of course, completely equivalent *in this case* to using th
+This is, of course, completely equivalent *in this case* to using the
``reindex`` method:
.. ipython:: python
@@ -455,7 +455,7 @@ parse HTML tables in the top-level pandas io function ``read_html``.
* Drawbacks
- * |lxml|_ does *not* make any guarantees about the results of it's parse
+ * |lxml|_ does *not* make any guarantees about the results of its parse
*unless* it is given |svm|_.
* In light of the above, we have chosen to allow you, the user, to use the
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 7133a6b6d6baf..a87476ee0f847 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -218,7 +218,6 @@ def __init__(self, key=None, level=None, freq=None, axis=0, sort=False):
self.obj=None
self.indexer=None
self.binner=None
- self.grouper=None
@property
def ax(self):
@@ -424,7 +423,7 @@ def _get_indices(self, names):
""" safe get multiple indices, translate keys for datelike to underlying repr """
def get_converter(s):
- # possibly convert to they actual key types
+ # possibly convert to the actual key types
# in the indices, could be a Timestamp or a np.datetime64
if isinstance(s, (Timestamp,datetime.datetime)):
return lambda key: Timestamp(key)
| https://api.github.com/repos/pandas-dev/pandas/pulls/11048 | 2015-09-10T10:52:17Z | 2015-09-10T20:48:47Z | 2015-09-10T20:48:47Z | 2015-09-10T20:48:47Z | |
DOC: correct quoting constants order | diff --git a/doc/source/io.rst b/doc/source/io.rst
index f3d14b78bbf54..f95fdd502d306 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -149,7 +149,8 @@ They can take a number of arguments:
Quoted items can include the delimiter and it will be ignored.
- ``quoting`` : int,
Controls whether quotes should be recognized. Values are taken from `csv.QUOTE_*` values.
- Acceptable values are 0, 1, 2, and 3 for QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONE, and QUOTE_NONNUMERIC, respectively.
+ Acceptable values are 0, 1, 2, and 3 for QUOTE_MINIMAL, QUOTE_ALL,
+ QUOTE_NONNUMERIC and QUOTE_NONE, respectively.
- ``skipinitialspace`` : boolean, default ``False``, Skip spaces after delimiter
- ``escapechar`` : string, to specify how to escape quoted data
- ``comment``: Indicates remainder of line should not be parsed. If found at the
| Small correction, QUOTE_NONE and QUOTE_NONNUMERIC have to be switched:
```
In [1]: import csv
In [2]: csv.QUOTE_NONNUMERIC
Out[2]: 2
In [3]: csv.QUOTE_NONE
Out[3]: 3
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11046 | 2015-09-10T08:50:49Z | 2015-09-10T10:57:47Z | 2015-09-10T10:57:47Z | 2015-09-10T10:57:48Z |
PERF: improves performance in GroupBy.cumcount | diff --git a/doc/source/whatsnew/v0.18.1.txt b/doc/source/whatsnew/v0.18.1.txt
index c6642c5216262..5193231407f12 100644
--- a/doc/source/whatsnew/v0.18.1.txt
+++ b/doc/source/whatsnew/v0.18.1.txt
@@ -138,6 +138,47 @@ API changes
- Provide a proper ``__name__`` and ``__qualname__`` attributes for generic functions (:issue:`12021`)
- ``pd.concat(ignore_index=True)`` now uses ``RangeIndex`` as default (:issue:`12695`)
+.. _whatsnew_0181.enhancements.groubynth:
+
+Index in ``Groupby.nth`` output is now more consistent with ``as_index``
+argument passed in (:issue:`11039`):
+
+Previous Behavior:
+
+.. code-block:: ipython
+
+ In [4]: df
+ Out[4]:
+ A B
+ 0 a 1
+ 1 b 2
+ 2 a 3
+
+ In [5]: df.groupby('A', as_index=True)['B'].nth(0)
+ Out[5]:
+ 0 1
+ 1 2
+ Name: B, dtype: int64
+
+
+New Behavior:
+
+.. code-block:: ipython
+
+ In [7]: df.groupby('A', as_index=True)['B'].nth(0)
+ Out[7]:
+ A
+ a 1
+ b 2
+ Name: B, dtype: int64
+
+ In [8]: df.groupby('A', as_index=False)['B'].nth(0)
+ Out[8]:
+ 0 1
+ 1 2
+ Name: B, dtype: int64
+
+
.. _whatsnew_0181.apply_resample:
Using ``.apply`` on groupby resampling
@@ -239,7 +280,7 @@ Deprecations
Performance Improvements
~~~~~~~~~~~~~~~~~~~~~~~~
-
+- Performance improvements in ``GroupBy.cumcount`` (:issue:`11039`)
- Improved performance of ``DataFrame.to_sql`` when checking case sensitivity for tables. Now only checks if table has been created correctly when table name is not lower case. (:issue:`12876`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 6996254f58f00..d7dbfbf01e9e7 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -653,37 +653,37 @@ def _iterate_slices(self):
def transform(self, func, *args, **kwargs):
raise AbstractMethodError(self)
- def _cumcount_array(self, arr=None, ascending=True):
+ def _cumcount_array(self, ascending=True):
"""
- arr is where cumcount gets its values from
+ Parameters
+ ----------
+ ascending : bool, default True
+ If False, number in reverse, from length of group - 1 to 0.
Note
----
this is currently implementing sort=False
(though the default is sort=True) for groupby in general
"""
- if arr is None:
- arr = np.arange(self.grouper._max_groupsize, dtype='int64')
-
- len_index = len(self._selected_obj.index)
- cumcounts = np.zeros(len_index, dtype=arr.dtype)
- if not len_index:
- return cumcounts
+ ids, _, ngroups = self.grouper.group_info
+ sorter = _get_group_index_sorter(ids, ngroups)
+ ids, count = ids[sorter], len(ids)
- indices, values = [], []
- for v in self.indices.values():
- indices.append(v)
+ if count == 0:
+ return np.empty(0, dtype=np.int64)
- if ascending:
- values.append(arr[:len(v)])
- else:
- values.append(arr[len(v) - 1::-1])
+ run = np.r_[True, ids[:-1] != ids[1:]]
+ rep = np.diff(np.r_[np.nonzero(run)[0], count])
+ out = (~run).cumsum()
- indices = np.concatenate(indices)
- values = np.concatenate(values)
- cumcounts[indices] = values
+ if ascending:
+ out -= np.repeat(out[run], rep)
+ else:
+ out = np.repeat(out[np.r_[run[1:], True]], rep) - out
- return cumcounts
+ rev = np.empty(count, dtype=np.intp)
+ rev[sorter] = np.arange(count, dtype=np.intp)
+ return out[rev].astype(np.int64, copy=False)
def _index_with_as_index(self, b):
"""
@@ -1170,47 +1170,21 @@ def nth(self, n, dropna=None):
else:
raise TypeError("n needs to be an int or a list/set/tuple of ints")
- m = self.grouper._max_groupsize
- # filter out values that are outside [-m, m)
- pos_nth_values = [i for i in nth_values if i >= 0 and i < m]
- neg_nth_values = [i for i in nth_values if i < 0 and i >= -m]
-
+ nth_values = np.array(nth_values, dtype=np.intp)
self._set_selection_from_grouper()
- if not dropna: # good choice
- if not pos_nth_values and not neg_nth_values:
- # no valid nth values
- return self._selected_obj.loc[[]]
-
- rng = np.zeros(m, dtype=bool)
- for i in pos_nth_values:
- rng[i] = True
- is_nth = self._cumcount_array(rng)
- if neg_nth_values:
- rng = np.zeros(m, dtype=bool)
- for i in neg_nth_values:
- rng[- i - 1] = True
- is_nth |= self._cumcount_array(rng, ascending=False)
+ if not dropna:
+ mask = np.in1d(self._cumcount_array(), nth_values) | \
+ np.in1d(self._cumcount_array(ascending=False) + 1, -nth_values)
- result = self._selected_obj[is_nth]
+ out = self._selected_obj[mask]
+ if not self.as_index:
+ return out
- # the result index
- if self.as_index:
- ax = self.obj._info_axis
- names = self.grouper.names
- if self.obj.ndim == 1:
- # this is a pass-thru
- pass
- elif all([x in ax for x in names]):
- indicies = [self.obj[name][is_nth] for name in names]
- result.index = MultiIndex.from_arrays(
- indicies).set_names(names)
- elif self._group_selection is not None:
- result.index = self.obj._get_axis(self.axis)[is_nth]
-
- result = result.sort_index()
+ ids, _, _ = self.grouper.group_info
+ out.index = self.grouper.result_index[ids[mask]]
- return result
+ return out.sort_index() if self.sort else out
if isinstance(self._selected_obj, DataFrame) and \
dropna not in ['any', 'all']:
@@ -1241,8 +1215,8 @@ def nth(self, n, dropna=None):
axis=self.axis, level=self.level,
sort=self.sort)
- sizes = dropped.groupby(grouper).size()
- result = dropped.groupby(grouper).nth(n)
+ grb = dropped.groupby(grouper, as_index=self.as_index, sort=self.sort)
+ sizes, result = grb.size(), grb.nth(n)
mask = (sizes < max_len).values
# set the results which don't meet the criteria
@@ -1380,11 +1354,8 @@ def head(self, n=5):
0 1 2
2 5 6
"""
-
- obj = self._selected_obj
- in_head = self._cumcount_array() < n
- head = obj[in_head]
- return head
+ mask = self._cumcount_array() < n
+ return self._selected_obj[mask]
@Substitution(name='groupby')
@Appender(_doc_template)
@@ -1409,12 +1380,8 @@ def tail(self, n=5):
0 a 1
2 b 1
"""
-
- obj = self._selected_obj
- rng = np.arange(0, -self.grouper._max_groupsize, -1, dtype='int64')
- in_tail = self._cumcount_array(rng, ascending=False) > -n
- tail = obj[in_tail]
- return tail
+ mask = self._cumcount_array(ascending=False) < n
+ return self._selected_obj[mask]
@Appender(GroupBy.__doc__)
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 6cf779bad1a41..24e5169f99942 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -167,8 +167,7 @@ def test_first_last_nth(self):
self.df.loc[self.df['A'] == 'foo', 'B'] = np.nan
self.assertTrue(com.isnull(grouped['B'].first()['foo']))
self.assertTrue(com.isnull(grouped['B'].last()['foo']))
- self.assertTrue(com.isnull(grouped['B'].nth(0)[0])
- ) # not sure what this is testing
+ self.assertTrue(com.isnull(grouped['B'].nth(0)['foo']))
# v0.14.0 whatsnew
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
@@ -221,12 +220,12 @@ def test_nth(self):
assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index('A'))
assert_frame_equal(g.nth(1), df.iloc[[1]].set_index('A'))
- assert_frame_equal(g.nth(2), df.loc[[], ['B']])
+ assert_frame_equal(g.nth(2), df.loc[[]].set_index('A'))
assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index('A'))
assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index('A'))
- assert_frame_equal(g.nth(-3), df.loc[[], ['B']])
- assert_series_equal(g.B.nth(0), df.B.iloc[[0, 2]])
- assert_series_equal(g.B.nth(1), df.B.iloc[[1]])
+ assert_frame_equal(g.nth(-3), df.loc[[]].set_index('A'))
+ assert_series_equal(g.B.nth(0), df.set_index('A').B.iloc[[0, 2]])
+ assert_series_equal(g.B.nth(1), df.set_index('A').B.iloc[[1]])
assert_frame_equal(g[['B']].nth(0),
df.ix[[0, 2], ['A', 'B']].set_index('A'))
@@ -262,11 +261,11 @@ def test_nth(self):
4: 0.70422799999999997}}).set_index(['color',
'food'])
- result = df.groupby(level=0).nth(2)
+ result = df.groupby(level=0, as_index=False).nth(2)
expected = df.iloc[[-1]]
assert_frame_equal(result, expected)
- result = df.groupby(level=0).nth(3)
+ result = df.groupby(level=0, as_index=False).nth(3)
expected = df.loc[[]]
assert_frame_equal(result, expected)
@@ -290,8 +289,7 @@ def test_nth(self):
# as it keeps the order in the series (and not the group order)
# related GH 7287
expected = s.groupby(g, sort=False).first()
- expected.index = pd.Index(range(1, 10), name=0)
- result = s.groupby(g).nth(0, dropna='all')
+ result = s.groupby(g, sort=False).nth(0, dropna='all')
assert_series_equal(result, expected)
# doc example
@@ -316,14 +314,14 @@ def test_nth(self):
assert_frame_equal(
g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index('A'))
assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index('A'))
- assert_frame_equal(g.nth([3, 4]), df.loc[[], ['B']])
+ assert_frame_equal(g.nth([3, 4]), df.loc[[]].set_index('A'))
business_dates = pd.date_range(start='4/1/2014', end='6/30/2014',
freq='B')
df = DataFrame(1, index=business_dates, columns=['a', 'b'])
# get the first, fourth and last two business days for each month
- result = df.groupby((df.index.year, df.index.month)).nth([0, 3, -2, -1
- ])
+ key = (df.index.year, df.index.month)
+ result = df.groupby(key, as_index=False).nth([0, 3, -2, -1])
expected_dates = pd.to_datetime(
['2014/4/1', '2014/4/4', '2014/4/29', '2014/4/30', '2014/5/1',
'2014/5/6', '2014/5/29', '2014/5/30', '2014/6/2', '2014/6/5',
| closes #12839
```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
groupby_ngroups_10000_cumcount | 3.9790 | 74.9559 | 0.0531 |
groupby_ngroups_100_cumcount | 0.6043 | 0.9940 | 0.6079 |
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
Ratio < 1.0 means the target commit is faster then the baseline.
Seed used: 1234
Target [2a1c935] : PERF: improves performance in GroupBy.cumcount
Base [5b1f3b6] : reverts 'from .pandas_vb_common import *'
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11039 | 2015-09-09T23:38:43Z | 2016-04-25T14:21:45Z | null | 2016-04-25T14:53:30Z |
DOC: Fix misspelling of max_colwidth in documentation. | diff --git a/doc/source/options.rst b/doc/source/options.rst
index 753c4cc52cab8..fb57175f96eaa 100644
--- a/doc/source/options.rst
+++ b/doc/source/options.rst
@@ -187,7 +187,7 @@ dataframes to stretch across pages, wrapped over the full column vs row-wise.
pd.reset_option('large_repr')
pd.reset_option('max_rows')
-``display.max_columnwidth`` sets the maximum width of columns. Cells
+``display.max_colwidth`` sets the maximum width of columns. Cells
of this length or longer will be truncated with an ellipsis.
.. ipython:: python
| One location referencing `display.max_colwidth` was incorrectly spelled as `display.max_columnwidth`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11037 | 2015-09-09T20:14:32Z | 2015-09-09T21:10:44Z | 2015-09-09T21:10:44Z | 2015-09-09T21:37:01Z |
BUG: Fix Timestamp __ne__ comparison issue | diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index 8a879a4de248b..5b3d6069f17ec 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -672,10 +672,7 @@ def na_op(x, y):
else:
y = y.view('i8')
- if name == '__ne__':
- mask = notnull(x)
- else:
- mask = isnull(x)
+ mask = isnull(x)
x = x.view('i8')
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 565ce43dc46a1..535332d6efc4c 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -2152,7 +2152,6 @@ def test_period_resample_with_local_timezone_dateutil(self):
expected = pd.Series(1, index=expected_index)
assert_series_equal(result, expected)
-
def test_pickle(self):
# GH4606
@@ -2171,6 +2170,12 @@ def test_pickle(self):
idx_p = self.round_trip_pickle(idx)
tm.assert_index_equal(idx, idx_p)
+ def test_timestamp_equality(self):
+ s = Series([Timestamp('2000-01-29 01:59:00')])
+ result = s != s
+ self.assertFalse(result.item())
+
+
def _simple_ts(start, end, freq='D'):
rng = date_range(start, end, freq=freq)
return Series(np.random.randn(len(rng)), index=rng)
| closes #11034
| https://api.github.com/repos/pandas-dev/pandas/pulls/11036 | 2015-09-09T17:05:23Z | 2015-09-09T21:09:17Z | null | 2015-09-09T21:09:17Z |
BUG: Fixed bug in len(DataFrame.groupby) causing IndexError when there's a NaN-only column (issue11016) | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 7100f78cb3c7a..6570306e79596 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -951,7 +951,7 @@ Bug Fixes
- Bug in ``to_datetime`` and ``to_timedelta`` causing ``Index`` name to be lost (:issue:`10875`)
-
+- Bug in ``len(DataFrame.groupby)`` causing IndexError when there's a column containing only NaNs (:issue: `11016`)
- Bug that caused segfault when resampling an empty Series (:issue:`10228`)
- Bug in ``DatetimeIndex`` and ``PeriodIndex.value_counts`` resets name from its result, but retains in result's ``Index``. (:issue:`10150`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 7133a6b6d6baf..1d5a92d43d680 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -400,7 +400,7 @@ def __init__(self, obj, keys=None, axis=0, level=None,
self.exclusions = set(exclusions) if exclusions else set()
def __len__(self):
- return len(self.indices)
+ return len(self.groups)
def __unicode__(self):
# TODO: Better unicode/repr for GroupBy object
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index a85e68602493b..a97a0a9ede6f9 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -837,6 +837,12 @@ def test_len(self):
expected = len(set([(x.year, x.month) for x in df.index]))
self.assertEqual(len(grouped), expected)
+ # issue 11016
+ df = pd.DataFrame(dict(a=[np.nan]*3, b=[1,2,3]))
+ self.assertEqual(len(df.groupby(('a'))), 0)
+ self.assertEqual(len(df.groupby(('b'))), 3)
+ self.assertEqual(len(df.groupby(('a', 'b'))), 3)
+
def test_groups(self):
grouped = self.df.groupby(['A'])
groups = grouped.groups
| This is the new PR for Fixed issue #11016
| https://api.github.com/repos/pandas-dev/pandas/pulls/11031 | 2015-09-09T01:51:42Z | 2015-09-09T11:16:52Z | 2015-09-09T11:16:52Z | 2015-09-09T12:40:45Z |
BUG: Fixed bug in len(DataFrame.groupby) causing IndexError when there's a NaN-only column (issue11016) | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 68d3861599cbd..e0d15aed05e0e 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -954,7 +954,7 @@ Bug Fixes
- Bug in ``Categorical.__iter__`` may not returning correct ``datetime`` and ``Period`` (:issue:`10713`)
- Bug in ``read_csv`` with ``engine='c'``: EOF preceded by a comment, blank line, etc. was not handled correctly (:issue:`10728`, :issue:`10548`)
-
+- Bug in ``len(DataFrame.groupby)`` causing IndexError when there's a column containing only NaNs (:issue: `11016`)
- Reading "famafrench" data via ``DataReader`` results in HTTP 404 error because of the website url is changed (:issue:`10591`).
- Bug in ``read_msgpack`` where DataFrame to decode has duplicate column names (:issue:`9618`)
- Bug in ``io.common.get_filepath_or_buffer`` which caused reading of valid S3 files to fail if the bucket also contained keys for which the user does not have read permission (:issue:`10604`)
@@ -986,3 +986,4 @@ Bug Fixes
- Bug when constructing ``DataFrame`` where passing a dictionary with only scalar values and specifying columns did not raise an error (:issue:`10856`)
- Bug in ``.var()`` causing roundoff errors for highly similar values (:issue:`10242`)
- Bug in ``DataFrame.plot(subplots=True)`` with duplicated columns outputs incorrect result (:issue:`10962`)
+
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 43110494d675b..367c1feacb324 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -403,7 +403,7 @@ def __init__(self, obj, keys=None, axis=0, level=None,
self.exclusions = set(exclusions) if exclusions else set()
def __len__(self):
- return len(self.indices)
+ return len(self.groups)
def __unicode__(self):
# TODO: Better unicode/repr for GroupBy object
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index f7b6f947d8924..af151544482e1 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -837,6 +837,12 @@ def test_len(self):
expected = len(set([(x.year, x.month) for x in df.index]))
self.assertEqual(len(grouped), expected)
+ # issue 11016
+ df = pd.DataFrame(dict(a=[np.nan]*3, b=[1,2,3]))
+ self.assertEqual(len(df.groupby(('a'))), 0)
+ self.assertEqual(len(df.groupby(('b'))), 3)
+ self.assertEqual(len(df.groupby(('a', 'b'))), 3)
+
def test_groups(self):
grouped = self.df.groupby(['A'])
groups = grouped.groups
| Fixed #11016
| https://api.github.com/repos/pandas-dev/pandas/pulls/11030 | 2015-09-09T01:18:09Z | 2015-09-09T01:52:42Z | null | 2015-09-09T01:52:44Z |
Fix for DataFrame.hist() with by- and weights-keyword | diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 9eab385a7a2a5..bee0817692bce 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -2700,7 +2700,7 @@ def plot_group(group, ax):
return fig
-def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
+def hist_frame(data, column=None, weights=None, by=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
sharey=False, figsize=None, layout=None, bins=10, **kwds):
"""
@@ -2711,6 +2711,8 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
data : DataFrame
column : string or sequence
If passed, will be used to limit data to a subset of columns
+ weights : string or sequence
+ If passed, will be used to weight the data
by : object, optional
If passed, then used to form histograms for separate groups
grid : boolean, default True
@@ -2742,7 +2744,7 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
"""
if by is not None:
- axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize,
+ axes = grouped_hist(data, column=column, weights=weights, by=by, ax=ax, grid=grid, figsize=figsize,
sharex=sharex, sharey=sharey, layout=layout, bins=bins,
xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot,
**kwds)
@@ -2846,7 +2848,7 @@ def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
return axes
-def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
+def grouped_hist(data, column=None, weights=None, by=None, ax=None, bins=50, figsize=None,
layout=None, sharex=False, sharey=False, rot=90, grid=True,
xlabelsize=None, xrot=None, ylabelsize=None, yrot=None,
**kwargs):
@@ -2857,6 +2859,7 @@ def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
----------
data: Series/DataFrame
column: object, optional
+ weights: object, optional
by: object, optional
ax: axes, optional
bins: int, default 50
@@ -2872,12 +2875,14 @@ def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None,
-------
axes: collection of Matplotlib Axes
"""
- def plot_group(group, ax):
- ax.hist(group.dropna().values, bins=bins, **kwargs)
+ def plot_group(group, ax, weights=None):
+ if weights is not None:
+ weights=weights.dropna().values
+ ax.hist(group.dropna().values, weights=weights, bins=bins, **kwargs)
xrot = xrot or rot
- fig, axes = _grouped_plot(plot_group, data, column=column,
+ fig, axes = _grouped_plot(plot_group, data, column=column, weights=weights,
by=by, sharex=sharex, sharey=sharey, ax=ax,
figsize=figsize, layout=layout, rot=rot)
@@ -2964,7 +2969,7 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
return ret
-def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True,
+def _grouped_plot(plotf, data, column=None, weights=None, by=None, numeric_only=True,
figsize=None, sharex=True, sharey=True, layout=None,
rot=0, ax=None, **kwargs):
from pandas import DataFrame
@@ -2977,6 +2982,8 @@ def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True,
grouped = data.groupby(by)
if column is not None:
+ if weights is not None:
+ weights = grouped[weights]
grouped = grouped[column]
naxes = len(grouped)
@@ -2986,11 +2993,20 @@ def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True,
_axes = _flatten(axes)
+ weight = None
for i, (key, group) in enumerate(grouped):
ax = _axes[i]
+ if weights is not None:
+ weight = weights.get_group(key)
if numeric_only and isinstance(group, DataFrame):
group = group._get_numeric_data()
- plotf(group, ax, **kwargs)
+ if weight is not None:
+ weight = weight._get_numeric_data()
+ if weight is not None:
+ plotf(group, ax, weight, **kwargs)
+ else:
+ # scatterplot etc has not the weight implemented in plotf
+ plotf(group, ax, **kwargs)
ax.set_title(com.pprint_thing(key))
return fig, axes
| closes https://github.com/pydata/pandas/issues/9540
for example:
``` python
import pandas as pd
d = {'one' : ['A', 'A', 'B', 'C'],
'two' : [4., 3., 2., 1.],
'three' : [10., 8., 5., 7.]}
df = pd.DataFrame(d)
df.hist('two', by='one', weights='three', bins=range(0, 10))
```
does not seem to break anything, but this is my first meddling in the pandas library, so a review would be nice
| https://api.github.com/repos/pandas-dev/pandas/pulls/11028 | 2015-09-08T20:34:19Z | 2015-10-27T20:25:50Z | null | 2015-10-27T20:25:50Z |
Fix common typo in documentation | diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index 2eaf143a3e0b8..8785a8d092d48 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -375,7 +375,7 @@ For example, horizontal and custom-positioned boxplot can be drawn by
See the :meth:`boxplot <matplotlib.axes.Axes.boxplot>` method and the
-`matplotlib boxplot documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot>`__ for more.
+`matplotlib boxplot documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot>`__ for more.
The existing interface ``DataFrame.boxplot`` to plot boxplot still can be used.
@@ -601,7 +601,7 @@ Below example shows a bubble chart using a dataframe column values as bubble siz
plt.close('all')
See the :meth:`scatter <matplotlib.axes.Axes.scatter>` method and the
-`matplotlib scatter documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`__ for more.
+`matplotlib scatter documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`__ for more.
.. _visualization.hexbin:
@@ -665,7 +665,7 @@ given by column ``z``. The bins are aggregated with numpy's ``max`` function.
plt.close('all')
See the :meth:`hexbin <matplotlib.axes.Axes.hexbin>` method and the
-`matplotlib hexbin documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hexbin>`__ for more.
+`matplotlib hexbin documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hexbin>`__ for more.
.. _visualization.pie:
@@ -761,7 +761,7 @@ If you pass values whose sum total is less than 1.0, matplotlib draws a semicirc
@savefig series_pie_plot_semi.png
series.plot(kind='pie', figsize=(6, 6))
-See the `matplotlib pie documenation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie>`__ for more.
+See the `matplotlib pie documentation <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie>`__ for more.
.. ipython:: python
:suppress:
@@ -1445,7 +1445,7 @@ Finally, there is a helper function ``pandas.tools.plotting.table`` to create a
plt.close('all')
-**Note**: You can get table instances on the axes using ``axes.tables`` property for further decorations. See the `matplotlib table documenation <http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.table>`__ for more.
+**Note**: You can get table instances on the axes using ``axes.tables`` property for further decorations. See the `matplotlib table documentation <http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.table>`__ for more.
.. _visualization.colormaps:
| documenation -> documentation
| https://api.github.com/repos/pandas-dev/pandas/pulls/11027 | 2015-09-08T17:22:31Z | 2015-09-08T17:27:36Z | 2015-09-08T17:27:36Z | 2015-09-08T17:28:01Z |
DOC: Add GroupBy.count | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 0293fc655742e..7133a6b6d6baf 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -719,6 +719,12 @@ def irow(self, i):
FutureWarning, stacklevel=2)
return self.nth(i)
+ def count(self):
+ """ Compute count of group, excluding missing values """
+
+ # defined here for API doc
+ raise NotImplementedError
+
def mean(self):
"""
Compute mean of groups, excluding missing values
@@ -2674,6 +2680,7 @@ def value_counts(self, normalize=False, sort=True, ascending=False,
return Series(out, index=mi)
def count(self):
+ """ Compute count of group, excluding missing values """
ids, _, ngroups = self.grouper.group_info
val = self.obj.get_values()
@@ -3458,6 +3465,7 @@ def _apply_to_column_groupbys(self, func):
keys=self._selected_obj.columns, axis=1)
def count(self):
+ """ Compute count of group, excluding missing values """
from functools import partial
from pandas.lib import count_level_2d
from pandas.core.common import _isnull_ndarraylike as isnull
| Related to #11013. Define `GroupBy.count` for API doc and added docstring.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11025 | 2015-09-08T13:51:54Z | 2015-09-08T15:21:31Z | 2015-09-08T15:21:31Z | 2015-09-08T20:35:25Z |
BUG: DatetimeIndex.freq can defer by ufunc | diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 1ec73edbb82e5..80145df181756 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -3151,6 +3151,39 @@ def test_nat(self):
self.assertIs(DatetimeIndex([np.nan])[0], pd.NaT)
+ def test_ufunc_coercions(self):
+ idx = date_range('2011-01-01', periods=3, freq='2D', name='x')
+
+ delta = np.timedelta64(1, 'D')
+ for result in [idx + delta, np.add(idx, delta)]:
+ tm.assertIsInstance(result, DatetimeIndex)
+ exp = date_range('2011-01-02', periods=3, freq='2D', name='x')
+ tm.assert_index_equal(result, exp)
+ self.assertEqual(result.freq, '2D')
+
+ for result in [idx - delta, np.subtract(idx, delta)]:
+ tm.assertIsInstance(result, DatetimeIndex)
+ exp = date_range('2010-12-31', periods=3, freq='2D', name='x')
+ tm.assert_index_equal(result, exp)
+ self.assertEqual(result.freq, '2D')
+
+ delta = np.array([np.timedelta64(1, 'D'), np.timedelta64(2, 'D'),
+ np.timedelta64(3, 'D')])
+ for result in [idx + delta, np.add(idx, delta)]:
+ tm.assertIsInstance(result, DatetimeIndex)
+ exp = DatetimeIndex(['2011-01-02', '2011-01-05', '2011-01-08'],
+ freq='3D', name='x')
+ tm.assert_index_equal(result, exp)
+ self.assertEqual(result.freq, '3D')
+
+ for result in [idx - delta, np.subtract(idx, delta)]:
+ tm.assertIsInstance(result, DatetimeIndex)
+ exp = DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'],
+ freq='D', name='x')
+ tm.assert_index_equal(result, exp)
+ self.assertEqual(result.freq, 'D')
+
+
class TestPeriodIndex(DatetimeLike, tm.TestCase):
_holder = PeriodIndex
_multiprocess_can_split_ = True
@@ -3306,7 +3339,7 @@ def test_pickle_compat_construction(self):
def test_ufunc_coercions(self):
# normal ops are also tested in tseries/test_timedeltas.py
idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'],
- freq='2H', name='x')
+ freq='2H', name='x')
for result in [idx * 2, np.multiply(idx, 2)]:
tm.assertIsInstance(result, TimedeltaIndex)
@@ -3323,7 +3356,7 @@ def test_ufunc_coercions(self):
self.assertEqual(result.freq, 'H')
idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'],
- freq='2H', name='x')
+ freq='2H', name='x')
for result in [ - idx, np.negative(idx)]:
tm.assertIsInstance(result, TimedeltaIndex)
exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'],
@@ -3332,7 +3365,7 @@ def test_ufunc_coercions(self):
self.assertEqual(result.freq, '-2H')
idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'],
- freq='H', name='x')
+ freq='H', name='x')
for result in [ abs(idx), np.absolute(idx)]:
tm.assertIsInstance(result, TimedeltaIndex)
exp = TimedeltaIndex(['2H', '1H', '0H', '1H', '2H'],
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 966bd5c8d0ab5..c2dc625bd6ece 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -694,6 +694,14 @@ def _sub_datelike(self, other):
result = self._maybe_mask_results(result,fill_value=tslib.iNaT)
return TimedeltaIndex(result,name=self.name,copy=False)
+ def _maybe_update_attributes(self, attrs):
+ """ Update Index attributes (e.g. freq) depending on op """
+ freq = attrs.get('freq', None)
+ if freq is not None:
+ # no need to infer if freq is None
+ attrs['freq'] = 'infer'
+ return attrs
+
def _add_delta(self, delta):
from pandas import TimedeltaIndex
name = self.name
| Follow up of #10638. `DatetimeIndex.freq` also can be changed when other arg is an ndarray.
As the same as #10638, freq is re-infered only when it exists. Otherwise, leave it as `None` even if the result can be on specific freq. This is based on other functions behavior as below:
```
idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'])
idx
# DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], dtype='datetime64[ns]', freq=None)
idx.take([0, 2])
# DatetimeIndex(['2011-01-01', '2011-01-03'], dtype='datetime64[ns]', freq=None)
idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], freq='D')
idx.take([0, 2])
# DatetimeIndex(['2011-01-01', '2011-01-03'], dtype='datetime64[ns]', freq='2D')
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11024 | 2015-09-08T13:07:49Z | 2015-09-09T08:47:32Z | 2015-09-09T08:47:32Z | 2015-09-09T08:47:50Z |
PERF: use NaT comparisons in int64/datetimelikes #11010 | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index cbcee664d8be4..7100f78cb3c7a 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1009,11 +1009,10 @@ Bug Fixes
- Bug in ``to_json`` which was causing segmentation fault when serializing 0-rank ndarray (:issue:`9576`)
- Bug in plotting functions may raise ``IndexError`` when plotted on ``GridSpec`` (:issue:`10819`)
- Bug in plot result may show unnecessary minor ticklabels (:issue:`10657`)
-- Bug in ``groupby`` incorrect computation for aggregation on ``DataFrame`` with ``NaT`` (E.g ``first``, ``last``, ``min``). (:issue:`10590`)
+- Bug in ``groupby`` incorrect computation for aggregation on ``DataFrame`` with ``NaT`` (E.g ``first``, ``last``, ``min``). (:issue:`10590`, :issue:`11010`)
- Bug when constructing ``DataFrame`` where passing a dictionary with only scalar values and specifying columns did not raise an error (:issue:`10856`)
- Bug in ``.var()`` causing roundoff errors for highly similar values (:issue:`10242`)
- Bug in ``DataFrame.plot(subplots=True)`` with duplicated columns outputs incorrect result (:issue:`10962`)
- Bug in ``Index`` arithmetic may result in incorrect class (:issue:`10638`)
- Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`)
- Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`)
-
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 1f5855e63dee8..0293fc655742e 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1523,8 +1523,6 @@ def aggregate(self, values, how, axis=0):
if is_datetime_or_timedelta_dtype(values.dtype):
values = values.view('int64')
- values[values == tslib.iNaT] = np.nan
- # GH 7754
is_numeric = True
elif is_bool_dtype(values.dtype):
values = _algos.ensure_float64(values)
diff --git a/pandas/src/generate_code.py b/pandas/src/generate_code.py
index b055d75df4cf4..8c5c7d709e5f1 100644
--- a/pandas/src/generate_code.py
+++ b/pandas/src/generate_code.py
@@ -739,7 +739,7 @@ def group_last_%(name)s(ndarray[%(dest_type2)s, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != %(nan_val)s:
nobs[lab, j] += 1
resx[lab, j] = val
@@ -785,7 +785,7 @@ def group_nth_%(name)s(ndarray[%(dest_type2)s, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != %(nan_val)s:
nobs[lab, j] += 1
if nobs[lab, j] == rank:
resx[lab, j] = val
@@ -1013,7 +1013,7 @@ def group_max_%(name)s(ndarray[%(dest_type2)s, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != %(nan_val)s:
nobs[lab, j] += 1
if val > maxx[lab, j]:
maxx[lab, j] = val
@@ -1027,7 +1027,7 @@ def group_max_%(name)s(ndarray[%(dest_type2)s, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != %(nan_val)s:
nobs[lab, 0] += 1
if val > maxx[lab, 0]:
maxx[lab, 0] = val
@@ -1076,7 +1076,8 @@ def group_min_%(name)s(ndarray[%(dest_type2)s, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != %(nan_val)s:
+
nobs[lab, j] += 1
if val < minx[lab, j]:
minx[lab, j] = val
@@ -1090,7 +1091,7 @@ def group_min_%(name)s(ndarray[%(dest_type2)s, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != %(nan_val)s:
nobs[lab, 0] += 1
if val < minx[lab, 0]:
minx[lab, 0] = val
diff --git a/pandas/src/generated.pyx b/pandas/src/generated.pyx
index 2f2fd528999d6..767e7d6292b6d 100644
--- a/pandas/src/generated.pyx
+++ b/pandas/src/generated.pyx
@@ -7315,7 +7315,7 @@ def group_last_float64(ndarray[float64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, j] += 1
resx[lab, j] = val
@@ -7360,7 +7360,7 @@ def group_last_float32(ndarray[float32_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, j] += 1
resx[lab, j] = val
@@ -7405,7 +7405,7 @@ def group_last_int64(ndarray[int64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != iNaT:
nobs[lab, j] += 1
resx[lab, j] = val
@@ -7451,7 +7451,7 @@ def group_nth_float64(ndarray[float64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, j] += 1
if nobs[lab, j] == rank:
resx[lab, j] = val
@@ -7497,7 +7497,7 @@ def group_nth_float32(ndarray[float32_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, j] += 1
if nobs[lab, j] == rank:
resx[lab, j] = val
@@ -7543,7 +7543,7 @@ def group_nth_int64(ndarray[int64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != iNaT:
nobs[lab, j] += 1
if nobs[lab, j] == rank:
resx[lab, j] = val
@@ -7592,7 +7592,8 @@ def group_min_float64(ndarray[float64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
+
nobs[lab, j] += 1
if val < minx[lab, j]:
minx[lab, j] = val
@@ -7606,7 +7607,7 @@ def group_min_float64(ndarray[float64_t, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, 0] += 1
if val < minx[lab, 0]:
minx[lab, 0] = val
@@ -7654,7 +7655,8 @@ def group_min_float32(ndarray[float32_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
+
nobs[lab, j] += 1
if val < minx[lab, j]:
minx[lab, j] = val
@@ -7668,7 +7670,7 @@ def group_min_float32(ndarray[float32_t, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, 0] += 1
if val < minx[lab, 0]:
minx[lab, 0] = val
@@ -7716,7 +7718,8 @@ def group_min_int64(ndarray[int64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != iNaT:
+
nobs[lab, j] += 1
if val < minx[lab, j]:
minx[lab, j] = val
@@ -7730,7 +7733,7 @@ def group_min_int64(ndarray[int64_t, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != iNaT:
nobs[lab, 0] += 1
if val < minx[lab, 0]:
minx[lab, 0] = val
@@ -7779,7 +7782,7 @@ def group_max_float64(ndarray[float64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, j] += 1
if val > maxx[lab, j]:
maxx[lab, j] = val
@@ -7793,7 +7796,7 @@ def group_max_float64(ndarray[float64_t, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, 0] += 1
if val > maxx[lab, 0]:
maxx[lab, 0] = val
@@ -7841,7 +7844,7 @@ def group_max_float32(ndarray[float32_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, j] += 1
if val > maxx[lab, j]:
maxx[lab, j] = val
@@ -7855,7 +7858,7 @@ def group_max_float32(ndarray[float32_t, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != NAN:
nobs[lab, 0] += 1
if val > maxx[lab, 0]:
maxx[lab, 0] = val
@@ -7903,7 +7906,7 @@ def group_max_int64(ndarray[int64_t, ndim=2] out,
val = values[i, j]
# not nan
- if val == val:
+ if val == val and val != iNaT:
nobs[lab, j] += 1
if val > maxx[lab, j]:
maxx[lab, j] = val
@@ -7917,7 +7920,7 @@ def group_max_int64(ndarray[int64_t, ndim=2] out,
val = values[i, 0]
# not nan
- if val == val:
+ if val == val and val != iNaT:
nobs[lab, 0] += 1
if val > maxx[lab, 0]:
maxx[lab, 0] = val
| closes #11010
```
In [10]: %timeit gr['3rd'].count()
100 loops, best of 3: 15.1 ms per loop
In [11]: %timeit gr['3rd'].min()
100 loops, best of 3: 8.4 ms per loop
In [12]: %timeit gr['3rd'].max()
100 loops, best of 3: 8.47 ms per loop
In [13]: %timeit gr['3rd'].first()
100 loops, best of 3: 10.5 ms per loop
In [14]: %timeit gr['3rd'].last()
100 loops, best of 3: 10.3 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11023 | 2015-09-07T22:43:56Z | 2015-09-08T00:30:05Z | 2015-09-08T00:30:05Z | 2015-09-08T00:30:05Z |
BUG: Exception when setting a major- or minor-axis slice of a Panel with RHS a DataFrame | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index f88e5c0a11f9f..4e8cfdfa16a12 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -964,6 +964,8 @@ Bug Fixes
- Bug causes memory leak in time-series line and area plot (:issue:`9003`)
+- Bug when setting a ``Panel`` sliced along the major or minor axes when the right-hand side is a ``DataFrame`` (:issue:`11014`)
+
- Bug in line and kde plot cannot accept multiple colors when ``subplots=True`` (:issue:`9894`)
- Bug in ``DataFrame.plot`` raises ``ValueError`` when color name is specified by multiple characters (:issue:`10387`)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 7cf1942046e75..71bba3a9edea2 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -442,11 +442,15 @@ def can_do_equal_len():
# we have an equal len Frame
if isinstance(value, ABCDataFrame) and value.ndim > 1:
+ sub_indexer = list(indexer)
for item in labels:
- # align to
- v = np.nan if item not in value else \
- self._align_series(indexer[0], value[item])
+ if item in value:
+ sub_indexer[info_axis] = item
+ v = self._align_series(tuple(sub_indexer), value[item])
+ else:
+ v = np.nan
+
setter(item, v)
# we have an equal len ndarray/convertible to our labels
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index d45e6e50cafb3..7c67ded16139c 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -506,6 +506,20 @@ def test_setitem_ndarray(self):
assert_almost_equal(P[key].values, data)
+ def test_set_minor_major(self):
+ # GH 11014
+ df1 = DataFrame(['a', 'a', 'a', np.nan, 'a', np.nan])
+ df2 = DataFrame([1.0, np.nan, 1.0, np.nan, 1.0, 1.0])
+ panel = Panel({'Item1' : df1, 'Item2': df2})
+
+ newminor = notnull(panel.iloc[:, :, 0])
+ panel.loc[:, :, 'NewMinor'] = newminor
+ assert_frame_equal(panel.loc[:, :, 'NewMinor'], newminor.astype(object))
+
+ newmajor = notnull(panel.iloc[:, 0, :])
+ panel.loc[:, 'NewMajor', :] = newmajor
+ assert_frame_equal(panel.loc[:, 'NewMajor', :], newmajor.astype(object))
+
def test_major_xs(self):
ref = self.panel['ItemA']
| Fixes GH #11014
This isn't actually a recent regression. The bug was introduced in 0.15.0 with this commit: https://github.com/pydata/pandas/commit/30246a7d2b113b7115fd0708655ae8e1c3f2e6c5; it was just made more common (i.e., it happens on panels without mixed dtype) in 0.16.2 by this commit: https://github.com/pydata/pandas/commit/5c394677e10dac38fe3375e2564bb76cf8bbffca.
| https://api.github.com/repos/pandas-dev/pandas/pulls/11021 | 2015-09-07T18:33:05Z | 2015-09-07T20:16:06Z | 2015-09-07T20:16:06Z | 2015-09-19T00:38:09Z |
BUG: Unable to infer negative freq | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index f88e5c0a11f9f..b861bf51b80eb 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1009,4 +1009,6 @@ Bug Fixes
- Bug in ``.var()`` causing roundoff errors for highly similar values (:issue:`10242`)
- Bug in ``DataFrame.plot(subplots=True)`` with duplicated columns outputs incorrect result (:issue:`10962`)
- Bug in ``Index`` arithmetic may result in incorrect class (:issue:`10638`)
+- Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`)
+- Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 36bc0755f9a6a..1ec73edbb82e5 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -3329,7 +3329,7 @@ def test_ufunc_coercions(self):
exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'],
freq='-2H', name='x')
tm.assert_index_equal(result, exp)
- self.assertEqual(result.freq, None)
+ self.assertEqual(result.freq, '-2H')
idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'],
freq='H', name='x')
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index d7eaab5a5a186..6a4257d101473 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -887,7 +887,8 @@ def __init__(self, index, warn=True):
if len(index) < 3:
raise ValueError('Need at least 3 dates to infer frequency')
- self.is_monotonic = self.index.is_monotonic
+ self.is_monotonic = (self.index.is_monotonic_increasing or
+ self.index.is_monotonic_decreasing)
@cache_readonly
def deltas(self):
@@ -971,7 +972,6 @@ def month_position_check(self):
from calendar import monthrange
for y, m, d, wd in zip(years, months, days, weekdays):
- wd = datetime(y, m, d).weekday()
if calendar_start:
calendar_start &= d == 1
@@ -1025,7 +1025,7 @@ def _infer_daily_rule(self):
monthly_rule = self._get_monthly_rule()
if monthly_rule:
- return monthly_rule
+ return _maybe_add_count(monthly_rule, self.mdiffs[0])
if self.is_unique:
days = self.deltas[0] / _ONE_DAY
@@ -1111,7 +1111,7 @@ def _infer_daily_rule(self):
def _maybe_add_count(base, count):
- if count > 1:
+ if count != 1:
return '%d%s' % (count, base)
else:
return base
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index fb6929c77f6b0..e15be45ef305a 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -2615,15 +2615,24 @@ def generate_range(start=None, end=None, periods=None,
start = end - (periods - 1) * offset
cur = start
-
- while cur <= end:
- yield cur
-
- # faster than cur + offset
- next_date = offset.apply(cur)
- if next_date <= cur:
- raise ValueError('Offset %s did not increment date' % offset)
- cur = next_date
+ if offset.n >= 0:
+ while cur <= end:
+ yield cur
+
+ # faster than cur + offset
+ next_date = offset.apply(cur)
+ if next_date <= cur:
+ raise ValueError('Offset %s did not increment date' % offset)
+ cur = next_date
+ else:
+ while cur >= end:
+ yield cur
+
+ # faster than cur + offset
+ next_date = offset.apply(cur)
+ if next_date >= cur:
+ raise ValueError('Offset %s did not decrement date' % offset)
+ cur = next_date
prefix_mapping = dict((offset._prefix, offset) for offset in [
YearBegin, # 'AS'
diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py
index 4a72b094917b5..24edc54582ec1 100644
--- a/pandas/tseries/tests/test_base.py
+++ b/pandas/tseries/tests/test_base.py
@@ -494,6 +494,15 @@ def test_take(self):
self.assert_index_equal(result, expected)
self.assertIsNone(result.freq)
+ def test_infer_freq(self):
+ # GH 11018
+ for freq in ['A', '2A', '-2A', 'Q', '-1Q', 'M', '-1M', 'D', '3D', '-3D',
+ 'W', '-1W', 'H', '2H', '-2H', 'T', '2T', 'S', '-3S']:
+ idx = pd.date_range('2011-01-01 09:00:00', freq=freq, periods=10)
+ result = pd.DatetimeIndex(idx.asi8, freq='infer')
+ tm.assert_index_equal(idx, result)
+ self.assertEqual(result.freq, freq)
+
class TestTimedeltaIndexOps(Ops):
@@ -1108,6 +1117,14 @@ def test_take(self):
self.assert_index_equal(result, expected)
self.assertIsNone(result.freq)
+ def test_infer_freq(self):
+ # GH 11018
+ for freq in ['D', '3D', '-3D', 'H', '2H', '-2H', 'T', '2T', 'S', '-3S']:
+ idx = pd.timedelta_range('1', freq=freq, periods=10)
+ result = pd.TimedeltaIndex(idx.asi8, freq='infer')
+ tm.assert_index_equal(idx, result)
+ self.assertEqual(result.freq, freq)
+
class TestPeriodIndexOps(Ops):
diff --git a/pandas/tseries/tests/test_frequencies.py b/pandas/tseries/tests/test_frequencies.py
index a642c12786940..d9bc64136e390 100644
--- a/pandas/tseries/tests/test_frequencies.py
+++ b/pandas/tseries/tests/test_frequencies.py
@@ -539,7 +539,7 @@ def test_infer_freq_businesshour(self):
def test_not_monotonic(self):
rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
rng = rng[::-1]
- self.assertIsNone(rng.inferred_freq)
+ self.assertEqual(rng.inferred_freq, '-1A-JAN')
def test_non_datetimeindex(self):
rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py
index d3d09356648b0..69dc70698ca28 100644
--- a/pandas/tseries/tests/test_timedeltas.py
+++ b/pandas/tseries/tests/test_timedeltas.py
@@ -1539,8 +1539,7 @@ def test_tdi_ops_attributes(self):
result = - rng
exp = timedelta_range('-2 days', periods=5, freq='-2D', name='x')
tm.assert_index_equal(result, exp)
- # tdi doesn't infer negative freq
- self.assertEqual(result.freq, None)
+ self.assertEqual(result.freq, '-2D')
rng = pd.timedelta_range('-2 days', periods=5, freq='D', name='x')
@@ -1548,7 +1547,6 @@ def test_tdi_ops_attributes(self):
exp = TimedeltaIndex(['2 days', '1 days', '0 days', '1 days',
'2 days'], name='x')
tm.assert_index_equal(result, exp)
- # tdi doesn't infer negative freq
self.assertEqual(result.freq, None)
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index a021195ea6c04..565ce43dc46a1 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -1260,6 +1260,18 @@ def test_date_range_gen_error(self):
rng = date_range('1/1/2000 00:00', '1/1/2000 00:18', freq='5min')
self.assertEqual(len(rng), 4)
+ def test_date_range_negative_freq(self):
+ # GH 11018
+ rng = date_range('2011-12-31', freq='-2A', periods=3)
+ exp = pd.DatetimeIndex(['2011-12-31', '2009-12-31', '2007-12-31'], freq='-2A')
+ self.assert_index_equal(rng, exp)
+ self.assertEqual(rng.freq, '-2A')
+
+ rng = date_range('2011-01-31', freq='-2M', periods=3)
+ exp = pd.DatetimeIndex(['2011-01-31', '2010-11-30', '2010-09-30'], freq='-2M')
+ self.assert_index_equal(rng, exp)
+ self.assertEqual(rng.freq, '-2M')
+
def test_first_subset(self):
ts = _simple_ts('1/1/2000', '1/1/2010', freq='12h')
result = ts.first('10d')
| Fixed 2 issues:
- `date_range` can't handle negative calendar-based freq (like `A`, `Q` and `M`).
```
import pandas as pd
# OK
pd.date_range('2011-01-01', freq='-1D', periods=3)
# DatetimeIndex(['2011-01-01', '2010-12-31', '2010-12-30'], dtype='datetime64[ns]', freq='-1D')
# NG
pd.date_range('2011-01-01', freq='-1M', periods=3)
# DatetimeIndex([], dtype='datetime64[ns]', freq='-1M')
```
- Unable to infer negative freq.
```
pd.DatetimeIndex(['2011-01-05', '2011-01-03', '2011-01-01'], freq='infer')
# DatetimeIndex(['2011-01-05', '2011-01-03', '2011-01-01'], dtype='datetime64[ns]', freq=None)
pd.TimedeltaIndex(['-1 days', '-3 days', '-5 days'], freq='infer')
# TimedeltaIndex(['-1 days', '-3 days', '-5 days'], dtype='timedelta64[ns]', freq=None)
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11018 | 2015-09-07T15:44:46Z | 2015-09-07T20:19:58Z | 2015-09-07T20:19:58Z | 2015-09-07T20:23:10Z |
BUG: Index dtype may not be applied properly | diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt
index 2c192ee33061b..a8ff45cc25a6b 100644
--- a/doc/source/whatsnew/v0.17.0.txt
+++ b/doc/source/whatsnew/v0.17.0.txt
@@ -1100,3 +1100,4 @@ Bug Fixes
- Bug in ``date_range`` results in empty if freq is negative annualy, quarterly and monthly (:issue:`11018`)
- Bug in ``DatetimeIndex`` cannot infer negative freq (:issue:`11018`)
- Remove use of some deprecated numpy comparison operations, mainly in tests. (:issue:`10569`)
+- Bug in ``Index`` dtype may not applied properly (:issue:`11017`)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index c60509f00ebac..d64a20fc9563c 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -117,7 +117,9 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
if fastpath:
return cls._simple_new(data, name)
- from pandas.tseries.period import PeriodIndex
+ if is_categorical_dtype(data) or is_categorical_dtype(dtype):
+ return CategoricalIndex(data, copy=copy, name=name, **kwargs)
+
if isinstance(data, (np.ndarray, Index, ABCSeries)):
if issubclass(data.dtype.type, np.datetime64) or is_datetimetz(data):
from pandas.tseries.index import DatetimeIndex
@@ -137,10 +139,11 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
if dtype is not None:
try:
data = np.array(data, dtype=dtype, copy=copy)
- except TypeError:
+ except (TypeError, ValueError):
pass
# maybe coerce to a sub-class
+ from pandas.tseries.period import PeriodIndex
if isinstance(data, PeriodIndex):
return PeriodIndex(data, copy=copy, name=name, **kwargs)
if issubclass(data.dtype.type, np.integer):
@@ -149,8 +152,6 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
return Float64Index(data, copy=copy, dtype=dtype, name=name)
elif issubclass(data.dtype.type, np.bool) or is_bool_dtype(data):
subarr = data.astype('object')
- elif is_categorical_dtype(data) or is_categorical_dtype(dtype):
- return CategoricalIndex(data, copy=copy, name=name, **kwargs)
else:
subarr = com._asarray_tuplesafe(data, dtype=object)
@@ -159,8 +160,28 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
if copy:
subarr = subarr.copy()
- elif is_categorical_dtype(data) or is_categorical_dtype(dtype):
- return CategoricalIndex(data, copy=copy, name=name, **kwargs)
+ if dtype is None:
+ inferred = lib.infer_dtype(subarr)
+ if inferred == 'integer':
+ return Int64Index(subarr.astype('i8'), copy=copy, name=name)
+ elif inferred in ['floating', 'mixed-integer-float']:
+ return Float64Index(subarr, copy=copy, name=name)
+ elif inferred == 'boolean':
+ # don't support boolean explicity ATM
+ pass
+ elif inferred != 'string':
+ if (inferred.startswith('datetime') or
+ tslib.is_timestamp_array(subarr)):
+ from pandas.tseries.index import DatetimeIndex
+ return DatetimeIndex(subarr, copy=copy, name=name, **kwargs)
+ elif (inferred.startswith('timedelta') or
+ lib.is_timedelta_array(subarr)):
+ from pandas.tseries.tdi import TimedeltaIndex
+ return TimedeltaIndex(subarr, copy=copy, name=name, **kwargs)
+ elif inferred == 'period':
+ return PeriodIndex(subarr, name=name, **kwargs)
+ return cls._simple_new(subarr, name)
+
elif hasattr(data, '__array__'):
return Index(np.asarray(data), dtype=dtype, copy=copy, name=name,
**kwargs)
@@ -172,9 +193,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
# we must be all tuples, otherwise don't construct
# 10697
if all( isinstance(e, tuple) for e in data ):
-
try:
-
# must be orderable in py3
if compat.PY3:
sorted(data)
@@ -183,32 +202,9 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, fastpath=False,
except (TypeError, KeyError):
# python2 - MultiIndex fails on mixed types
pass
-
# other iterable of some kind
subarr = com._asarray_tuplesafe(data, dtype=object)
-
- if dtype is None:
- inferred = lib.infer_dtype(subarr)
- if inferred == 'integer':
- return Int64Index(subarr.astype('i8'), copy=copy, name=name)
- elif inferred in ['floating', 'mixed-integer-float']:
- return Float64Index(subarr, copy=copy, name=name)
- elif inferred == 'boolean':
- # don't support boolean explicity ATM
- pass
- elif inferred != 'string':
- if (inferred.startswith('datetime') or
- tslib.is_timestamp_array(subarr)):
- from pandas.tseries.index import DatetimeIndex
- return DatetimeIndex(subarr, copy=copy, name=name, **kwargs)
- elif (inferred.startswith('timedelta') or
- lib.is_timedelta_array(subarr)):
- from pandas.tseries.tdi import TimedeltaIndex
- return TimedeltaIndex(subarr, copy=copy, name=name, **kwargs)
- elif inferred == 'period':
- return PeriodIndex(subarr, name=name, **kwargs)
-
- return cls._simple_new(subarr, name)
+ return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs)
@classmethod
def _simple_new(cls, values, name=None, dtype=None, **kwargs):
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 0ab80ad91829a..75daabe2dab67 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -651,6 +651,11 @@ def test_constructor_from_series(self):
df = pd.DataFrame(np.random.rand(5,3))
df['date'] = ['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990']
result = DatetimeIndex(df['date'], freq='MS')
+ self.assertTrue(result.equals(expected))
+ self.assertEqual(df['date'].dtype, object)
+
+ exp = pd.Series(['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'], name='date')
+ self.assert_series_equal(df['date'], exp)
# GH 6274
# infer freq of same
@@ -693,6 +698,55 @@ def test_constructor_simple_new(self):
result = idx._simple_new(idx, 'obj')
self.assertTrue(result.equals(idx))
+ def test_constructor_dtypes(self):
+
+ for idx in [Index(np.array([1, 2, 3], dtype=int)),
+ Index(np.array([1, 2, 3], dtype=int), dtype=int),
+ Index(np.array([1., 2., 3.], dtype=float), dtype=int),
+ Index([1, 2, 3], dtype=int),
+ Index([1., 2., 3.], dtype=int)]:
+ self.assertIsInstance(idx, Int64Index)
+
+ for idx in [Index(np.array([1., 2., 3.], dtype=float)),
+ Index(np.array([1, 2, 3], dtype=int), dtype=float),
+ Index(np.array([1., 2., 3.], dtype=float), dtype=float),
+ Index([1, 2, 3], dtype=float),
+ Index([1., 2., 3.], dtype=float)]:
+ self.assertIsInstance(idx, Float64Index)
+
+ for idx in [Index(np.array([True, False, True], dtype=bool)),
+ Index([True, False, True]),
+ Index(np.array([True, False, True], dtype=bool), dtype=bool),
+ Index([True, False, True], dtype=bool)]:
+ self.assertIsInstance(idx, Index)
+ self.assertEqual(idx.dtype, object)
+
+ for idx in [Index(np.array([1, 2, 3], dtype=int), dtype='category'),
+ Index([1, 2, 3], dtype='category'),
+ Index(np.array([np.datetime64('2011-01-01'), np.datetime64('2011-01-02')]), dtype='category'),
+ Index([datetime(2011, 1, 1), datetime(2011, 1, 2)], dtype='category')]:
+ self.assertIsInstance(idx, CategoricalIndex)
+
+ for idx in [Index(np.array([np.datetime64('2011-01-01'), np.datetime64('2011-01-02')])),
+ Index([datetime(2011, 1, 1), datetime(2011, 1, 2)])]:
+ self.assertIsInstance(idx, DatetimeIndex)
+
+ for idx in [Index(np.array([np.datetime64('2011-01-01'), np.datetime64('2011-01-02')]), dtype=object),
+ Index([datetime(2011, 1, 1), datetime(2011, 1, 2)], dtype=object)]:
+ self.assertNotIsInstance(idx, DatetimeIndex)
+ self.assertIsInstance(idx, Index)
+ self.assertEqual(idx.dtype, object)
+
+ for idx in [Index(np.array([np.timedelta64(1, 'D'), np.timedelta64(1, 'D')])),
+ Index([timedelta(1), timedelta(1)])]:
+ self.assertIsInstance(idx, TimedeltaIndex)
+
+ for idx in [Index(np.array([np.timedelta64(1, 'D'), np.timedelta64(1, 'D')]), dtype=object),
+ Index([timedelta(1), timedelta(1)], dtype=object)]:
+ self.assertNotIsInstance(idx, TimedeltaIndex)
+ self.assertIsInstance(idx, Index)
+ self.assertEqual(idx.dtype, object)
+
def test_view_with_args(self):
restricted = ['unicodeIndex','strIndex','catIndex','boolIndex','empty']
| Fixed 2 problems:
- Specified `dtype` is not applied to other iterables.
```
import numpy as np
import pandas as pd
pd.Index([1, 2, 3], dtype=int)
# Index([1, 2, 3], dtype='object')
```
- Specifying `category` to ndarray-like results in `TypeError`
```
pd.Index(np.array([1, 2, 3]), dtype='category')
# TypeError: data type "category" not understood
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/11017 | 2015-09-07T14:46:47Z | 2015-09-11T14:24:25Z | null | 2015-09-11T14:36:06Z |
BUG: .ix with PeriodIndex is fixed | diff --git a/pandas/core/index.py b/pandas/core/index.py
index c64e181f4c721..9344e849981c9 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2,18 +2,18 @@
import datetime
import warnings
import operator
-
from functools import partial
-from pandas.compat import range, zip, lrange, lzip, u, reduce, filter, map
-from pandas import compat
-import numpy as np
-
from sys import getsizeof
+
+import numpy as np
import pandas.tslib as tslib
import pandas.lib as lib
import pandas.algos as _algos
import pandas.index as _index
from pandas.lib import Timestamp, Timedelta, is_datetime_array
+
+from pandas.compat import range, zip, lrange, lzip, u, map
+from pandas import compat
from pandas.core.base import PandasObject, FrozenList, FrozenNDArray, IndexOpsMixin, _shared_docs, PandasDelegate
from pandas.util.decorators import (Appender, Substitution, cache_readonly,
deprecate, deprecate_kwarg)
@@ -26,6 +26,9 @@
from pandas.core.config import get_option
from pandas.io.common import PerformanceWarning
+
+
+
# simplify
default_pprint = lambda x, max_seq_items=None: com.pprint_thing(x,
escape_chars=('\t', '\r', '\n'),
@@ -973,7 +976,9 @@ def _convert_list_indexer(self, keyarr, kind=None):
and we have a mixed index (e.g. number/labels). figure out
the indexer. return None if we can't help
"""
- if (kind is None or kind in ['iloc','ix']) and (is_integer_dtype(keyarr) and not self.is_floating()):
+ if (kind is None or kind in ['iloc', 'ix']) and (
+ is_integer_dtype(keyarr) and not self.is_floating() and not com.is_period_arraylike(keyarr)):
+
if self.inferred_type != 'integer':
keyarr = np.where(keyarr < 0,
len(self) + keyarr, keyarr)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 36bc0755f9a6a..d9c08a3c54947 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -3221,6 +3221,14 @@ def test_repeat(self):
self.assert_index_equal(res, exp)
self.assertEqual(res.freqstr, 'D')
+ def test_period_index_indexer(self):
+
+ #GH4125
+ idx = pd.period_range('2002-01','2003-12', freq='M')
+ df = pd.DataFrame(pd.np.random.randn(24,10), index=idx)
+ self.assert_frame_equal(df, df.ix[idx])
+ self.assert_frame_equal(df, df.ix[list(idx)])
+
class TestTimedeltaIndex(DatetimeLike, tm.TestCase):
_holder = TimedeltaIndex
| Solves https://github.com/pydata/pandas/issues/4125
It doesn't feel like an elegant solution, but I think it works.
I think when Period gets its own dtype, these will all go away?
| https://api.github.com/repos/pandas-dev/pandas/pulls/11015 | 2015-09-07T04:21:55Z | 2015-09-09T21:40:50Z | null | 2015-12-08T03:52:34Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.