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 |
|---|---|---|---|---|---|---|---|
DOC: suppress warnings with okwarning in whatsnew | diff --git a/doc/source/v0.10.1.txt b/doc/source/v0.10.1.txt
index 0d92e359c2a4a..13cc61c517bc8 100644
--- a/doc/source/v0.10.1.txt
+++ b/doc/source/v0.10.1.txt
@@ -66,6 +66,7 @@ perform queries on a table, by passing a list to ``data_columns``
Retrieving unique values in an indexable or data column.
.. ipython:: python
+ :okwarning:
import warnings
with warnings.catch_warnings():
diff --git a/doc/source/v0.12.0.txt b/doc/source/v0.12.0.txt
index 43b5479159b38..8d9c266a864b3 100644
--- a/doc/source/v0.12.0.txt
+++ b/doc/source/v0.12.0.txt
@@ -186,6 +186,7 @@ I/O Enhancements
You can use ``pd.read_html()`` to read the output from ``DataFrame.to_html()`` like so
.. ipython :: python
+ :okwarning:
df = DataFrame({'a': range(3), 'b': list('abc')})
print(df)
@@ -252,6 +253,7 @@ I/O Enhancements
store when iteration is finished. This is only for *tables*
.. ipython:: python
+ :okwarning:
path = 'store_iterator.h5'
DataFrame(randn(10,2)).to_hdf(path,'df',table=True)
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 8d34c45bbe3e5..c29d8efd8ed0c 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -149,6 +149,7 @@ API changes
The following warning / exception will show if this is attempted.
.. ipython:: python
+ :okwarning:
dfc.loc[0]['A'] = 1111
| Using the new functionality of @y-p from #6082, suppressing some warnings in the older whatsnew sections.
Some of them are deprecation warnings, so from older functinality. We could also change the code example, but since it's from whatsnew I think it's more logical to leave it as it is (when they start to generate errors, then of course we have to do something else)
| https://api.github.com/repos/pandas-dev/pandas/pulls/6086 | 2014-01-25T13:08:01Z | 2014-01-25T14:43:25Z | 2014-01-25T14:43:25Z | 2014-06-24T21:27:07Z |
Added 'Experimental' to Docstrings For GBQ | diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 7b0c3137e79ac..1af9f4a8d8383 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -351,6 +351,8 @@ def to_gbq(dataframe, destination_table, schema=None, col_order=None,
if_exists='fail', **kwargs):
"""Write a DataFrame to a Google BigQuery table.
+ THIS IS AN EXPERIMENTAL LIBRARY
+
If the table exists, the DataFrame will be appended. If not, a new table
will be created, in which case the schema will have to be specified. By
default, rows will be written in the order they appear in the DataFrame,
@@ -472,6 +474,8 @@ def read_gbq(query, project_id=None, destination_table=None, index_col=None,
col_order=None, **kwargs):
"""Load data from Google BigQuery.
+ THIS IS AN EXPERIMENTAL LIBRARY
+
The main method a user calls to load data from Google BigQuery into a
pandas DataFrame. This is a simple wrapper for Google's bq.py and
bigquery_client.py, which we use to get the source data. Because of this,
| Added "THIS IS AN EXPERIMENTAL LIBRARY" to docstrings for read_gbq() and to_gbq() methods per:
closes https://github.com/pydata/pandas/issues/5956
| https://api.github.com/repos/pandas-dev/pandas/pulls/6084 | 2014-01-25T04:57:41Z | 2014-01-25T08:30:47Z | 2014-01-25T08:30:47Z | 2014-07-12T12:36:41Z |
BUG: not converting scalars properly to M8/m8 on assignment (GH6079) | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index f76f952c53d1d..729d4e4059595 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -154,7 +154,7 @@ def factorize(values, sort=False, order=None, na_sentinel=-1):
uniques = uniques.take(sorter)
if is_datetime:
- uniques = uniques.view('M8[ns]')
+ uniques = uniques.astype('M8[ns]')
if isinstance(values, PeriodIndex):
uniques = PeriodIndex(ordinal=uniques, freq=values.freq)
@@ -279,6 +279,7 @@ def rank(values, axis=0, method='average', na_option='keep',
f, values = _get_data_algo(values, _rank2d_functions)
ranks = f(values, axis=axis, ties_method=method,
ascending=ascending, na_option=na_option)
+
return ranks
@@ -364,12 +365,22 @@ def _interpolate(a, b, fraction):
def _get_data_algo(values, func_map):
+ mask = None
if com.is_float_dtype(values):
f = func_map['float64']
values = com._ensure_float64(values)
elif com.is_datetime64_dtype(values):
- f = func_map['int64']
- values = values.view('i8')
+
+ # if we have NaT, punt to object dtype
+ mask = com.isnull(values)
+ if mask.ravel().any():
+ f = func_map['generic']
+ values = com._ensure_object(values)
+ values[mask] = np.nan
+ else:
+ f = func_map['int64']
+ values = values.view('i8')
+
elif com.is_integer_dtype(values):
f = func_map['int64']
values = com._ensure_int64(values)
diff --git a/pandas/core/array.py b/pandas/core/array.py
index f267771bb770f..495f231921a19 100644
--- a/pandas/core/array.py
+++ b/pandas/core/array.py
@@ -35,18 +35,3 @@
NA = np.nan
-# a series-like ndarray ####
-
-
-class SNDArray(Array):
-
- def __new__(cls, data, index=None, name=None):
- data = data.view(SNDArray)
- data.index = index
- data.name = name
-
- return data
-
- @property
- def values(self):
- return self.view(Array)
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 3cedc37533e0c..30ce5166b71e7 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -8,6 +8,7 @@
import codecs
import csv
import types
+from datetime import datetime, timedelta
from numpy.lib.format import read_array, write_array
import numpy as np
@@ -39,7 +40,7 @@ class AmbiguousIndexError(PandasError, KeyError):
pass
-_POSSIBLY_CAST_DTYPES = set([np.dtype(t)
+_POSSIBLY_CAST_DTYPES = set([np.dtype(t).name
for t in ['M8[ns]', '>M8[ns]', '<M8[ns]',
'm8[ns]', '>m8[ns]', '<m8[ns]',
'O', 'int8',
@@ -867,11 +868,14 @@ def _infer_dtype_from_scalar(val):
dtype = np.object_
- elif isinstance(val, np.datetime64):
- # ugly hacklet
+ elif isinstance(val, (np.datetime64, datetime)) and getattr(val,'tz',None) is None:
val = lib.Timestamp(val).value
dtype = np.dtype('M8[ns]')
+ elif isinstance(val, (np.timedelta64, timedelta)):
+ val = tslib.convert_to_timedelta(val,'ns')
+ dtype = np.dtype('m8[ns]')
+
elif is_bool(val):
dtype = np.bool_
@@ -1608,7 +1612,7 @@ def _possibly_convert_objects(values, convert_dates=True,
def _possibly_castable(arr):
- return arr.dtype not in _POSSIBLY_CAST_DTYPES
+ return arr.dtype.name not in _POSSIBLY_CAST_DTYPES
def _possibly_convert_platform(values):
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5a0d975a473e1..b00ffd9edfb1a 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4696,9 +4696,14 @@ def _convert_object_array(content, columns, coerce_float=False, dtype=None):
raise AssertionError('%d columns passed, passed data had %s '
'columns' % (len(columns), len(content)))
- arrays = [lib.maybe_convert_objects(arr, try_float=coerce_float)
- if dtype != object and dtype != np.object else arr
- for arr in content]
+ # provide soft conversion of object dtypes
+ def convert(arr):
+ if dtype != object and dtype != np.object:
+ arr = lib.maybe_convert_objects(arr, try_float=coerce_float)
+ arr = com._possibly_cast_to_datetime(arr, dtype)
+ return arr
+
+ arrays = [ convert(arr) for arr in content ]
return arrays, columns
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index eb3f518b0dd4b..aa553e93e72b8 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -71,6 +71,7 @@ def test_read_dta1(self):
def test_read_dta2(self):
if LooseVersion(sys.version) < '2.7':
raise nose.SkipTest('datetime interp under 2.6 is faulty')
+ skip_if_not_little_endian()
expected = DataFrame.from_records(
[
diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx
index e23afad278ee7..c048b2786bd91 100644
--- a/pandas/src/inference.pyx
+++ b/pandas/src/inference.pyx
@@ -56,7 +56,14 @@ def infer_dtype(object _values):
if n == 0:
return 'empty'
- val = util.get_value_1d(values, 0)
+ # make contiguous
+ values = values.ravel()
+
+ # try to use a valid value
+ for i in range(n):
+ val = util.get_value_1d(values, i)
+ if not is_null_datetimelike(val):
+ break
if util.is_datetime64_object(val) or val is NaT:
if is_datetime64_array(values):
diff --git a/pandas/src/reduce.pyx b/pandas/src/reduce.pyx
index bfbe0f3ea7938..50fff7f9eb460 100644
--- a/pandas/src/reduce.pyx
+++ b/pandas/src/reduce.pyx
@@ -2,7 +2,6 @@
from numpy cimport *
import numpy as np
-from pandas.core.array import SNDArray
from distutils.version import LooseVersion
is_numpy_prior_1_6_2 = LooseVersion(np.__version__) < '1.6.2'
@@ -114,8 +113,8 @@ cdef class Reducer:
# use the cached_typ if possible
if cached_typ is not None:
- cached_typ._data._block.values = chunk
- cached_typ.name = name
+ object.__setattr__(cached_typ._data._block, 'values', chunk)
+ object.__setattr__(cached_typ, 'name', name)
res = self.f(cached_typ)
else:
res = self.f(chunk)
@@ -164,7 +163,7 @@ cdef class SeriesBinGrouper:
bint passed_dummy
cdef public:
- object arr, index, dummy_arr, dummy_index, values, f, bins, typ, ityp, name
+ object arr, index, dummy_arr, dummy_index, values, f, bins, typ, name
def __init__(self, object series, object f, object bins, object dummy):
n = len(series)
@@ -178,7 +177,6 @@ cdef class SeriesBinGrouper:
self.arr = values
self.index = series.index
self.typ = type(series)
- self.ityp = type(series.index)
self.name = getattr(series,'name',None)
self.dummy_arr, self.dummy_index = self._check_dummy(dummy)
@@ -210,9 +208,10 @@ cdef class SeriesBinGrouper:
ndarray[int64_t] counts
Py_ssize_t i, n, group_size
object res
- bint initialized = 0, needs_typ = 1, try_typ = 0
+ bint initialized = 0
Slider vslider, islider
- object gin, typ, ityp, name
+ object gin, typ, name
+ object cached_typ = None
counts = np.zeros(self.ngroups, dtype=np.int64)
@@ -226,8 +225,6 @@ cdef class SeriesBinGrouper:
group_size = 0
n = len(self.arr)
- typ = self.typ
- ityp = self.ityp
name = self.name
vslider = Slider(self.arr, self.dummy_arr)
@@ -235,11 +232,6 @@ cdef class SeriesBinGrouper:
gin = self.dummy_index._engine
- # old numpy issue, need to always create and pass the Series
- if is_numpy_prior_1_6_2:
- try_typ = 1
- needs_typ = 1
-
try:
for i in range(self.ngroups):
group_size = counts[i]
@@ -247,24 +239,15 @@ cdef class SeriesBinGrouper:
islider.set_length(group_size)
vslider.set_length(group_size)
- # see if we need to create the object proper
- if try_typ:
- if needs_typ:
- res = self.f(typ(vslider.buf, index=islider.buf,
- name=name, fastpath=True))
- else:
- res = self.f(SNDArray(vslider.buf,islider.buf,name=name))
+ if cached_typ is None:
+ cached_typ = self.typ(vslider.buf, index=islider.buf,
+ name=name)
else:
- try:
- res = self.f(SNDArray(vslider.buf,islider.buf,name=name))
- needs_typ = 0
- except:
- res = self.f(typ(vslider.buf, index=islider.buf,
- name=name, fastpath=True))
- needs_typ = 1
-
- try_typ = 1
+ object.__setattr__(cached_typ._data._block, 'values', vslider.buf)
+ object.__setattr__(cached_typ, '_index', islider.buf)
+ object.__setattr__(cached_typ, 'name', name)
+ res = self.f(cached_typ)
res = _extract_result(res)
if not initialized:
result = self._get_result_array(res)
@@ -309,7 +292,7 @@ cdef class SeriesGrouper:
bint passed_dummy
cdef public:
- object arr, index, dummy_arr, dummy_index, f, labels, values, typ, ityp, name
+ object arr, index, dummy_arr, dummy_index, f, labels, values, typ, name
def __init__(self, object series, object f, object labels,
Py_ssize_t ngroups, object dummy):
@@ -324,7 +307,6 @@ cdef class SeriesGrouper:
self.arr = values
self.index = series.index
self.typ = type(series)
- self.ityp = type(series.index)
self.name = getattr(series,'name',None)
self.dummy_arr, self.dummy_index = self._check_dummy(dummy)
@@ -351,16 +333,15 @@ cdef class SeriesGrouper:
ndarray[int64_t] labels, counts
Py_ssize_t i, n, group_size, lab
object res
- bint initialized = 0, needs_typ = 1, try_typ = 0
+ bint initialized = 0
Slider vslider, islider
- object gin, typ, ityp, name
+ object gin, typ, name
+ object cached_typ = None
labels = self.labels
counts = np.zeros(self.ngroups, dtype=np.int64)
group_size = 0
n = len(self.arr)
- typ = self.typ
- ityp = self.ityp
name = self.name
vslider = Slider(self.arr, self.dummy_arr)
@@ -368,11 +349,6 @@ cdef class SeriesGrouper:
gin = self.dummy_index._engine
- # old numpy issue, need to always create and pass the Series
- if is_numpy_prior_1_6_2:
- try_typ = 1
- needs_typ = 1
-
try:
for i in range(n):
group_size += 1
@@ -389,27 +365,15 @@ cdef class SeriesGrouper:
islider.set_length(group_size)
vslider.set_length(group_size)
- # see if we need to create the object proper
- # try on the first go around
- if try_typ:
- if needs_typ:
- res = self.f(typ(vslider.buf, index=islider.buf,
- name=name, fastpath=True))
- else:
- res = self.f(SNDArray(vslider.buf,islider.buf,name=name))
+ if cached_typ is None:
+ cached_typ = self.typ(vslider.buf, index=islider.buf,
+ name=name)
else:
+ object.__setattr__(cached_typ._data._block, 'values', vslider.buf)
+ object.__setattr__(cached_typ, '_index', islider.buf)
+ object.__setattr__(cached_typ, 'name', name)
- # try with a numpy array directly
- try:
- res = self.f(SNDArray(vslider.buf,islider.buf,name=name))
- needs_typ = 0
- except (Exception), detail:
- res = self.f(typ(vslider.buf, index=islider.buf,
- name=name, fastpath=True))
- needs_typ = 1
-
- try_typ = 1
-
+ res = self.f(cached_typ)
res = _extract_result(res)
if not initialized:
result = self._get_result_array(res)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index d966dcf5d3721..ad8b29d9448bf 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -10489,13 +10489,17 @@ def test_rank2(self):
[datetime(2000, 1, 2), datetime(2000, 1, 3),
datetime(2000, 1, 1)]]
df = DataFrame(data)
+
+ # check the rank
expected = DataFrame([[2., nan, 1.],
[2., 3., 1.]])
result = df.rank(1, numeric_only=False)
assert_frame_equal(result, expected)
# mixed-type frames
- self.mixed_frame['foo'] = datetime.now()
+ self.mixed_frame['datetime'] = datetime.now()
+ self.mixed_frame['timedelta'] = timedelta(days=1,seconds=1)
+
result = self.mixed_frame.rank(1)
expected = self.mixed_frame.rank(1, numeric_only=True)
assert_frame_equal(result, expected)
@@ -11087,6 +11091,31 @@ def test_constructor_with_convert(self):
None], np.object_))
assert_series_equal(result, expected)
+ def test_construction_with_mixed(self):
+ # test construction edge cases with mixed types
+
+ # f7u12, this does not work without extensive workaround
+ data = [[datetime(2001, 1, 5), nan, datetime(2001, 1, 2)],
+ [datetime(2000, 1, 2), datetime(2000, 1, 3),
+ datetime(2000, 1, 1)]]
+ df = DataFrame(data)
+
+ # check dtypes
+ result = df.get_dtype_counts().order()
+ expected = Series({ 'datetime64[ns]' : 3 })
+
+ # mixed-type frames
+ self.mixed_frame['datetime'] = datetime.now()
+ self.mixed_frame['timedelta'] = timedelta(days=1,seconds=1)
+ self.assert_(self.mixed_frame['datetime'].dtype == 'M8[ns]')
+ self.assert_(self.mixed_frame['timedelta'].dtype == 'm8[ns]')
+ result = self.mixed_frame.get_dtype_counts().order()
+ expected = Series({ 'float64' : 4,
+ 'object' : 1,
+ 'datetime64[ns]' : 1,
+ 'timedelta64[ns]' : 1}).order()
+ assert_series_equal(result,expected)
+
def test_constructor_frame_copy(self):
cop = DataFrame(self.frame, copy=True)
cop['A'] = 5
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 3270d80dc9dad..de6092a65f507 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -14,6 +14,7 @@
from pandas.core.index import (Index, Float64Index, Int64Index, MultiIndex,
InvalidIndexError)
+from pandas.tseries.index import DatetimeIndex
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from pandas.util.testing import (assert_almost_equal, assertRaisesRegexp,
@@ -32,6 +33,9 @@
from pandas import _np_version_under1p7
+def _skip_if_need_numpy_1_7():
+ if _np_version_under1p7:
+ raise nose.SkipTest('numpy >= 1.7 required')
class TestIndex(tm.TestCase):
_multiprocess_can_split_ = True
@@ -236,12 +240,7 @@ def test_asof(self):
tm.assert_isinstance(self.dateIndex.asof(d), Timestamp)
def test_nanosecond_index_access(self):
- if _np_version_under1p7:
- import nose
-
- raise nose.SkipTest('numpy >= 1.7 required')
-
- from pandas import Series, Timestamp, DatetimeIndex
+ _skip_if_need_numpy_1_7()
s = Series([Timestamp('20130101')]).values.view('i8')[0]
r = DatetimeIndex([s + 50 + i for i in range(100)])
@@ -1607,11 +1606,12 @@ def test_get_level_values_na(self):
expected = ['a', np.nan, 1]
assert_array_equal(values.values, expected)
- arrays = [['a', 'b', 'b'], pd.DatetimeIndex([0, 1, pd.NaT])]
- index = pd.MultiIndex.from_arrays(arrays)
- values = index.get_level_values(1)
- expected = pd.DatetimeIndex([0, 1, pd.NaT])
- assert_array_equal(values.values, expected.values)
+ if not _np_version_under1p7:
+ arrays = [['a', 'b', 'b'], pd.DatetimeIndex([0, 1, pd.NaT])]
+ index = pd.MultiIndex.from_arrays(arrays)
+ values = index.get_level_values(1)
+ expected = pd.DatetimeIndex([0, 1, pd.NaT])
+ assert_array_equal(values.values, expected.values)
arrays = [[], []]
index = pd.MultiIndex.from_arrays(arrays)
| partial fix of #6079
| https://api.github.com/repos/pandas-dev/pandas/pulls/6083 | 2014-01-25T02:07:49Z | 2014-01-25T22:03:54Z | 2014-01-25T22:03:54Z | 2014-06-18T17:57:32Z |
BLD/DOC: report context on warnings and add :okwarning: to ipython_directive | diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py
index 137201ef942b2..6bdb601897ca4 100644
--- a/doc/sphinxext/ipython_directive.py
+++ b/doc/sphinxext/ipython_directive.py
@@ -111,6 +111,7 @@
import tempfile
import ast
from pandas.compat import zip, range, map, lmap, u, cStringIO as StringIO
+import warnings
# To keep compatibility with various python versions
try:
@@ -375,6 +376,7 @@ def process_input(self, data, input_prompt, lineno):
decorator.startswith('@doctest')) or self.is_doctest
is_suppress = decorator=='@suppress' or self.is_suppress
is_okexcept = decorator=='@okexcept' or self.is_okexcept
+ is_okwarning = decorator=='@okwarning' or self.is_okwarning
is_savefig = decorator is not None and \
decorator.startswith('@savefig')
@@ -404,28 +406,30 @@ def process_input(self, data, input_prompt, lineno):
else:
store_history = True
- for i, line in enumerate(input_lines):
- if line.endswith(';'):
- is_semicolon = True
-
- if i == 0:
- # process the first input line
- if is_verbatim:
- self.process_input_line('')
- self.IP.execution_count += 1 # increment it anyway
+ # Note: catch_warnings is not thread safe
+ with warnings.catch_warnings(record=True) as ws:
+ for i, line in enumerate(input_lines):
+ if line.endswith(';'):
+ is_semicolon = True
+
+ if i == 0:
+ # process the first input line
+ if is_verbatim:
+ self.process_input_line('')
+ self.IP.execution_count += 1 # increment it anyway
+ else:
+ # only submit the line in non-verbatim mode
+ self.process_input_line(line, store_history=store_history)
+ formatted_line = '%s %s'%(input_prompt, line)
else:
- # only submit the line in non-verbatim mode
- self.process_input_line(line, store_history=store_history)
- formatted_line = '%s %s'%(input_prompt, line)
- else:
- # process a continuation line
- if not is_verbatim:
- self.process_input_line(line, store_history=store_history)
+ # process a continuation line
+ if not is_verbatim:
+ self.process_input_line(line, store_history=store_history)
- formatted_line = '%s %s'%(continuation, line)
+ formatted_line = '%s %s'%(continuation, line)
- if not is_suppress:
- ret.append(formatted_line)
+ if not is_suppress:
+ ret.append(formatted_line)
if not is_suppress and len(rest.strip()) and is_verbatim:
# the "rest" is the standard output of the
@@ -440,21 +444,36 @@ def process_input(self, data, input_prompt, lineno):
elif is_semicolon: # get spacing right
ret.append('')
+ # context information
+ filename = self.state.document.current_source
+ lineno = self.state.document.current_line
+ try:
+ lineno -= 1
+ except:
+ pass
+
# output any exceptions raised during execution to stdout
# unless :okexcept: has been specified.
if not is_okexcept and "Traceback" in output:
- filename = self.state.document.current_source
- lineno = self.state.document.current_line
- try:
- lineno = int(lineno) -1
- except:
- pass
s = "\nException in %s at line %s:\n" % (filename, lineno)
sys.stdout.write('\n\n>>>'+'-'*73)
sys.stdout.write(s)
sys.stdout.write(output)
sys.stdout.write('<<<' + '-'*73+'\n\n')
+ # output any warning raised during execution to stdout
+ # unless :okwarning: has been specified.
+ if not is_okwarning:
+ for w in ws:
+ s = "\nWarning raised in %s at line %s:\n" % (filename, lineno)
+ sys.stdout.write('\n\n>>>'+'-'*73)
+ sys.stdout.write(s)
+ sys.stdout.write('-'*76+'\n')
+ s=warnings.formatwarning(w.message, w.category,
+ w.filename, w.lineno, w.line)
+ sys.stdout.write(s)
+ sys.stdout.write('\n<<<' + '-'*73+'\n\n')
+
self.cout.truncate(0)
return (ret, input_lines, output, is_doctest, decorator, image_file,
image_directive)
@@ -698,7 +717,8 @@ class IPythonDirective(Directive):
'suppress' : directives.flag,
'verbatim' : directives.flag,
'doctest' : directives.flag,
- 'okexcept': directives.flag
+ 'okexcept': directives.flag,
+ 'okwarning': directives.flag
}
shell = None
@@ -797,6 +817,7 @@ def run(self):
self.shell.is_doctest = 'doctest' in options
self.shell.is_verbatim = 'verbatim' in options
self.shell.is_okexcept = 'okexcept' in options
+ self.shell.is_okwarning = 'okwarning' in options
# handle pure python code
if 'python' in self.arguments:
| I plan to get this upstream soon, unless joris find bugs.
Reports context on warnings just like recently added context for raised exceptions.
adds :okwarning: option to ipython directive to suppress them.
```
reading sources... [ 6%] basics
>>>-------------------------------------------------------------------------
Warning raised in /home/user1/src/pandas/doc/source/basics.rst at line 734:
----------------------------------------------------------------------------
/home/user1/src/pandas/pandas/core/frame.py:2805: FutureWarning: TimeSeries broadcasting along DataFrame index by default is deprecated. Please use DataFrame.<op> to explicitly broadcast arithmetic operations along the index
FutureWarning)
<<<-------------------------------------------------------------------------
```
Let's get rid of the noise.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6082 | 2014-01-25T01:48:20Z | 2014-01-25T01:48:26Z | 2014-01-25T01:48:26Z | 2014-07-16T08:48:53Z |
BUG: fix broken BigqueryError reference | diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 7b0c3137e79ac..0ae63eeb88c64 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -288,7 +288,7 @@ def _parse_data(client, job, index_col=None, col_order=None):
kwds['startIndex'] = start_row
data = client.apiclient.jobs().getQueryResults(**kwds).execute()
if not data['jobComplete']:
- raise BigqueryError('Job was not completed, or was invalid')
+ raise bigquery_client.BigqueryError('Job was not completed, or was invalid')
# How many rows are there across all pages?
# Note: This is presently the only reason we don't just use
| `BigqueryError` wasn't imported directly, and so has to be referred to via the module.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6080 | 2014-01-25T01:15:50Z | 2014-01-28T11:32:07Z | 2014-01-28T11:32:07Z | 2014-06-13T04:07:33Z |
DOC/BUG: Fix documentation for `infer_datetime_format` #6073 | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 17f61cf8a3055..e11f177eca939 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -387,11 +387,6 @@ The simplest case is to just pass in ``parse_dates=True``:
# These are python datetime objects
df.index
-.. ipython:: python
- :suppress:
-
- os.remove('foo.csv')
-
It is often the case that we may want to store date and time data separately,
or store various date fields separately. the ``parse_dates`` keyword can be
used to specify a combination of columns to parse the dates and/or times from.
@@ -503,29 +498,29 @@ a single date rather than the entire array.
Inferring Datetime Format
~~~~~~~~~~~~~~~~~~~~~~~~~
-If you have `parse_dates` enabled for some or all of your columns, and your
+If you have ``parse_dates`` enabled for some or all of your columns, and your
datetime strings are all formatted the same way, you may get a large speed
-up by setting `infer_datetime_format=True`. If set, pandas will attempt
+up by setting ``infer_datetime_format=True``. If set, pandas will attempt
to guess the format of your datetime strings, and then use a faster means
of parsing the strings. 5-10x parsing speeds have been observed. Pandas
will fallback to the usual parsing if either the format cannot be guessed
or the format that was guessed cannot properly parse the entire column
-of strings. So in general, `infer_datetime_format` should not have any
+of strings. So in general, ``infer_datetime_format`` should not have any
negative consequences if enabled.
Here are some examples of datetime strings that can be guessed (All
representing December 30th, 2011 at 00:00:00)
-"20111230"
-"2011/12/30"
-"20111230 00:00:00"
-"12/30/2011 00:00:00"
-"30/Dec/2011 00:00:00"
-"30/December/2011 00:00:00"
+- "20111230"
+- "2011/12/30"
+- "20111230 00:00:00"
+- "12/30/2011 00:00:00"
+- "30/Dec/2011 00:00:00"
+- "30/December/2011 00:00:00"
-`infer_datetime_format` is sensitive to `dayfirst`. With `dayfirst=True`, it
-will guess "01/12/2011" to be December 1st. With `dayfirst=False` (default)
-it will guess "01/12/2011" to be January 12th.
+``infer_datetime_format`` is sensitive to ``dayfirst``. With
+``dayfirst=True``, it will guess "01/12/2011" to be December 1st. With
+``dayfirst=False`` (default) it will guess "01/12/2011" to be January 12th.
.. ipython:: python
@@ -533,6 +528,10 @@ it will guess "01/12/2011" to be January 12th.
df = pd.read_csv('foo.csv', index_col=0, parse_dates=True,
infer_datetime_format=True)
+.. ipython:: python
+ :suppress:
+
+ os.remove('foo.csv')
International Date Formats
~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 55599bb47cd8e..47cee452ab2fe 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -148,19 +148,19 @@ Enhancements
result
result.loc[:,:,'ItemA']
-- Added optional `infer_datetime_format` to `read_csv`, `Series.from_csv` and
- `DataFrame.read_csv` (:issue:`5490`)
+- Added optional ``infer_datetime_format`` to ``read_csv``, ``Series.from_csv``
+ and ``DataFrame.read_csv`` (:issue:`5490`)
- If `parse_dates` is enabled and this flag is set, pandas will attempt to
+ If ``parse_dates`` is enabled and this flag is set, pandas will attempt to
infer the format of the datetime strings in the columns, and if it can
be inferred, switch to a faster method of parsing them. In some cases
this can increase the parsing speed by ~5-10x.
- .. ipython:: python
+ .. code-block:: python
- # Try to infer the format for the index column
- df = pd.read_csv('foo.csv', index_col=0, parse_dates=True,
- infer_datetime_format=True)
+ # Try to infer the format for the index column
+ df = pd.read_csv('foo.csv', index_col=0, parse_dates=True,
+ infer_datetime_format=True)
Experimental
~~~~~~~~~~~~
| Fix formatting typos and ensure the "foo.csv" ipython processing works.
Fixes #6073
| https://api.github.com/repos/pandas-dev/pandas/pulls/6078 | 2014-01-25T00:43:23Z | 2014-01-25T01:00:47Z | 2014-01-25T01:00:47Z | 2014-07-03T00:34:12Z |
Pr ipython directive context | diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py
index e228542b64b4d..137201ef942b2 100644
--- a/doc/sphinxext/ipython_directive.py
+++ b/doc/sphinxext/ipython_directive.py
@@ -247,13 +247,15 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
class EmbeddedSphinxShell(object):
"""An embedded IPython instance to run inside Sphinx"""
- def __init__(self, exec_lines=None):
+ def __init__(self, exec_lines=None,state=None):
self.cout = StringIO()
if exec_lines is None:
exec_lines = []
+ self.state = state
+
# Create config object for IPython
config = Config()
config.InteractiveShell.autocall = False
@@ -438,8 +440,20 @@ def process_input(self, data, input_prompt, lineno):
elif is_semicolon: # get spacing right
ret.append('')
+ # output any exceptions raised during execution to stdout
+ # unless :okexcept: has been specified.
if not is_okexcept and "Traceback" in output:
+ filename = self.state.document.current_source
+ lineno = self.state.document.current_line
+ try:
+ lineno = int(lineno) -1
+ except:
+ pass
+ s = "\nException in %s at line %s:\n" % (filename, lineno)
+ sys.stdout.write('\n\n>>>'+'-'*73)
+ sys.stdout.write(s)
sys.stdout.write(output)
+ sys.stdout.write('<<<' + '-'*73+'\n\n')
self.cout.truncate(0)
return (ret, input_lines, output, is_doctest, decorator, image_file,
@@ -735,7 +749,7 @@ def setup(self):
# Must be called after (potentially) importing matplotlib and
# setting its backend since exec_lines might import pylab.
- self.shell = EmbeddedSphinxShell(exec_lines)
+ self.shell = EmbeddedSphinxShell(exec_lines, self.state)
# Store IPython directive to enable better error messages
self.shell.directive = self
| ```
Running Sphinx v1.1.3
loading pickled environment... not yet created
loading intersphinx inventory from http://statsmodels.sourceforge.net/devel/objects.inv...
loading intersphinx inventory from http://docs.python.org/objects.inv...
building [html]: targets for 2 source files that are out of date
updating environment: 2 added, 0 changed, 0 removed
reading sources... [ 50%] dsintro
>>>-------------------------------------------------------------------------
Exception in /home/user1/src/pandas/doc/source/dsintro.rst at line 33: # <<<< This is new
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-4-05c9758a9c21> in <module>()
----> 1 1/0
ZeroDivisionError: integer division or modulo by zero
<<<-------------------------------------------------------------------------
```
No more excruciating "guess where" on errors.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6075 | 2014-01-24T23:46:33Z | 2014-01-24T23:47:00Z | 2014-01-24T23:47:00Z | 2014-07-16T08:48:48Z |
TST: Fix test_eval.py | diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py
index e6d2484a41019..6cfb8ac45312f 100644
--- a/pandas/computation/tests/test_eval.py
+++ b/pandas/computation/tests/test_eval.py
@@ -228,8 +228,8 @@ def check_complex_cmp_op(self, lhs, cmp1, rhs, binop, cmp2):
local_dict={'lhs': lhs, 'rhs': rhs},
engine=self.engine, parser=self.parser)
elif _bool_and_frame(lhs, rhs):
- self.assertRaises(TypeError, _eval_single_bin, lhs_new, '&',
- rhs_new, self.engine)
+ self.assertRaises(TypeError, _eval_single_bin, lhs, '&',
+ rhs, self.engine)
self.assertRaises(TypeError, pd.eval, ex,
local_dict={'lhs': lhs, 'rhs': rhs},
engine=self.engine, parser=self.parser)
@@ -281,7 +281,7 @@ def check_operands(left, right, cmp_op):
ex2 = 'lhs {0} mid and mid {1} rhs'.format(cmp1, cmp2)
ex3 = '(lhs {0} mid) & (mid {1} rhs)'.format(cmp1, cmp2)
for ex in (ex1, ex2, ex3):
- with assertRaises(NotImplementedError):
+ with tm.assertRaises(NotImplementedError):
pd.eval(ex, engine=self.engine, parser=self.parser)
return
if (np.isscalar(right) and not np.isscalar(left) and cmp_op in
| Fixes typos found in #GH 6069. Does not change the tests to ensure those branches are exercised.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6074 | 2014-01-24T23:26:12Z | 2014-01-25T00:36:16Z | 2014-01-25T00:36:16Z | 2014-06-21T03:05:17Z |
DOC: Explain the use of NDFrame.equals | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index e9cc03c098d03..9521bae373060 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -215,14 +215,6 @@ These operations produce a pandas object the same type as the left-hand-side inp
that if of dtype ``bool``. These ``boolean`` objects can be used in indexing operations,
see :ref:`here<indexing.boolean>`
-As of v0.13.1, Series, DataFrames and Panels have an equals method to compare if
-two such objects are equal.
-
-.. ipython:: python
-
- df.equals(df)
- df.equals(df2)
-
.. _basics.reductions:
Boolean Reductions
@@ -281,6 +273,35 @@ To evaluate single-element pandas objects in a boolean context, use the method `
See :ref:`gotchas<gotchas.truth>` for a more detailed discussion.
+.. _basics.equals:
+
+Often you may find there is more than one way to compute the same
+result. As a simple example, consider ``df+df`` and ``df*2``. To test
+that these two computations produce the same result, given the tools
+shown above, you might imagine using ``(df+df == df*2).all()``. But in
+fact, this expression is False:
+
+.. ipython:: python
+
+ df+df == df*2
+ (df+df == df*2).all()
+
+Notice that the boolean DataFrame ``df+df == df*2`` contains some False values!
+That is because NaNs do not compare as equals:
+
+.. ipython:: python
+
+ np.nan == np.nan
+
+So, as of v0.13.1, NDFrames (such as Series, DataFrames, and Panels)
+have an ``equals`` method for testing equality, with NaNs in corresponding
+locations treated as equal.
+
+.. ipython:: python
+
+ (df+df).equals(df*2)
+
+
Combining overlapping data sets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -497,7 +518,7 @@ of a 1D array of values. It can also be used as a function on regular arrays:
s.value_counts()
value_counts(data)
-Similarly, you can get the most frequently occuring value(s) (the mode) of the values in a Series or DataFrame:
+Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame:
.. ipython:: python
@@ -783,7 +804,7 @@ DataFrame's index.
pre-aligned data**. Adding two unaligned DataFrames internally triggers a
reindexing step. For exploratory analysis you will hardly notice the
difference (because ``reindex`` has been heavily optimized), but when CPU
- cycles matter sprinking a few explicit ``reindex`` calls here and there can
+ cycles matter sprinkling a few explicit ``reindex`` calls here and there can
have an impact.
.. _basics.reindex_like:
@@ -1013,7 +1034,7 @@ containing the data in each row:
...: print('%s\n%s' % (row_index, row))
...:
-For instance, a contrived way to transpose the dataframe would be:
+For instance, a contrived way to transpose the DataFrame would be:
.. ipython:: python
@@ -1160,12 +1181,12 @@ relies on strict ``re.match``, while ``contains`` relies on ``re.search``.
This old, deprecated behavior of ``match`` is still the default. As
demonstrated above, use the new behavior by setting ``as_indexer=True``.
- In this mode, ``match`` is analagous to ``contains``, returning a boolean
+ In this mode, ``match`` is analogous to ``contains``, returning a boolean
Series. The new behavior will become the default behavior in a future
release.
Methods like ``match``, ``contains``, ``startswith``, and ``endswith`` take
- an extra ``na`` arguement so missing values can be considered True or False:
+ an extra ``na`` argument so missing values can be considered True or False:
.. ipython:: python
@@ -1189,7 +1210,7 @@ Methods like ``match``, ``contains``, ``startswith``, and ``endswith`` take
``slice_replace``,Replace slice in each string with passed value
``count``,Count occurrences of pattern
``startswith``,Equivalent to ``str.startswith(pat)`` for each element
- ``endswidth``,Equivalent to ``str.endswith(pat)`` for each element
+ ``endswith``,Equivalent to ``str.endswith(pat)`` for each element
``findall``,Compute list of all occurrences of pattern/regex for each string
``match``,"Call ``re.match`` on each element, returning matched groups as list"
``extract``,"Call ``re.match`` on each element, as ``match`` does, but return matched groups as strings for convenience."
@@ -1364,7 +1385,7 @@ from the current type (say ``int`` to ``float``)
df3.dtypes
The ``values`` attribute on a DataFrame return the *lower-common-denominator* of the dtypes, meaning
-the dtype that can accomodate **ALL** of the types in the resulting homogenous dtyped numpy array. This can
+the dtype that can accommodate **ALL** of the types in the resulting homogenous dtyped numpy array. This can
force some *upcasting*.
.. ipython:: python
@@ -1376,7 +1397,7 @@ astype
.. _basics.cast:
-You can use the ``astype`` method to explicity convert dtypes from one to another. These will by default return a copy,
+You can use the ``astype`` method to explicitly convert dtypes from one to another. These will by default return a copy,
even if the dtype was unchanged (pass ``copy=False`` to change this behavior). In addition, they will raise an
exception if the astype operation is invalid.
@@ -1411,7 +1432,7 @@ they will be set to ``np.nan``.
df3.dtypes
To force conversion to ``datetime64[ns]``, pass ``convert_dates='coerce'``.
-This will convert any datetimelike object to dates, forcing other values to ``NaT``.
+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 has non-dates intermixed and you want to represent as missing.
@@ -1598,7 +1619,7 @@ For instance:
The ``set_printoptions`` function has a number of options for controlling how
-floating point numbers are formatted (using hte ``precision`` argument) in the
+floating point numbers are formatted (using the ``precision`` argument) in the
console and . The ``max_rows`` and ``max_columns`` control how many rows and
columns of DataFrame objects are shown by default. If ``max_columns`` is set to
0 (the default, in fact), the library will attempt to fit the DataFrame's
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 55599bb47cd8e..ef9df31b9f99d 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -46,7 +46,7 @@ API changes
equal have equal axes, dtypes, and values. Added the
``array_equivalent`` function to compare if two ndarrays are
equal. NaNs in identical locations are treated as
- equal. (:issue:`5283`)
+ equal. (:issue:`5283`) See also :ref:`the docs<basics.equals>` for a motivating example.
.. ipython:: python
| https://api.github.com/repos/pandas-dev/pandas/pulls/6072 | 2014-01-24T22:52:31Z | 2014-01-24T23:50:24Z | 2014-01-24T23:50:24Z | 2014-06-13T07:12:23Z | |
ENH: Keep series name when merging GroupBy result | diff --git a/doc/source/groupby.rst b/doc/source/groupby.rst
index a88b7332d9b9e..34291c75ea155 100644
--- a/doc/source/groupby.rst
+++ b/doc/source/groupby.rst
@@ -734,3 +734,28 @@ Regroup columns of a DataFrame according to their sum, and sum the aggregated on
df = pd.DataFrame({'a':[1,0,0], 'b':[0,1,0], 'c':[1,0,0], 'd':[2,3,4]})
df
df.groupby(df.sum(), axis=1).sum()
+
+
+Group DataFrame columns, compute a set of metrics and return a named Series.
+The Series name is used as the name for the column index. This is especially
+useful in conjunction with reshaping operations such as stacking in which the
+column index name will be used as the name of the inserted column:
+
+.. ipython:: python
+
+ df = pd.DataFrame({
+ 'a': [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
+ 'b': [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
+ 'c': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
+ 'd': [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
+ })
+
+ def compute_metrics(x):
+ result = {'b_sum': x['b'].sum(), 'c_mean': x['c'].mean()}
+ return pd.Series(result, name='metrics')
+
+ result = df.groupby('a').apply(compute_metrics)
+
+ result
+
+ result.stack()
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 1819272c59243..91c5a25ed4bab 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -112,6 +112,16 @@ API Changes
- ``df.iloc[:-len(df)]`` is now empty
- ``df.iloc[len(df)::-1]`` now enumerates all elements in reverse
+- Better propagation/preservation of Series names when performing groupby
+ operations:
+ - ``SeriesGroupBy.agg`` will ensure that the name attribute of the original
+ series is propagated to the result (:issue:`6265`).
+ - If the function provided to ``GroupBy.apply`` returns a named series, the
+ name of the series will be kept as the name of the column index of the
+ DataFrame returned by ``GroupBy.apply`` (:issue:`6124`). This facilitates
+ ``DataFrame.stack`` operations where the name of the column index is used as
+ the name of the inserted column containing the pivoted data.
+
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index f0588524e16eb..cda73401d2d8d 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1783,7 +1783,8 @@ def _wrap_aggregated_output(self, output, names=None):
def _wrap_applied_output(self, keys, values, not_indexed_same=False):
if len(keys) == 0:
- return Series([])
+ # GH #6265
+ return Series([], name=self.name)
def _get_index():
if self.grouper.nkeys > 1:
@@ -1805,7 +1806,8 @@ def _get_index():
return self._concat_objects(keys, values,
not_indexed_same=not_indexed_same)
else:
- return Series(values, index=_get_index())
+ # GH #6265
+ return Series(values, index=_get_index(), name=self.name)
def _aggregate_named(self, func, *args, **kwargs):
result = {}
@@ -2262,17 +2264,29 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
try:
if self.axis == 0:
+ # GH6124 if the list of Series have a consistent name,
+ # then propagate that name to the result.
+ index = v.index.copy()
+ if index.name is None:
+ # Only propagate the series name to the result
+ # if all series have a consistent name. If the
+ # series do not have a consistent name, do
+ # nothing.
+ names = set(v.name for v in values)
+ if len(names) == 1:
+ index.name = list(names)[0]
# normally use vstack as its faster than concat
# and if we have mi-columns
if not _np_version_under1p7 or isinstance(v.index,MultiIndex):
stacked_values = np.vstack([np.asarray(x) for x in values])
- result = DataFrame(stacked_values,index=key_index,columns=v.index)
+ result = DataFrame(stacked_values,index=key_index,columns=index)
else:
# GH5788 instead of stacking; concat gets the dtypes correct
from pandas.tools.merge import concat
result = concat(values,keys=key_index,names=key_index.names,
axis=self.axis).unstack()
+ result.columns = index
else:
stacked_values = np.vstack([np.asarray(x) for x in values])
result = DataFrame(stacked_values.T,index=v.index,columns=key_index)
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 4eee1d3a212e0..53e093741b63c 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2057,6 +2057,41 @@ def test_groupby_series_with_name(self):
self.assertIn('A', result2)
self.assertIn('B', result2)
+ def test_seriesgroupby_name_attr(self):
+ # GH 6265
+ result = self.df.groupby('A')['C']
+ self.assertEquals(result.count().name, 'C')
+ self.assertEquals(result.mean().name, 'C')
+
+ testFunc = lambda x: np.sum(x)*2
+ self.assertEquals(result.agg(testFunc).name, 'C')
+
+ def test_groupby_name_propagation(self):
+ # GH 6124
+ def summarize(df, name=None):
+ return Series({
+ 'count': 1,
+ 'mean': 2,
+ 'omissions': 3,
+ }, name=name)
+
+ def summarize_random_name(df):
+ # Provide a different name for each Series. In this case, groupby
+ # should not attempt to propagate the Series name since they are
+ # inconsistent.
+ return Series({
+ 'count': 1,
+ 'mean': 2,
+ 'omissions': 3,
+ }, name=df.iloc[0]['A'])
+
+ metrics = self.df.groupby('A').apply(summarize)
+ self.assertEqual(metrics.columns.name, None)
+ metrics = self.df.groupby('A').apply(summarize, 'metrics')
+ self.assertEqual(metrics.columns.name, 'metrics')
+ metrics = self.df.groupby('A').apply(summarize_random_name)
+ self.assertEqual(metrics.columns.name, None)
+
def test_groupby_nonstring_columns(self):
df = DataFrame([np.arange(10) for x in range(10)])
grouped = df.groupby(0)
| closes #6124
closes #6265
## Use case
This will facilitate DataFrame group/apply transformations when using a function that returns a Series. Right now, if we perform the following:
```
import pandas
df = pandas.DataFrame(
{'a': [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
'b': [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
'c': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
'd': [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
})
def count_values(df):
return pandas.Series({'count': df['b'].sum(), 'mean': df['c'].mean()}, name='metrics')
result = df.groupby('a').apply(count_values)
print result.stack().reset_index()
```
We get the following output:
```
a level_1 0
0 0 count 2.0
1 0 mean 0.5
2 1 count 2.0
3 1 mean 0.5
4 2 count 2.0
5 2 mean 0.5
[6 rows x 3 columns]
```
Ideally, the series name should be preserved and propagated through these operations such that we get the following output:
```
a metrics 0
0 0 count 2.0
1 0 mean 0.5
2 1 count 2.0
3 1 mean 0.5
4 2 count 2.0
5 2 mean 0.5
[6 rows x 3 columns]
```
The only way to achieve this (currently) is:
```
result = df.groupby('a').apply(count_values)
result.columns.name = 'metrics'
print result.stack().reset_index()
```
However, the key issue here is 1) this adds an extra line of code and 2) the name of the series created in the applied function may not be known in the outside block (so we can't properly fix the result.columns.name attribute).
The other work-around is to name the index of the series:
```
def count_values(df):
series = pandas.Series({'count': df['b'].sum(), 'mean': df['c'].mean()})
series.index.name = 'metrics'
return series
```
During the group/apply operation, this pull request will check to see whether series.index has the name attribute set. If the name attribute is not set, it will set the index.name attribute to the name of the series (thus ensuring the name propagates).
| https://api.github.com/repos/pandas-dev/pandas/pulls/6068 | 2014-01-24T19:10:46Z | 2014-03-05T21:58:54Z | 2014-03-05T21:58:54Z | 2014-07-06T10:27:46Z |
BUG: suble iloc indexing bug with single block and multi-axis indexing (surfaced in GH6059) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index a69c0f8acaa46..d7c8a9f45999d 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -140,6 +140,7 @@ Bug Fixes
- Bug in setting using fancy indexing a single element with a non-scalar (e.g. a list),
(:issue:`6043`)
- Regression in ``.get(None)`` indexing from 0.12 (:issue:`5652`)
+ - Subtle ``iloc`` indexing bug, surfaced in (:issue:`6059`)
pandas 0.13.0
-------------
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index dacab4fd6e6c6..ffd72b63618bd 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -2586,11 +2586,27 @@ def get_slice(self, slobj, axis=0, raise_on_error=False):
if axis == 0:
new_items = new_axes[0]
+
+ # we want to preserver the view of a single-block
if len(self.blocks) == 1:
+
blk = self.blocks[0]
+
+ # see GH 6059
+ ref_locs = blk._ref_locs
+ if ref_locs is not None:
+
+ # need to preserve the ref_locs and just shift them
+ indexer = np.ones(len(ref_locs),dtype=bool)
+ indexer[slobj] = False
+ indexer = indexer.astype(int).cumsum()[slobj]
+ ref_locs = ref_locs[slobj]
+ ref_locs -= indexer
+
newb = make_block(blk._slice(slobj), new_items, new_items,
klass=blk.__class__, fastpath=True,
- placement=blk._ref_locs)
+ placement=ref_locs)
+
new_blocks = [newb]
else:
return self.reindex_items(
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index b4fa32ba3160c..a8d2d497f176f 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -720,6 +720,49 @@ def test_iloc_getitem_frame(self):
# trying to use a label
self.assertRaises(ValueError, df.iloc.__getitem__, tuple(['j','D']))
+
+ def test_iloc_getitem_doc_issue(self):
+
+ # multi axis slicing issue with single block
+ # surfaced in GH 6059
+
+ arr = np.random.randn(6,4)
+ index = date_range('20130101',periods=6)
+ columns = list('ABCD')
+ df = DataFrame(arr,index=index,columns=columns)
+
+ # defines ref_locs
+ df.describe()
+
+ result = df.iloc[3:5,0:2]
+ str(result)
+ result.dtypes
+
+ expected = DataFrame(arr[3:5,0:2],index=index[3:5],columns=columns[0:2])
+ assert_frame_equal(result,expected)
+
+ # for dups
+ df.columns = list('aaaa')
+ result = df.iloc[3:5,0:2]
+ str(result)
+ result.dtypes
+
+ expected = DataFrame(arr[3:5,0:2],index=index[3:5],columns=list('aa'))
+ assert_frame_equal(result,expected)
+
+ # related
+ arr = np.random.randn(6,4)
+ index = list(range(0,12,2))
+ columns = list(range(0,8,2))
+ df = DataFrame(arr,index=index,columns=columns)
+
+ df._data.blocks[0].ref_locs
+ result = df.iloc[1:5,2:4]
+ str(result)
+ result.dtypes
+ expected = DataFrame(arr[1:5,2:4],index=index[1:5],columns=columns[2:4])
+ assert_frame_equal(result,expected)
+
def test_setitem_ndarray_1d(self):
# GH5508
| surfaced in #6059
very subtle iloc bug that requires both axis slicing then trying dtypes
| https://api.github.com/repos/pandas-dev/pandas/pulls/6065 | 2014-01-24T18:58:11Z | 2014-01-24T21:49:17Z | 2014-01-24T21:49:17Z | 2014-06-13T04:25:18Z |
BLD: add IPython and sphinx to show_versions #6059 | diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py
index f1cd2c92f68d2..ca0fbb172066e 100644
--- a/pandas/util/print_versions.py
+++ b/pandas/util/print_versions.py
@@ -64,6 +64,8 @@ def show_versions(as_json=False):
("numpy", lambda mod: mod.version.version),
("scipy", lambda mod: mod.version.version),
("statsmodels", lambda mod: mod.__version__),
+ ("IPython", lambda mod: mod.__version__),
+ ("sphinx", lambda mod: mod.__version__),
("patsy", lambda mod: mod.__version__),
("scikits.timeseries", lambda mod: mod.__version__),
("dateutil", lambda mod: mod.__version__),
| https://api.github.com/repos/pandas-dev/pandas/pulls/6064 | 2014-01-24T16:36:42Z | 2014-01-24T16:36:47Z | 2014-01-24T16:36:47Z | 2014-07-01T14:52:34Z | |
TST/DOC: addtl tests and docs for (GH6056) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4ed792afc0bcf..a69c0f8acaa46 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -136,7 +136,7 @@ Bug Fixes
- Bug in Series.xs with a multi-index (:issue:`6018`)
- Bug in Series construction of mixed type with datelike and an integer (which should result in
object type and not automatic conversion) (:issue:`6028`)
- - Possible segfault when chained indexing with an object array under numpy 1.7.1 (:issue:`6016`)
+ - Possible segfault when chained indexing with an object array under numpy 1.7.1 (:issue:`6026`, :issue:`6056`)
- Bug in setting using fancy indexing a single element with a non-scalar (e.g. a list),
(:issue:`6043`)
- Regression in ``.get(None)`` indexing from 0.12 (:issue:`5652`)
diff --git a/doc/source/tutorials.rst b/doc/source/tutorials.rst
index 03d54e326e90c..6a1b288e10d38 100644
--- a/doc/source/tutorials.rst
+++ b/doc/source/tutorials.rst
@@ -1,8 +1,8 @@
.. _tutorials:
-****************
-Pandas Tutorials
-****************
+*********
+Tutorials
+*********
This is a guide to many pandas tutorials, geared mainly for new users.
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index ee9e16d5f02f6..3efe79ce281db 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -15,6 +15,28 @@ There are several new or updated docs sections including:
- :ref:`Tutorials<tutorials>`, a guide to community developed pandas tutorials.
- :ref:`Pandas Ecosystem<ecosystem>`, a guide to complementary projects built on top of pandas.
+.. warning::
+
+ 0.13.1 fixes a bug that was caused by a combination of having numpy < 1.8, and doing
+ chained assignent on a string-like array. Please review :ref:`the docs<indexing.view_versus_copy>`,
+ chained indexing can have unexpected results and should generally be avoided.
+
+ This would previously segfault:
+
+ .. ipython:: python
+
+ df = DataFrame(dict(A = np.array(['foo','bar','bah','foo','bar'])))
+ df['A'].iloc[0] = np.nan
+ df
+
+ The recommended way to do this type of assignment is:
+
+ .. ipython:: python
+
+ df = DataFrame(dict(A = np.array(['foo','bar','bah','foo','bar'])))
+ df.ix[0,'A'] = np.nan
+ df
+
API changes
~~~~~~~~~~~
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 8c4572cf63dd1..b4fa32ba3160c 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2015,6 +2015,18 @@ def test_setitem_chained_setfault(self):
df.response[mask] = 'none'
assert_frame_equal(df, DataFrame({'response': mdata, 'response1' : data }))
+ # GH 6056
+ expected = DataFrame(dict(A = [np.nan,'bar','bah','foo','bar']))
+ df = DataFrame(dict(A = np.array(['foo','bar','bah','foo','bar'])))
+ df['A'].iloc[0] = np.nan
+ result = df.head()
+ assert_frame_equal(result, expected)
+
+ df = DataFrame(dict(A = np.array(['foo','bar','bah','foo','bar'])))
+ df.A.iloc[0] = np.nan
+ result = df.head()
+ assert_frame_equal(result, expected)
+
def test_detect_chained_assignment(self):
pd.set_option('chained_assignment','raise')
| related #6056
| https://api.github.com/repos/pandas-dev/pandas/pulls/6058 | 2014-01-24T14:12:23Z | 2014-01-24T15:39:15Z | 2014-01-24T15:39:15Z | 2014-06-19T09:30:48Z |
ENH Add MultiIndex.from_product convenience function | diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 9c3412d35d286..6e6bb1aa012ee 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -1539,8 +1539,9 @@ The ``MultiIndex`` object is the hierarchical analogue of the standard
``Index`` object which typically stores the axis labels in pandas objects. You
can think of ``MultiIndex`` an array of tuples where each tuple is unique. A
``MultiIndex`` can be created from a list of arrays (using
-``MultiIndex.from_arrays``) or an array of tuples (using
-``MultiIndex.from_tuples``).
+``MultiIndex.from_arrays``), an array of tuples (using
+``MultiIndex.from_tuples``), or a crossed set of iterables (using
+``MultiIndex.from_product``).
.. ipython:: python
@@ -1552,6 +1553,14 @@ can think of ``MultiIndex`` an array of tuples where each tuple is unique. A
s = Series(randn(8), index=index)
s
+When you want every pairing of the elements in two iterables, it can be easier
+to use the ``MultiIndex.from_product`` function:
+
+.. ipython:: python
+
+ iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
+ MultiIndex.from_product(iterables, names=['first', 'second'])
+
As a convenience, you can pass a list of arrays directly into Series or
DataFrame to construct a MultiIndex automatically:
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index ded0e3b495be2..0a827c0ceab22 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -73,6 +73,16 @@ Enhancements
improves parsing perf in many cases. Thanks to @lexual for suggesting and @danbirken
for rapidly implementing. (:issue:`5490`, :issue:`6021`)
+- ``MultiIndex.from_product`` convenience function for creating a MultiIndex from
+ the cartesian product of a set of iterables (:issue:`6055`):
+
+ .. ipython:: python
+
+ shades = ['light', 'dark']
+ colors = ['red', 'green', 'blue']
+
+ MultiIndex.from_product([shades, colors], names=['shade', 'color'])
+
- The ``ArrayFormatter`` for ``datetime`` and ``timedelta64`` now intelligently
limit precision based on the values in the array (:issue:`3401`)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 86344b1cc2161..c42d7a29bb8f6 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2491,6 +2491,8 @@ def from_arrays(cls, arrays, sortorder=None, names=None):
See Also
--------
MultiIndex.from_tuples : Convert list of tuples to MultiIndex
+ MultiIndex.from_product : Make a MultiIndex from cartesian product
+ of iterables
"""
from pandas.core.categorical import Categorical
@@ -2534,6 +2536,8 @@ def from_tuples(cls, tuples, sortorder=None, names=None):
See Also
--------
MultiIndex.from_arrays : Convert list of arrays to MultiIndex
+ MultiIndex.from_product : Make a MultiIndex from cartesian product
+ of iterables
"""
if len(tuples) == 0:
# I think this is right? Not quite sure...
@@ -2552,6 +2556,45 @@ def from_tuples(cls, tuples, sortorder=None, names=None):
return MultiIndex.from_arrays(arrays, sortorder=sortorder,
names=names)
+ @classmethod
+ def from_product(cls, iterables, sortorder=None, names=None):
+ """
+ Make a MultiIndex from the cartesian product of multiple iterables
+
+ Parameters
+ ----------
+ iterables : list / sequence of iterables
+ Each iterable has unique labels for each level of the index.
+ sortorder : int or None
+ Level of sortedness (must be lexicographically sorted by that
+ level).
+ names : list / sequence of strings or None
+ Names for the levels in the index.
+
+ Returns
+ -------
+ index : MultiIndex
+
+ Examples
+ --------
+ >>> numbers = [0, 1, 2]
+ >>> colors = [u'green', u'purple']
+ >>> MultiIndex.from_product([numbers, colors],
+ names=['number', 'color'])
+ MultiIndex(levels=[[0, 1, 2], [u'green', u'purple']],
+ labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
+ names=[u'number', u'color'])
+
+ See Also
+ --------
+ MultiIndex.from_arrays : Convert list of arrays to MultiIndex
+ MultiIndex.from_tuples : Convert list of tuples to MultiIndex
+ """
+ from pandas.tools.util import cartesian_product
+ product = cartesian_product(iterables)
+ return MultiIndex.from_arrays(product, sortorder=sortorder,
+ names=names)
+
@property
def nlevels(self):
return len(self.levels)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index de6092a65f507..fc94a9da00dae 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1561,6 +1561,20 @@ def test_from_arrays(self):
result = MultiIndex.from_arrays(arrays)
self.assertEquals(list(result), list(self.index))
+ def test_from_product(self):
+ first = ['foo', 'bar', 'buz']
+ second = ['a', 'b', 'c']
+ names = ['first', 'second']
+ result = MultiIndex.from_product([first, second], names=names)
+
+ tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'),
+ ('bar', 'a'), ('bar', 'b'), ('bar', 'c'),
+ ('buz', 'a'), ('buz', 'b'), ('buz', 'c')]
+ expected = MultiIndex.from_tuples(tuples, names=names)
+
+ assert_array_equal(result, expected)
+ self.assertEquals(result.names, names)
+
def test_append(self):
result = self.index[:3].append(self.index[3:])
self.assert_(result.equals(self.index))
| Following up on this [StackOverflow post](http://stackoverflow.com/questions/21316628/make-a-pandas-multiindex-from-a-product-of-iterables).
This is a convenience function for when you have a set of iterables and you want to make a MultiIndex with each unique paring of the values in those iterables.
~~I'm testing it against `itertools.product` since it uses the internal `cartesian_product` function; please let me know if there are additional tests that would make sense.~~
Testing against MultiIndex.from_tuples instead.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6055 | 2014-01-24T03:00:50Z | 2014-01-25T23:21:53Z | 2014-01-25T23:21:53Z | 2021-09-04T21:18:45Z |
DOC: Clarify that DataFrame string formatters must return strings | diff --git a/pandas/core/format.py b/pandas/core/format.py
index fce0ef6a27889..2032e88a7c594 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -43,11 +43,11 @@
string representation of NAN to use, default 'NaN'
formatters : list or dict of one-parameter functions, optional
formatter functions to apply to columns' elements by position or name,
- default None, if the result is a string , it must be a unicode
- string. List must be of length equal to the number of columns.
+ default None. The result of each function must be a unicode string.
+ List must be of length equal to the number of columns.
float_format : one-parameter function, optional
- formatter function to apply to columns' elements if they are floats
- default None
+ formatter function to apply to columns' elements if they are floats,
+ default None. The result of this function must be a unicode string.
sparsify : bool, optional
Set to False for a DataFrame with a hierarchical index to print every
multiindex key at each row, default True
| I am not 100% sure that string formatters must really return _unicode_ strings
(non-unicode strings seem to work, too), but I am leaving that because it's
what is already documented.
related #6052
| https://api.github.com/repos/pandas-dev/pandas/pulls/6054 | 2014-01-23T21:41:08Z | 2014-02-14T17:38:07Z | 2014-02-14T17:38:07Z | 2015-09-11T05:19:16Z |
BUG: Regression in .get(None) from 0.12 (GH5652) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index e1325c676340e..4ed792afc0bcf 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -139,6 +139,7 @@ Bug Fixes
- Possible segfault when chained indexing with an object array under numpy 1.7.1 (:issue:`6016`)
- Bug in setting using fancy indexing a single element with a non-scalar (e.g. a list),
(:issue:`6043`)
+ - Regression in ``.get(None)`` indexing from 0.12 (:issue:`5652`)
pandas 0.13.0
-------------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 63454d32a5fa1..bd53e1a35e166 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -981,7 +981,7 @@ def get(self, key, default=None):
"""
try:
return self[key]
- except KeyError:
+ except (KeyError, ValueError):
return default
def __getitem__(self, item):
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index f122a88fe7a25..5b821000fe96e 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -147,6 +147,11 @@ def test_get(self):
self.assert_(self.frame.get('foo') is None)
assert_series_equal(self.frame.get('foo', self.frame['B']),
self.frame['B'])
+ # None
+ # GH 5652
+ for df in [DataFrame(), DataFrame(columns=list('AB')), DataFrame(columns=list('AB'),index=range(3)) ]:
+ result = df.get(None)
+ self.assert_(result is None)
def test_getitem_iterator(self):
idx = iter(['A', 'B', 'C'])
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 6df7028092a7a..675852027ce6e 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -724,6 +724,12 @@ def test_getitem_get(self):
d = self.ts.index[0] - datetools.bday
self.assertRaises(KeyError, self.ts.__getitem__, d)
+ # None
+ # GH 5652
+ for s in [Series(), Series(index=list('abc'))]:
+ result = s.get(None)
+ self.assert_(result is None)
+
def test_iget(self):
s = Series(np.random.randn(10), index=lrange(0, 20, 2))
for i in range(len(s)):
| closes #5652
| https://api.github.com/repos/pandas-dev/pandas/pulls/6053 | 2014-01-23T21:29:36Z | 2014-01-23T22:03:09Z | 2014-01-23T22:03:09Z | 2014-06-24T00:49:34Z |
CLN: ipython expects None from _repr_html_ to signal no html repr GH5922 | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2d4fd2d792732..f4bdde332ac81 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -474,7 +474,8 @@ def _repr_html_(self):
# behaves badly when outputting an HTML table
# that doesn't fit the window, so disable it.
if com.in_qtconsole():
- raise NotImplementedError('HTML output is disabled in QtConsole')
+ # 'HTML output is disabled in QtConsole'
+ return None
if self._info_repr():
buf = StringIO(u(""))
| ipython is still deciding what the proper convention is for supressing the warning.
turns out None has worked for previous versions as well, so let's just do that.
closes #5922
| https://api.github.com/repos/pandas-dev/pandas/pulls/6045 | 2014-01-23T15:47:32Z | 2014-01-23T15:48:05Z | 2014-01-23T15:48:05Z | 2014-07-16T08:22:53Z |
BUG: Bug in setting using fancy indexing a single element with a non-scalar (e.g. a list) (GH6043) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 77ce69c40bb9b..151402a8b5370 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -135,6 +135,8 @@ Bug Fixes
- Bug in Series construction of mixed type with datelike and an integer (which should result in
object type and not automatic conversion) (:issue:`6028`)
- Possible segfault when chained indexing with an object array under numpy 1.7.1 (:issue:`6016`)
+ - Bug in setting using fancy indexing a single element with a non-scalar (e.g. a list),
+ (:issue:`6043`)
pandas 0.13.0
-------------
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index f73440be61600..dacab4fd6e6c6 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -605,10 +605,18 @@ def setitem(self, indexer, value):
"different length than the value")
try:
+ # setting a single element for each dim and with a rhs that could be say a list
+ # GH 6043
+ if arr_value.ndim == 1 and (
+ np.isscalar(indexer) or (isinstance(indexer, tuple) and all([ np.isscalar(idx) for idx in indexer ]))):
+ values[indexer] = value
+
# if we are an exact match (ex-broadcasting),
# then use the resultant dtype
- if len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and np.prod(arr_value.shape) == np.prod(values.shape):
+ elif len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and np.prod(arr_value.shape) == np.prod(values.shape):
values = arr_value.reshape(values.shape)
+
+ # set
else:
values[indexer] = value
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index b763b885fe7b8..f80b0d36445cf 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1286,6 +1286,48 @@ def test_ix_get_set_consistency(self):
self.assert_(df.ix['e', 8] == 45)
self.assert_(df.loc['e', 8] == 45)
+ def test_setitem_list(self):
+
+ # GH 6043
+ # ix with a list
+ df = DataFrame(index=[0,1], columns=[0])
+ df.ix[1,0] = [1,2,3]
+ df.ix[1,0] = [1,2]
+
+ result = DataFrame(index=[0,1], columns=[0])
+ result.ix[1,0] = [1,2]
+
+ assert_frame_equal(result,df)
+
+ # ix with an object
+ class TO(object):
+ def __init__(self, value):
+ self.value = value
+ def __str__(self):
+ return "[{0}]".format(self.value)
+ __repr__ = __str__
+ def __eq__(self, other):
+ return self.value == other.value
+ def view(self):
+ return self
+
+ df = DataFrame(index=[0,1], columns=[0])
+ df.ix[1,0] = TO(1)
+ df.ix[1,0] = TO(2)
+
+ result = DataFrame(index=[0,1], columns=[0])
+ result.ix[1,0] = TO(2)
+
+ assert_frame_equal(result,df)
+
+ # remains object dtype even after setting it back
+ df = DataFrame(index=[0,1], columns=[0])
+ df.ix[1,0] = TO(1)
+ df.ix[1,0] = np.nan
+ result = DataFrame(index=[0,1], columns=[0])
+
+ assert_frame_equal(result, df)
+
def test_iloc_mask(self):
# GH 3631, iloc with a mask (of a series) should raise
| closes #6043
| https://api.github.com/repos/pandas-dev/pandas/pulls/6044 | 2014-01-23T01:15:41Z | 2014-01-23T01:30:42Z | 2014-01-23T01:30:42Z | 2014-06-15T17:31:01Z |
BUG: less false positives with SettingWithCopy (GH6025) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 77ce69c40bb9b..0117d77d4143d 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -59,7 +59,7 @@ API Changes
- ``Series.sort`` will raise a ``ValueError`` (rather than a ``TypeError``) on sorting an
object that is a view of another (:issue:`5856`, :issue:`5853`)
- Raise/Warn ``SettingWithCopyError`` (according to the option ``chained_assignment`` in more cases,
- when detecting chained assignment, related (:issue:`5938`)
+ when detecting chained assignment, related (:issue:`5938`, :issue:`6025`)
- DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
- ``autocorrelation_plot`` now accepts ``**kwargs``. (:issue:`5623`)
- ``convert_objects`` now accepts a ``convert_timedeltas='coerce'`` argument to allow forced dtype conversion of
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index adb7b2d2b2691..2d4fd2d792732 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1582,7 +1582,7 @@ def _ixs(self, i, axis=0, copy=False):
new_values, copy = self._data.fast_2d_xs(i, copy=copy)
result = Series(new_values, index=self.columns,
name=self.index[i], dtype=new_values.dtype)
- result.is_copy=copy
+ result._set_is_copy(self, copy=copy)
return result
# icol
@@ -1707,7 +1707,7 @@ def _getitem_multilevel(self, key):
if isinstance(result, Series):
result = Series(result, index=self.index, name=key)
- result.is_copy=True
+ result._set_is_copy(self)
return result
else:
return self._get_item_cache(key)
@@ -1878,6 +1878,7 @@ 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):
@@ -1912,6 +1913,7 @@ def _setitem_frame(self, key, value):
raise TypeError(
'Cannot do boolean setting on mixed-type frame')
+ self._check_setitem_copy()
self.where(-key, value, inplace=True)
def _ensure_valid_index(self, value):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index eb24301e5e603..63454d32a5fa1 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2,6 +2,7 @@
import warnings
import operator
import weakref
+import gc
import numpy as np
import pandas.lib as lib
@@ -97,7 +98,7 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
for i, ax in enumerate(axes):
data = data.reindex_axis(ax, axis=i)
- object.__setattr__(self, 'is_copy', False)
+ object.__setattr__(self, 'is_copy', None)
object.__setattr__(self, '_data', data)
object.__setattr__(self, '_item_cache', {})
@@ -994,6 +995,9 @@ def _get_item_cache(self, item):
res = self._box_item_values(item, values)
cache[item] = res
res._set_as_cached(item, self)
+
+ # for a chain
+ res.is_copy = self.is_copy
return res
def _set_as_cached(self, item, cacher):
@@ -1031,16 +1035,14 @@ def _maybe_update_cacher(self, clear=False):
# a copy
if ref is None:
del self._cacher
- self.is_copy = True
- self._check_setitem_copy(stacklevel=5, t='referant')
else:
try:
ref._maybe_cache_changed(cacher[0], self)
except:
pass
- if ref.is_copy:
- self.is_copy = True
- self._check_setitem_copy(stacklevel=5, t='referant')
+
+ # check if we are a copy
+ self._check_setitem_copy(stacklevel=5, t='referant')
if clear:
self._clear_item_cache()
@@ -1055,13 +1057,35 @@ def _set_item(self, key, value):
self._data.set(key, value)
self._clear_item_cache()
+ def _set_is_copy(self, ref=None, copy=True):
+ if not copy:
+ self.is_copy = None
+ else:
+ if ref is not None:
+ self.is_copy = weakref.ref(ref)
+ else:
+ self.is_copy = None
+
def _check_setitem_copy(self, stacklevel=4, t='setting'):
""" 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*"""
if 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
if t == 'referant':
t = ("A value is trying to be set on a copy of a slice from a "
@@ -1143,7 +1167,7 @@ def take(self, indices, axis=0, convert=True, is_copy=True):
# maybe set copy if we didn't actually change the index
if is_copy and not result._get_axis(axis).equals(self._get_axis(axis)):
- result.is_copy=is_copy
+ result._set_is_copy(self)
return result
@@ -1276,12 +1300,12 @@ def xs(self, key, axis=0, level=None, copy=True, drop_level=True):
new_values, copy = self._data.fast_2d_xs(loc, copy=copy)
result = Series(new_values, index=self.columns,
name=self.index[loc])
- result.is_copy=True
else:
result = self[loc]
result.index = new_index
+ result._set_is_copy(self)
return result
_xs = xs
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 474b5ae3ac6d6..9a67f5fe3854e 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -211,7 +211,7 @@ def _setitem_with_indexer(self, indexer, value):
labels = _safe_append_to_index(index, key)
self.obj._data = self.obj.reindex_axis(labels, i)._data
self.obj._maybe_update_cacher(clear=True)
- self.obj.is_copy=False
+ self.obj.is_copy=None
if isinstance(labels, MultiIndex):
self.obj.sortlevel(inplace=True)
@@ -418,6 +418,7 @@ def can_do_equal_len():
if isinstance(value, ABCPanel):
value = self._align_panel(indexer, value)
+ # actually do the set
self.obj._data = self.obj._data.setitem(indexer, value)
self.obj._maybe_update_cacher(clear=True)
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 698f7777a1100..4ed325df9a747 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -60,7 +60,7 @@ def __init__(self, obj, orient, date_format, double_precision,
self.date_unit = date_unit
self.default_handler = default_handler
- self.is_copy = False
+ self.is_copy = None
self._format_axes()
def _format_axes(self):
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 7daf95ac15a95..3270d80dc9dad 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1380,10 +1380,10 @@ def test_set_value_keeps_names(self):
columns=['one', 'two', 'three', 'four'],
index=idx)
df = df.sortlevel()
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
self.assertEqual(df.index.names, ('Name', 'Number'))
df = df.set_value(('grethe', '4'), 'one', 99.34)
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
self.assertEqual(df.index.names, ('Name', 'Number'))
def test_names(self):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index b763b885fe7b8..645ec532f8510 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1980,7 +1980,7 @@ def test_detect_chained_assignment(self):
# work with the chain
expected = DataFrame([[-5,1],[-6,3]],columns=list('AB'))
df = DataFrame(np.arange(4).reshape(2,2),columns=list('AB'),dtype='int64')
- self.assert_(not df.is_copy)
+ self.assert_(df.is_copy is None)
df['A'][0] = -5
df['A'][1] = -6
@@ -1988,11 +1988,11 @@ def test_detect_chained_assignment(self):
expected = DataFrame([[-5,2],[np.nan,3.]],columns=list('AB'))
df = DataFrame({ 'A' : Series(range(2),dtype='int64'), 'B' : np.array(np.arange(2,4),dtype=np.float64)})
- self.assert_(not df.is_copy)
+ self.assert_(df.is_copy is None)
df['A'][0] = -5
df['A'][1] = np.nan
assert_frame_equal(df, expected)
- self.assert_(not df['A'].is_copy)
+ self.assert_(df['A'].is_copy is None)
# using a copy (the chain), fails
df = DataFrame({ 'A' : Series(range(2),dtype='int64'), 'B' : np.array(np.arange(2,4),dtype=np.float64)})
@@ -2004,7 +2004,7 @@ def f():
df = DataFrame({'a' : ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c' : Series(range(7),dtype='int64') })
- self.assert_(not df.is_copy)
+ self.assert_(df.is_copy is None)
expected = DataFrame({'a' : ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c' : [42,42,2,3,4,42,6]})
@@ -2033,7 +2033,7 @@ def f():
# make sure that is_copy is picked up reconstruction
# GH5475
df = DataFrame({"A": [1,2]})
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
with tm.ensure_clean('__tmp__pickle') as path:
df.to_pickle(path)
df2 = pd.read_pickle(path)
@@ -2058,25 +2058,34 @@ def random_text(nobs=100):
# always a copy
x = df.iloc[[0,1,2]]
- self.assert_(x.is_copy is True)
+ self.assert_(x.is_copy is not None)
x = df.iloc[[0,1,2,4]]
- self.assert_(x.is_copy is True)
+ self.assert_(x.is_copy is not None)
# explicity copy
indexer = df.letters.apply(lambda x : len(x) > 10)
df = df.ix[indexer].copy()
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
df['letters'] = df['letters'].apply(str.lower)
# implicity take
df = random_text(100000)
indexer = df.letters.apply(lambda x : len(x) > 10)
df = df.ix[indexer]
- self.assert_(df.is_copy is True)
+ self.assert_(df.is_copy is not None)
+ df['letters'] = df['letters'].apply(str.lower)
+
+ # implicity take 2
+ df = random_text(100000)
+ indexer = df.letters.apply(lambda x : len(x) > 10)
+ df = df.ix[indexer]
+ self.assert_(df.is_copy is not None)
df.loc[:,'letters'] = df['letters'].apply(str.lower)
- # this will raise
- #df['letters'] = df['letters'].apply(str.lower)
+ # should be ok even though its a copy!
+ self.assert_(df.is_copy is None)
+ df['letters'] = df['letters'].apply(str.lower)
+ self.assert_(df.is_copy is None)
df = random_text(100000)
indexer = df.letters.apply(lambda x : len(x) > 10)
@@ -2084,7 +2093,7 @@ def random_text(nobs=100):
# an identical take, so no copy
df = DataFrame({'a' : [1]}).dropna()
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
df['a'] += 1
# inplace ops
@@ -2123,7 +2132,15 @@ def f():
df[['c']][mask] = df[['b']][mask]
self.assertRaises(com.SettingWithCopyError, f)
- pd.set_option('chained_assignment','warn')
+ # false positives GH6025
+ df = DataFrame ({'column1':['a', 'a', 'a'], 'column2': [4,8,9] })
+ str(df)
+ df['column1'] = df['column1'] + 'b'
+ str(df)
+ df = df [df['column2']!=8]
+ str(df)
+ df['column1'] = df['column1'] + 'c'
+ str(df)
def test_float64index_slicing_bug(self):
# GH 5557, related to slicing a float index
diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py
index 0ede6bd2bd46d..1571cf3bf6a7d 100644
--- a/pandas/tools/tests/test_pivot.py
+++ b/pandas/tools/tests/test_pivot.py
@@ -174,7 +174,7 @@ def _check_output(res, col, rows=['A', 'B'], cols=['C']):
exp = self.data.groupby(rows)[col].mean()
tm.assert_series_equal(cmarg, exp)
- res.sortlevel(inplace=True)
+ res = res.sortlevel()
rmarg = res.xs(('All', ''))[:-1]
exp = self.data.groupby(cols)[col].mean()
tm.assert_series_equal(rmarg, exp)
| closes #6025
| https://api.github.com/repos/pandas-dev/pandas/pulls/6042 | 2014-01-22T23:20:22Z | 2014-01-23T02:24:57Z | 2014-01-23T02:24:57Z | 2014-06-19T06:37:29Z |
ENH add show_dimensions display config | diff --git a/doc/source/faq.rst b/doc/source/faq.rst
index 68f6e3d53cdca..0fc925dad8b61 100644
--- a/doc/source/faq.rst
+++ b/doc/source/faq.rst
@@ -47,6 +47,7 @@ As of 0.13, these are the relevant options, all under the `display` namespace,
truncated table or, with this set to 'info', as a short summary view.
- max_columns (default 20): max dataframe columns to display.
- max_rows (default 60): max dataframe rows display.
+- show_dimenstions (default True): whether to show number of rows and columns.
Two additional options only apply to displaying DataFrames in terminals,
not to the HTML view:
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 08c8eb76caaf8..c1aa97e5a8773 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -50,6 +50,16 @@ Enhancements
df['diff'] = df['today']-df['age']
df
+- Add ``show_dimensions`` display option for the new DataFrame repr:
+
+ .. ipython:: python
+
+ df = DataFrame([[1, 2], [3, 4]])
+ pd.set_option('show_dimensions', False)
+ df
+
+ pd.set_option('show_dimensions', True)
+
- ``Panel.apply`` will work on non-ufuncs. See :ref:`the docs<basics.apply_panel>`.
.. ipython:: python
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index c617c58c527a8..9533c0921e1e3 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -119,6 +119,11 @@
wrap-around across multiple "pages" if it's width exceeds `display.width`.
"""
+pc_show_dimensions_doc = """
+: boolean
+ Whether to print out dimensions at the end of DataFrame repr.
+"""
+
pc_line_width_doc = """
: int
Deprecated.
@@ -163,7 +168,6 @@
If set to None, the number of items to be printed is unlimited.
"""
-
pc_max_info_rows_doc = """
: int or None
df.info() will usually show null-counts for each column.
@@ -243,6 +247,7 @@ def mpl_style_cb(key):
cf.register_option('encoding', detect_console_encoding(), pc_encoding_doc,
validator=is_text)
cf.register_option('expand_frame_repr', True, pc_expand_repr_doc)
+ cf.register_option('show_dimensions', True, pc_show_dimensions_doc)
cf.register_option('chop_threshold', None, pc_chop_threshold_doc)
cf.register_option('max_seq_items', 100, pc_max_seq_items)
cf.register_option('mpl_style', None, pc_mpl_style_doc,
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index adb7b2d2b2691..d40c7e49fc0c9 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -451,12 +451,13 @@ def __unicode__(self):
max_rows = get_option("display.max_rows")
max_cols = get_option("display.max_columns")
+ show_dimensions = get_option("display.show_dimensions")
if get_option("display.expand_frame_repr"):
width, _ = fmt.get_console_size()
else:
width = None
self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,
- line_width=width, show_dimensions=True)
+ line_width=width, show_dimensions=show_dimensions)
return buf.getvalue()
@@ -484,11 +485,12 @@ def _repr_html_(self):
if get_option("display.notebook_repr_html"):
max_rows = get_option("display.max_rows")
max_cols = get_option("display.max_columns")
+ show_dimensions = get_option("display.show_dimensions")
return ('<div style="max-height:1000px;'
'max-width:1500px;overflow:auto;">\n' +
self.to_html(max_rows=max_rows, max_cols=max_cols,
- show_dimensions=True) + '\n</div>')
+ show_dimensions=show_dimensions) + '\n</div>')
else:
return None
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index d0c783725f8bb..ebb2e351c7c1c 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -1428,6 +1428,13 @@ def test_repr_html(self):
fmt.reset_option('^display.')
+ df = DataFrame([[1, 2], [3, 4]])
+ self.assertTrue('2 rows' in df._repr_html_())
+ fmt.set_option('display.show_dimensions', False)
+ self.assertFalse('2 rows' in df._repr_html_())
+
+ fmt.reset_option('^display.')
+
def test_repr_html_wide(self):
row = lambda l, k: [tm.rands(k) for _ in range(l)]
max_cols = get_option('display.max_columns')
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index f122a88fe7a25..e45309a19ed9e 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -4170,6 +4170,15 @@ def test_repr(self):
self.assertFalse("\r" in repr(df))
self.assertFalse("a\n" in repr(df))
+ def test_repr_dimensions(self):
+ df = DataFrame([[1, 2,], [3, 4]])
+ self.assertTrue("2 rows x 2 columns" in repr(df))
+
+ fmt.set_option('display.show_dimensions', False)
+ self.assertFalse("2 rows x 2 columns" in repr(df))
+
+ fmt.reset_option('^display\.')
+
@slow
def test_repr_big(self):
buf = StringIO()
| see http://stackoverflow.com/questions/21293983/disabling-dataframe-dimensions-printing
If you've already done this @DSM054 apologies, just saw your comment... :s
| https://api.github.com/repos/pandas-dev/pandas/pulls/6041 | 2014-01-22T23:09:30Z | 2014-01-26T12:47:58Z | null | 2014-06-21T02:57:57Z |
TST: fix test that repr returns str | diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index d0c783725f8bb..86627271c8e6a 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -181,7 +181,7 @@ def test_repr_should_return_str(self):
u("\u03c6")]
cols = [u("\u03c8")]
df = DataFrame(data, columns=cols, index=index1)
- self.assertTrue(type(df.__repr__() == str)) # both py2 / 3
+ self.assertTrue(type(df.__repr__()) == str) # both py2 / 3
def test_repr_no_backslash(self):
with option_context('mode.sim_interactive', True):
| Unfortunately placed parentheses meant that we were checking whether `type(False)` was truelike, and `bool(bool) is True`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6040 | 2014-01-22T22:20:42Z | 2014-01-23T00:20:19Z | 2014-01-23T00:20:19Z | 2014-07-16T08:48:15Z |
Make -NaN and -nan default NA values | diff --git a/doc/source/io.rst b/doc/source/io.rst
index cba81a8b39600..fdad28688b7c6 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -575,7 +575,7 @@ the corresponding equivalent values will also imply a missing value (in this cas
To completely override the default values that are recognized as missing, specify ``keep_default_na=False``.
The default ``NaN`` recognized values are ``['-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A','N/A', 'NA',
-'#NA', 'NULL', 'NaN', 'nan']``.
+'#NA', 'NULL', 'NaN', '-NaN', 'nan', '-nan']``.
.. code-block:: python
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 3cee4473aab66..e1325c676340e 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -64,6 +64,8 @@ API Changes
- ``autocorrelation_plot`` now accepts ``**kwargs``. (:issue:`5623`)
- ``convert_objects`` now accepts a ``convert_timedeltas='coerce'`` argument to allow forced dtype conversion of
timedeltas (:issue:`5458`,:issue:`5689`)
+ - Add ``-NaN`` and ``-nan`` to the default set of NA values
+ (:issue:`5952`). See :ref:`NA Values <io.na_values>`.
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 08c8eb76caaf8..33dc92343427b 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -18,6 +18,9 @@ There are several new or updated docs sections including:
API changes
~~~~~~~~~~~
+- Add ``-NaN`` and ``-nan`` to the default set of NA values (:issue:`5952`).
+ See :ref:`NA Values <io.na_values>`.
+
Prior Version Deprecations/Changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 796475aa24a58..689d4aab48758 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -449,7 +449,7 @@ def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, **kwds):
# '1.#INF','-1.#INF', '1.#INF000000',
_NA_VALUES = set([
'-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A', 'N/A', 'NA', '#NA',
- 'NULL', 'NaN', 'nan', ''
+ 'NULL', 'NaN', '-NaN', 'nan', '-nan', ''
])
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index f04c055692386..76006507be524 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -33,6 +33,7 @@
import pandas.tseries.tools as tools
from numpy.testing.decorators import slow
+from numpy.testing import assert_array_equal
from pandas.parser import OverflowError
@@ -685,8 +686,8 @@ def test_non_string_na_values(self):
def test_default_na_values(self):
_NA_VALUES = set(['-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN',
'#N/A','N/A', 'NA', '#NA', 'NULL', 'NaN',
- 'nan', ''])
-
+ 'nan', '-NaN', '-nan', ''])
+ assert_array_equal (_NA_VALUES, parsers._NA_VALUES)
nv = len(_NA_VALUES)
def f(i, v):
if i == 0:
| closes #5952
| https://api.github.com/repos/pandas-dev/pandas/pulls/6038 | 2014-01-22T17:32:02Z | 2014-01-23T20:17:02Z | 2014-01-23T20:17:02Z | 2014-06-16T15:10:38Z |
FIX: extend access to `quotechar` param in `DataFrame.to_csv` | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 2caad982f044b..857e3524f1444 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -55,6 +55,7 @@ New features
- Added ``date_format`` and ``datetime_format`` attribute to ExcelWriter.
(:issue:`4133`)
+ - ``DataFrame.to_csv`` now accepts ``quotechar`` parameter (:issue:`6034`)
API Changes
~~~~~~~~~~~
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4c19831c6cbe3..a19f08cee1794 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1070,7 +1070,7 @@ def to_panel(self):
def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,
cols=None, header=True, index=True, index_label=None,
mode='w', nanRep=None, encoding=None, quoting=None,
- line_terminator='\n', chunksize=None,
+ quotechar='"', line_terminator='\n', chunksize=None,
tupleize_cols=False, date_format=None, **kwds):
r"""Write DataFrame to a comma-separated values (csv) file
@@ -1109,6 +1109,8 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,
file
quoting : optional constant from csv module
defaults to csv.QUOTE_MINIMAL
+ quotechar : string (length 1), default '"'
+ character used to quote fields
chunksize : int or None
rows to write at a time
tupleize_cols : boolean, default False
@@ -1129,8 +1131,8 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,
float_format=float_format, cols=cols,
header=header, index=index,
index_label=index_label, mode=mode,
- chunksize=chunksize, engine=kwds.get(
- "engine"),
+ chunksize=chunksize, quotechar=quotechar,
+ engine=kwds.get("engine"),
tupleize_cols=tupleize_cols,
date_format=date_format)
formatter.save()
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index bf71f2e3b1431..2e7394c9a9cc1 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -1669,10 +1669,10 @@ def test_to_latex(self):
\end{tabular}
"""
self.assertEqual(withoutindex_result, withoutindex_expected)
-
+
def test_to_latex_escape_special_chars(self):
special_characters = ['&','%','$','#','_',
- '{','}','~','^','\\']
+ '{','}','~','^','\\']
df = DataFrame(data=special_characters)
observed = df.to_latex()
expected = r"""\begin{tabular}{ll}
@@ -1694,6 +1694,24 @@ def test_to_latex_escape_special_chars(self):
"""
self.assertEqual(observed, expected)
+ def test_to_csv_quotechar(self):
+ df = DataFrame({'col' : [1,2]})
+ expected = """\
+$$,$col$
+$0$,$1$
+$1$,$2$
+"""
+ from tempfile import NamedTemporaryFile
+ with NamedTemporaryFile() as output:
+ df.to_csv(output.name, quoting=1, quotechar="$") # QUOTE_ALL
+ results = open(output.name).read()
+ self.assertEqual(results, expected)
+
+ df.to_csv(output.name, quoting=1, quotechar="$", engine='python')
+ results = open(output.name).read()
+ self.assertEqual(results, expected)
+
+
class TestSeriesFormatting(tm.TestCase):
_multiprocess_can_split_ = True
| Existing `pandas.core.format.CSVFormatter` param `quotechar` can now be
specified as keyword arg to `DataFrame.to_csv`
| https://api.github.com/repos/pandas-dev/pandas/pulls/6034 | 2014-01-22T08:54:47Z | 2014-01-31T07:46:11Z | null | 2014-06-23T14:29:47Z |
BUG: Possible segfault when chained indexing with an object array under numpy 1.7.1 (GH6016) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 69dc688cd6097..77ce69c40bb9b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -134,6 +134,7 @@ Bug Fixes
- Bug in Series.xs with a multi-index (:issue:`6018`)
- Bug in Series construction of mixed type with datelike and an integer (which should result in
object type and not automatic conversion) (:issue:`6028`)
+ - Possible segfault when chained indexing with an object array under numpy 1.7.1 (:issue:`6016`)
pandas 0.13.0
-------------
diff --git a/pandas/__init__.py b/pandas/__init__.py
index 0fdcf655ca47a..ff5588e778284 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -29,6 +29,7 @@
_np_version = np.version.short_version
_np_version_under1p6 = LooseVersion(_np_version) < '1.6'
_np_version_under1p7 = LooseVersion(_np_version) < '1.7'
+_np_version_under1p8 = LooseVersion(_np_version) < '1.8'
from pandas.version import version as __version__
from pandas.info import __doc__
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 000d6a4f6da9b..eb24301e5e603 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1005,9 +1005,14 @@ def _box_item_values(self, key, values):
raise NotImplementedError
def _maybe_cache_changed(self, item, value):
- """ the object has called back to us saying
- maybe it has changed """
- self._data.set(item, value)
+ """
+ the object has called back to us saying
+ maybe it has changed
+
+ numpy < 1.8 has an issue with object arrays and aliasing
+ GH6026
+ """
+ self._data.set(item, value, check=pd._np_version_under1p8)
@property
def _is_cached(self):
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 60e9baf005eb4..f73440be61600 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -26,7 +26,6 @@
from pandas.compat import range, lrange, lmap, callable, map, zip, u
from pandas.tseries.timedeltas import _coerce_scalar_to_timedelta_type
-
class Block(PandasObject):
"""
@@ -279,7 +278,7 @@ def get(self, item):
def iget(self, i):
return self.values[i]
- def set(self, item, value):
+ def set(self, item, value, check=False):
"""
Modify Block in-place with new item value
@@ -1360,6 +1359,26 @@ def convert(self, convert_dates=True, convert_numeric=True, convert_timedeltas=T
return blocks
+ def set(self, item, value, check=False):
+ """
+ Modify Block in-place with new item value
+
+ Returns
+ -------
+ None
+ """
+
+ loc = self.items.get_loc(item)
+
+ # GH6026
+ if check:
+ try:
+ if (self.values[loc] == value).all():
+ return
+ except:
+ pass
+ self.values[loc] = value
+
def _maybe_downcast(self, blocks, downcast=None):
if downcast is not None:
@@ -1601,7 +1620,7 @@ def astype(self, dtype, copy=False, raise_on_error=True):
return self._astype(dtype, copy=copy, raise_on_error=raise_on_error,
klass=klass)
- def set(self, item, value):
+ def set(self, item, value, check=False):
"""
Modify Block in-place with new item value
@@ -1714,7 +1733,7 @@ def prepare_for_merge(self, **kwargs):
def post_merge(self, items, **kwargs):
return self
- def set(self, item, value):
+ def set(self, item, value, check=False):
self.values = value
def get(self, item):
@@ -2879,10 +2898,11 @@ def delete(self, item):
if not is_unique:
self._consolidate_inplace()
- def set(self, item, value):
+ def set(self, item, value, check=False):
"""
Set new item in-place. Does not consolidate. Adds new Block if not
contained in the current set of items
+ if check, then validate that we are not setting the same data in-place
"""
if not isinstance(value, SparseArray):
if value.ndim == self.ndim - 1:
@@ -2898,7 +2918,7 @@ def _set_item(item, arr):
self._delete_from_block(i, item)
self._add_new_block(item, arr, loc=None)
else:
- block.set(item, arr)
+ block.set(item, arr, check=check)
try:
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 4e60037017645..b763b885fe7b8 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1950,6 +1950,29 @@ def test_setitem_cache_updating(self):
self.assert_(df.ix[0,'c'] == 0.0)
self.assert_(df.ix[7,'c'] == 1.0)
+ def test_setitem_chained_setfault(self):
+
+ # GH6026
+ # setfaults under numpy 1.7.1 (ok on 1.8)
+ data = ['right', 'left', 'left', 'left', 'right', 'left', 'timeout']
+ mdata = ['right', 'left', 'left', 'left', 'right', 'left', 'none']
+
+ df = DataFrame({'response': np.array(data)})
+ mask = df.response == 'timeout'
+ df.response[mask] = 'none'
+ assert_frame_equal(df, DataFrame({'response': mdata }))
+
+ recarray = np.rec.fromarrays([data], names=['response'])
+ df = DataFrame(recarray)
+ mask = df.response == 'timeout'
+ df.response[mask] = 'none'
+ assert_frame_equal(df, DataFrame({'response': mdata }))
+
+ df = DataFrame({'response': data, 'response1' : data })
+ mask = df.response == 'timeout'
+ df.response[mask] = 'none'
+ assert_frame_equal(df, DataFrame({'response': mdata, 'response1' : data }))
+
def test_detect_chained_assignment(self):
pd.set_option('chained_assignment','raise')
| closes #6026
| https://api.github.com/repos/pandas-dev/pandas/pulls/6031 | 2014-01-21T22:36:12Z | 2014-01-21T23:06:39Z | 2014-01-21T23:06:39Z | 2014-06-23T22:12:48Z |
BUG: Bug in Series construction of mixed type with datelike and an integer | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 6b167a8939bb5..a3792ae74b023 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -130,6 +130,8 @@ Bug Fixes
and off-diagonal plots, see (:issue:`5497`).
- Regression in Series with a multi-index via ix (:issue:`6018`)
- Bug in Series.xs with a multi-index (:issue:`6018`)
+ - Bug in Series construction of mixed type with datelike and an integer (which should result in
+ object type and not automatic conversion) (:issue:`6028`)
pandas 0.13.0
-------------
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 7c01f5f700c2b..4e60037017645 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -623,6 +623,12 @@ def test_loc_general(self):
self.assert_((result.columns == ['A','B']).all() == True)
self.assert_((result.index == ['A','B']).all() == True)
+ # mixed type
+ result = DataFrame({ 'a' : [Timestamp('20130101')], 'b' : [1] }).iloc[0]
+ expected = Series([ Timestamp('20130101'), 1],index=['a','b'])
+ assert_series_equal(result,expected)
+ self.assert_(result.dtype == object)
+
def test_loc_setitem_frame(self):
df = self.frame_labels
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index f3f3127bbe875..6df7028092a7a 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -573,6 +573,11 @@ def test_constructor_dtype_datetime64(self):
result = Series([datetime(3000,1,1)])
self.assert_(result[0] == datetime(3000,1,1,0,0))
+ # don't mix types
+ result = Series([ Timestamp('20130101'), 1],index=['a','b'])
+ self.assert_(result['a'] == Timestamp('20130101'))
+ self.assert_(result['b'] == 1)
+
def test_constructor_dict(self):
d = {'a': 0., 'b': 1., 'c': 2.}
result = Series(d, index=['b', 'c', 'd', 'a'])
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index c2a727d7d3394..ccf7174c7ae05 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1005,7 +1005,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
ndarray[int64_t] iresult
ndarray[object] oresult
pandas_datetimestruct dts
- bint utc_convert = bool(utc)
+ bint utc_convert = bool(utc), seen_integer=0, seen_datetime=0
_TSObject _ts
int64_t m = cast_from_unit(None,unit)
@@ -1017,6 +1017,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
if _checknull_with_nat(val):
iresult[i] = iNaT
elif PyDateTime_Check(val):
+ seen_datetime=1
if val.tzinfo is not None:
if utc_convert:
_ts = convert_to_tsobject(val, None, unit)
@@ -1047,6 +1048,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
iresult[i] = _date_to_datetime64(val, &dts)
try:
_check_dts_bounds(&dts)
+ seen_datetime=1
except ValueError:
if coerce:
iresult[i] = iNaT
@@ -1058,6 +1060,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
else:
try:
iresult[i] = _get_datetime64_nanos(val)
+ seen_datetime=1
except ValueError:
if coerce:
iresult[i] = iNaT
@@ -1070,11 +1073,13 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
iresult[i] = iNaT
else:
iresult[i] = val*m
+ seen_integer=1
elif util.is_float_object(val) and not coerce:
if val != val or val == iNaT:
iresult[i] = iNaT
else:
iresult[i] = cast_from_unit(val,unit)
+ seen_integer=1
else:
try:
if len(val) == 0:
@@ -1114,6 +1119,12 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
continue
raise
+ # don't allow mixed integers and datetime like
+ # higher levels can catch and coerce to object, for
+ # example
+ if seen_integer and seen_datetime:
+ raise ValueError("mixed datetimes and integers in passed array")
+
return result
except OutOfBoundsDatetime:
if raise_:
| should result in object type and not automatic conversion
| https://api.github.com/repos/pandas-dev/pandas/pulls/6028 | 2014-01-21T18:43:34Z | 2014-01-21T19:26:52Z | 2014-01-21T19:26:52Z | 2014-06-19T14:23:55Z |
PERF: apply perf enhancements | diff --git a/doc/source/release.rst b/doc/source/release.rst
index f58620020d254..69dc688cd6097 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -88,6 +88,7 @@ Improvements to existing features
- perf improvments in indexing with object dtypes (:issue:`5968`)
- improved dtype inference for ``timedelta`` like passed to constructors (:issue:`5458`,:issue:`5689`)
- escape special characters when writing to latex (:issue: `5374`)
+ - perf improvements in ``DataFrame.apply`` (:issue:`6013`)
.. _release.bug_fixes-0.13.1:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index a400bc1b644ba..adb7b2d2b2691 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -24,7 +24,7 @@
from pandas.core.common import (isnull, notnull, PandasError, _try_sort,
_default_index, _maybe_upcast, _is_sequence,
_infer_dtype_from_scalar, _values_from_object,
- _DATELIKE_DTYPES, is_list_like)
+ is_list_like)
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (_maybe_droplevels,
@@ -1581,7 +1581,7 @@ def _ixs(self, i, axis=0, copy=False):
else:
new_values, copy = self._data.fast_2d_xs(i, copy=copy)
result = Series(new_values, index=self.columns,
- name=self.index[i])
+ name=self.index[i], dtype=new_values.dtype)
result.is_copy=copy
return result
@@ -3324,8 +3324,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
if reduce:
try:
- if self._is_mixed_type: # maybe a hack for now
- raise AssertionError('Must be mixed type DataFrame')
+ # the is the fast-path
values = self.values
dummy = Series(NA, index=self._get_axis(axis),
dtype=values.dtype)
@@ -3333,7 +3332,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
labels = self._get_agg_axis(axis)
result = lib.reduce(values, func, axis=axis, dummy=dummy,
labels=labels)
- return Series(result, index=self._get_agg_axis(axis))
+ return Series(result, index=labels)
except Exception:
pass
@@ -3393,12 +3392,12 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
result = result.T
result = result.convert_objects(copy=False)
- return result
else:
- s = Series(results)
- s.index = res_index
- return s
+ result = Series(results)
+ result.index = res_index
+
+ return result
def _apply_broadcast(self, func, axis):
if axis == 0:
@@ -3932,8 +3931,7 @@ def _reduce(self, op, axis=0, skipna=True, numeric_only=None,
labels = self._get_agg_axis(axis)
# exclude timedelta/datetime unless we are uniform types
- if axis == 1 and self._is_mixed_type and len(set(self.dtypes) &
- _DATELIKE_DTYPES):
+ if axis == 1 and self._is_mixed_type and self._is_datelike_mixed_type:
numeric_only = True
if numeric_only is None:
@@ -3945,7 +3943,14 @@ def _reduce(self, op, axis=0, skipna=True, numeric_only=None,
# try by-column first
if filter_type is None and axis == 0:
try:
- return self.apply(f).iloc[0]
+
+ # this can end up with a non-reduction
+ # but not always. if the types are mixed
+ # with datelike then need to make sure a series
+ result = self.apply(f,reduce=False)
+ if result.ndim == self.ndim:
+ result = result.iloc[0]
+ return result
except:
pass
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6393083c182e3..000d6a4f6da9b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -78,7 +78,8 @@ class NDFrame(PandasObject):
copy : boolean, default False
"""
_internal_names = ['_data', '_cacher', '_item_cache', '_cache',
- 'is_copy', '_subtyp', '_index', '_default_kind', '_default_fill_value']
+ 'is_copy', '_subtyp', '_index', '_default_kind',
+ '_default_fill_value','__array_struct__','__array_interface__']
_internal_names_set = set(_internal_names)
_metadata = []
is_copy = None
@@ -698,6 +699,14 @@ def __array_wrap__(self, result):
d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False)
return self._constructor(result, **d).__finalize__(self)
+ # ideally we would define this to avoid the getattr checks, but
+ # is slower
+ #@property
+ #def __array_interface__(self):
+ # """ provide numpy array interface method """
+ # values = self.values
+ # return dict(typestr=values.dtype.str,shape=values.shape,data=values)
+
def to_dense(self):
"Return dense representation of NDFrame (as opposed to sparse)"
# compat
@@ -1828,6 +1837,11 @@ def _is_numeric_mixed_type(self):
f = lambda: self._data.is_numeric_mixed_type
return self._protect_consolidate(f)
+ @property
+ def _is_datelike_mixed_type(self):
+ f = lambda: self._data.is_datelike_mixed_type
+ return self._protect_consolidate(f)
+
def _protect_consolidate(self, f):
blocks_before = len(self._data.blocks)
result = f()
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 0603746cf9dc5..60e9baf005eb4 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -83,6 +83,11 @@ def _consolidate_key(self):
def _is_single_block(self):
return self.ndim == 1
+ @property
+ def is_datelike(self):
+ """ return True if I am a non-datelike """
+ return self.is_datetime or self.is_timedelta
+
@property
def fill_value(self):
return np.nan
@@ -2439,6 +2444,12 @@ def is_numeric_mixed_type(self):
self._consolidate_inplace()
return all([block.is_numeric for block in self.blocks])
+ @property
+ def is_datelike_mixed_type(self):
+ # Warning, consolidation needs to get checked upstairs
+ self._consolidate_inplace()
+ return any([block.is_datelike for block in self.blocks])
+
def get_block_map(self, copy=False, typ=None, columns=None,
is_numeric=False, is_bool=False):
""" return a dictionary mapping the ftype -> block list
diff --git a/pandas/src/reduce.pyx b/pandas/src/reduce.pyx
index 13df983c45d53..bfbe0f3ea7938 100644
--- a/pandas/src/reduce.pyx
+++ b/pandas/src/reduce.pyx
@@ -35,18 +35,15 @@ cdef class Reducer:
self.chunksize = k
self.increment = k * arr.dtype.itemsize
+
self.f = f
self.arr = arr
self.typ = None
self.labels = labels
- self.dummy, index = self._check_dummy(dummy)
+ self.dummy, index = self._check_dummy(dummy=dummy)
- if axis == 0:
- self.labels = index
- self.index = labels
- else:
- self.labels = labels
- self.index = index
+ self.labels = labels
+ self.index = index
def _check_dummy(self, dummy=None):
cdef object index
@@ -54,6 +51,10 @@ cdef class Reducer:
if dummy is None:
dummy = np.empty(self.chunksize, dtype=self.arr.dtype)
index = None
+
+ # our ref is stolen later since we are creating this array
+ # in cython, so increment first
+ Py_INCREF(dummy)
else:
if dummy.dtype != self.arr.dtype:
raise ValueError('Dummy array must be same dtype')
@@ -76,7 +77,8 @@ cdef class Reducer:
ndarray arr, result, chunk
Py_ssize_t i, incr
flatiter it
- object res, tchunk, name, labels, index, typ
+ object res, name, labels, index
+ object cached_typ = None
arr = self.arr
chunk = self.dummy
@@ -84,31 +86,39 @@ cdef class Reducer:
chunk.data = arr.data
labels = self.labels
index = self.index
- typ = self.typ
incr = self.increment
try:
for i in range(self.nresults):
- # need to make sure that we pass an actual object to the function
- # and not just an ndarray
- if typ is not None:
- try:
- if labels is not None:
- name = labels[i]
+
+ if labels is not None:
+ name = util.get_value_at(labels, i)
+ else:
+ name = None
+
+ # create the cached type
+ # each time just reassign the data
+ if i == 0:
+
+ if self.typ is not None:
# recreate with the index if supplied
if index is not None:
- tchunk = typ(chunk, index=index, name=name, fastpath=True)
+
+ cached_typ = self.typ(chunk, index=index, name=name)
+
else:
- tchunk = typ(chunk, name=name)
- except:
- tchunk = chunk
- typ = None
- else:
- tchunk = chunk
+ # use the passsed typ, sans index
+ cached_typ = self.typ(chunk, name=name)
- res = self.f(tchunk)
+ # use the cached_typ if possible
+ if cached_typ is not None:
+ cached_typ._data._block.values = chunk
+ cached_typ.name = name
+ res = self.f(cached_typ)
+ else:
+ res = self.f(chunk)
if hasattr(res,'values'):
res = res.values
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 3b6e4ba445ce0..f122a88fe7a25 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -9035,6 +9035,16 @@ def test_apply_mixed_dtype_corner(self):
expected = Series(np.nan, index=[])
assert_series_equal(result, expected)
+ df = DataFrame({'A': ['foo'],
+ 'B': [1.]})
+ result = df.apply(lambda x: x['A'], axis=1)
+ expected = Series(['foo'],index=[0])
+ assert_series_equal(result, expected)
+
+ result = df.apply(lambda x: x['B'], axis=1)
+ expected = Series([1.],index=[0])
+ assert_series_equal(result, expected)
+
def test_apply_empty_infer_type(self):
no_cols = DataFrame(index=['a', 'b', 'c'])
no_index = DataFrame(columns=['a', 'b', 'c'])
@@ -9970,7 +9980,8 @@ def test_count(self):
self._check_stat_op('count', f,
has_skipna=False,
has_numeric_only=True,
- check_dtypes=False)
+ check_dtype=False,
+ check_dates=True)
# corner case
frame = DataFrame()
@@ -9999,10 +10010,9 @@ def test_count(self):
def test_sum(self):
self._check_stat_op('sum', np.sum, has_numeric_only=True)
- def test_sum_mixed_numeric(self):
- raise nose.SkipTest("skipping for now")
- # mixed types
- self._check_stat_op('sum', np.sum, frame = self.mixed_float, has_numeric_only=True)
+ # mixed types (with upcasting happening)
+ self._check_stat_op('sum', np.sum, frame=self.mixed_float.astype('float32'),
+ has_numeric_only=True, check_dtype=False, check_less_precise=True)
def test_stat_operators_attempt_obj_array(self):
data = {
@@ -10028,7 +10038,7 @@ def test_stat_operators_attempt_obj_array(self):
assert_series_equal(result, expected)
def test_mean(self):
- self._check_stat_op('mean', np.mean)
+ self._check_stat_op('mean', np.mean, check_dates=True)
def test_product(self):
self._check_stat_op('product', np.prod)
@@ -10039,10 +10049,10 @@ def wrapper(x):
return np.nan
return np.median(x)
- self._check_stat_op('median', wrapper)
+ self._check_stat_op('median', wrapper, check_dates=True)
def test_min(self):
- self._check_stat_op('min', np.min)
+ self._check_stat_op('min', np.min, check_dates=True)
self._check_stat_op('min', np.min, frame=self.intframe)
def test_cummin(self):
@@ -10092,7 +10102,7 @@ def test_cummax(self):
self.assertEqual(np.shape(cummax_xs), np.shape(self.tsframe))
def test_max(self):
- self._check_stat_op('max', np.max)
+ self._check_stat_op('max', np.max, check_dates=True)
self._check_stat_op('max', np.max, frame=self.intframe)
def test_mad(self):
@@ -10154,7 +10164,8 @@ def alt(x):
assert_series_equal(df.kurt(), df.kurt(level=0).xs('bar'))
def _check_stat_op(self, name, alternative, frame=None, has_skipna=True,
- has_numeric_only=False, check_dtypes=True):
+ has_numeric_only=False, check_dtype=True, check_dates=False,
+ check_less_precise=False):
if frame is None:
frame = self.frame
# set some NAs
@@ -10163,14 +10174,16 @@ def _check_stat_op(self, name, alternative, frame=None, has_skipna=True,
f = getattr(frame, name)
- if not ('max' in name or 'min' in name or 'count' in name):
+ if check_dates:
df = DataFrame({'b': date_range('1/1/2001', periods=2)})
_f = getattr(df, name)
- #print(df)
- self.assertFalse(len(_f()))
+ result = _f()
+ self.assert_(isinstance(result, Series))
df['a'] = lrange(len(df))
- self.assert_(len(getattr(df, name)()))
+ result = getattr(df, name)()
+ self.assert_(isinstance(result, Series))
+ self.assert_(len(result))
if has_skipna:
def skipna_wrapper(x):
@@ -10184,21 +10197,27 @@ def wrapper(x):
result0 = f(axis=0, skipna=False)
result1 = f(axis=1, skipna=False)
- assert_series_equal(result0, frame.apply(wrapper))
+ assert_series_equal(result0, frame.apply(wrapper),
+ check_dtype=check_dtype,
+ check_less_precise=check_less_precise)
assert_series_equal(result1, frame.apply(wrapper, axis=1),
- check_dtype=False) # HACK: win32
+ check_dtype=False,
+ check_less_precise=check_less_precise) # HACK: win32
else:
skipna_wrapper = alternative
wrapper = alternative
result0 = f(axis=0)
result1 = f(axis=1)
- assert_series_equal(result0, frame.apply(skipna_wrapper))
+ assert_series_equal(result0, frame.apply(skipna_wrapper),
+ check_dtype=check_dtype,
+ check_less_precise=check_less_precise)
assert_series_equal(result1, frame.apply(skipna_wrapper, axis=1),
- check_dtype=False)
+ check_dtype=False,
+ check_less_precise=check_less_precise)
# check dtypes
- if check_dtypes:
+ if check_dtype:
lcd_dtype = frame.values.dtype
self.assert_(lcd_dtype == result0.dtype)
self.assert_(lcd_dtype == result1.dtype)
@@ -10331,7 +10350,8 @@ def wrapper(x):
return np.nan
return np.median(x)
- self._check_stat_op('median', wrapper, frame=self.intframe, check_dtypes=False)
+ self._check_stat_op('median', wrapper, frame=self.intframe,
+ check_dtype=False, check_dates=True)
def test_quantile(self):
from pandas.compat.scipy import scoreatpercentile
diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py
index 7215b9dbf934b..5de5eee0ec011 100644
--- a/pandas/tests/test_tseries.py
+++ b/pandas/tests/test_tseries.py
@@ -661,7 +661,6 @@ def test_int_index(self):
from pandas.core.series import Series
arr = np.random.randn(100, 4)
-
result = lib.reduce(arr, np.sum, labels=Index(np.arange(4)))
expected = arr.sum(0)
assert_almost_equal(result, expected)
diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py
index 88d773319817d..c3425389684ae 100644
--- a/vb_suite/frame_methods.py
+++ b/vb_suite/frame_methods.py
@@ -324,8 +324,43 @@ def f(K=100):
df = DataFrame({ i:s for i in range(1028) })
"""
frame_apply_user_func = Benchmark('df.apply(lambda x: np.corrcoef(x,s)[0,1])', setup,
+ name = 'frame_apply_user_func',
start_date=datetime(2012,1,1))
+setup = common_setup + """
+df = DataFrame(np.random.randn(1000,100))
+"""
+frame_apply_lambda_mean = Benchmark('df.apply(lambda x: x.sum())', setup,
+ name = 'frame_apply_lambda_mean',
+ start_date=datetime(2012,1,1))
+setup = common_setup + """
+df = DataFrame(np.random.randn(1000,100))
+"""
+frame_apply_np_mean = Benchmark('df.apply(np.mean)', setup,
+ name = 'frame_apply_np_mean',
+ start_date=datetime(2012,1,1))
+
+setup = common_setup + """
+df = DataFrame(np.random.randn(1000,100))
+"""
+frame_apply_pass_thru = Benchmark('df.apply(lambda x: x)', setup,
+ name = 'frame_apply_pass_thru',
+ start_date=datetime(2012,1,1))
+
+setup = common_setup + """
+df = DataFrame(np.random.randn(1000,100))
+"""
+frame_apply_axis_1 = Benchmark('df.apply(lambda x: x+1,axis=1)', setup,
+ name = 'frame_apply_axis_1',
+ start_date=datetime(2012,1,1))
+
+setup = common_setup + """
+df = DataFrame(np.random.randn(1000,3),columns=list('ABC'))
+"""
+frame_apply_ref_by_name = Benchmark('df.apply(lambda x: x["A"] + x["B"],axis=1)', setup,
+ name = 'frame_apply_ref_by_name',
+ start_date=datetime(2012,1,1))
+
#----------------------------------------------------------------------
# dtypes
| added vbenches and make most apply operations a fair bit faster
closes #6013
I can't put this one in the vbench as its cython based, but previously was about 100ms (on my machine)
0.12 clocks in at 15ms (the remaining difference in time is due to the sub-indexing, e.g. x['a'] which in theory could also be speeded but a bit tricky and not a lot more to win)
```
In [6]: %timeit df.apply(lambda x: integrate_f_typed(x['a'], x['b'], x['N']), axis=1)
10 loops, best of 3: 26.2 ms per loop
```
Here's a related benchmark from #5654 (a version of which is in the vbenches):
```
In [16]: s = pd.Series(np.arange(4096.))
In [17]: df = pd.DataFrame({i:s for i in range(4096)})
```
0.12
```
In [18]: %timeit df.apply((lambda x: np.corrcoef(x, s)[0, 1]), axis=1)
1 loops, best of 3: 1.11 s per loop
```
with this PR
```
In [3]: In [18]: %timeit df.apply((lambda x: np.corrcoef(x, s)[0, 1]), axis=1)
1 loops, best of 3: 1.24 s per loop
```
```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
frame_apply_ref_by_name | 15.4320 | 32.2250 | 0.4789 | like the cython example above
frame_apply_user_func | 166.7013 | 232.7064 | 0.7164 | bench for example right above
frame_apply_axis_1 | 108.5210 | 109.1857 | 0.9939 |
frame_apply_pass_thru | 6.5626 | 6.4860 | 1.0118 |
frame_apply_np_mean | 3.9033 | 0.9290 | 4.2018 | this suffers from some construction overhead, not much I can do
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/6024 | 2014-01-21T15:16:05Z | 2014-01-21T21:44:21Z | 2014-01-21T21:44:20Z | 2014-06-26T18:44:46Z |
BUG: regression in GH6018, indexing with a Series multi-index | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 94652eb489f4a..6b167a8939bb5 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -126,8 +126,10 @@ Bug Fixes
of pandas in QTConsole, now fixed. If you're using an older version and
need to supress the warnings, see (:issue:`5922`).
- Bug in merging ``timedelta`` dtypes (:issue:`5695`)
- - Bug in plotting.scatter_matrix function. Wrong alignment among diagonal
+ - Bug in plotting.scatter_matrix function. Wrong alignment among diagonal
and off-diagonal plots, see (:issue:`5497`).
+ - Regression in Series with a multi-index via ix (:issue:`6018`)
+ - Bug in Series.xs with a multi-index (:issue:`6018`)
pandas 0.13.0
-------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index fbd49dbe6eeaf..a400bc1b644ba 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2037,145 +2037,6 @@ def _sanitize_column(self, key, value):
def _series(self):
return self._data.get_series_dict()
- def xs(self, key, axis=0, level=None, copy=True, drop_level=True):
- """
- Returns a cross-section (row(s) or column(s)) from the DataFrame.
- Defaults to cross-section on the rows (axis=0).
-
- Parameters
- ----------
- key : object
- Some label contained in the index, or partially in a MultiIndex
- axis : int, default 0
- Axis to retrieve cross-section on
- level : object, defaults to first n levels (n=1 or len(key))
- In case of a key partially contained in a MultiIndex, indicate
- which levels are used. Levels can be referred by label or position.
- copy : boolean, default True
- Whether to make a copy of the data
- drop_level : boolean, default True
- If False, returns object with same levels as self.
-
- Examples
- --------
- >>> df
- A B C
- a 4 5 2
- b 4 0 9
- c 9 7 3
- >>> df.xs('a')
- A 4
- B 5
- C 2
- Name: a
- >>> df.xs('C', axis=1)
- a 2
- b 9
- c 3
- Name: C
- >>> s = df.xs('a', copy=False)
- >>> s['A'] = 100
- >>> df
- A B C
- a 100 5 2
- b 4 0 9
- c 9 7 3
-
-
- >>> df
- A B C D
- first second third
- bar one 1 4 1 8 9
- two 1 7 5 5 0
- baz one 1 6 6 8 0
- three 2 5 3 5 3
- >>> df.xs(('baz', 'three'))
- A B C D
- third
- 2 5 3 5 3
- >>> df.xs('one', level=1)
- A B C D
- first third
- bar 1 4 1 8 9
- baz 1 6 6 8 0
- >>> df.xs(('baz', 2), level=[0, 'third'])
- A B C D
- second
- three 5 3 5 3
-
- Returns
- -------
- xs : Series or DataFrame
-
- """
- axis = self._get_axis_number(axis)
- labels = self._get_axis(axis)
- if level is not None:
- loc, new_ax = labels.get_loc_level(key, level=level,
- drop_level=drop_level)
-
- if not copy and not isinstance(loc, slice):
- raise ValueError('Cannot retrieve view (copy=False)')
-
- # level = 0
- loc_is_slice = isinstance(loc, slice)
- if not loc_is_slice:
- indexer = [slice(None)] * 2
- indexer[axis] = loc
- indexer = tuple(indexer)
- else:
- indexer = loc
- lev_num = labels._get_level_number(level)
- if labels.levels[lev_num].inferred_type == 'integer':
- indexer = self.index[loc]
-
- # select on the correct axis
- if axis == 1 and loc_is_slice:
- indexer = slice(None), indexer
- result = self.ix[indexer]
- setattr(result, result._get_axis_name(axis), new_ax)
- return result
-
- if axis == 1:
- data = self[key]
- if copy:
- data = data.copy()
- return data
-
- self._consolidate_inplace()
-
- index = self.index
- if isinstance(index, MultiIndex):
- loc, new_index = self.index.get_loc_level(key,
- drop_level=drop_level)
- else:
- loc = self.index.get_loc(key)
-
- if isinstance(loc, np.ndarray):
- if loc.dtype == np.bool_:
- inds, = loc.nonzero()
- return self.take(inds, axis=axis, convert=False)
- else:
- return self.take(loc, axis=axis, convert=True)
-
- if not np.isscalar(loc):
- new_index = self.index[loc]
-
- if np.isscalar(loc):
-
- new_values, copy = self._data.fast_2d_xs(loc, copy=copy)
- result = Series(new_values, index=self.columns,
- name=self.index[loc])
- result.is_copy=True
-
- else:
- result = self[loc]
- result.index = new_index
-
- return result
-
- _xs = xs
-
def lookup(self, row_labels, col_labels):
"""Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f1e890216830a..6393083c182e3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1133,6 +1133,145 @@ def take(self, indices, axis=0, convert=True, is_copy=True):
return result
+ def xs(self, key, axis=0, level=None, copy=True, drop_level=True):
+ """
+ Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.
+ Defaults to cross-section on the rows (axis=0).
+
+ Parameters
+ ----------
+ key : object
+ Some label contained in the index, or partially in a MultiIndex
+ axis : int, default 0
+ Axis to retrieve cross-section on
+ level : object, defaults to first n levels (n=1 or len(key))
+ In case of a key partially contained in a MultiIndex, indicate
+ which levels are used. Levels can be referred by label or position.
+ copy : boolean, default True
+ Whether to make a copy of the data
+ drop_level : boolean, default True
+ If False, returns object with same levels as self.
+
+ Examples
+ --------
+ >>> df
+ A B C
+ a 4 5 2
+ b 4 0 9
+ c 9 7 3
+ >>> df.xs('a')
+ A 4
+ B 5
+ C 2
+ Name: a
+ >>> df.xs('C', axis=1)
+ a 2
+ b 9
+ c 3
+ Name: C
+ >>> s = df.xs('a', copy=False)
+ >>> s['A'] = 100
+ >>> df
+ A B C
+ a 100 5 2
+ b 4 0 9
+ c 9 7 3
+
+
+ >>> df
+ A B C D
+ first second third
+ bar one 1 4 1 8 9
+ two 1 7 5 5 0
+ baz one 1 6 6 8 0
+ three 2 5 3 5 3
+ >>> df.xs(('baz', 'three'))
+ A B C D
+ third
+ 2 5 3 5 3
+ >>> df.xs('one', level=1)
+ A B C D
+ first third
+ bar 1 4 1 8 9
+ baz 1 6 6 8 0
+ >>> df.xs(('baz', 2), level=[0, 'third'])
+ A B C D
+ second
+ three 5 3 5 3
+
+ Returns
+ -------
+ xs : Series or DataFrame
+
+ """
+ axis = self._get_axis_number(axis)
+ labels = self._get_axis(axis)
+ if level is not None:
+ loc, new_ax = labels.get_loc_level(key, level=level,
+ drop_level=drop_level)
+
+ if not copy and not isinstance(loc, slice):
+ raise ValueError('Cannot retrieve view (copy=False)')
+
+ # level = 0
+ loc_is_slice = isinstance(loc, slice)
+ if not loc_is_slice:
+ indexer = [slice(None)] * self.ndim
+ indexer[axis] = loc
+ indexer = tuple(indexer)
+ else:
+ indexer = loc
+ lev_num = labels._get_level_number(level)
+ if labels.levels[lev_num].inferred_type == 'integer':
+ indexer = self.index[loc]
+
+ # select on the correct axis
+ if axis == 1 and loc_is_slice:
+ indexer = slice(None), indexer
+ result = self.ix[indexer]
+ setattr(result, result._get_axis_name(axis), new_ax)
+ return result
+
+ if axis == 1:
+ data = self[key]
+ if copy:
+ data = data.copy()
+ return data
+
+ self._consolidate_inplace()
+
+ index = self.index
+ if isinstance(index, MultiIndex):
+ loc, new_index = self.index.get_loc_level(key,
+ drop_level=drop_level)
+ else:
+ loc = self.index.get_loc(key)
+
+ if isinstance(loc, np.ndarray):
+ if loc.dtype == np.bool_:
+ inds, = loc.nonzero()
+ return self.take(inds, axis=axis, convert=False)
+ else:
+ return self.take(loc, axis=axis, convert=True)
+
+ if not np.isscalar(loc):
+ new_index = self.index[loc]
+
+ if np.isscalar(loc):
+ from pandas import Series
+ new_values, copy = self._data.fast_2d_xs(loc, copy=copy)
+ result = Series(new_values, index=self.columns,
+ name=self.index[loc])
+ result.is_copy=True
+
+ else:
+ result = self[loc]
+ result.index = new_index
+
+ return result
+
+ _xs = xs
+
# TODO: Check if this was clearer in 0.12
def select(self, crit, axis=0):
"""
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 751c020fecc27..474b5ae3ac6d6 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -57,7 +57,9 @@ def __getitem__(self, key):
def _get_label(self, label, axis=0):
# ueber-hack
- if (isinstance(label, tuple) and
+ if self.ndim == 1:
+ return self.obj[label]
+ elif (isinstance(label, tuple) and
isinstance(label[axis], slice)):
raise IndexingError('no slices here')
@@ -1364,46 +1366,6 @@ def _crit(v):
return not both_none and (_crit(obj.start) and _crit(obj.stop))
-class _SeriesIndexer(_IXIndexer):
-
- """
- Class to support fancy indexing, potentially using labels
-
- Notes
- -----
- Indexing based on labels is INCLUSIVE
- Slicing uses PYTHON SEMANTICS (endpoint is excluded)
-
- If Index contains int labels, these will be used rather than the locations,
- so be very careful (ambiguous).
-
- Examples
- --------
- >>> ts.ix[5:10] # equivalent to ts[5:10]
- >>> ts.ix[[date1, date2, date3]]
- >>> ts.ix[date1:date2] = 0
- """
-
- def _get_label(self, key, axis=0):
- return self.obj[key]
-
- def _get_loc(self, key, axis=0):
- return self.obj.values[key]
-
- def _slice(self, indexer, axis=0, typ=None):
- return self.obj._get_values(indexer)
-
- def _setitem_with_indexer(self, indexer, value):
-
- # need to delegate to the super setter
- if isinstance(indexer, dict):
- return super(_SeriesIndexer, self)._setitem_with_indexer(indexer,
- value)
-
- # fast access
- self.obj._set_values(indexer, value)
-
-
def _check_bool_indexer(ax, key):
# boolean indexing, need to check that the data are aligned, otherwise
# disallowed
diff --git a/pandas/core/series.py b/pandas/core/series.py
index a5459bfb2ae8c..555208a7849dc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -28,7 +28,7 @@
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
_ensure_index, _handle_legacy_indexes)
from pandas.core.indexing import (
- _SeriesIndexer, _check_bool_indexer, _check_slice_bounds,
+ _check_bool_indexer, _check_slice_bounds,
_is_index_slice, _maybe_convert_indices)
from pandas.core import generic
from pandas.core.internals import SingleBlockManager
@@ -445,11 +445,6 @@ def _maybe_box(self, values):
return values
- def _xs(self, key, axis=0, level=None, copy=True):
- return self.__getitem__(key)
-
- xs = _xs
-
def _ixs(self, i, axis=0):
"""
Return the i-th value or values in the Series by location
@@ -2473,10 +2468,6 @@ def to_period(self, freq=None, copy=True):
Series._add_numeric_operations()
_INDEX_TYPES = ndarray, Index, list, tuple
-# reinstall the SeriesIndexer
-# defined in indexing.py; pylint: disable=E0203
-Series._create_indexer('ix', _SeriesIndexer)
-
#------------------------------------------------------------------------------
# Supplementary functions
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 8f3f122fefb88..7c01f5f700c2b 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -832,6 +832,31 @@ def test_loc_multiindex(self):
xp = mi_int.ix[4]
assert_frame_equal(rs,xp)
+ def test_series_getitem_multiindex(self):
+
+ # GH 6018
+ # series regression getitem with a multi-index
+
+ s = Series([1,2,3])
+ s.index = MultiIndex.from_tuples([(0,0),(1,1), (2,1)])
+
+ result = s[:,0]
+ expected = Series([1],index=[0])
+ assert_series_equal(result,expected)
+
+ result = s.ix[:,1]
+ expected = Series([2,3],index=[1,2])
+ assert_series_equal(result,expected)
+
+ # xs
+ result = s.xs(0,level=0)
+ expected = Series([1],index=[0])
+ assert_series_equal(result,expected)
+
+ result = s.xs(1,level=1)
+ expected = Series([2,3],index=[1,2])
+ assert_series_equal(result,expected)
+
def test_ix_general(self):
# ix general issues
| closes #6018
| https://api.github.com/repos/pandas-dev/pandas/pulls/6022 | 2014-01-21T14:11:10Z | 2014-01-21T14:42:07Z | 2014-01-21T14:42:07Z | 2014-06-24T12:46:16Z |
Infer datetime format | diff --git a/doc/source/io.rst b/doc/source/io.rst
index fdad28688b7c6..e0ed2b930f449 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -500,6 +500,40 @@ a single date rather than the entire array.
.. _io.dayfirst:
+
+Inferring Datetime Format
+~~~~~~~~~~~~~~~~~~~~~~~~~
+If you have `parse_dates` enabled for some or all of your columns, and your
+datetime strings are all formatted the same way, you may get a large speed
+up by setting `infer_datetime_format=True`. If set, pandas will attempt
+to guess the format of your datetime strings, and then use a faster means
+of parsing the strings. 5-10x parsing speeds have been observed. Pandas
+will fallback to the usual parsing if either the format cannot be guessed
+or the format that was guessed cannot properly parse the entire column
+of strings. So in general, `infer_datetime_format` should not have any
+negative consequences if enabled.
+
+Here are some examples of datetime strings that can be guessed (All
+representing December 30th, 2011 at 00:00:00)
+
+"20111230"
+"2011/12/30"
+"20111230 00:00:00"
+"12/30/2011 00:00:00"
+"30/Dec/2011 00:00:00"
+"30/December/2011 00:00:00"
+
+`infer_datetime_format` is sensitive to `dayfirst`. With `dayfirst=True`, it
+will guess "01/12/2011" to be December 1st. With `dayfirst=False` (default)
+it will guess "01/12/2011" to be January 12th.
+
+.. ipython:: python
+
+ # Try to infer the format for the index column
+ df = pd.read_csv('foo.csv', index_col=0, parse_dates=True,
+ infer_datetime_format=True)
+
+
International Date Formats
~~~~~~~~~~~~~~~~~~~~~~~~~~
While US date formats tend to be MM/DD/YYYY, many international formats use
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index ee9e16d5f02f6..c877724613ef4 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -107,6 +107,20 @@ Enhancements
result
result.loc[:,:,'ItemA']
+- Added optional `infer_datetime_format` to `read_csv`, `Series.from_csv` and
+ `DataFrame.read_csv` (:issue:`5490`)
+
+ If `parse_dates` is enabled and this flag is set, pandas will attempt to
+ infer the format of the datetime strings in the columns, and if it can
+ be inferred, switch to a faster method of parsing them. In some cases
+ this can increase the parsing speed by ~5-10x.
+
+ .. ipython:: python
+
+ # Try to infer the format for the index column
+ df = pd.read_csv('foo.csv', index_col=0, parse_dates=True,
+ infer_datetime_format=True)
+
Experimental
~~~~~~~~~~~~
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index f4bdde332ac81..5a0d975a473e1 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -947,7 +947,8 @@ def _from_arrays(cls, arrays, columns, index, dtype=None):
@classmethod
def from_csv(cls, path, header=0, sep=',', index_col=0,
- parse_dates=True, encoding=None, tupleize_cols=False):
+ parse_dates=True, encoding=None, tupleize_cols=False,
+ infer_datetime_format=False):
"""
Read delimited file into DataFrame
@@ -966,6 +967,10 @@ def from_csv(cls, path, header=0, sep=',', index_col=0,
tupleize_cols : boolean, default False
write multi_index columns as a list of tuples (if True)
or new (expanded format) if False)
+ infer_datetime_format: boolean, default False
+ If True and `parse_dates` is True for a column, try to infer the
+ datetime format based on the first datetime string. If the format
+ can be inferred, there often will be a large parsing speed-up.
Notes
-----
@@ -980,7 +985,8 @@ def from_csv(cls, path, header=0, sep=',', index_col=0,
from pandas.io.parsers import read_table
return read_table(path, header=header, sep=sep,
parse_dates=parse_dates, index_col=index_col,
- encoding=encoding, tupleize_cols=tupleize_cols)
+ encoding=encoding, tupleize_cols=tupleize_cols,
+ infer_datetime_format=infer_datetime_format)
def to_sparse(self, fill_value=None, kind='block'):
"""
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 555208a7849dc..a3bf9be71af3c 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2178,7 +2178,7 @@ def between(self, left, right, inclusive=True):
@classmethod
def from_csv(cls, path, sep=',', parse_dates=True, header=None,
- index_col=0, encoding=None):
+ index_col=0, encoding=None, infer_datetime_format=False):
"""
Read delimited file into Series
@@ -2197,6 +2197,10 @@ def from_csv(cls, path, sep=',', parse_dates=True, header=None,
encoding : string, optional
a string representing the encoding to use if the contents are
non-ascii, for python versions prior to 3
+ infer_datetime_format: boolean, default False
+ If True and `parse_dates` is True for a column, try to infer the
+ datetime format based on the first datetime string. If the format
+ can be inferred, there often will be a large parsing speed-up.
Returns
-------
@@ -2205,7 +2209,8 @@ def from_csv(cls, path, sep=',', parse_dates=True, header=None,
from pandas.core.frame import DataFrame
df = DataFrame.from_csv(path, header=header, index_col=index_col,
sep=sep, parse_dates=parse_dates,
- encoding=encoding)
+ encoding=encoding,
+ infer_datetime_format=infer_datetime_format)
result = df.icol(0)
result.index.name = result.name = None
return result
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 689d4aab48758..6b0d56b5c383e 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -16,6 +16,7 @@
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.tseries import tools
from pandas.util.decorators import Appender
@@ -143,6 +144,9 @@
warn_bad_lines: boolean, default True
If error_bad_lines is False, and warn_bad_lines is True, a warning for each
"bad line" will be output. (Only valid with C parser).
+infer_datetime_format : boolean, default False
+ If True and parse_dates is enabled for a column, attempt to infer
+ the datetime format to speed up the processing
Returns
-------
@@ -262,6 +266,7 @@ def _read(filepath_or_buffer, kwds):
'compression': None,
'mangle_dupe_cols': True,
'tupleize_cols': False,
+ 'infer_datetime_format': False,
}
@@ -349,7 +354,8 @@ def parser_f(filepath_or_buffer,
encoding=None,
squeeze=False,
mangle_dupe_cols=True,
- tupleize_cols=False):
+ tupleize_cols=False,
+ infer_datetime_format=False):
# Alias sep -> delimiter.
if delimiter is None:
@@ -408,7 +414,8 @@ def parser_f(filepath_or_buffer,
low_memory=low_memory,
buffer_lines=buffer_lines,
mangle_dupe_cols=mangle_dupe_cols,
- tupleize_cols=tupleize_cols)
+ tupleize_cols=tupleize_cols,
+ infer_datetime_format=infer_datetime_format)
return _read(filepath_or_buffer, kwds)
@@ -665,9 +672,13 @@ def __init__(self, kwds):
self.true_values = kwds.get('true_values')
self.false_values = kwds.get('false_values')
self.tupleize_cols = kwds.get('tupleize_cols', False)
+ self.infer_datetime_format = kwds.pop('infer_datetime_format', False)
- self._date_conv = _make_date_converter(date_parser=self.date_parser,
- dayfirst=self.dayfirst)
+ self._date_conv = _make_date_converter(
+ date_parser=self.date_parser,
+ dayfirst=self.dayfirst,
+ infer_datetime_format=self.infer_datetime_format
+ )
# validate header options for mi
self.header = kwds.get('header')
@@ -1178,6 +1189,10 @@ def TextParser(*args, **kwds):
Encoding to use for UTF when reading/writing (ex. 'utf-8')
squeeze : boolean, default False
returns Series if only one column
+ infer_datetime_format: boolean, default False
+ If True and `parse_dates` is True for a column, try to infer the
+ datetime format based on the first datetime string. If the format
+ can be inferred, there often will be a large parsing speed-up.
"""
kwds['engine'] = 'python'
return TextFileReader(*args, **kwds)
@@ -1870,13 +1885,19 @@ def _get_lines(self, rows=None):
return self._check_thousands(lines)
-def _make_date_converter(date_parser=None, dayfirst=False):
+def _make_date_converter(date_parser=None, dayfirst=False,
+ infer_datetime_format=False):
def converter(*date_cols):
if date_parser is None:
strs = _concat_date_cols(date_cols)
try:
- return tslib.array_to_datetime(com._ensure_object(strs),
- utc=None, dayfirst=dayfirst)
+ return tools.to_datetime(
+ com._ensure_object(strs),
+ utc=None,
+ box=False,
+ dayfirst=dayfirst,
+ infer_datetime_format=infer_datetime_format
+ )
except:
return lib.try_parse_dates(strs, dayfirst=dayfirst)
else:
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index bae93602cb840..8cce0162e0854 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -18,6 +18,7 @@
from pandas.core.daterange import DateRange
import pandas.core.datetools as datetools
import pandas.tseries.offsets as offsets
+import pandas.tseries.tools as tools
import pandas.tseries.frequencies as fmod
import pandas as pd
@@ -49,6 +50,11 @@ def _skip_if_no_pytz():
except ImportError:
raise nose.SkipTest("pytz not installed")
+def _skip_if_has_locale():
+ import locale
+ lang, _ = locale.getlocale()
+ if lang is not None:
+ raise nose.SkipTest("Specific locale is set {0}".format(lang))
class TestTimeSeriesDuplicates(tm.TestCase):
_multiprocess_can_split_ = True
@@ -909,12 +915,8 @@ def test_to_datetime_on_datetime64_series(self):
self.assertEquals(result[0], s[0])
def test_to_datetime_with_apply(self):
-
# this is only locale tested with US/None locales
- import locale
- (lang,encoding) = locale.getlocale()
- if lang is not None:
- raise nose.SkipTest("format codes cannot work with a locale of {0}".format(lang))
+ _skip_if_has_locale()
# GH 5195
# with a format and coerce a single item to_datetime fails
@@ -3124,6 +3126,177 @@ def test_date_range_fy5252(self):
self.assertEqual(dr[1], Timestamp('2014-01-30'))
+class TestToDatetimeInferFormat(tm.TestCase):
+ def test_to_datetime_infer_datetime_format_consistent_format(self):
+ time_series = pd.Series(
+ pd.date_range('20000101', periods=50, freq='H')
+ )
+
+ test_formats = [
+ '%m-%d-%Y',
+ '%m/%d/%Y %H:%M:%S.%f',
+ '%Y-%m-%dT%H:%M:%S.%f',
+ ]
+
+ for test_format in test_formats:
+ s_as_dt_strings = time_series.apply(
+ lambda x: x.strftime(test_format)
+ )
+
+ with_format = pd.to_datetime(s_as_dt_strings, format=test_format)
+ no_infer = pd.to_datetime(
+ s_as_dt_strings, infer_datetime_format=False
+ )
+ yes_infer = pd.to_datetime(
+ s_as_dt_strings, infer_datetime_format=True
+ )
+
+ # Whether the format is explicitly passed, it is inferred, or
+ # it is not inferred, the results should all be the same
+ self.assert_(np.array_equal(with_format, no_infer))
+ self.assert_(np.array_equal(no_infer, yes_infer))
+
+ def test_to_datetime_infer_datetime_format_inconsistent_format(self):
+ test_series = pd.Series(
+ np.array([
+ '01/01/2011 00:00:00',
+ '01-02-2011 00:00:00',
+ '2011-01-03T00:00:00',
+ ]))
+
+ # When the format is inconsistent, infer_datetime_format should just
+ # fallback to the default parsing
+ self.assert_(np.array_equal(
+ pd.to_datetime(test_series, infer_datetime_format=False),
+ pd.to_datetime(test_series, infer_datetime_format=True)
+ ))
+
+ test_series = pd.Series(
+ np.array([
+ 'Jan/01/2011',
+ 'Feb/01/2011',
+ 'Mar/01/2011',
+ ]))
+
+ self.assert_(np.array_equal(
+ pd.to_datetime(test_series, infer_datetime_format=False),
+ pd.to_datetime(test_series, infer_datetime_format=True)
+ ))
+
+ def test_to_datetime_infer_datetime_format_series_with_nans(self):
+ test_series = pd.Series(
+ np.array([
+ '01/01/2011 00:00:00',
+ np.nan,
+ '01/03/2011 00:00:00',
+ np.nan,
+ ]))
+
+ self.assert_(np.array_equal(
+ pd.to_datetime(test_series, infer_datetime_format=False),
+ pd.to_datetime(test_series, infer_datetime_format=True)
+ ))
+
+ def test_to_datetime_infer_datetime_format_series_starting_with_nans(self):
+ test_series = pd.Series(
+ np.array([
+ np.nan,
+ np.nan,
+ '01/01/2011 00:00:00',
+ '01/02/2011 00:00:00',
+ '01/03/2011 00:00:00',
+ ]))
+
+ self.assert_(np.array_equal(
+ pd.to_datetime(test_series, infer_datetime_format=False),
+ pd.to_datetime(test_series, infer_datetime_format=True)
+ ))
+
+
+class TestGuessDatetimeFormat(tm.TestCase):
+ def test_guess_datetime_format_with_parseable_formats(self):
+ dt_string_to_format = (
+ ('20111230', '%Y%m%d'),
+ ('2011-12-30', '%Y-%m-%d'),
+ ('30-12-2011', '%d-%m-%Y'),
+ ('2011-12-30 00:00:00', '%Y-%m-%d %H:%M:%S'),
+ ('2011-12-30T00:00:00', '%Y-%m-%dT%H:%M:%S'),
+ ('2011-12-30 00:00:00.000000', '%Y-%m-%d %H:%M:%S.%f'),
+ )
+
+ for dt_string, dt_format in dt_string_to_format:
+ self.assertEquals(
+ tools._guess_datetime_format(dt_string),
+ dt_format
+ )
+
+ def test_guess_datetime_format_with_dayfirst(self):
+ ambiguous_string = '01/01/2011'
+ self.assertEquals(
+ tools._guess_datetime_format(ambiguous_string, dayfirst=True),
+ '%d/%m/%Y'
+ )
+ self.assertEquals(
+ tools._guess_datetime_format(ambiguous_string, dayfirst=False),
+ '%m/%d/%Y'
+ )
+
+ def test_guess_datetime_format_with_locale_specific_formats(self):
+ # The month names will vary depending on the locale, in which
+ # case these wont be parsed properly (dateutil can't parse them)
+ _skip_if_has_locale()
+
+ dt_string_to_format = (
+ ('30/Dec/2011', '%d/%b/%Y'),
+ ('30/December/2011', '%d/%B/%Y'),
+ ('30/Dec/2011 00:00:00', '%d/%b/%Y %H:%M:%S'),
+ )
+
+ for dt_string, dt_format in dt_string_to_format:
+ self.assertEquals(
+ tools._guess_datetime_format(dt_string),
+ dt_format
+ )
+
+ def test_guess_datetime_format_invalid_inputs(self):
+ # A datetime string must include a year, month and a day for it
+ # to be guessable, in addition to being a string that looks like
+ # a datetime
+ invalid_dts = [
+ '2013',
+ '01/2013',
+ '12:00:00',
+ '1/1/1/1',
+ 'this_is_not_a_datetime',
+ '51a',
+ 9,
+ datetime(2011, 1, 1),
+ ]
+
+ for invalid_dt in invalid_dts:
+ self.assertTrue(tools._guess_datetime_format(invalid_dt) is None)
+
+ 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)
+
+ test_arrays = [
+ np.array([dt_string, dt_string, dt_string], dtype='O'),
+ np.array([np.nan, np.nan, dt_string], dtype='O'),
+ np.array([dt_string, 'random_string'], dtype='O'),
+ ]
+
+ for test_array in test_arrays:
+ self.assertEqual(
+ tools._guess_datetime_format_for_array(test_array),
+ expected_format
+ )
+
+ format_for_string_of_nans = tools._guess_datetime_format_for_array(
+ np.array([np.nan, np.nan, np.nan], dtype='O')
+ )
+ self.assertTrue(format_for_string_of_nans is None)
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)
diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py
index 2d4f27cb12ece..6761b5cbb04b0 100644
--- a/pandas/tseries/tools.py
+++ b/pandas/tseries/tools.py
@@ -24,6 +24,21 @@
print('Please install python-dateutil via easy_install or some method!')
raise # otherwise a 2nd import won't show the message
+_DATEUTIL_LEXER_SPLIT = None
+try:
+ # Since these are private methods from dateutil, it is safely imported
+ # here so in case this interface changes, pandas will just fallback
+ # to not using the functionality
+ from dateutil.parser import _timelex
+
+ if hasattr(_timelex, 'split'):
+ def _lexer_split_from_str(dt_str):
+ # The StringIO(str(_)) is for dateutil 2.2 compatibility
+ return _timelex.split(StringIO(str(dt_str)))
+
+ _DATEUTIL_LEXER_SPLIT = _lexer_split_from_str
+except (ImportError, AttributeError):
+ pass
def _infer_tzinfo(start, end):
def _infer(a, b):
@@ -50,9 +65,126 @@ def _maybe_get_tz(tz):
tz = pytz.FixedOffset(tz / 60)
return tz
+def _guess_datetime_format(dt_str, dayfirst=False,
+ dt_str_parse=compat.parse_date,
+ dt_str_split=_DATEUTIL_LEXER_SPLIT):
+ """
+ Guess the datetime format of a given datetime string.
+
+ Parameters
+ ----------
+ dt_str : string, datetime string to guess the format of
+ dayfirst : boolean, default False
+ If True parses dates with the day first, eg 20/01/2005
+ Warning: dayfirst=True is not strict, but will prefer to parse
+ with day first (this is a known bug).
+ dt_str_parse : function, defaults to `compate.parse_date` (dateutil)
+ This function should take in a datetime string and return
+ a `datetime.datetime` guess that the datetime string represents
+ dt_str_split : function, defaults to `_DATEUTIL_LEXER_SPLIT` (dateutil)
+ This function should take in a datetime string and return
+ a list of strings, the guess of the various specific parts
+ e.g. '2011/12/30' -> ['2011', '/', '12', '/', '30']
+
+ Returns
+ -------
+ ret : datetime formatt string (for `strftime` or `strptime`)
+ """
+ if dt_str_parse is None or dt_str_split is None:
+ return None
+
+ if not isinstance(dt_str, compat.string_types):
+ return None
+
+ day_attribute_and_format = (('day',), '%d')
+
+ datetime_attrs_to_format = [
+ (('year', 'month', 'day'), '%Y%m%d'),
+ (('year',), '%Y'),
+ (('month',), '%B'),
+ (('month',), '%b'),
+ (('month',), '%m'),
+ day_attribute_and_format,
+ (('hour',), '%H'),
+ (('minute',), '%M'),
+ (('second',), '%S'),
+ (('microsecond',), '%f'),
+ (('second', 'microsecond'), '%S.%f'),
+ ]
+
+ if dayfirst:
+ datetime_attrs_to_format.remove(day_attribute_and_format)
+ datetime_attrs_to_format.insert(0, day_attribute_and_format)
+
+ try:
+ parsed_datetime = dt_str_parse(dt_str, dayfirst=dayfirst)
+ except:
+ # In case the datetime can't be parsed, its format cannot be guessed
+ return None
+
+ if parsed_datetime is None:
+ return None
+
+ try:
+ tokens = dt_str_split(dt_str)
+ except:
+ # In case the datetime string can't be split, its format cannot
+ # be guessed
+ return None
+
+ format_guess = [None] * len(tokens)
+ found_attrs = set()
+
+ for attrs, attr_format 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)
+ if set(attrs) & found_attrs:
+ continue
+
+ if all(getattr(parsed_datetime, attr) is not None for attr in attrs):
+ for i, token_format in enumerate(format_guess):
+ if (token_format is None and
+ tokens[i] == parsed_datetime.strftime(attr_format)):
+ format_guess[i] = attr_format
+ found_attrs.update(attrs)
+ break
+
+ # Only consider it a valid guess if we have a year, month and day
+ if len(set(['year', 'month', 'day']) & found_attrs) != 3:
+ return None
+
+ output_format = []
+ for i, guess in enumerate(format_guess):
+ if guess is not None:
+ # Either fill in the format placeholder (like %Y)
+ output_format.append(guess)
+ else:
+ # Or just the token separate (IE, the dashes in "01-01-2013")
+ try:
+ # If the token is numeric, then we likely didn't parse it
+ # properly, so our guess is wrong
+ float(tokens[i])
+ return None
+ except ValueError:
+ pass
+
+ output_format.append(tokens[i])
+
+ guessed_format = ''.join(output_format)
+
+ if parsed_datetime.strftime(guessed_format) == dt_str:
+ return guessed_format
+
+def _guess_datetime_format_for_array(arr, **kwargs):
+ # Try to guess the format based on the first non-NaN element
+ non_nan_elements = com.notnull(arr).nonzero()[0]
+ if len(non_nan_elements):
+ return _guess_datetime_format(arr[non_nan_elements[0]], **kwargs)
def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True,
- format=None, coerce=False, unit='ns'):
+ format=None, coerce=False, unit='ns',
+ infer_datetime_format=False):
"""
Convert argument to datetime
@@ -75,6 +207,9 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True,
coerce : force errors to NaT (False by default)
unit : unit of the arg (D,s,ms,us,ns) denote the unit in epoch
(e.g. a unix timestamp), which is an integer/float number
+ infer_datetime_format: boolean, default False
+ If no `format` is given, try to infer the format based on the first
+ datetime string. Provides a large speed-up in many cases.
Returns
-------
@@ -98,7 +233,7 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True,
from pandas.core.series import Series
from pandas.tseries.index import DatetimeIndex
- def _convert_listlike(arg, box):
+ def _convert_listlike(arg, box, format):
if isinstance(arg, (list,tuple)):
arg = np.array(arg, dtype='O')
@@ -113,10 +248,26 @@ def _convert_listlike(arg, box):
return arg
arg = com._ensure_object(arg)
- try:
+
+ if infer_datetime_format and format is None:
+ format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst)
+
if format is not None:
- result = None
+ # There is a special fast-path for iso8601 formatted
+ # datetime strings, so in those cases don't use the inferred
+ # format because this path makes process slower in this
+ # special case
+ format_is_iso8601 = (
+ '%Y-%m-%dT%H:%M:%S.%f'.startswith(format) or
+ '%Y-%m-%d %H:%M:%S.%f'.startswith(format)
+ )
+ if format_is_iso8601:
+ format = None
+ try:
+ result = None
+
+ if format is not None:
# shortcut formatting here
if format == '%Y%m%d':
try:
@@ -127,15 +278,24 @@ def _convert_listlike(arg, box):
# fallback
if result is None:
try:
- result = tslib.array_strptime(arg, format, coerce=coerce)
+ result = tslib.array_strptime(
+ arg, format, coerce=coerce
+ )
except (tslib.OutOfBoundsDatetime):
if errors == 'raise':
raise
result = arg
- else:
+ except ValueError:
+ # Only raise this error if the user provided the
+ # datetime format, and not when it was inferred
+ if not infer_datetime_format:
+ raise
+
+ if result is None and (format is None or infer_datetime_format):
result = tslib.array_to_datetime(arg, raise_=errors == 'raise',
utc=utc, dayfirst=dayfirst,
coerce=coerce, unit=unit)
+
if com.is_datetime64_dtype(result) and box:
result = DatetimeIndex(result, tz='utc' if utc else None)
return result
@@ -152,12 +312,12 @@ def _convert_listlike(arg, box):
elif isinstance(arg, Timestamp):
return arg
elif isinstance(arg, Series):
- values = _convert_listlike(arg.values, box=False)
+ values = _convert_listlike(arg.values, False, format)
return Series(values, index=arg.index, name=arg.name)
elif com.is_list_like(arg):
- return _convert_listlike(arg, box=box)
+ return _convert_listlike(arg, box, format)
- return _convert_listlike(np.array([ arg ]), box=box)[0]
+ return _convert_listlike(np.array([ arg ]), box, format)[0]
class DateParseError(ValueError):
pass
diff --git a/vb_suite/io_bench.py b/vb_suite/io_bench.py
index 4fc14459e83f5..b70a060233dae 100644
--- a/vb_suite/io_bench.py
+++ b/vb_suite/io_bench.py
@@ -98,3 +98,36 @@ def create_cols(name):
frame_to_csv_date_formatting = Benchmark(stmt, setup,
start_date=datetime(2013, 9, 1))
+
+#----------------------------------------------------------------------
+# infer datetime format
+
+setup = common_setup + """
+rng = date_range('1/1/2000', periods=1000)
+data = '\\n'.join(rng.map(lambda x: x.strftime("%Y-%m-%d %H:%M:%S")))
+"""
+
+stmt = ("read_csv(StringIO(data), header=None, names=['foo'], "
+ " parse_dates=['foo'], infer_datetime_format=True)")
+
+read_csv_infer_datetime_format_iso8601 = Benchmark(stmt, setup)
+
+setup = common_setup + """
+rng = date_range('1/1/2000', periods=1000)
+data = '\\n'.join(rng.map(lambda x: x.strftime("%Y%m%d")))
+"""
+
+stmt = ("read_csv(StringIO(data), header=None, names=['foo'], "
+ " parse_dates=['foo'], infer_datetime_format=True)")
+
+read_csv_infer_datetime_format_ymd = Benchmark(stmt, setup)
+
+setup = common_setup + """
+rng = date_range('1/1/2000', periods=1000)
+data = '\\n'.join(rng.map(lambda x: x.strftime("%m/%d/%Y %H:%M:%S.%f")))
+"""
+
+stmt = ("read_csv(StringIO(data), header=None, names=['foo'], "
+ " parse_dates=['foo'], infer_datetime_format=True)")
+
+read_csv_infer_datetime_format_custom = Benchmark(stmt, setup)
| closes #5490
Basically this attempts to figure out the the datetime format if given a list of datetime strings. If the format can be guessed successfully, then to_datetime() attempts to use a faster way of processing the datetime strings.
Here is a gist that shows some timings of this function: https://gist.github.com/danbirken/8533199
If the format can be guessed, this generally speeds up the processing by 10x. In the case where the format string is guessed to be an iso8601 string or subset of that, then the format is _not_ used, because the iso8601 fast-path is much faster than this (about 30-40x faster).
I just did a pretty basic way of guessing the format using only dateutil.parse, a simple regex and some simple logic. This doesn't use any private methods of dateutil. It certainly can be improved, but I wanted to get something started first before I went crazy having to handle more advanced cases.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6021 | 2014-01-21T02:13:15Z | 2014-01-24T21:49:48Z | 2014-01-24T21:49:48Z | 2014-06-12T16:18:50Z |
DOC: make zipped HTML docs available GH1876 | diff --git a/doc/make.py b/doc/make.py
index 532395b41ce95..9d38fc2a3608f 100755
--- a/doc/make.py
+++ b/doc/make.py
@@ -103,7 +103,14 @@ def html():
if os.system('sphinx-build -P -b html -d build/doctrees '
'source build/html'):
raise SystemExit("Building HTML failed.")
-
+ try:
+ print("\nZipping up HTML docs...")
+ # just in case the wonky build box doesn't have zip
+ # don't fail this.
+ os.system('cd build; rm -f html/pandas.zip; zip html/pandas.zip -r -q html/* ')
+ print("\n")
+ except:
+ pass
def latex():
check_build()
diff --git a/doc/source/index.rst b/doc/source/index.rst
index 78b57795854fa..126a3ce08afe6 100644
--- a/doc/source/index.rst
+++ b/doc/source/index.rst
@@ -6,6 +6,8 @@ pandas: powerful Python data analysis toolkit
`PDF Version <pandas.pdf>`__
+`Zipped HTML <pandas.zip>`__
+
.. module:: pandas
**Date**: |today| **Version**: |version|
| closes #1876
| https://api.github.com/repos/pandas-dev/pandas/pulls/6020 | 2014-01-20T23:59:14Z | 2014-01-20T23:59:21Z | 2014-01-20T23:59:21Z | 2014-06-15T00:41:51Z |
Remove duplicated code and fix travis | diff --git a/ci/install.sh b/ci/install.sh
index 660b05932a5ec..cb0dff6e5c7d9 100755
--- a/ci/install.sh
+++ b/ci/install.sh
@@ -37,9 +37,9 @@ pip install wheel
# comment this line to disable the fetching of wheel files
base_url=http://cache27diy-cpycloud.rhcloud.com
wheel_box=${TRAVIS_PYTHON_VERSION}${JOB_TAG}
-PIP_ARGS+=" -I --use-wheel --find-links=$base_url/$wheel_box/"
+PIP_ARGS+=" -I --use-wheel --find-links=$base_url/$wheel_box/ --allow-external --allow-insecure"
-# Force virtualenv to accpet system_site_packages
+# Force virtualenv to accept system_site_packages
rm -f $VIRTUAL_ENV/lib/python$TRAVIS_PYTHON_VERSION/no-global-site-packages.txt
@@ -49,11 +49,12 @@ if [ -n "$LOCALE_OVERRIDE" ]; then
time sudo locale-gen "$LOCALE_OVERRIDE"
fi
-time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.txt
# we need these for numpy
time sudo apt-get $APT_ARGS install libatlas-base-dev gfortran
+time pip install $PIP_ARGS -r ci/requirements-${wheel_box}.txt
+
# 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
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 918043dcacd37..a5459bfb2ae8c 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1349,11 +1349,7 @@ def describe(self, percentile_width=50):
-------
desc : Series
"""
- try:
- from collections import Counter
- except ImportError: # pragma: no cover
- # For Python < 2.7, we include a local copy of this:
- from pandas.util.counter import Counter
+ from pandas.compat import Counter
if self.dtype == object:
names = ['count', 'unique']
diff --git a/pandas/util/counter.py b/pandas/util/counter.py
deleted file mode 100644
index 75f7b214ce6a5..0000000000000
--- a/pandas/util/counter.py
+++ /dev/null
@@ -1,296 +0,0 @@
-# This is copied from collections in Python 2.7, for compatibility with older
-# versions of Python. It can be dropped when we depend on Python 2.7/3.1
-
-from pandas import compat
-import heapq as _heapq
-from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
-from operator import itemgetter as _itemgetter
-from pandas.compat import map
-
-try:
- from collections import Mapping
-except:
- # ABCs were only introduced in Python 2.6, so this is a hack for Python 2.5
- Mapping = dict
-
-
-class Counter(dict):
- '''Dict subclass for counting hashable items. Sometimes called a bag
- or multiset. Elements are stored as dictionary keys and their counts
- are stored as dictionary values.
-
- >>> c = Counter('abcdeabcdabcaba') # count elements from a string
-
- >>> c.most_common(3) # three most common elements
- [('a', 5), ('b', 4), ('c', 3)]
- >>> sorted(c) # list all unique elements
- ['a', 'b', 'c', 'd', 'e']
- >>> ''.join(sorted(c.elements())) # list elements with repetitions
- 'aaaaabbbbcccdde'
- >>> sum(c.values()) # total of all counts
- 15
-
- >>> c['a'] # count of letter 'a'
- 5
- >>> for elem in 'shazam': # update counts from an iterable
- ... c[elem] += 1 # by adding 1 to each element's count
- >>> c['a'] # now there are seven 'a'
- 7
- >>> del c['b'] # remove all 'b'
- >>> c['b'] # now there are zero 'b'
- 0
-
- >>> d = Counter('simsalabim') # make another counter
- >>> c.update(d) # add in the second counter
- >>> c['a'] # now there are nine 'a'
- 9
-
- >>> c.clear() # empty the counter
- >>> c
- Counter()
-
- Note: If a count is set to zero or reduced to zero, it will remain
- in the counter until the entry is deleted or the counter is cleared:
-
- >>> c = Counter('aaabbc')
- >>> c['b'] -= 2 # reduce the count of 'b' by two
- >>> c.most_common() # 'b' is still in, but its count is zero
- [('a', 3), ('c', 1), ('b', 0)]
-
- '''
- # References:
- # http://en.wikipedia.org/wiki/Multiset
- # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
- # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
- # http://code.activestate.com/recipes/259174/
- # Knuth, TAOCP Vol. II section 4.6.3
-
- def __init__(self, iterable=None, **kwds):
- '''Create a new, empty Counter object. And if given, count elements
- from an input iterable. Or, initialize the count from another mapping
- of elements to their counts.
-
- >>> c = Counter() # a new, empty counter
- >>> c = Counter('gallahad') # a new counter from an iterable
- >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
- >>> c = Counter(a=4, b=2) # a new counter from keyword args
-
- '''
- super(Counter, self).__init__()
- self.update(iterable, **kwds)
-
- def __missing__(self, key):
- 'The count of elements not in the Counter is zero.'
- # Needed so that self[missing_item] does not raise KeyError
- return 0
-
- def most_common(self, n=None):
- '''List the n most common elements and their counts from the most
- common to the least. If n is None, then list all element counts.
-
- >>> Counter('abcdeabcdabcaba').most_common(3)
- [('a', 5), ('b', 4), ('c', 3)]
-
- '''
- # Emulate Bag.sortedByCount from Smalltalk
- if n is None:
- return sorted(compat.iteritems(self), key=_itemgetter(1), reverse=True)
- return _heapq.nlargest(n, compat.iteritems(self), key=_itemgetter(1))
-
- def elements(self):
- '''Iterator over elements repeating each as many times as its count.
-
- >>> c = Counter('ABCABC')
- >>> sorted(c.elements())
- ['A', 'A', 'B', 'B', 'C', 'C']
-
- # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
- >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
- >>> product = 1
- >>> for factor in prime_factors.elements(): # loop over factors
- ... product *= factor # and multiply them
- >>> product
- 1836
-
- Note, if an element's count has been set to zero or is a negative
- number, elements() will ignore it.
-
- '''
- # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
- return _chain.from_iterable(_starmap(_repeat, compat.iteritems(self)))
-
- # Override dict methods where necessary
-
- @classmethod
- def fromkeys(cls, iterable, v=None):
- # There is no equivalent method for counters because setting v=1
- # means that no element can have a count greater than one.
- raise NotImplementedError(
- 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
-
- def update(self, iterable=None, **kwds):
- '''Like dict.update() but add counts instead of replacing them.
-
- Source can be an iterable, a dictionary, or another Counter instance.
-
- >>> c = Counter('which')
- >>> c.update('witch') # add elements from another iterable
- >>> d = Counter('watch')
- >>> c.update(d) # add elements from another counter
- >>> c['h'] # four 'h' in which, witch, and watch
- 4
-
- '''
- # The regular dict.update() operation makes no sense here because the
- # replace behavior results in the some of original untouched counts
- # being mixed-in with all of the other counts for a mismash that
- # doesn't have a straight-forward interpretation in most counting
- # contexts. Instead, we implement straight-addition. Both the inputs
- # and outputs are allowed to contain zero and negative counts.
-
- if iterable is not None:
- if isinstance(iterable, Mapping):
- if self:
- self_get = self.get
- for elem, count in compat.iteritems(iterable):
- self[elem] = self_get(elem, 0) + count
- else:
- # fast path when counter is empty
- super(Counter, self).update(iterable)
- else:
- self_get = self.get
- for elem in iterable:
- self[elem] = self_get(elem, 0) + 1
- if kwds:
- self.update(kwds)
-
- def subtract(self, iterable=None, **kwds):
- '''Like dict.update() but subtracts counts instead of replacing them.
- Counts can be reduced below zero. Both the inputs and outputs are
- allowed to contain zero and negative counts.
-
- Source can be an iterable, a dictionary, or another Counter instance.
-
- >>> c = Counter('which')
- >>> c.subtract('witch') # subtract elements from another iterable
- >>> c.subtract(Counter('watch')) # subtract elements from another counter
- >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
- 0
- >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
- -1
-
- '''
- if iterable is not None:
- self_get = self.get
- if isinstance(iterable, Mapping):
- for elem, count in iterable.items():
- self[elem] = self_get(elem, 0) - count
- else:
- for elem in iterable:
- self[elem] = self_get(elem, 0) - 1
- if kwds:
- self.subtract(kwds)
-
- def copy(self):
- 'Return a shallow copy.'
- return self.__class__(self)
-
- def __reduce__(self):
- return self.__class__, (dict(self),)
-
- def __delitem__(self, elem):
- """
- Like dict.__delitem__() but does not raise KeyError for missing values.
- """
- if elem in self:
- super(Counter, self).__delitem__(elem)
-
- def __repr__(self):
- if not self:
- return '%s()' % self.__class__.__name__
- items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
- return '%s({%s})' % (self.__class__.__name__, items)
-
- # Multiset-style mathematical operations discussed in:
- # Knuth TAOCP Volume II section 4.6.3 exercise 19
- # and at http://en.wikipedia.org/wiki/Multiset
- #
- # Outputs guaranteed to only include positive counts.
- #
- # To strip negative and zero counts, add-in an empty counter:
- # c += Counter()
-
- def __add__(self, other):
- '''Add counts from two counters.
-
- >>> Counter('abbb') + Counter('bcc')
- Counter({'b': 4, 'c': 2, 'a': 1})
-
- '''
- if not isinstance(other, Counter):
- return NotImplemented
- result = Counter()
- for elem, count in self.items():
- newcount = count + other[elem]
- if newcount > 0:
- result[elem] = newcount
- for elem, count in other.items():
- if elem not in self and count > 0:
- result[elem] = count
- return result
-
- def __sub__(self, other):
- ''' Subtract count, but keep only results with positive counts.
-
- >>> Counter('abbbc') - Counter('bccd')
- Counter({'b': 2, 'a': 1})
-
- '''
- if not isinstance(other, Counter):
- return NotImplemented
- result = Counter()
- for elem, count in self.items():
- newcount = count - other[elem]
- if newcount > 0:
- result[elem] = newcount
- for elem, count in other.items():
- if elem not in self and count < 0:
- result[elem] = 0 - count
- return result
-
- def __or__(self, other):
- '''Union is the maximum of value in either of the input counters.
-
- >>> Counter('abbb') | Counter('bcc')
- Counter({'b': 3, 'c': 2, 'a': 1})
-
- '''
- if not isinstance(other, Counter):
- return NotImplemented
- result = Counter()
- for elem, count in self.items():
- other_count = other[elem]
- newcount = other_count if count < other_count else count
- if newcount > 0:
- result[elem] = newcount
- for elem, count in other.items():
- if elem not in self and count > 0:
- result[elem] = count
- return result
-
- def __and__(self, other):
- ''' Intersection is the minimum of corresponding counts.
-
- >>> Counter('abbb') & Counter('bcc')
- Counter({'b': 1})
-
- '''
- if not isinstance(other, Counter):
- return NotImplemented
- result = Counter()
- for elem, count in self.items():
- other_count = other[elem]
- newcount = count if count < other_count else other_count
- if newcount > 0:
- result[elem] = newcount
- return result
| No idea why all the travis builds didn't break sooner, only numpy < 1.8
apperently forgives missing atlas at compilation time? don't know.
six errors are a red herring.
closes #6006
| https://api.github.com/repos/pandas-dev/pandas/pulls/6017 | 2014-01-20T22:00:24Z | 2014-01-20T22:19:02Z | 2014-01-20T22:19:02Z | 2014-07-16T08:47:48Z |
ENH: Add sym_diff for index | diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index afeb3fcc7764c..e3ee7d7c64c44 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -1504,6 +1504,18 @@ operators:
a & b
a - b
+Also available is the ``sym_diff (^)`` operation, which returns elements
+that appear in either ``idx1`` or ``idx2`` but not both. This is
+equivalent to the Index created by ``(idx1 - idx2) + (idx2 - idx1)``,
+with duplicates dropped.
+
+.. ipython:: python
+
+ idx1 = Index([1, 2, 3, 4])
+ idx2 = Index([2, 3, 4, 5])
+ idx1.sym_diff(idx2)
+ idx1 ^ idx2
+
The ``isin`` method of Index objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 6e1632f036f38..93c9812524278 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -54,6 +54,7 @@ New features
~~~~~~~~~~~~
- Hexagonal bin plots from ``DataFrame.plot`` with ``kind='hexbin'`` (:issue:`5478`)
+- Added the ``sym_diff`` method to ``Index`` (:issue:`5543`)
API Changes
~~~~~~~~~~~
diff --git a/pandas/core/index.py b/pandas/core/index.py
index a4eca1216ea84..8798a4dca472b 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -866,6 +866,9 @@ def __and__(self, other):
def __or__(self, other):
return self.union(other)
+ def __xor__(self, other):
+ return self.sym_diff(other)
+
def union(self, other):
"""
Form the union of two Index objects and sorts if possible
@@ -973,16 +976,20 @@ def diff(self, other):
"""
Compute sorted set difference of two Index objects
+ Parameters
+ ----------
+ other : Index or array-like
+
+ Returns
+ -------
+ diff : Index
+
Notes
-----
One can do either of these and achieve the same result
>>> index - index2
>>> index.diff(index2)
-
- Returns
- -------
- diff : Index
"""
if not hasattr(other, '__iter__'):
@@ -1000,6 +1007,49 @@ def diff(self, other):
theDiff = sorted(set(self) - set(other))
return Index(theDiff, name=result_name)
+ def sym_diff(self, other, result_name=None):
+ """
+ Compute the sorted symmetric_difference of two Index objects.
+
+ Parameters
+ ----------
+
+ other : array-like
+ result_name : str
+
+ Returns
+ -------
+ sym_diff : Index
+
+ Notes
+ -----
+ ``sym_diff`` contains elements that appear in either ``idx1`` or
+ ``idx2`` but not both. Equivalent to the Index created by
+ ``(idx1 - idx2) + (idx2 - idx1)`` with duplicates dropped.
+
+ Examples
+ --------
+ >>> idx1 = Index([1, 2, 3, 4])
+ >>> idx2 = Index([2, 3, 4, 5])
+ >>> idx1.sym_diff(idx2)
+ Int64Index([1, 5], dtype='int64')
+
+ You can also use the ``^`` operator:
+
+ >>> idx1 ^ idx2
+ Int64Index([1, 5], dtype='int64')
+ """
+ if not hasattr(other, '__iter__'):
+ raise TypeError('Input must be iterable!')
+
+ if not isinstance(other, Index):
+ other = Index(other)
+ result_name = result_name or self.name
+
+ the_diff = sorted(set((self - other) + (other - self)))
+ return Index(the_diff, name=result_name)
+
+
def unique(self):
"""
Return array of unique values in the Index. Significantly faster than
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index f938066011e06..59cec4f733b82 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -471,6 +471,52 @@ def test_diff(self):
# non-iterable input
assertRaisesRegexp(TypeError, "iterable", first.diff, 0.5)
+ def test_symmetric_diff(self):
+ # smoke
+ idx1 = Index([1, 2, 3, 4], name='idx1')
+ idx2 = Index([2, 3, 4, 5])
+ result = idx1.sym_diff(idx2)
+ expected = Index([1, 5])
+ self.assert_(tm.equalContents(result, expected))
+ self.assert_(result.name is None)
+
+ # __xor__ syntax
+ expected = idx1 ^ idx2
+ self.assert_(tm.equalContents(result, expected))
+ self.assert_(result.name is None)
+
+ # multiIndex
+ idx1 = MultiIndex.from_tuples(self.tuples)
+ idx2 = MultiIndex.from_tuples([('foo', 1), ('bar', 3)])
+ result = idx1.sym_diff(idx2)
+ expected = MultiIndex.from_tuples([('bar', 2), ('baz', 3), ('bar', 3)])
+ self.assert_(tm.equalContents(result, expected))
+
+ # nans:
+ idx1 = Index([1, 2, np.nan])
+ idx2 = Index([0, 1, np.nan])
+ result = idx1.sym_diff(idx2)
+ expected = Index([0.0, np.nan, 2.0, np.nan]) # oddness with nans
+ nans = pd.isnull(expected)
+ self.assert_(pd.isnull(result[nans]).all())
+ self.assert_(tm.equalContents(result[~nans], expected[~nans]))
+
+ # other not an Index:
+ idx1 = Index([1, 2, 3, 4], name='idx1')
+ idx2 = np.array([2, 3, 4, 5])
+ expected = Index([1, 5])
+ result = idx1.sym_diff(idx2)
+ self.assert_(tm.equalContents(result, expected))
+ self.assertEquals(result.name, 'idx1')
+
+ result = idx1.sym_diff(idx2, result_name='new_name')
+ self.assert_(tm.equalContents(result, expected))
+ self.assertEquals(result.name, 'new_name')
+
+ # other isn't iterable
+ with tm.assertRaises(TypeError):
+ idx1 - 1
+
def test_pickle(self):
def testit(index):
pickled = pickle.dumps(index)
| Close https://github.com/pydata/pandas/issues/5543
If there's any interest for this in 0.14, here's the code.
Thoughts on the method name? A regular difference is `diff` so I want to be consistent with that. I figured it would be a bit weird to truncate `difference` to `diff` but not truncate `symmetric` to `sym` (or `symm`) so I went with `sym_diff` (python sets use `symmetric_difference`).
Also when writing the tests, I discovered that NaNs are _even_ weirder than I thought:
``` python
In [20]: idx = pd.Index([np.nan, 1, np.nan])
In [21]: sorted(set(idx))
Out[21]: [nan, 1.0, nan]
```
Seems like neither `set` nor `sorted` did anything. Anyway my PR should be consistent with this weirdness.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6016 | 2014-01-20T20:05:35Z | 2014-02-17T17:46:58Z | 2014-02-17T17:46:58Z | 2017-05-15T21:15:51Z |
BUG: changed io.wb.get_countries URL | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 90e440a80ac1c..0db9023301dab 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -102,6 +102,7 @@ Improvements to existing features
Bug Fixes
~~~~~~~~~
+ - Bug in ``io.wb.get_countries`` not including all countries (:issue:`6008`)
- Bug in Series replace with timestamp dict (:issue:`5797`)
- read_csv/read_table now respects the `prefix` kwarg (:issue:`5732`).
- Bug in selection with missing values via ``.ix`` from a duplicate indexed DataFrame failing (:issue:`5835`)
diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py
index 6bdb601897ca4..e6f6f13c6cd26 100644
--- a/doc/sphinxext/ipython_directive.py
+++ b/doc/sphinxext/ipython_directive.py
@@ -447,15 +447,11 @@ def process_input(self, data, input_prompt, lineno):
# context information
filename = self.state.document.current_source
lineno = self.state.document.current_line
- try:
- lineno -= 1
- except:
- pass
# output any exceptions raised during execution to stdout
# unless :okexcept: has been specified.
if not is_okexcept and "Traceback" in output:
- s = "\nException in %s at line %s:\n" % (filename, lineno)
+ s = "\nException in %s at block ending on line %s\n" % (filename, lineno)
sys.stdout.write('\n\n>>>'+'-'*73)
sys.stdout.write(s)
sys.stdout.write(output)
@@ -464,15 +460,16 @@ def process_input(self, data, input_prompt, lineno):
# output any warning raised during execution to stdout
# unless :okwarning: has been specified.
if not is_okwarning:
+ import textwrap
for w in ws:
- s = "\nWarning raised in %s at line %s:\n" % (filename, lineno)
+ s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
sys.stdout.write('\n\n>>>'+'-'*73)
sys.stdout.write(s)
sys.stdout.write('-'*76+'\n')
s=warnings.formatwarning(w.message, w.category,
w.filename, w.lineno, w.line)
- sys.stdout.write(s)
- sys.stdout.write('\n<<<' + '-'*73+'\n\n')
+ sys.stdout.write('\n'.join(textwrap.wrap(s,80)))
+ sys.stdout.write('\n<<<' + '-'*73+'\n')
self.cout.truncate(0)
return (ret, input_lines, output, is_doctest, decorator, image_file,
diff --git a/pandas/io/tests/test_wb.py b/pandas/io/tests/test_wb.py
index 9549372823af8..da0efacacc7de 100644
--- a/pandas/io/tests/test_wb.py
+++ b/pandas/io/tests/test_wb.py
@@ -1,19 +1,20 @@
import nose
+from nose.tools import assert_equal
import pandas
from pandas.compat import u
from pandas.util.testing import network
from pandas.util.testing import assert_frame_equal
from numpy.testing.decorators import slow
-from pandas.io.wb import search, download
+from pandas.io.wb import search, download, get_countries
import pandas.util.testing as tm
+
class TestWB(tm.TestCase):
@slow
@network
def test_wdi_search(self):
- raise nose.SkipTest
expected = {u('id'): {2634: u('GDPPCKD'),
4649: u('NY.GDP.PCAP.KD'),
@@ -30,11 +31,9 @@ def test_wdi_search(self):
expected.index = result.index
assert_frame_equal(result, expected)
-
@slow
@network
def test_wdi_download(self):
- raise nose.SkipTest
expected = {'GDPPCKN': {(u('United States'), u('2003')): u('40800.0735367688'), (u('Canada'), u('2004')): u('37857.1261134552'), (u('United States'), u('2005')): u('42714.8594790102'), (u('Canada'), u('2003')): u('37081.4575704003'), (u('United States'), u('2004')): u('41826.1728310667'), (u('Mexico'), u('2003')): u('72720.0691255285'), (u('Mexico'), u('2004')): u('74751.6003347038'), (u('Mexico'), u('2005')): u('76200.2154469437'), (u('Canada'), u('2005')): u('38617.4563629611')}, 'GDPPCKD': {(u('United States'), u('2003')): u('40800.0735367688'), (u('Canada'), u('2004')): u('34397.055116118'), (u('United States'), u('2005')): u('42714.8594790102'), (u('Canada'), u('2003')): u('33692.2812368928'), (u('United States'), u('2004')): u('41826.1728310667'), (u('Mexico'), u('2003')): u('7608.43848670658'), (u('Mexico'), u('2004')): u('7820.99026814334'), (u('Mexico'), u('2005')): u('7972.55364129367'), (u('Canada'), u('2005')): u('35087.8925933298')}}
expected = pandas.DataFrame(expected)
@@ -43,6 +42,13 @@ def test_wdi_download(self):
expected.index = result.index
assert_frame_equal(result, pandas.DataFrame(expected))
+ @slow
+ @network
+ def test_wdi_get_countries(self):
+
+ result = get_countries()
+ assert_equal(result[-1:].name, 'Zimbabwe')
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
diff --git a/pandas/io/wb.py b/pandas/io/wb.py
index 362b7b192f746..d815bb19ec8b8 100644
--- a/pandas/io/wb.py
+++ b/pandas/io/wb.py
@@ -106,7 +106,7 @@ def _get_data(indicator="NY.GNS.ICTR.GN.ZS", country='US',
def get_countries():
'''Query information about countries
'''
- url = 'http://api.worldbank.org/countries/all?format=json'
+ url = 'http://api.worldbank.org/countries/?per_page=1000&format=json'
with urlopen(url) as response:
data = response.read()
data = json.loads(data)[1]
| Only 50 countries show up for the get_countries() call in io.wb, rather than the 256 that actually exist. Looks like a typo in the [World Bank Documentation](http://data.worldbank.org/node/18). The workaround is to request 1000 countries. Running this change by @vincentarelbundock.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6008 | 2014-01-20T06:04:15Z | 2014-01-25T19:27:51Z | null | 2014-06-16T16:32:48Z |
API: clarify DataFrame.apply reduction on empty frames | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 2153c50155ad0..0d4c937d3bdd7 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -62,6 +62,9 @@ API Changes
when detecting chained assignment, related (:issue:`5938`)
- DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
- ``autocorrelation_plot`` now accepts ``**kwargs``. (:issue:`5623`)
+ - ``DataFrame.apply`` will use the ``reduce`` argument to determine whether a
+ ``Series`` or a ``DataFrame`` should be returned when the ``DataFrame`` is
+ empty (:issue:`6007`).
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 31004d24e56a6..98aedb902d898 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -18,6 +18,37 @@ There are several new or updated docs sections including:
API changes
~~~~~~~~~~~
+- ``DataFrame.apply`` will use the ``reduce`` argument to determine whether a
+ ``Series`` or a ``DataFrame`` should be returned when the ``DataFrame`` is
+ empty (:issue:`6007`).
+
+ Previously, calling ``DataFrame.apply`` an empty ``DataFrame`` would return
+ either a ``DataFrame`` if there were no columns, or the function being
+ applied would be called with an empty ``Series`` to guess whether a
+ ``Series`` or ``DataFrame`` should be returned:
+
+ .. ipython:: python
+
+ def applied_func(col):
+ print "Apply function being called with:", col
+ return col.sum()
+
+ import pandas as pd
+ empty = pd.DataFrame(columns=['a', 'b'])
+ empty.apply(applied_func)
+
+ Now, when ``apply`` is called on an empty ``DataFrame``: if the ``reduce``
+ argument is ``True`` a ``Series`` will returned, if it is ``False`` a
+ ``DataFrame`` will be returned, and if it is ``None`` (the default) the
+ function being applied will be called with an empty series to try and guess
+ the return type.
+
+ .. ipython:: python
+
+ empty.apply(applied_func, reduce=True)
+ empty.apply(applied_func, reduce=False)
+
+
Prior Version Deprecations/Changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 82bc3ac25f68a..ce66c92f7f64d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3362,14 +3362,15 @@ def diff(self, periods=1):
#----------------------------------------------------------------------
# Function application
- def apply(self, func, axis=0, broadcast=False, raw=False, reduce=True,
+ def apply(self, func, axis=0, broadcast=False, raw=False, reduce=None,
args=(), **kwds):
"""
Applies function along input axis of DataFrame.
Objects passed to functions are Series objects having index
either the DataFrame's index (axis=0) or the columns (axis=1).
- Return type depends on whether passed function aggregates
+ Return type depends on whether passed function aggregates, or the
+ reduce argument if the DataFrame is empty.
Parameters
----------
@@ -3381,8 +3382,14 @@ def apply(self, func, axis=0, broadcast=False, raw=False, reduce=True,
broadcast : boolean, default False
For aggregation functions, return object of same size with values
propagated
- reduce : boolean, default True
- Try to apply reduction procedures
+ reduce : boolean or None, default None
+ Try to apply reduction procedures. If the DataFrame is empty,
+ apply will use reduce to determine whether the result should be a
+ Series or a DataFrame. If reduce is None (the default), apply's
+ return value will be guessed by calling func an empty Series (note:
+ while guessing, exceptions raised by func will be ignored). If
+ reduce is True a Series will always be returned, and if False a
+ DataFrame will always be returned.
raw : boolean, default False
If False, convert each row or column into a Series. If raw=True the
passed function will receive ndarray objects instead. If you are
@@ -3407,15 +3414,15 @@ def apply(self, func, axis=0, broadcast=False, raw=False, reduce=True,
-------
applied : Series or DataFrame
"""
- if len(self.columns) == 0 and len(self.index) == 0:
- return self
-
axis = self._get_axis_number(axis)
if kwds or args and not isinstance(func, np.ufunc):
f = lambda x: func(x, *args, **kwds)
else:
f = func
+ if len(self.columns) == 0 and len(self.index) == 0:
+ return self._apply_empty_result(func, axis, reduce)
+
if isinstance(f, np.ufunc):
results = f(self.values)
return self._constructor(data=results, index=self.index,
@@ -3423,25 +3430,30 @@ def apply(self, func, axis=0, broadcast=False, raw=False, reduce=True,
else:
if not broadcast:
if not all(self.shape):
- # How to determine this better?
- is_reduction = False
- try:
- is_reduction = not isinstance(f(_EMPTY_SERIES), Series)
- except Exception:
- pass
-
- if is_reduction:
- return Series(NA, index=self._get_agg_axis(axis))
- else:
- return self.copy()
+ return self._apply_empty_result(func, axis, reduce)
if raw and not self._is_mixed_type:
return self._apply_raw(f, axis)
else:
+ if reduce is None:
+ reduce = True
return self._apply_standard(f, axis, reduce=reduce)
else:
return self._apply_broadcast(f, axis)
+ def _apply_empty_result(self, func, axis, reduce):
+ if reduce is None:
+ reduce = False
+ try:
+ reduce = not isinstance(func(_EMPTY_SERIES), Series)
+ except Exception:
+ pass
+
+ if reduce:
+ return Series(NA, index=self._get_agg_axis(axis))
+ else:
+ return self.copy()
+
def _apply_raw(self, func, axis):
try:
result = lib.reduce(self.values, func, axis=axis)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 3b6e4ba445ce0..6760653d10f3e 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -8978,6 +8978,22 @@ def test_apply_empty(self):
rs = xp.apply(lambda x: x['a'], axis=1)
assert_frame_equal(xp, rs)
+ # reduce with an empty DataFrame
+ x = []
+ result = self.empty.apply(x.append, axis=1, reduce=False)
+ assert_frame_equal(result, self.empty)
+ result = self.empty.apply(x.append, axis=1, reduce=True)
+ assert_series_equal(result, Series([]))
+
+ empty_with_cols = DataFrame(columns=['a', 'b', 'c'])
+ result = empty_with_cols.apply(x.append, axis=1, reduce=False)
+ assert_frame_equal(result, empty_with_cols)
+ result = empty_with_cols.apply(x.append, axis=1, reduce=True)
+ assert_series_equal(result, Series([]))
+
+ # Ensure that x.append hasn't been called
+ self.assertEqual(x, [])
+
def test_apply_standard_nonunique(self):
df = DataFrame(
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['a', 'a', 'c'])
| Add `is_reduction` argument to `DataFrame.apply` to avoid undefined behavior when `.apply` is called on an empty DataFrame when function being applied is only defined for valid inputs.
Currently, if the DataFrame is empty, a guess is made at the correct return value (either a `DataFrame` or a `Series`) by calling the function being applied with an empty Series as an argument:
``` python
if not all(self.shape):
# How to determine this better?
is_reduction = False
try:
is_reduction = not isinstance(f(_EMPTY_SERIES), Series)
except Exception:
pass
if is_reduction:
return Series(NA, index=self._get_agg_axis(axis))
else:
return self.copy()
```
For reduction functions which produce undefined results on unexpected input (ex, a function which doesn't expect an empty argument), this means that the the result of `apply` is also undefined.
This pull request adds an explicit `is_reduction` argument so that it's possible to explicitly control this otherwise undefined behavior.
**Update**: there has been the suggestion that the existing `reduce` argument should be used. Is this reasonable? The PR would be updated as follows:
- Remove the `is_reduction` argument
- Change the default value of `reduce` from `True` to `None` (to preserve the current behavior of checking the return value of the function being applied)
- In the case of an empty DataFrame, treat `reduce` in the same way that I'm currently treating `is_reduction`
- Otherwise treat `reduce` as normal
Ref:
- http://stackoverflow.com/q/21225608/71522
- http://stackoverflow.com/q/21225552/71522
| https://api.github.com/repos/pandas-dev/pandas/pulls/6007 | 2014-01-20T03:48:55Z | 2014-01-26T15:31:13Z | null | 2014-06-14T13:07:38Z |
TST: pytables test changes to work in 3.1rc1 | diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index e478f46a7345f..219281ac00840 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -226,24 +226,24 @@ def test_api(self):
_maybe_remove(store,'df')
store.append('df',df.iloc[:10],append=True,format='table')
store.append('df',df.iloc[10:],append=True,format='table')
- assert_frame_equal(read_hdf(path,'df'),df)
+ assert_frame_equal(store.select('df'),df)
# append to False
_maybe_remove(store,'df')
store.append('df',df.iloc[:10],append=False,format='table')
store.append('df',df.iloc[10:],append=True,format='table')
- assert_frame_equal(read_hdf(path,'df'),df)
+ assert_frame_equal(store.select('df'),df)
# formats
_maybe_remove(store,'df')
store.append('df',df.iloc[:10],append=False,format='table')
store.append('df',df.iloc[10:],append=True,format='table')
- assert_frame_equal(read_hdf(path,'df'),df)
+ assert_frame_equal(store.select('df'),df)
_maybe_remove(store,'df')
store.append('df',df.iloc[:10],append=False,format='table')
store.append('df',df.iloc[10:],append=True,format=None)
- assert_frame_equal(read_hdf(path,'df'),df)
+ assert_frame_equal(store.select('df'),df)
with ensure_clean_path(self.path) as path:
| https://api.github.com/repos/pandas-dev/pandas/pulls/6005 | 2014-01-19T20:34:31Z | 2014-01-19T20:49:08Z | 2014-01-19T20:49:08Z | 2014-06-25T08:30:09Z | |
BUG: possible fsync error when filno is negative (GH5999) | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index bc99417c67310..b49c1b94b32ac 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -568,7 +568,10 @@ def flush(self, fsync=False):
if self._handle is not None:
self._handle.flush()
if fsync:
- os.fsync(self._handle.fileno())
+ try:
+ os.fsync(self._handle.fileno())
+ except:
+ pass
def get(self, key):
"""
| closes #5999
| https://api.github.com/repos/pandas-dev/pandas/pulls/6004 | 2014-01-19T18:44:36Z | 2014-01-19T19:02:13Z | 2014-01-19T19:02:13Z | 2014-07-16T08:47:39Z |
DOC: update numpydoc to current master (commit 223df02530) | diff --git a/doc/sphinxext/MANIFEST.in b/doc/sphinxext/MANIFEST.in
deleted file mode 100755
index f88ed785c525f..0000000000000
--- a/doc/sphinxext/MANIFEST.in
+++ /dev/null
@@ -1,2 +0,0 @@
-recursive-include tests *.py
-include *.txt
diff --git a/doc/sphinxext/__init__.py b/doc/sphinxext/__init__.py
deleted file mode 100755
index ae9073bc4115f..0000000000000
--- a/doc/sphinxext/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from numpydoc import setup
diff --git a/doc/sphinxext/LICENSE.txt b/doc/sphinxext/numpydoc/LICENSE.txt
similarity index 97%
rename from doc/sphinxext/LICENSE.txt
rename to doc/sphinxext/numpydoc/LICENSE.txt
index e00efc31ec257..b15c699dcecaa 100755
--- a/doc/sphinxext/LICENSE.txt
+++ b/doc/sphinxext/numpydoc/LICENSE.txt
@@ -1,8 +1,6 @@
-------------------------------------------------------------------------------
The files
- numpydoc.py
- - autosummary.py
- - autosummary_generate.py
- docscrape.py
- docscrape_sphinx.py
- phantom_import.py
@@ -71,10 +69,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
- The files
- - only_directives.py
+ The file
- plot_directive.py
- originate from Matplotlib (http://matplotlib.sf.net/) which has
+ originates from Matplotlib (http://matplotlib.sf.net/) which has
the following license:
Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved.
diff --git a/doc/sphinxext/README.txt b/doc/sphinxext/numpydoc/README.rst
similarity index 79%
rename from doc/sphinxext/README.txt
rename to doc/sphinxext/numpydoc/README.rst
index f3d782c9557d4..89b9f2fd23e9b 100755
--- a/doc/sphinxext/README.txt
+++ b/doc/sphinxext/numpydoc/README.rst
@@ -14,17 +14,10 @@ The following extensions are available:
- ``numpydoc.traitsdoc``: For gathering documentation about Traits attributes.
- - ``numpydoc.plot_directives``: Adaptation of Matplotlib's ``plot::``
+ - ``numpydoc.plot_directive``: Adaptation of Matplotlib's ``plot::``
directive. Note that this implementation may still undergo severe
changes or eventually be deprecated.
- - ``numpydoc.only_directives``: (DEPRECATED)
-
- - ``numpydoc.autosummary``: (DEPRECATED) An ``autosummary::`` directive.
- Available in Sphinx 0.6.2 and (to-be) 1.0 as ``sphinx.ext.autosummary``,
- and it the Sphinx 1.0 version is recommended over that included in
- Numpydoc.
-
numpydoc
========
@@ -47,6 +40,12 @@ The following options can be set in conf.py:
Whether to show all members of a class in the Methods and Attributes
sections automatically.
+- numpydoc_class_members_toctree: bool
+
+ Whether to create a Sphinx table of contents for the lists of class
+ methods and attributes. If a table of contents is made, Sphinx expects
+ each entry to have a separate page.
+
- numpydoc_edit_link: bool (DEPRECATED -- edit your HTML template instead)
Whether to insert an edit link after docstrings.
diff --git a/doc/sphinxext/numpydoc/__init__.py b/doc/sphinxext/numpydoc/__init__.py
new file mode 100755
index 0000000000000..0fce2cf747e23
--- /dev/null
+++ b/doc/sphinxext/numpydoc/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import division, absolute_import, print_function
+
+from .numpydoc import setup
diff --git a/doc/sphinxext/comment_eater.py b/doc/sphinxext/numpydoc/comment_eater.py
similarity index 89%
rename from doc/sphinxext/comment_eater.py
rename to doc/sphinxext/numpydoc/comment_eater.py
index af1e21d7bb4ee..8cddd3305f0bc 100755
--- a/doc/sphinxext/comment_eater.py
+++ b/doc/sphinxext/numpydoc/comment_eater.py
@@ -1,25 +1,29 @@
-from cStringIO import StringIO
+from __future__ import division, absolute_import, print_function
+
+import sys
+if sys.version_info[0] >= 3:
+ from io import StringIO
+else:
+ from io import StringIO
+
import compiler
import inspect
import textwrap
import tokenize
-from compiler_unparse import unparse
+from .compiler_unparse import unparse
class Comment(object):
-
""" A comment block.
"""
is_comment = True
-
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
- # str : The text block including '#' character but not any leading
- # spaces.
+ # str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
@@ -31,15 +35,13 @@ def add(self, string, start, end, line):
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
- self.end_lineno, self.text)
+ self.end_lineno, self.text)
class NonComment(object):
-
""" A non-comment block of code.
"""
is_comment = False
-
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
@@ -54,14 +56,12 @@ def add(self, string, start, end, line):
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
- self.end_lineno)
+ self.end_lineno)
class CommentBlocker(object):
-
""" Pull out contiguous comment blocks.
"""
-
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
@@ -75,7 +75,11 @@ def __init__(self):
def process_file(self, file):
""" Process a file object.
"""
- for token in tokenize.generate_tokens(file.next):
+ if sys.version_info[0] >= 3:
+ nxt = file.__next__
+ else:
+ nxt = file.next
+ for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
@@ -160,6 +164,6 @@ def get_class_traits(klass):
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
- doc = strip_comment_marker(
- cb.search_for_comment(node.lineno, default=''))
+ doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
+
diff --git a/doc/sphinxext/compiler_unparse.py b/doc/sphinxext/numpydoc/compiler_unparse.py
similarity index 83%
rename from doc/sphinxext/compiler_unparse.py
rename to doc/sphinxext/numpydoc/compiler_unparse.py
index 8233e968071ec..8933a83db3f23 100755
--- a/doc/sphinxext/compiler_unparse.py
+++ b/doc/sphinxext/numpydoc/compiler_unparse.py
@@ -10,34 +10,35 @@
fixme: We may want to move to using _ast trees because the compiler for
them is about 6 times faster than compiler.compile.
"""
+from __future__ import division, absolute_import, print_function
import sys
-import cStringIO
from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add
+if sys.version_info[0] >= 3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
def unparse(ast, single_line_functions=False):
- s = cStringIO.StringIO()
+ s = StringIO()
UnparseCompilerAst(ast, s, single_line_functions)
return s.getvalue().lstrip()
-op_precedence = {
- 'compiler.ast.Power': 3, 'compiler.ast.Mul': 2, 'compiler.ast.Div': 2,
- 'compiler.ast.Add': 1, 'compiler.ast.Sub': 1}
-
+op_precedence = { 'compiler.ast.Power':3, 'compiler.ast.Mul':2, 'compiler.ast.Div':2,
+ 'compiler.ast.Add':1, 'compiler.ast.Sub':1 }
class UnparseCompilerAst:
-
""" Methods in this class recursively traverse an AST and
output source code for the abstract syntax; original formatting
is disregarged.
"""
- #
+ #########################################################################
# object interface.
- #
+ #########################################################################
- def __init__(self, tree, file=sys.stdout, single_line_functions=False):
+ def __init__(self, tree, file = sys.stdout, single_line_functions=False):
""" Unparser(tree, file=sys.stdout) -> None.
Print the source for tree to file.
@@ -50,16 +51,16 @@ def __init__(self, tree, file=sys.stdout, single_line_functions=False):
self._write("\n")
self.f.flush()
- #
+ #########################################################################
# Unparser private interface.
- #
+ #########################################################################
- # format, output, and dispatch methods ################################
+ ### format, output, and dispatch methods ################################
- def _fill(self, text=""):
+ def _fill(self, text = ""):
"Indent a piece of text, according to the current indentation level"
if self._do_indent:
- self._write("\n" + " " * self._indent + text)
+ self._write("\n"+" "*self._indent + text)
else:
self._write(text)
@@ -82,17 +83,19 @@ def _dispatch(self, tree):
for t in tree:
self._dispatch(t)
return
- meth = getattr(self, "_" + tree.__class__.__name__)
+ meth = getattr(self, "_"+tree.__class__.__name__)
if tree.__class__.__name__ == 'NoneType' and not self._do_indent:
return
meth(tree)
- #
+
+ #########################################################################
# compiler.ast unparsing methods.
#
# There should be one method per concrete grammar type. They are
# organized in alphabetical order.
- #
+ #########################################################################
+
def _Add(self, t):
self.__binary_op(t, '+')
@@ -100,7 +103,7 @@ def _And(self, t):
self._write(" (")
for i, node in enumerate(t.nodes):
self._dispatch(node)
- if i != len(t.nodes) - 1:
+ if i != len(t.nodes)-1:
self._write(") and (")
self._write(")")
@@ -108,7 +111,7 @@ def _AssAttr(self, t):
""" Handle assigning an attribute of an object
"""
self._dispatch(t.expr)
- self._write('.' + t.attrname)
+ self._write('.'+t.attrname)
def _Assign(self, t):
""" Expression Assignment such as "a = 1".
@@ -150,7 +153,7 @@ def _AugAssign(self, t):
self._fill()
self._dispatch(t.node)
- self._write(' ' + t.op + ' ')
+ self._write(' '+t.op+' ')
self._dispatch(t.expr)
if not self._do_indent:
self._write(';')
@@ -163,7 +166,7 @@ def _Bitand(self, t):
self._write("(")
self._dispatch(node)
self._write(")")
- if i != len(t.nodes) - 1:
+ if i != len(t.nodes)-1:
self._write(" & ")
def _Bitor(self, t):
@@ -174,7 +177,7 @@ def _Bitor(self, t):
self._write("(")
self._dispatch(node)
self._write(")")
- if i != len(t.nodes) - 1:
+ if i != len(t.nodes)-1:
self._write(" | ")
def _CallFunc(self, t):
@@ -184,23 +187,17 @@ def _CallFunc(self, t):
self._write("(")
comma = False
for e in t.args:
- if comma:
- self._write(", ")
- else:
- comma = True
+ if comma: self._write(", ")
+ else: comma = True
self._dispatch(e)
if t.star_args:
- if comma:
- self._write(", ")
- else:
- comma = True
+ if comma: self._write(", ")
+ else: comma = True
self._write("*")
self._dispatch(t.star_args)
if t.dstar_args:
- if comma:
- self._write(", ")
- else:
- comma = True
+ if comma: self._write(", ")
+ else: comma = True
self._write("**")
self._dispatch(t.dstar_args)
self._write(")")
@@ -224,11 +221,11 @@ def _Decorators(self, t):
def _Dict(self, t):
self._write("{")
- for i, (k, v) in enumerate(t.items):
+ for i, (k, v) in enumerate(t.items):
self._dispatch(k)
self._write(": ")
self._dispatch(v)
- if i < len(t.items) - 1:
+ if i < len(t.items)-1:
self._write(", ")
self._write("}")
@@ -251,12 +248,12 @@ def _From(self, t):
self._fill("from ")
self._write(t.modname)
self._write(" import ")
- for i, (name, asname) in enumerate(t.names):
+ for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
- self._write(" as " + asname)
+ self._write(" as "+asname)
def _Function(self, t):
""" Handle function definitions
@@ -264,15 +261,14 @@ def _Function(self, t):
if t.decorators is not None:
self._fill("@")
self._dispatch(t.decorators)
- self._fill("def " + t.name + "(")
- defaults = [None] * (
- len(t.argnames) - len(t.defaults)) + list(t.defaults)
+ self._fill("def "+t.name + "(")
+ defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults)
for i, arg in enumerate(zip(t.argnames, defaults)):
self._write(arg[0])
if arg[1] is not None:
self._write('=')
self._dispatch(arg[1])
- if i < len(t.argnames) - 1:
+ if i < len(t.argnames)-1:
self._write(', ')
self._write(")")
if self._single_func:
@@ -291,13 +287,13 @@ def _Getattr(self, t):
self._write(')')
else:
self._dispatch(t.expr)
-
- self._write('.' + t.attrname)
-
+
+ self._write('.'+t.attrname)
+
def _If(self, t):
self._fill()
-
- for i, (compare, code) in enumerate(t.tests):
+
+ for i, (compare,code) in enumerate(t.tests):
if i == 0:
self._write("if ")
else:
@@ -316,7 +312,7 @@ def _If(self, t):
self._dispatch(t.else_)
self._leave()
self._write("\n")
-
+
def _IfExp(self, t):
self._dispatch(t.then)
self._write(" if ")
@@ -331,13 +327,13 @@ def _Import(self, t):
""" Handle "import xyz.foo".
"""
self._fill("import ")
-
- for i, (name, asname) in enumerate(t.names):
+
+ for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
- self._write(" as " + asname)
+ self._write(" as "+asname)
def _Keyword(self, t):
""" Keyword value assignment within function calls and definitions.
@@ -345,12 +341,12 @@ def _Keyword(self, t):
self._write(t.name)
self._write("=")
self._dispatch(t.expr)
-
+
def _List(self, t):
self._write("[")
- for i, node in enumerate(t.nodes):
+ for i,node in enumerate(t.nodes):
self._dispatch(node)
- if i < len(t.nodes) - 1:
+ if i < len(t.nodes)-1:
self._write(", ")
self._write("]")
@@ -367,20 +363,20 @@ def _Name(self, t):
def _NoneType(self, t):
self._write("None")
-
+
def _Not(self, t):
self._write('not (')
self._dispatch(t.expr)
self._write(')')
-
+
def _Or(self, t):
self._write(" (")
for i, node in enumerate(t.nodes):
self._dispatch(node)
- if i != len(t.nodes) - 1:
+ if i != len(t.nodes)-1:
self._write(") or (")
self._write(")")
-
+
def _Pass(self, t):
self._write("pass\n")
@@ -392,10 +388,8 @@ def _Printnl(self, t):
self._write(", ")
comma = False
for node in t.nodes:
- if comma:
- self._write(', ')
- else:
- comma = True
+ if comma: self._write(', ')
+ else: comma = True
self._dispatch(node)
def _Power(self, t):
@@ -405,7 +399,7 @@ def _Return(self, t):
self._fill("return ")
if t.value:
if isinstance(t.value, Tuple):
- text = ', '.join([name.name for name in t.value.asList()])
+ text = ', '.join([ name.name for name in t.value.asList() ])
self._write(text)
else:
self._dispatch(t.value)
@@ -420,7 +414,7 @@ def _Slice(self, t):
self._write(":")
if t.upper:
self._dispatch(t.upper)
- # if t.step:
+ #if t.step:
# self._write(":")
# self._dispatch(t.step)
self._write("]")
@@ -463,7 +457,7 @@ def _TryExcept(self, t):
self._enter()
self._dispatch(handler[2])
self._leave()
-
+
if t.else_:
self._fill("else")
self._enter()
@@ -488,14 +482,14 @@ def _Tuple(self, t):
self._dispatch(last_element)
self._write(")")
-
+
def _UnaryAdd(self, t):
self._write("+")
self._dispatch(t.expr)
-
+
def _UnarySub(self, t):
self._write("-")
- self._dispatch(t.expr)
+ self._dispatch(t.expr)
def _With(self, t):
self._fill('with ')
@@ -507,7 +501,7 @@ def _With(self, t):
self._dispatch(t.body)
self._leave()
self._write('\n')
-
+
def _int(self, t):
self._write(repr(t))
@@ -516,7 +510,7 @@ def __binary_op(self, t, symbol):
has_paren = False
left_class = str(t.left.__class__)
if (left_class in op_precedence.keys() and
- op_precedence[left_class] < op_precedence[str(t.__class__)]):
+ op_precedence[left_class] < op_precedence[str(t.__class__)]):
has_paren = True
if has_paren:
self._write('(')
@@ -529,7 +523,7 @@ def __binary_op(self, t, symbol):
has_paren = False
right_class = str(t.right.__class__)
if (right_class in op_precedence.keys() and
- op_precedence[right_class] < op_precedence[str(t.__class__)]):
+ op_precedence[right_class] < op_precedence[str(t.__class__)]):
has_paren = True
if has_paren:
self._write('(')
@@ -544,18 +538,18 @@ def _float(self, t):
def _str(self, t):
self._write(repr(t))
-
+
def _tuple(self, t):
self._write(str(t))
- #
+ #########################################################################
# These are the methods from the _ast modules unparse.
#
# As our needs to handle more advanced code increase, we may want to
# modify some of the methods below so that they work for compiler.ast.
- #
+ #########################################################################
-# stmt
+# # stmt
# def _Expr(self, tree):
# self._fill()
# self._dispatch(tree.value)
@@ -572,18 +566,18 @@ def _tuple(self, t):
# if a.asname:
# self._write(" as "+a.asname)
#
-# def _ImportFrom(self, t):
-# self._fill("from ")
-# self._write(t.module)
-# self._write(" import ")
-# for i, a in enumerate(t.names):
-# if i == 0:
-# self._write(", ")
-# self._write(a.name)
-# if a.asname:
-# self._write(" as "+a.asname)
-# XXX(jpe) what is level for?
-#
+## def _ImportFrom(self, t):
+## self._fill("from ")
+## self._write(t.module)
+## self._write(" import ")
+## for i, a in enumerate(t.names):
+## if i == 0:
+## self._write(", ")
+## self._write(a.name)
+## if a.asname:
+## self._write(" as "+a.asname)
+## # XXX(jpe) what is level for?
+##
#
# def _Break(self, t):
# self._fill("break")
@@ -725,10 +719,10 @@ def _tuple(self, t):
# self._dispatch(t.orelse)
# self._leave
#
-# expr
+# # expr
# def _Str(self, tree):
# self._write(repr(tree.s))
-#
+##
# def _Repr(self, t):
# self._write("`")
# self._dispatch(t.value)
@@ -799,31 +793,31 @@ def _tuple(self, t):
# self._write(".")
# self._write(t.attr)
#
-# def _Call(self, t):
-# self._dispatch(t.func)
-# self._write("(")
-# comma = False
-# for e in t.args:
-# if comma: self._write(", ")
-# else: comma = True
-# self._dispatch(e)
-# for e in t.keywords:
-# if comma: self._write(", ")
-# else: comma = True
-# self._dispatch(e)
-# if t.starargs:
-# if comma: self._write(", ")
-# else: comma = True
-# self._write("*")
-# self._dispatch(t.starargs)
-# if t.kwargs:
-# if comma: self._write(", ")
-# else: comma = True
-# self._write("**")
-# self._dispatch(t.kwargs)
-# self._write(")")
-#
-# slice
+## def _Call(self, t):
+## self._dispatch(t.func)
+## self._write("(")
+## comma = False
+## for e in t.args:
+## if comma: self._write(", ")
+## else: comma = True
+## self._dispatch(e)
+## for e in t.keywords:
+## if comma: self._write(", ")
+## else: comma = True
+## self._dispatch(e)
+## if t.starargs:
+## if comma: self._write(", ")
+## else: comma = True
+## self._write("*")
+## self._dispatch(t.starargs)
+## if t.kwargs:
+## if comma: self._write(", ")
+## else: comma = True
+## self._write("**")
+## self._dispatch(t.kwargs)
+## self._write(")")
+#
+# # slice
# def _Index(self, t):
# self._dispatch(t.value)
#
@@ -833,7 +827,7 @@ def _tuple(self, t):
# self._write(': ')
# self._dispatch(d)
#
-# others
+# # others
# def _arguments(self, t):
# first = True
# nonDef = len(t.args)-len(t.defaults)
@@ -856,13 +850,16 @@ def _tuple(self, t):
# else: self._write(", ")
# self._write("**"+t.kwarg)
#
-# def _keyword(self, t):
-# self._write(t.arg)
-# self._write("=")
-# self._dispatch(t.value)
+## def _keyword(self, t):
+## self._write(t.arg)
+## self._write("=")
+## self._dispatch(t.value)
#
# def _Lambda(self, t):
# self._write("lambda ")
# self._dispatch(t.args)
# self._write(": ")
# self._dispatch(t.body)
+
+
+
diff --git a/doc/sphinxext/docscrape.py b/doc/sphinxext/numpydoc/docscrape.py
similarity index 79%
rename from doc/sphinxext/docscrape.py
rename to doc/sphinxext/numpydoc/docscrape.py
index a8323c2c74361..4ee0f2e400d0e 100755
--- a/doc/sphinxext/docscrape.py
+++ b/doc/sphinxext/numpydoc/docscrape.py
@@ -1,21 +1,20 @@
"""Extract reference documentation from the NumPy source tree.
"""
+from __future__ import division, absolute_import, print_function
import inspect
import textwrap
import re
import pydoc
-from StringIO import StringIO
from warnings import warn
import collections
-class Reader(object):
+class Reader(object):
"""A line-based string reader.
"""
-
def __init__(self, data):
"""
Parameters
@@ -24,10 +23,10 @@ def __init__(self, data):
String with lines separated by '\n'.
"""
- if isinstance(data, list):
+ if isinstance(data,list):
self._str = data
else:
- self._str = data.split('\n') # store string as list of lines
+ self._str = data.split('\n') # store string as list of lines
self.reset()
@@ -35,7 +34,7 @@ def __getitem__(self, n):
return self._str[n]
def reset(self):
- self._l = 0 # current line nr
+ self._l = 0 # current line nr
def read(self):
if not self.eof():
@@ -62,12 +61,11 @@ def read_to_condition(self, condition_func):
return self[start:self._l]
self._l += 1
if self.eof():
- return self[start:self._l + 1]
+ return self[start:self._l+1]
return []
def read_to_next_empty_line(self):
self.seek_next_non_empty_line()
-
def is_empty(line):
return not line.strip()
return self.read_to_condition(is_empty)
@@ -77,7 +75,7 @@ def is_unindented(line):
return (line.strip() and (len(line.lstrip()) == len(line)))
return self.read_to_condition(is_unindented)
- def peek(self, n=0):
+ def peek(self,n=0):
if self._l + n < len(self._str):
return self[self._l + n]
else:
@@ -88,7 +86,6 @@ def is_empty(self):
class NumpyDocString(object):
-
def __init__(self, docstring, config={}):
docstring = textwrap.dedent(docstring).split('\n')
@@ -110,15 +107,15 @@ def __init__(self, docstring, config={}):
'References': '',
'Examples': '',
'index': {}
- }
+ }
self._parse()
- def __getitem__(self, key):
+ def __getitem__(self,key):
return self._parsed_data[key]
- def __setitem__(self, key, val):
- if not self._parsed_data.has_key(key):
+ def __setitem__(self,key,val):
+ if key not in self._parsed_data:
warn("Unknown section %s" % key)
else:
self._parsed_data[key] = val
@@ -134,27 +131,25 @@ def _is_at_section(self):
if l1.startswith('.. index::'):
return True
- l2 = self._doc.peek(1).strip() # ---------- or ==========
- return l2.startswith('-' * len(l1)) or l2.startswith('=' * len(l1))
+ l2 = self._doc.peek(1).strip() # ---------- or ==========
+ return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))
- def _strip(self, doc):
+ def _strip(self,doc):
i = 0
j = 0
- for i, line in enumerate(doc):
- if line.strip():
- break
+ for i,line in enumerate(doc):
+ if line.strip(): break
- for j, line in enumerate(doc[::-1]):
- if line.strip():
- break
+ for j,line in enumerate(doc[::-1]):
+ if line.strip(): break
- return doc[i:len(doc) - j]
+ return doc[i:len(doc)-j]
def _read_to_next_section(self):
section = self._doc.read_to_next_empty_line()
while not self._is_at_section() and not self._doc.eof():
- if not self._doc.peek(-1).strip(): # previous line was empty
+ if not self._doc.peek(-1).strip(): # previous line was empty
section += ['']
section += self._doc.read_to_next_empty_line()
@@ -166,14 +161,14 @@ def _read_sections(self):
data = self._read_to_next_section()
name = data[0].strip()
- if name.startswith('..'): # index section
+ if name.startswith('..'): # index section
yield name, data[1:]
elif len(data) < 2:
yield StopIteration
else:
yield name, self._strip(data[2:])
- def _parse_param_list(self, content):
+ def _parse_param_list(self,content):
r = Reader(content)
params = []
while not r.eof():
@@ -186,13 +181,13 @@ def _parse_param_list(self, content):
desc = r.read_to_next_unindented_line()
desc = dedent_lines(desc)
- params.append((arg_name, arg_type, desc))
+ params.append((arg_name,arg_type,desc))
return params
+
_name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X)
-
def _parse_see_also(self, content):
"""
func_name : Descriptive text
@@ -225,8 +220,7 @@ def push_item(name, rest):
rest = []
for line in content:
- if not line.strip():
- continue
+ if not line.strip(): continue
m = self._name_rgx.match(line)
if m and line[m.end():].strip().startswith(':'):
@@ -273,13 +267,17 @@ def _parse_summary(self):
if self._is_at_section():
return
- summary = self._doc.read_to_next_empty_line()
- summary_str = " ".join([s.strip() for s in summary]).strip()
- if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str):
- self['Signature'] = summary_str
- if not self._is_at_section():
- self['Summary'] = self._doc.read_to_next_empty_line()
- else:
+ # If several signatures present, take the last one
+ while True:
+ summary = self._doc.read_to_next_empty_line()
+ summary_str = " ".join([s.strip() for s in summary]).strip()
+ if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str):
+ self['Signature'] = summary_str
+ if not self._is_at_section():
+ continue
+ break
+
+ if summary is not None:
self['Summary'] = summary
if not self._is_at_section():
@@ -289,12 +287,11 @@ def _parse(self):
self._doc.reset()
self._parse_summary()
- for (section, content) in self._read_sections():
+ for (section,content) in self._read_sections():
if not section.startswith('..'):
- section = ' '.join([s.capitalize()
- for s in section.split(' ')])
- if section in ('Parameters', 'Attributes', 'Methods',
- 'Returns', 'Raises', 'Warns'):
+ section = ' '.join([s.capitalize() for s in section.split(' ')])
+ if section in ('Parameters', 'Returns', 'Raises', 'Warns',
+ 'Other Parameters', 'Attributes', 'Methods'):
self[section] = self._parse_param_list(content)
elif section.startswith('.. index::'):
self['index'] = self._parse_index(section, content)
@@ -306,17 +303,17 @@ def _parse(self):
# string conversion routines
def _str_header(self, name, symbol='-'):
- return [name, len(name) * symbol]
+ return [name, len(name)*symbol]
def _str_indent(self, doc, indent=4):
out = []
for line in doc:
- out += [' ' * indent + line]
+ out += [' '*indent + line]
return out
def _str_signature(self):
if self['Signature']:
- return [self['Signature'].replace('*', '\*')] + ['']
+ return [self['Signature'].replace('*','\*')] + ['']
else:
return ['']
@@ -336,8 +333,11 @@ def _str_param_list(self, name):
out = []
if self[name]:
out += self._str_header(name)
- for param, param_type, desc in self[name]:
- out += ['%s : %s' % (param, param_type)]
+ for param,param_type,desc in self[name]:
+ if param_type:
+ out += ['%s : %s' % (param, param_type)]
+ else:
+ out += [param]
out += self._str_indent(desc)
out += ['']
return out
@@ -351,8 +351,7 @@ def _str_section(self, name):
return out
def _str_see_also(self, func_role):
- if not self['See Also']:
- return []
+ if not self['See Also']: return []
out = []
out += self._str_header("See Also")
last_had_desc = True
@@ -379,8 +378,8 @@ def _str_see_also(self, func_role):
def _str_index(self):
idx = self['index']
out = []
- out += ['.. index:: %s' % idx.get('default', '')]
- for section, references in idx.iteritems():
+ out += ['.. index:: %s' % idx.get('default','')]
+ for section, references in idx.items():
if section == 'default':
continue
out += [' :%s: %s' % (section, ', '.join(references))]
@@ -391,11 +390,12 @@ def __str__(self, func_role=''):
out += self._str_signature()
out += self._str_summary()
out += self._str_extended_summary()
- for param_list in ('Parameters', 'Returns', 'Raises'):
+ for param_list in ('Parameters', 'Returns', 'Other Parameters',
+ 'Raises', 'Warns'):
out += self._str_param_list(param_list)
out += self._str_section('Warnings')
out += self._str_see_also(func_role)
- for s in ('Notes', 'References', 'Examples'):
+ for s in ('Notes','References','Examples'):
out += self._str_section(s)
for param_list in ('Attributes', 'Methods'):
out += self._str_param_list(param_list)
@@ -403,28 +403,25 @@ def __str__(self, func_role=''):
return '\n'.join(out)
-def indent(str, indent=4):
- indent_str = ' ' * indent
+def indent(str,indent=4):
+ indent_str = ' '*indent
if str is None:
return indent_str
lines = str.split('\n')
return '\n'.join(indent_str + l for l in lines)
-
def dedent_lines(lines):
"""Deindent a list of lines maximally"""
return textwrap.dedent("\n".join(lines)).split("\n")
-
def header(text, style='-'):
- return text + '\n' + style * len(text) + '\n'
+ return text + '\n' + style*len(text) + '\n'
class FunctionDoc(NumpyDocString):
-
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
- self._role = role # e.g. "func" or "meth"
+ self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
@@ -438,9 +435,9 @@ def __init__(self, func, role='func', doc=None, config={}):
# try to read signature
argspec = inspect.getargspec(func)
argspec = inspect.formatargspec(*argspec)
- argspec = argspec.replace('*', '\*')
+ argspec = argspec.replace('*','\*')
signature = '%s%s' % (func_name, argspec)
- except TypeError, e:
+ except TypeError as e:
signature = '%s()' % func_name
self['Signature'] = signature
@@ -462,9 +459,9 @@ def __str__(self):
'meth': 'method'}
if self._role:
- if not roles.has_key(self._role):
+ if self._role not in roles:
print("Warning: invalid role %s" % self._role)
- out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''),
+ out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''),
func_name)
out += super(FunctionDoc, self).__str__(func_role=self._role)
@@ -493,12 +490,19 @@ def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
NumpyDocString.__init__(self, doc)
if config.get('show_class_members', True):
- if not self['Methods']:
- self['Methods'] = [(name, '', '')
- for name in sorted(self.methods)]
- if not self['Attributes']:
- self['Attributes'] = [(name, '', '')
- for name in sorted(self.properties)]
+ def splitlines_x(s):
+ if not s:
+ return []
+ else:
+ return s.splitlines()
+
+ for field, items in [('Methods', self.methods),
+ ('Attributes', self.properties)]:
+ if not self[field]:
+ self[field] = [
+ (name, '',
+ splitlines_x(pydoc.getdoc(getattr(self._cls, name))))
+ for name in sorted(items)]
@property
def methods(self):
@@ -516,4 +520,4 @@ def properties(self):
return [name for name,func in inspect.getmembers(self._cls)
if not name.startswith('_') and
(func is None or isinstance(func, property) or
- inspect.isgetsetdescriptor(func))]
\ No newline at end of file
+ inspect.isgetsetdescriptor(func))]
diff --git a/doc/sphinxext/docscrape_sphinx.py b/doc/sphinxext/numpydoc/docscrape_sphinx.py
similarity index 66%
rename from doc/sphinxext/docscrape_sphinx.py
rename to doc/sphinxext/numpydoc/docscrape_sphinx.py
index cf3873c3a5f0c..ba93b2eab779d 100755
--- a/doc/sphinxext/docscrape_sphinx.py
+++ b/doc/sphinxext/numpydoc/docscrape_sphinx.py
@@ -1,17 +1,25 @@
-import re
-import inspect
-import textwrap
-import pydoc
+from __future__ import division, absolute_import, print_function
+
+import sys, re, inspect, textwrap, pydoc
import sphinx
-from docscrape import NumpyDocString, FunctionDoc, ClassDoc
+import collections
+from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
+if sys.version_info[0] >= 3:
+ sixu = lambda s: s
+else:
+ sixu = lambda s: unicode(s, 'unicode_escape')
-class SphinxDocString(NumpyDocString):
+class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config={}):
- self.use_plots = config.get('use_plots', False)
+ # Subclasses seemingly do not call this.
NumpyDocString.__init__(self, docstring, config=config)
+ def load_config(self, config):
+ self.use_plots = config.get('use_plots', False)
+ self.class_members_toctree = config.get('class_members_toctree', True)
+
# string conversion routines
def _str_header(self, name, symbol='`'):
return ['.. rubric:: ' + name, '']
@@ -22,7 +30,7 @@ def _str_field_list(self, name):
def _str_indent(self, doc, indent=4):
out = []
for line in doc:
- out += [' ' * indent + line]
+ out += [' '*indent + line]
return out
def _str_signature(self):
@@ -38,16 +46,37 @@ def _str_summary(self):
def _str_extended_summary(self):
return self['Extended Summary'] + ['']
+ def _str_returns(self):
+ out = []
+ if self['Returns']:
+ out += self._str_field_list('Returns')
+ out += ['']
+ for param, param_type, desc in self['Returns']:
+ if param_type:
+ out += self._str_indent(['**%s** : %s' % (param.strip(),
+ param_type)])
+ else:
+ out += self._str_indent([param.strip()])
+ if desc:
+ out += ['']
+ out += self._str_indent(desc, 8)
+ out += ['']
+ return out
+
def _str_param_list(self, name):
out = []
if self[name]:
out += self._str_field_list(name)
out += ['']
for param, param_type, desc in self[name]:
- out += self._str_indent(['**%s** : %s' % (param.strip(),
- param_type)])
- out += ['']
- out += self._str_indent(desc, 8)
+ if param_type:
+ out += self._str_indent(['**%s** : %s' % (param.strip(),
+ param_type)])
+ else:
+ out += self._str_indent(['**%s**' % param.strip()])
+ if desc:
+ out += ['']
+ out += self._str_indent(desc, 8)
out += ['']
return out
@@ -77,25 +106,36 @@ def _str_member_list(self, name):
others = []
for param, param_type, desc in self[name]:
param = param.strip()
- if not self._obj or hasattr(self._obj, param):
+
+ # Check if the referenced member can have a docstring or not
+ param_obj = getattr(self._obj, param, None)
+ if not (callable(param_obj)
+ or isinstance(param_obj, property)
+ 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))
if autosum:
- out += ['.. autosummary::', ' :toctree:', '']
- out += autosum
+ out += ['.. autosummary::']
+ if self.class_members_toctree:
+ out += [' :toctree:']
+ out += [''] + autosum
if others:
- maxlen_0 = max([len(x[0]) for x in others])
- maxlen_1 = max([len(x[1]) for x in others])
- hdr = "=" * maxlen_0 + " " + "=" * maxlen_1 + " " + "=" * 10
- fmt = '%%%ds %%%ds ' % (maxlen_0, maxlen_1)
- n_indent = maxlen_0 + maxlen_1 + 4
- out += [hdr]
+ maxlen_0 = max(3, max([len(x[0]) for x in others]))
+ hdr = sixu("=")*maxlen_0 + sixu(" ") + sixu("=")*10
+ fmt = sixu('%%%ds %%s ') % (maxlen_0,)
+ out += ['', hdr]
for param, param_type, desc in others:
- out += [fmt % (param.strip(), param_type)]
- out += self._str_indent(desc, n_indent)
+ desc = sixu(" ").join(x.strip() for x in desc).strip()
+ if param_type:
+ desc = "(%s) %s" % (param_type, desc)
+ out += [fmt % (param.strip(), desc)]
out += [hdr]
out += ['']
return out
@@ -131,8 +171,8 @@ def _str_index(self):
if len(idx) == 0:
return out
- out += ['.. index:: %s' % idx.get('default', '')]
- for section, references in idx.iteritems():
+ out += ['.. index:: %s' % idx.get('default','')]
+ for section, references in idx.items():
if section == 'default':
continue
elif section == 'refguide':
@@ -152,9 +192,9 @@ def _str_references(self):
# Latex collects all references to a separate bibliography,
# so we need to insert links to it
if sphinx.__version__ >= "0.6":
- out += ['.. only:: latex', '']
+ out += ['.. only:: latex','']
else:
- out += ['.. latexonly::', '']
+ out += ['.. latexonly::','']
items = []
for line in self['References']:
m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I)
@@ -183,7 +223,9 @@ def __str__(self, indent=0, func_role="obj"):
out += self._str_index() + ['']
out += self._str_summary()
out += self._str_extended_summary()
- for param_list in ('Parameters', 'Returns', 'Raises'):
+ out += self._str_param_list('Parameters')
+ out += self._str_returns()
+ for param_list in ('Other Parameters', 'Raises', 'Warns'):
out += self._str_param_list(param_list)
out += self._str_warnings()
out += self._str_see_also(func_role)
@@ -192,38 +234,32 @@ def __str__(self, indent=0, func_role="obj"):
out += self._str_examples()
for param_list in ('Attributes', 'Methods'):
out += self._str_member_list(param_list)
- out = self._str_indent(out, indent)
+ out = self._str_indent(out,indent)
return '\n'.join(out)
-
class SphinxFunctionDoc(SphinxDocString, FunctionDoc):
-
def __init__(self, obj, doc=None, config={}):
- self.use_plots = config.get('use_plots', False)
+ self.load_config(config)
FunctionDoc.__init__(self, obj, doc=doc, config=config)
-
class SphinxClassDoc(SphinxDocString, ClassDoc):
-
def __init__(self, obj, doc=None, func_doc=None, config={}):
- self.use_plots = config.get('use_plots', False)
+ self.load_config(config)
ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config)
-
class SphinxObjDoc(SphinxDocString):
-
def __init__(self, obj, doc=None, config={}):
self._f = obj
+ self.load_config(config)
SphinxDocString.__init__(self, doc, config=config)
-
def get_doc_object(obj, what=None, doc=None, config={}):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
- elif callable(obj):
+ elif isinstance(obj, collections.Callable):
what = 'function'
else:
what = 'object'
diff --git a/doc/sphinxext/numpydoc/linkcode.py b/doc/sphinxext/numpydoc/linkcode.py
new file mode 100644
index 0000000000000..1ad3ab82cb49c
--- /dev/null
+++ b/doc/sphinxext/numpydoc/linkcode.py
@@ -0,0 +1,83 @@
+# -*- coding: utf-8 -*-
+"""
+ linkcode
+ ~~~~~~~~
+
+ Add external links to module code in Python object descriptions.
+
+ :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+
+"""
+from __future__ import division, absolute_import, print_function
+
+import warnings
+import collections
+
+warnings.warn("This extension has been accepted to Sphinx upstream. "
+ "Use the version from there (Sphinx >= 1.2) "
+ "https://bitbucket.org/birkenfeld/sphinx/pull-request/47/sphinxextlinkcode",
+ FutureWarning, stacklevel=1)
+
+
+from docutils import nodes
+
+from sphinx import addnodes
+from sphinx.locale import _
+from sphinx.errors import SphinxError
+
+class LinkcodeError(SphinxError):
+ category = "linkcode error"
+
+def doctree_read(app, doctree):
+ env = app.builder.env
+
+ resolve_target = getattr(env.config, 'linkcode_resolve', None)
+ if not isinstance(env.config.linkcode_resolve, collections.Callable):
+ raise LinkcodeError(
+ "Function `linkcode_resolve` is not given in conf.py")
+
+ domain_keys = dict(
+ py=['module', 'fullname'],
+ c=['names'],
+ cpp=['names'],
+ js=['object', 'fullname'],
+ )
+
+ for objnode in doctree.traverse(addnodes.desc):
+ domain = objnode.get('domain')
+ uris = set()
+ for signode in objnode:
+ if not isinstance(signode, addnodes.desc_signature):
+ continue
+
+ # Convert signode to a specified format
+ info = {}
+ for key in domain_keys.get(domain, []):
+ value = signode.get(key)
+ if not value:
+ value = ''
+ info[key] = value
+ if not info:
+ continue
+
+ # Call user code to resolve the link
+ uri = resolve_target(domain, info)
+ if not uri:
+ # no source
+ continue
+
+ if uri in uris or not uri:
+ # only one link per name, please
+ continue
+ uris.add(uri)
+
+ onlynode = addnodes.only(expr='html')
+ onlynode += nodes.reference('', '', internal=False, refuri=uri)
+ onlynode[0] += nodes.inline('', _('[source]'),
+ classes=['viewcode-link'])
+ signode += onlynode
+
+def setup(app):
+ app.connect('doctree-read', doctree_read)
+ app.add_config_value('linkcode_resolve', None, '')
diff --git a/doc/sphinxext/numpydoc.py b/doc/sphinxext/numpydoc/numpydoc.py
similarity index 65%
rename from doc/sphinxext/numpydoc.py
rename to doc/sphinxext/numpydoc/numpydoc.py
index 1cba77cd7412e..2bc2d1e91ed3f 100755
--- a/doc/sphinxext/numpydoc.py
+++ b/doc/sphinxext/numpydoc/numpydoc.py
@@ -12,53 +12,64 @@
- Renumber references.
- Extract the signature from the docstring, if it can't be determined otherwise.
-.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard
+.. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
"""
+from __future__ import division, absolute_import, print_function
+import os, sys, re, pydoc
import sphinx
+import inspect
+import collections
if sphinx.__version__ < '1.0.1':
raise RuntimeError("Sphinx 1.0.1 or newer is required")
-import os
-import re
-import pydoc
-from docscrape_sphinx import get_doc_object, SphinxDocString
+from .docscrape_sphinx import get_doc_object, SphinxDocString
from sphinx.util.compat import Directive
-import inspect
+
+if sys.version_info[0] >= 3:
+ sixu = lambda s: s
+else:
+ sixu = lambda s: unicode(s, 'unicode_escape')
def mangle_docstrings(app, what, name, obj, options, lines,
reference_offset=[0]):
cfg = dict(use_plots=app.config.numpydoc_use_plots,
- show_class_members=app.config.numpydoc_show_class_members)
+ show_class_members=app.config.numpydoc_show_class_members,
+ class_members_toctree=app.config.numpydoc_class_members_toctree,
+ )
if what == 'module':
# Strip top title
- title_re = re.compile(ur'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
- re.I | re.S)
- lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n")
+ title_re = re.compile(sixu('^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'),
+ re.I|re.S)
+ lines[:] = title_re.sub(sixu(''), sixu("\n").join(lines)).split(sixu("\n"))
else:
- doc = get_doc_object(obj, what, u"\n".join(lines), config=cfg)
- lines[:] = unicode(doc).split(u"\n")
+ doc = get_doc_object(obj, what, sixu("\n").join(lines), config=cfg)
+ if sys.version_info[0] >= 3:
+ doc = str(doc)
+ else:
+ doc = unicode(doc)
+ lines[:] = doc.split(sixu("\n"))
if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
- obj.__name__:
+ obj.__name__:
if hasattr(obj, '__module__'):
- v = dict(full_name=u"%s.%s" % (obj.__module__, obj.__name__))
+ v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__))
else:
v = dict(full_name=obj.__name__)
- lines += [u'', u'.. htmlonly::', '']
- lines += [u' %s' % x for x in
+ lines += [sixu(''), sixu('.. htmlonly::'), sixu('')]
+ lines += [sixu(' %s') % x for x in
(app.config.numpydoc_edit_link % v).split("\n")]
# replace reference numbers so that there are no duplicates
references = []
for line in lines:
line = line.strip()
- m = re.match(ur'^.. \[([a-z0-9_.-])\]', line, re.I)
+ m = re.match(sixu('^.. \\[([a-z0-9_.-])\\]'), line, re.I)
if m:
references.append(m.group(1))
@@ -67,37 +78,36 @@ def mangle_docstrings(app, what, name, obj, options, lines,
if references:
for i, line in enumerate(lines):
for r in references:
- if re.match(ur'^\d+$', r):
- new_r = u"R%d" % (reference_offset[0] + int(r))
+ if re.match(sixu('^\\d+$'), r):
+ new_r = sixu("R%d") % (reference_offset[0] + int(r))
else:
- new_r = u"%s%d" % (r, reference_offset[0])
- lines[i] = lines[i].replace(u'[%s]_' % r,
- u'[%s]_' % new_r)
- lines[i] = lines[i].replace(u'.. [%s]' % r,
- u'.. [%s]' % new_r)
+ new_r = sixu("%s%d") % (r, reference_offset[0])
+ lines[i] = lines[i].replace(sixu('[%s]_') % r,
+ sixu('[%s]_') % new_r)
+ lines[i] = lines[i].replace(sixu('.. [%s]') % r,
+ sixu('.. [%s]') % new_r)
reference_offset[0] += len(references)
-
def mangle_signature(app, what, name, obj, options, sig, retann):
# Do not try to inspect classes that don't define `__init__`
if (inspect.isclass(obj) and
(not hasattr(obj, '__init__') or
- 'initializes x; see ' in pydoc.getdoc(obj.__init__))):
+ 'initializes x; see ' in pydoc.getdoc(obj.__init__))):
return '', ''
- if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')):
- return
- if not hasattr(obj, '__doc__'):
- return
+ if not (isinstance(obj, collections.Callable) or hasattr(obj, '__argspec_is_invalid_')): return
+ if not hasattr(obj, '__doc__'): return
doc = SphinxDocString(pydoc.getdoc(obj))
if doc['Signature']:
- sig = re.sub(u"^[^(]*", u"", doc['Signature'])
- return sig, u''
-
+ sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature'])
+ return sig, sixu('')
def setup(app, get_doc_object_=get_doc_object):
+ if not hasattr(app, 'add_config_value'):
+ return # probably called by nose, better bail out
+
global get_doc_object
get_doc_object = get_doc_object_
@@ -106,6 +116,7 @@ def setup(app, get_doc_object_=get_doc_object):
app.add_config_value('numpydoc_edit_link', None, False)
app.add_config_value('numpydoc_use_plots', None, False)
app.add_config_value('numpydoc_show_class_members', True, True)
+ app.add_config_value('numpydoc_class_members_toctree', True, True)
# Extra mangling domains
app.add_domain(NumpyPythonDomain)
@@ -119,7 +130,6 @@ def setup(app, get_doc_object_=get_doc_object):
from sphinx.domains.c import CDomain
from sphinx.domains.python import PythonDomain
-
class ManglingDomainBase(object):
directive_mangling_map = {}
@@ -128,11 +138,10 @@ def __init__(self, *a, **kw):
self.wrap_mangling_directives()
def wrap_mangling_directives(self):
- for name, objtype in self.directive_mangling_map.items():
+ for name, objtype in list(self.directive_mangling_map.items()):
self.directives[name] = wrap_mangling_directive(
self.directives[name], objtype)
-
class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
name = 'np'
directive_mangling_map = {
@@ -144,7 +153,7 @@ class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
'staticmethod': 'function',
'attribute': 'attribute',
}
-
+ indices = []
class NumpyCDomain(ManglingDomainBase, CDomain):
name = 'np-c'
@@ -156,10 +165,8 @@ class NumpyCDomain(ManglingDomainBase, CDomain):
'var': 'object',
}
-
def wrap_mangling_directive(base_directive, objtype):
class directive(base_directive):
-
def run(self):
env = self.state.document.settings.env
diff --git a/doc/sphinxext/phantom_import.py b/doc/sphinxext/numpydoc/phantom_import.py
similarity index 88%
rename from doc/sphinxext/phantom_import.py
rename to doc/sphinxext/numpydoc/phantom_import.py
index b69f09ea612a0..9a60b4a35b18f 100755
--- a/doc/sphinxext/phantom_import.py
+++ b/doc/sphinxext/numpydoc/phantom_import.py
@@ -14,20 +14,14 @@
.. [1] http://code.google.com/p/pydocweb
"""
-import imp
-import sys
-import compiler
-import types
-import os
-import inspect
-import re
+from __future__ import division, absolute_import, print_function
+import imp, sys, compiler, types, os, inspect, re
def setup(app):
app.connect('builder-inited', initialize)
app.add_config_value('phantom_import_file', None, True)
-
def initialize(app):
fn = app.config.phantom_import_file
if (fn and os.path.isfile(fn)):
@@ -37,8 +31,6 @@ def initialize(app):
#------------------------------------------------------------------------------
# Creating 'phantom' modules from an XML description
#------------------------------------------------------------------------------
-
-
def import_phantom_module(xml_file):
"""
Insert a fake Python module to sys.modules, based on a XML file.
@@ -56,7 +48,7 @@ def import_phantom_module(xml_file):
----------
xml_file : str
Name of an XML file to read
-
+
"""
import lxml.etree as etree
@@ -69,7 +61,7 @@ def import_phantom_module(xml_file):
# - Base classes come before classes inherited from them
# - Modules come before their contents
all_nodes = dict([(n.attrib['id'], n) for n in root])
-
+
def _get_bases(node, recurse=False):
bases = [x.attrib['ref'] for x in node.findall('base')]
if recurse:
@@ -77,31 +69,26 @@ def _get_bases(node, recurse=False):
while True:
try:
b = bases[j]
- except IndexError:
- break
+ except IndexError: break
if b in all_nodes:
bases.extend(_get_bases(all_nodes[b]))
j += 1
return bases
type_index = ['module', 'class', 'callable', 'object']
-
+
def base_cmp(a, b):
x = cmp(type_index.index(a.tag), type_index.index(b.tag))
- if x != 0:
- return x
+ if x != 0: return x
if a.tag == 'class' and b.tag == 'class':
a_bases = _get_bases(a, recurse=True)
b_bases = _get_bases(b, recurse=True)
x = cmp(len(a_bases), len(b_bases))
- if x != 0:
- return x
- if a.attrib['id'] in b_bases:
- return -1
- if b.attrib['id'] in a_bases:
- return 1
-
+ if x != 0: return x
+ if a.attrib['id'] in b_bases: return -1
+ if b.attrib['id'] in a_bases: return 1
+
return cmp(a.attrib['id'].count('.'), b.attrib['id'].count('.'))
nodes = root.getchildren()
@@ -111,17 +98,14 @@ def base_cmp(a, b):
for node in nodes:
name = node.attrib['id']
doc = (node.text or '').decode('string-escape') + "\n"
- if doc == "\n":
- doc = ""
+ if doc == "\n": doc = ""
# create parent, if missing
parent = name
while True:
parent = '.'.join(parent.split('.')[:-1])
- if not parent:
- break
- if parent in object_cache:
- break
+ if not parent: break
+ if parent in object_cache: break
obj = imp.new_module(parent)
object_cache[parent] = obj
sys.modules[parent] = obj
@@ -147,14 +131,16 @@ def base_cmp(a, b):
doc = "%s%s\n\n%s" % (funcname, argspec, doc)
obj = lambda: 0
obj.__argspec_is_invalid_ = True
- obj.func_name = funcname
+ if sys.version_info[0] >= 3:
+ obj.__name__ = funcname
+ else:
+ obj.func_name = funcname
obj.__name__ = name
obj.__doc__ = doc
if inspect.isclass(object_cache[parent]):
obj.__objclass__ = object_cache[parent]
else:
- class Dummy(object):
- pass
+ class Dummy(object): pass
obj = Dummy()
obj.__name__ = name
obj.__doc__ = doc
@@ -170,8 +156,7 @@ class Dummy(object):
# Populate items
for node in root:
obj = object_cache.get(node.attrib['id'])
- if obj is None:
- continue
+ if obj is None: continue
for ref in node.findall('ref'):
if node.tag == 'class':
if ref.attrib['ref'].startswith(node.attrib['id'] + '.'):
diff --git a/doc/sphinxext/plot_directive.py b/doc/sphinxext/numpydoc/plot_directive.py
similarity index 93%
rename from doc/sphinxext/plot_directive.py
rename to doc/sphinxext/numpydoc/plot_directive.py
index 0a85c6c7f108a..2014f857076c1 100755
--- a/doc/sphinxext/plot_directive.py
+++ b/doc/sphinxext/numpydoc/plot_directive.py
@@ -74,19 +74,16 @@
to make them appear side-by-side, or in floats.
"""
+from __future__ import division, absolute_import, print_function
-import sys
-import os
-import glob
-import shutil
-import imp
-import warnings
-import cStringIO
-import re
-import textwrap
-import traceback
+import sys, os, glob, shutil, imp, warnings, re, textwrap, traceback
import sphinx
+if sys.version_info[0] >= 3:
+ from io import StringIO
+else:
+ from io import StringIO
+
import warnings
warnings.warn("A plot_directive module is also available under "
"matplotlib.sphinxext; expect this numpydoc.plot_directive "
@@ -119,13 +116,11 @@ def setup(app):
from docutils.parsers.rst import directives
from docutils import nodes
-
def plot_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
return run(arguments, content, options, state_machine, state, lineno)
plot_directive.__doc__ = __doc__
-
def _option_boolean(arg):
if not arg or not arg.strip():
# no argument given, assume used as a flag
@@ -137,11 +132,9 @@ def _option_boolean(arg):
else:
raise ValueError('"%s" unknown boolean' % arg)
-
def _option_format(arg):
return directives.choice(arg, ('python', 'lisp'))
-
def _option_align(arg):
return directives.choice(arg, ("top", "middle", "bottom", "left", "center",
"right"))
@@ -165,12 +158,10 @@ def _option_align(arg):
try:
# Sphinx depends on either Jinja or Jinja2
import jinja2
-
def format_template(template, **kw):
return jinja2.Template(template).render(**kw)
except ImportError:
import jinja
-
def format_template(template, **kw):
return jinja.from_string(template, **kw)
@@ -219,9 +210,7 @@ def format_template(template, **kw):
"""
-
class ImageFile(object):
-
def __init__(self, basename, dirname):
self.basename = basename
self.dirname = dirname
@@ -233,7 +222,6 @@ def filename(self, format):
def filenames(self):
return [self.filename(fmt) for fmt in self.formats]
-
def run(arguments, content, options, state_machine, state, lineno):
if arguments and content:
raise RuntimeError("plot:: directive can't have both args and content")
@@ -275,7 +263,7 @@ def run(arguments, content, options, state_machine, state, lineno):
# is it in doctest format?
is_doctest = contains_doctest(code)
- if options.has_key('format'):
+ if 'format' in options:
if options['format'] == 'python':
is_doctest = False
else:
@@ -309,7 +297,7 @@ def run(arguments, content, options, state_machine, state, lineno):
results = makefig(code, source_file_name, build_dir, output_base,
config)
errors = []
- except PlotError, err:
+ except PlotError as err:
reporter = state.memo.reporter
sm = reporter.system_message(
2, "Exception occurred in plotting %s: %s" % (output_base, err),
@@ -332,15 +320,11 @@ def run(arguments, content, options, state_machine, state, lineno):
else:
source_code = ""
- opts = [':%s: %s' % (key, val) for key, val in options.items()
+ opts = [':%s: %s' % (key, val) for key, val in list(options.items())
if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
- if sphinx.__version__ >= "0.6":
- only_html = ".. only:: html"
- only_latex = ".. only:: latex"
- else:
- only_html = ".. htmlonly::"
- only_latex = ".. latexonly::"
+ only_html = ".. only:: html"
+ only_latex = ".. only:: latex"
if j == 0:
src_link = source_link
@@ -398,7 +382,6 @@ def run(arguments, content, options, state_machine, state, lineno):
import exceptions
-
def contains_doctest(text):
try:
# check if it's valid Python as-is
@@ -410,7 +393,6 @@ def contains_doctest(text):
m = r.search(text)
return bool(m)
-
def unescape_doctest(text):
"""
Extract code from a piece of text, which contains either Python code
@@ -431,7 +413,6 @@ def unescape_doctest(text):
code += "\n"
return code
-
def split_code_at_show(text):
"""
Split code at plt.show()
@@ -444,7 +425,7 @@ def split_code_at_show(text):
part = []
for line in text.split("\n"):
if (not is_doctest and line.strip() == 'plt.show()') or \
- (is_doctest and line.strip() == '>>> plt.show()'):
+ (is_doctest and line.strip() == '>>> plt.show()'):
part.append(line)
parts.append("\n".join(part))
part = []
@@ -454,11 +435,9 @@ def split_code_at_show(text):
parts.append("\n".join(part))
return parts
-
class PlotError(RuntimeError):
pass
-
def run_code(code, code_path, ns=None):
# Change the working directory to the directory of the example, so
# it can get at its data files, if any.
@@ -471,21 +450,21 @@ def run_code(code, code_path, ns=None):
# Redirect stdout
stdout = sys.stdout
- sys.stdout = cStringIO.StringIO()
+ sys.stdout = StringIO()
# Reset sys.argv
old_sys_argv = sys.argv
sys.argv = [code_path]
-
+
try:
try:
code = unescape_doctest(code)
if ns is None:
ns = {}
if not ns:
- exec setup.config.plot_pre_code in ns
- exec code in ns
- except (Exception, SystemExit), err:
+ exec(setup.config.plot_pre_code, ns)
+ exec(code, ns)
+ except (Exception, SystemExit) as err:
raise PlotError(traceback.format_exc())
finally:
os.chdir(pwd)
@@ -521,7 +500,7 @@ def makefig(code, code_path, output_dir, output_base, config):
for fmt in config.plot_formats:
if isinstance(fmt, str):
formats.append((fmt, default_dpi.get(fmt, 80)))
- elif type(fmt) in (tuple, list) and len(fmt) == 2:
+ elif type(fmt) in (tuple, list) and len(fmt)==2:
formats.append((str(fmt[0]), int(fmt[1])))
else:
raise PlotError('invalid image format "%r" in plot_formats' % fmt)
@@ -547,7 +526,7 @@ def makefig(code, code_path, output_dir, output_base, config):
all_exists = True
for i, code_piece in enumerate(code_pieces):
images = []
- for j in xrange(1000):
+ for j in range(1000):
img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir)
for format, dpi in formats:
if out_of_date(code_path, img.filename(format)):
@@ -591,9 +570,8 @@ def makefig(code, code_path, output_dir, output_base, config):
images.append(img)
for format, dpi in formats:
try:
- figman.canvas.figure.savefig(img.filename(format), dpi=dpi,
- bbox_inches='tight')
- except exceptions.BaseException, err:
+ figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
+ except exceptions.BaseException as err:
raise PlotError(traceback.format_exc())
img.formats.append(format)
@@ -615,7 +593,7 @@ def makefig(code, code_path, output_dir, output_base, config):
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
from os.path import sep, curdir, join, abspath, commonprefix, \
- pardir
+ pardir
if not path:
raise ValueError("no path specified")
@@ -626,7 +604,7 @@ def relpath(path, start=os.path.curdir):
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
- rel_list = [pardir] * (len(start_list) - i) + path_list[i:]
+ rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
@@ -634,7 +612,7 @@ def relpath(path, start=os.path.curdir):
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
from os.path import sep, curdir, join, abspath, commonprefix, \
- pardir, splitunc
+ pardir, splitunc
if not path:
raise ValueError("no path specified")
@@ -645,10 +623,10 @@ def relpath(path, start=os.path.curdir):
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
- % (path, start))
+ % (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
- % (path_list[0], start_list[0]))
+ % (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
@@ -656,7 +634,7 @@ def relpath(path, start=os.path.curdir):
else:
i += 1
- rel_list = [pardir] * (len(start_list) - i) + path_list[i:]
+ rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
diff --git a/doc/sphinxext/tests/test_docscrape.py b/doc/sphinxext/numpydoc/tests/test_docscrape.py
similarity index 70%
rename from doc/sphinxext/tests/test_docscrape.py
rename to doc/sphinxext/numpydoc/tests/test_docscrape.py
index a66e4222b380d..b682504e1618f 100755
--- a/doc/sphinxext/tests/test_docscrape.py
+++ b/doc/sphinxext/numpydoc/tests/test_docscrape.py
@@ -1,15 +1,20 @@
# -*- encoding:utf-8 -*-
+from __future__ import division, absolute_import, print_function
-import sys
-import os
-sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
+import sys, textwrap
-from docscrape import NumpyDocString, FunctionDoc, ClassDoc
-from docscrape_sphinx import SphinxDocString, SphinxClassDoc
+from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc
+from numpydoc.docscrape_sphinx import SphinxDocString, SphinxClassDoc
from nose.tools import *
+if sys.version_info[0] >= 3:
+ sixu = lambda s: s
+else:
+ sixu = lambda s: unicode(s, 'unicode_escape')
+
+
doc_txt = '''\
- numpy.multivariate_normal(mean, cov, shape=None)
+ numpy.multivariate_normal(mean, cov, shape=None, spam=None)
Draw values from a multivariate normal distribution with specified
mean and covariance.
@@ -26,7 +31,7 @@
(1+2+3)/3
- cov : (N,N) ndarray
+ cov : (N, N) ndarray
Covariance matrix of the distribution.
shape : tuple of ints
Given a shape of, for example, (m,n,k), m*n*k samples are
@@ -42,6 +47,24 @@
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
+ list of str
+ This is not a real return value. It exists to test
+ anonymous return values.
+
+ Other Parameters
+ ----------------
+ spam : parrot
+ A parrot off its mortal coil.
+
+ Raises
+ ------
+ RuntimeError
+ Some error
+
+ Warns
+ -----
+ RuntimeWarning
+ Some warning
Warnings
--------
@@ -49,7 +72,6 @@
Notes
-----
-
Instead of specifying the full covariance matrix, popular
approximations include:
@@ -85,13 +107,13 @@
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
- >>> print(x.shape)
+ >>> print x.shape
(3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the
standard deviation:
- >>> print(list( (x[0,0,:] - mean) < 0.6 ))
+ >>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
.. index:: random
@@ -103,74 +125,76 @@
def test_signature():
assert doc['Signature'].startswith('numpy.multivariate_normal(')
- assert doc['Signature'].endswith('shape=None)')
-
+ assert doc['Signature'].endswith('spam=None)')
def test_summary():
assert doc['Summary'][0].startswith('Draw values')
assert doc['Summary'][-1].endswith('covariance.')
-
def test_extended_summary():
assert doc['Extended Summary'][0].startswith('The multivariate normal')
-
def test_parameters():
assert_equal(len(doc['Parameters']), 3)
- assert_equal(
- [n for n, _, _ in doc['Parameters']], ['mean', 'cov', 'shape'])
+ assert_equal([n for n,_,_ in doc['Parameters']], ['mean','cov','shape'])
arg, arg_type, desc = doc['Parameters'][1]
- assert_equal(arg_type, '(N,N) ndarray')
+ assert_equal(arg_type, '(N, N) ndarray')
assert desc[0].startswith('Covariance matrix')
assert doc['Parameters'][0][-1][-2] == ' (1+2+3)/3'
+def test_other_parameters():
+ assert_equal(len(doc['Other Parameters']), 1)
+ assert_equal([n for n,_,_ in doc['Other Parameters']], ['spam'])
+ arg, arg_type, desc = doc['Other Parameters'][0]
+ assert_equal(arg_type, 'parrot')
+ assert desc[0].startswith('A parrot off its mortal coil')
def test_returns():
- assert_equal(len(doc['Returns']), 1)
+ assert_equal(len(doc['Returns']), 2)
arg, arg_type, desc = doc['Returns'][0]
assert_equal(arg, 'out')
assert_equal(arg_type, 'ndarray')
assert desc[0].startswith('The drawn samples')
assert desc[-1].endswith('distribution.')
+ arg, arg_type, desc = doc['Returns'][1]
+ assert_equal(arg, 'list of str')
+ assert_equal(arg_type, '')
+ assert desc[0].startswith('This is not a real')
+ assert desc[-1].endswith('anonymous return values.')
def test_notes():
assert doc['Notes'][0].startswith('Instead')
assert doc['Notes'][-1].endswith('definite.')
assert_equal(len(doc['Notes']), 17)
-
def test_references():
assert doc['References'][0].startswith('..')
assert doc['References'][-1].endswith('2001.')
-
def test_examples():
assert doc['Examples'][0].startswith('>>>')
assert doc['Examples'][-1].endswith('True]')
-
def test_index():
assert_equal(doc['index']['default'], 'random')
- print(doc['index'])
assert_equal(len(doc['index']), 2)
assert_equal(len(doc['index']['refguide']), 2)
-
-def non_blank_line_by_line_compare(a, b):
- a = [l for l in a.split('\n') if l.strip()]
- b = [l for l in b.split('\n') if l.strip()]
- for n, line in enumerate(a):
+def non_blank_line_by_line_compare(a,b):
+ a = textwrap.dedent(a)
+ b = textwrap.dedent(b)
+ a = [l.rstrip() for l in a.split('\n') if l.strip()]
+ b = [l.rstrip() for l in b.split('\n') if l.strip()]
+ for n,line in enumerate(a):
if not line == b[n]:
raise AssertionError("Lines %s of a and b differ: "
"\n>>> %s\n<<< %s\n" %
- (n, line, b[n]))
-
-
+ (n,line,b[n]))
def test_str():
non_blank_line_by_line_compare(str(doc),
- """numpy.multivariate_normal(mean, cov, shape=None)
+"""numpy.multivariate_normal(mean, cov, shape=None, spam=None)
Draw values from a multivariate normal distribution with specified
mean and covariance.
@@ -187,7 +211,7 @@ def test_str():
(1+2+3)/3
-cov : (N,N) ndarray
+cov : (N, N) ndarray
Covariance matrix of the distribution.
shape : tuple of ints
Given a shape of, for example, (m,n,k), m*n*k samples are
@@ -203,6 +227,24 @@ def test_str():
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
+list of str
+ This is not a real return value. It exists to test
+ anonymous return values.
+
+Other Parameters
+----------------
+spam : parrot
+ A parrot off its mortal coil.
+
+Raises
+------
+RuntimeError
+ Some error
+
+Warns
+-----
+RuntimeWarning
+ Some warning
Warnings
--------
@@ -247,13 +289,13 @@ def test_str():
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
->>> print(x.shape)
+>>> print x.shape
(3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the
standard deviation:
->>> print(list( (x[0,0,:] - mean) < 0.6 ))
+>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
.. index:: random
@@ -263,7 +305,7 @@ def test_str():
def test_sphinx_str():
sphinx_doc = SphinxDocString(doc_txt)
non_blank_line_by_line_compare(str(sphinx_doc),
- """
+"""
.. index:: random
single: random;distributions, random;gauss
@@ -283,7 +325,7 @@ def test_sphinx_str():
(1+2+3)/3
- **cov** : (N,N) ndarray
+ **cov** : (N, N) ndarray
Covariance matrix of the distribution.
@@ -304,6 +346,29 @@ def test_sphinx_str():
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
+ list of str
+
+ This is not a real return value. It exists to test
+ anonymous return values.
+
+:Other Parameters:
+
+ **spam** : parrot
+
+ A parrot off its mortal coil.
+
+:Raises:
+
+ **RuntimeError**
+
+ Some error
+
+:Warns:
+
+ **RuntimeWarning**
+
+ Some warning
+
.. warning::
Certain warnings apply.
@@ -351,13 +416,13 @@ def test_sphinx_str():
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
->>> print(x.shape)
+>>> print x.shape
(3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the
standard deviation:
->>> print(list( (x[0,0,:] - mean) < 0.6 ))
+>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
""")
@@ -373,7 +438,6 @@ def test_sphinx_str():
If None, the index is into the flattened array, otherwise along
the specified axis""")
-
def test_parameters_without_extended_description():
assert_equal(len(doc2['Parameters']), 2)
@@ -383,7 +447,6 @@ def test_parameters_without_extended_description():
Return this and that.
""")
-
def test_escape_stars():
signature = str(doc3).split('\n')[0]
assert_equal(signature, 'my_signature(\*params, \*\*kwds)')
@@ -393,7 +456,6 @@ def test_escape_stars():
Return an array with all complex-valued elements conjugated.""")
-
def test_empty_extended_summary():
assert_equal(doc4['Extended Summary'], [])
@@ -406,19 +468,27 @@ def test_empty_extended_summary():
LinAlgException
If array is singular.
+ Warns
+ -----
+ SomeWarning
+ If needed
""")
-
def test_raises():
assert_equal(len(doc5['Raises']), 1)
- name, _, desc = doc5['Raises'][0]
- assert_equal(name, 'LinAlgException')
- assert_equal(desc, ['If array is singular.'])
+ name,_,desc = doc5['Raises'][0]
+ assert_equal(name,'LinAlgException')
+ assert_equal(desc,['If array is singular.'])
+def test_warns():
+ assert_equal(len(doc5['Warns']), 1)
+ name,_,desc = doc5['Warns'][0]
+ assert_equal(name,'SomeWarning')
+ assert_equal(desc,['If needed'])
def test_see_also():
doc6 = NumpyDocString(
- """
+ """
z(x,theta)
See Also
@@ -458,10 +528,8 @@ def test_see_also():
elif func == 'class_j':
assert desc == ['fubar', 'foobar']
-
def test_see_also_print():
class Dummy(object):
-
"""
See Also
--------
@@ -484,7 +552,6 @@ class Dummy(object):
""")
-
def test_empty_first_line():
assert doc7['Summary'][0].startswith('Doc starts')
@@ -512,8 +579,8 @@ def test_unicode():
äää
""")
- assert doc['Summary'][0] == u'öäöäöäöäöåååå'.encode('utf-8')
-
+ assert isinstance(doc['Summary'][0], str)
+ assert doc['Summary'][0] == 'öäöäöäöäöåååå'
def test_plot_examples():
cfg = dict(use_plots=True)
@@ -538,34 +605,163 @@ def test_plot_examples():
""", config=cfg)
assert str(doc).count('plot::') == 1, str(doc)
-
def test_class_members():
class Dummy(object):
-
"""
Dummy class.
"""
-
def spam(self, a, b):
"""Spam\n\nSpam spam."""
pass
-
def ham(self, c, d):
"""Cheese\n\nNo cheese."""
pass
+ @property
+ def spammity(self):
+ """Spammity index"""
+ return 0.95
+
+ class Ignorable(object):
+ """local class, to be ignored"""
+ pass
for cls in (ClassDoc, SphinxClassDoc):
doc = cls(Dummy, config=dict(show_class_members=False))
assert 'Methods' not in str(doc), (cls, str(doc))
assert 'spam' not in str(doc), (cls, str(doc))
assert 'ham' not in str(doc), (cls, str(doc))
+ assert 'spammity' not in str(doc), (cls, str(doc))
+ assert 'Spammity index' not in str(doc), (cls, str(doc))
doc = cls(Dummy, config=dict(show_class_members=True))
assert 'Methods' in str(doc), (cls, str(doc))
assert 'spam' in str(doc), (cls, str(doc))
assert 'ham' in str(doc), (cls, str(doc))
+ assert 'spammity' in str(doc), (cls, str(doc))
if cls is SphinxClassDoc:
assert '.. autosummary::' in str(doc), str(doc)
+ else:
+ assert 'Spammity index' in str(doc), str(doc)
+
+def test_duplicate_signature():
+ # Duplicate function signatures occur e.g. in ufuncs, when the
+ # automatic mechanism adds one, and a more detailed comes from the
+ # docstring itself.
+
+ doc = NumpyDocString(
+ """
+ z(x1, x2)
+
+ z(a, theta)
+ """)
+
+ assert doc['Signature'].strip() == 'z(a, theta)'
+
+
+class_doc_txt = """
+ Foo
+
+ Parameters
+ ----------
+ f : callable ``f(t, y, *f_args)``
+ Aaa.
+ jac : callable ``jac(t, y, *jac_args)``
+ Bbb.
+
+ Attributes
+ ----------
+ t : float
+ Current time.
+ y : ndarray
+ Current variable values.
+
+ Methods
+ -------
+ a
+ b
+ c
+
+ Examples
+ --------
+ For usage examples, see `ode`.
+"""
+
+def test_class_members_doc():
+ doc = ClassDoc(None, class_doc_txt)
+ non_blank_line_by_line_compare(str(doc),
+ """
+ Foo
+
+ Parameters
+ ----------
+ f : callable ``f(t, y, *f_args)``
+ Aaa.
+ jac : callable ``jac(t, y, *jac_args)``
+ Bbb.
+
+ Examples
+ --------
+ For usage examples, see `ode`.
+
+ Attributes
+ ----------
+ t : float
+ Current time.
+ y : ndarray
+ Current variable values.
+
+ Methods
+ -------
+ a
+
+ b
+
+ c
+
+ .. index::
+
+ """)
+
+def test_class_members_doc_sphinx():
+ doc = SphinxClassDoc(None, class_doc_txt)
+ non_blank_line_by_line_compare(str(doc),
+ """
+ Foo
+
+ :Parameters:
+
+ **f** : callable ``f(t, y, *f_args)``
+
+ Aaa.
+
+ **jac** : callable ``jac(t, y, *jac_args)``
+
+ Bbb.
+
+ .. rubric:: Examples
+
+ For usage examples, see `ode`.
+
+ .. rubric:: Attributes
+
+ === ==========
+ t (float) Current time.
+ y (ndarray) Current variable values.
+ === ==========
+
+ .. rubric:: Methods
+
+ === ==========
+ a
+ b
+ c
+ === ==========
+
+ """)
+
+if __name__ == "__main__":
+ import nose
+ nose.run()
diff --git a/doc/sphinxext/numpydoc/tests/test_linkcode.py b/doc/sphinxext/numpydoc/tests/test_linkcode.py
new file mode 100644
index 0000000000000..340166a485fcd
--- /dev/null
+++ b/doc/sphinxext/numpydoc/tests/test_linkcode.py
@@ -0,0 +1,5 @@
+from __future__ import division, absolute_import, print_function
+
+import numpydoc.linkcode
+
+# No tests at the moment...
diff --git a/doc/sphinxext/numpydoc/tests/test_phantom_import.py b/doc/sphinxext/numpydoc/tests/test_phantom_import.py
new file mode 100644
index 0000000000000..173b5662b8df7
--- /dev/null
+++ b/doc/sphinxext/numpydoc/tests/test_phantom_import.py
@@ -0,0 +1,5 @@
+from __future__ import division, absolute_import, print_function
+
+import numpydoc.phantom_import
+
+# No tests at the moment...
diff --git a/doc/sphinxext/numpydoc/tests/test_plot_directive.py b/doc/sphinxext/numpydoc/tests/test_plot_directive.py
new file mode 100644
index 0000000000000..0e511fcbc1428
--- /dev/null
+++ b/doc/sphinxext/numpydoc/tests/test_plot_directive.py
@@ -0,0 +1,5 @@
+from __future__ import division, absolute_import, print_function
+
+import numpydoc.plot_directive
+
+# No tests at the moment...
diff --git a/doc/sphinxext/numpydoc/tests/test_traitsdoc.py b/doc/sphinxext/numpydoc/tests/test_traitsdoc.py
new file mode 100644
index 0000000000000..d36e5ddbd751f
--- /dev/null
+++ b/doc/sphinxext/numpydoc/tests/test_traitsdoc.py
@@ -0,0 +1,5 @@
+from __future__ import division, absolute_import, print_function
+
+import numpydoc.traitsdoc
+
+# No tests at the moment...
diff --git a/doc/sphinxext/traitsdoc.py b/doc/sphinxext/numpydoc/traitsdoc.py
similarity index 86%
rename from doc/sphinxext/traitsdoc.py
rename to doc/sphinxext/numpydoc/traitsdoc.py
index f39fe0c2e23da..596c54eb389a3 100755
--- a/doc/sphinxext/traitsdoc.py
+++ b/doc/sphinxext/numpydoc/traitsdoc.py
@@ -13,20 +13,22 @@
.. [2] http://code.enthought.com/projects/traits/
"""
+from __future__ import division, absolute_import, print_function
import inspect
+import os
import pydoc
+import collections
-import docscrape
-from docscrape_sphinx import SphinxClassDoc, SphinxFunctionDoc, SphinxDocString
+from . import docscrape
+from . import docscrape_sphinx
+from .docscrape_sphinx import SphinxClassDoc, SphinxFunctionDoc, SphinxDocString
-import numpydoc
-
-import comment_eater
+from . import numpydoc
+from . import comment_eater
class SphinxTraitsDoc(SphinxClassDoc):
-
def __init__(self, cls, modulename='', func_doc=SphinxFunctionDoc):
if not inspect.isclass(cls):
raise ValueError("Initialise using a class. Got %r" % cls)
@@ -48,7 +50,7 @@ def __init__(self, cls, modulename='', func_doc=SphinxFunctionDoc):
except ValueError:
indent = 0
- for n, line in enumerate(docstring):
+ for n,line in enumerate(docstring):
docstring[n] = docstring[n][indent:]
self._doc = docscrape.Reader(docstring)
@@ -70,7 +72,7 @@ def __init__(self, cls, modulename='', func_doc=SphinxFunctionDoc):
'Example': '',
'Examples': '',
'index': {}
- }
+ }
self._parse()
@@ -87,17 +89,16 @@ def __str__(self, indent=0, func_role="func"):
out += self._str_summary()
out += self._str_extended_summary()
for param_list in ('Parameters', 'Traits', 'Methods',
- 'Returns', 'Raises'):
+ 'Returns','Raises'):
out += self._str_param_list(param_list)
out += self._str_see_also("obj")
out += self._str_section('Notes')
out += self._str_references()
out += self._str_section('Example')
out += self._str_section('Examples')
- out = self._str_indent(out, indent)
+ out = self._str_indent(out,indent)
return '\n'.join(out)
-
def looks_like_issubclass(obj, classname):
""" Return True if the object has a class or superclass with the given class
name.
@@ -112,20 +113,18 @@ def looks_like_issubclass(obj, classname):
return True
return False
-
def get_doc_object(obj, what=None, config=None):
if what is None:
if inspect.isclass(obj):
what = 'class'
elif inspect.ismodule(obj):
what = 'module'
- elif callable(obj):
+ elif isinstance(obj, collections.Callable):
what = 'function'
else:
what = 'object'
if what == 'class':
- doc = SphinxTraitsDoc(
- obj, '', func_doc=SphinxFunctionDoc, config=config)
+ doc = SphinxTraitsDoc(obj, '', func_doc=SphinxFunctionDoc, config=config)
if looks_like_issubclass(obj, 'HasTraits'):
for name, trait, comment in comment_eater.get_class_traits(obj):
# Exclude private traits.
@@ -137,7 +136,7 @@ def get_doc_object(obj, what=None, config=None):
else:
return SphinxDocString(pydoc.getdoc(obj), config=config)
-
def setup(app):
# init numpydoc
numpydoc.setup(app, get_doc_object)
+
diff --git a/doc/sphinxext/only_directives.py b/doc/sphinxext/only_directives.py
deleted file mode 100755
index 25cef30d21dc8..0000000000000
--- a/doc/sphinxext/only_directives.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#
-# A pair of directives for inserting content that will only appear in
-# either html or latex.
-#
-
-from docutils.nodes import Body, Element
-from docutils.writers.html4css1 import HTMLTranslator
-try:
- from sphinx.latexwriter import LaTeXTranslator
-except ImportError:
- from sphinx.writers.latex import LaTeXTranslator
-
- import warnings
- warnings.warn("The numpydoc.only_directives module is deprecated;"
- "please use the only:: directive available in Sphinx >= 0.6",
- DeprecationWarning, stacklevel=2)
-
-from docutils.parsers.rst import directives
-
-
-class html_only(Body, Element):
- pass
-
-
-class latex_only(Body, Element):
- pass
-
-
-def run(content, node_class, state, content_offset):
- text = '\n'.join(content)
- node = node_class(text)
- state.nested_parse(content, content_offset, node)
- return [node]
-
-try:
- from docutils.parsers.rst import Directive
-except ImportError:
- from docutils.parsers.rst.directives import _directives
-
- def html_only_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- return run(content, html_only, state, content_offset)
-
- def latex_only_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- return run(content, latex_only, state, content_offset)
-
- for func in (html_only_directive, latex_only_directive):
- func.content = 1
- func.options = {}
- func.arguments = None
-
- _directives['htmlonly'] = html_only_directive
- _directives['latexonly'] = latex_only_directive
-else:
- class OnlyDirective(Directive):
- has_content = True
- required_arguments = 0
- optional_arguments = 0
- final_argument_whitespace = True
- option_spec = {}
-
- def run(self):
- self.assert_has_content()
- return run(self.content, self.node_class,
- self.state, self.content_offset)
-
- class HtmlOnlyDirective(OnlyDirective):
- node_class = html_only
-
- class LatexOnlyDirective(OnlyDirective):
- node_class = latex_only
-
- directives.register_directive('htmlonly', HtmlOnlyDirective)
- directives.register_directive('latexonly', LatexOnlyDirective)
-
-
-def setup(app):
- app.add_node(html_only)
- app.add_node(latex_only)
-
- # Add visit/depart methods to HTML-Translator:
- def visit_perform(self, node):
- pass
-
- def depart_perform(self, node):
- pass
-
- def visit_ignore(self, node):
- node.children = []
-
- def depart_ignore(self, node):
- node.children = []
-
- HTMLTranslator.visit_html_only = visit_perform
- HTMLTranslator.depart_html_only = depart_perform
- HTMLTranslator.visit_latex_only = visit_ignore
- HTMLTranslator.depart_latex_only = depart_ignore
-
- LaTeXTranslator.visit_html_only = visit_ignore
- LaTeXTranslator.depart_html_only = depart_ignore
- LaTeXTranslator.visit_latex_only = visit_perform
- LaTeXTranslator.depart_latex_only = depart_perform
diff --git a/doc/sphinxext/setup.py b/doc/sphinxext/setup.py
deleted file mode 100755
index f73287eee2351..0000000000000
--- a/doc/sphinxext/setup.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from distutils.core import setup
-import setuptools
-import sys
-import os
-
-version = "0.3.dev"
-
-setup(
- name="numpydoc",
- packages=["numpydoc"],
- package_dir={"numpydoc": ""},
- version=version,
- description="Sphinx extension to support docstrings in Numpy format",
- # classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers
- classifiers=["Development Status :: 3 - Alpha",
- "Environment :: Plugins",
- "License :: OSI Approved :: BSD License",
- "Topic :: Documentation"],
- keywords="sphinx numpy",
- author="Pauli Virtanen and others",
- author_email="pav@iki.fi",
- url="http://projects.scipy.org/numpy/browser/trunk/doc/sphinxext",
- license="BSD",
- zip_safe=False,
- install_requires=["Sphinx >= 0.5"],
- package_data={'numpydoc': 'tests', '': ''},
- entry_points={
- "console_scripts": [
- "autosummary_generate = numpydoc.autosummary_generate:main",
- ],
- },
-)
| This PR updates our local copy of numpydoc to latest upstream version (I just fully copied over that version, only left out setup.py and manifest.in). This would be a solution to the numpydoc part of issue #5221.
The intent would then be, from now on, to not touch this code, apart of pulling an updated version from numpydoc upstream from time to time. If we want to make a change, also send it upstreams to not let the two versions diverge.
**Other options** to solve this issue would be to just add numpydoc as a requirement for the doc building and removing out local option, or to add it as a git submodule. I am slightly in favor of removing our local copy, but I understood from previous comments it would be better to not have more build dependencies (and it would also tie us to a specific version).
I did build the docs with this and all seems OK. From looking at the history, I think only py3compat changes are done to these files after the initial import from Wes (@jtratner, @cpcloud you are the ones who touched these files, do you remember if you did something else than py3compat issues?)
| https://api.github.com/repos/pandas-dev/pandas/pulls/6003 | 2014-01-19T15:44:09Z | 2014-01-24T16:50:52Z | 2014-01-24T16:50:52Z | 2014-06-15T14:16:41Z |
DOC: add sklearn-pandas to pandas ecosystem section | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index a86c1aa4c0258..c1b7cf30067e3 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -56,8 +56,15 @@ more advanced types of plots then those offered by pandas.
`Geopandas <https://github.com/kjordahl/geopandas>`__
-------------------------------------------------------
+-----------------------------------------------------
Geopandas extends pandas data objects to include geographic information which support
geometric operations. If your work entails maps and geographical coordinates, and
you love pandas, you should take a close look at Geopandas.
+
+`sklearn-pandas <https://github.com/paulgb/sklearn-pandas>`__
+-------------------------------------------------------------
+
+Use pandas DataFrames in your scikit-learn ML pipeline.
+
+
| cc @paulgb. awesome stuff.
| https://api.github.com/repos/pandas-dev/pandas/pulls/6001 | 2014-01-19T14:57:34Z | 2014-01-19T14:57:44Z | 2014-01-19T14:57:44Z | 2014-07-16T08:47:36Z |
BUG: use astype for scipy datetime interpolation | diff --git a/pandas/core/common.py b/pandas/core/common.py
index cd78f35aabdf9..774ef02b594f3 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1414,9 +1414,9 @@ def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
'piecewise_polynomial': interpolate.piecewise_polynomial_interpolate,
}
- if hasattr(x, 'asi8'):
+ if getattr(x, 'is_all_dates', False):
# GH 5975, scipy.interp1d can't hande datetime64s
- x, new_x = x.values.view('i8'), new_x.view('i8')
+ x, new_x = x.values.astype('i8'), new_x.astype('i8')
try:
alt_methods['pchip'] = interpolate.pchip_interpolate
| Closes #5975 (again), with the issue raised at https://github.com/pydata/pandas/pull/5977#issuecomment-32691271.
I'm using `astype` instead of `view` now, as Jeff suggested. I also didn't realize that `asi8` was a method on all `Index`es, and not just `DatetimeIndex`es. So instead of checking for that attr, I just check if it's a DatetimeIndex.
@y-p this should fix the doc example. It built for me anyway, but I've had trouble building the docs off my working branch.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5998 | 2014-01-19T00:49:53Z | 2014-01-19T09:43:24Z | 2014-01-19T09:43:24Z | 2016-11-03T12:37:43Z |
DOC: add guidelines for building the docs | diff --git a/doc/README.rst b/doc/README.rst
new file mode 100644
index 0000000000000..29c4113f90909
--- /dev/null
+++ b/doc/README.rst
@@ -0,0 +1,151 @@
+.. _contributing.docs:
+
+Contributing to the documentation
+=================================
+
+If you're not the developer type, contributing to the documentation is still
+of huge value. You don't even have to be an expert on
+*pandas* to do so! Something as simple as rewriting small passages for clarity
+as you reference the docs is a simple but effective way to contribute. The
+next person to read that passage will be in your debt!
+
+Actually, there are sections of the docs that are worse off by being written
+by experts. If something in the docs doesn't make sense to you, updating the
+relevant section after you figure it out is a simple way to ensure it will
+help the next person.
+
+.. contents:: Table of contents:
+ :local:
+
+
+About the pandas documentation
+------------------------------
+
+The documentation is written in **reStructuredText**, which is almost like writing
+in plain English, and built using `Sphinx <http://sphinx.pocoo.org/>`__. The
+Sphinx Documentation has an excellent `introduction to reST
+<http://sphinx.pocoo.org/rest.html>`__. Review the Sphinx docs to perform more
+complex changes to the documentation as well.
+
+Some other important things to know about the docs:
+
+- The pandas documentation consists of two parts: the docstrings in the code
+ itself and the docs in this folder ``pandas/doc/``.
+
+ The docstrings provide a clear explanation of the usage of the individual
+ functions, while the documentation in this filder consists of tutorial-like
+ overviews per topic together with some other information (whatsnew,
+ installation, etc).
+
+- The docstrings follow the **Numpy Docstring Standard** which is used widely
+ in the Scientific Python community. This standard specifies the format of
+ the different sections of the docstring. See `this document
+ <https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_
+ for a detailed explanation, or look at some of the existing functions to
+ extend it in a similar manner.
+
+- The tutorials make heavy use of the `ipython directive
+ <http://matplotlib.org/sampledoc/ipython_directive.html>`_ sphinx extension.
+ This directive lets you put code in the documentation which will be run
+ during the doc build. For example:
+
+ ::
+
+ .. ipython:: python
+
+ x = 2
+ x**3
+
+ will be renderd as
+
+ ::
+
+ In [1]: x = 2
+
+ In [2]: x**3
+ Out[2]: 8
+
+ This means that almost all code examples in the docs are always run (and the
+ ouptut saved) during the doc build. This way, they will always be up to date,
+ but it makes the doc building a bit more complex.
+
+
+How to build the pandas documentation
+-------------------------------------
+
+Requirements
+^^^^^^^^^^^^
+
+To build the pandas docs there are some extra requirements: you will need to
+have ``sphinx`` and ``ipython`` installed. `numpydoc
+<https://github.com/numpy/numpydoc>`_ is used to parse the docstrings that
+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.
+
+Furthermore, it is recommended to have all `optional dependencies
+<http://pandas.pydata.org/pandas-docs/dev/install.html#optional-dependencies>`_
+installed. This is not needed, but be aware that you will see some error
+messages. Because all the code in the documentation is executed during the doc
+build, the examples using this optional dependencies will generate errors.
+Run ``pd.show_version()`` to get an overview of the installed version of all
+dependencies.
+
+.. warning::
+
+ Building the docs with Sphinx version 1.2 is broken. Use the
+ latest stable version (1.2.1) or the older 1.1.3.
+
+Building pandas
+^^^^^^^^^^^^^^^
+
+For a step-by-step overview on how to set up your environment, to work with
+the pandas code and git, see `the developer pages
+<http://pandas.pydata.org/developers.html#working-with-the-code>`_.
+When you start to work on some docs, be sure to update your code to the latest
+development version ('master')::
+
+ git fetch upstream
+ git rebase upstream/master
+
+Often it will be necessary to rebuild the C extension after updating::
+
+ python setup.py build_ext --inplace
+
+Building the documentation
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+So how do you build the docs? Navigate to your local the folder
+``pandas/doc/`` directory in the console and run::
+
+ python make.py html
+
+And then you can find the html output in the folder ``pandas/doc/build/html/``.
+
+The first time it will take quite a while, because it has to run all the code
+examples in the documentation and build all generated docstring pages.
+In subsequent evocations, sphinx will try to only build the pages that have
+been modified.
+
+If you want to do a full clean build, do::
+
+ python make.py clean
+ python make.py build
+
+
+Where to start?
+---------------
+
+There are a number of issues listed under `Docs
+<https://github.com/pydata/pandas/issues?labels=Docs&sort=updated&state=open>`_
+and `Good as first PR
+<https://github.com/pydata/pandas/issues?labels=Good+as+first+PR&sort=updated&state=open>`_
+where you could start out.
+
+Or maybe you have an idea of you own, by using pandas, looking for something
+in the documentation and thinking 'this can be improved', let's do something
+about that!
+
+Feel free to ask questions on `mailing list
+<https://groups.google.com/forum/?fromgroups#!forum/pydata>`_ or submit an
+issue on Github.
diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst
new file mode 100644
index 0000000000000..d0385df02ea15
--- /dev/null
+++ b/doc/source/contributing.rst
@@ -0,0 +1,5 @@
+**********************
+Contributing to pandas
+**********************
+
+.. include:: ../README.rst
diff --git a/doc/source/index.rst b/doc/source/index.rst
index 78b57795854fa..145eb4e2352e6 100644
--- a/doc/source/index.rst
+++ b/doc/source/index.rst
@@ -135,4 +135,5 @@ See the package overview for more detail about what's in the library.
comparison_with_r
comparison_with_sql
api
+ contributing
release
| First draft of some guidelines on contributing to and building the docs (following #5934). Comments are very welcome.
Rendered version can be seen here: https://github.com/jorisvandenbossche/pandas/blob/doc-guide/doc/README.rst
TODO:
- [x] update section on Sphinx 1.2 now 1.2.1 is released
| https://api.github.com/repos/pandas-dev/pandas/pulls/5996 | 2014-01-18T22:54:08Z | 2014-01-25T01:09:54Z | 2014-01-25T01:09:54Z | 2014-07-02T10:56:37Z |
BUG/CLN: clarified timedelta inferences | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 1ae70b1d93420..6e764e39b4db8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -62,6 +62,8 @@ API Changes
when detecting chained assignment, related (:issue:`5938`)
- DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
- ``autocorrelation_plot`` now accepts ``**kwargs``. (:issue:`5623`)
+ - ``convert_objects`` now accepts a ``convert_timedeltas='coerce'`` argument to allow forced dtype conversion of
+ timedeltas (:issue:`5458`,:issue:`5689`)
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
@@ -78,12 +80,13 @@ Improvements to existing features
- support ``dtypes`` property on ``Series/Panel/Panel4D``
- extend ``Panel.apply`` to allow arbitrary functions (rather than only ufuncs) (:issue:`1148`)
allow multiple axes to be used to operate on slabs of a ``Panel``
- - The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
+ - The ``ArrayFormatter`` for ``datetime`` and ``timedelta64`` now intelligently
limit precision based on the values in the array (:issue:`3401`)
- pd.show_versions() is now available for convenience when reporting issues.
- perf improvements to Series.str.extract (:issue:`5944`)
- perf improvments in ``dtypes/ftypes`` methods (:issue:`5968`)
- perf improvments in indexing with object dtypes (:issue:`5968`)
+ - improved dtype inference for ``timedelta`` like passed to constructors (:issue:`5458`,:issue:`5689`)
.. _release.bug_fixes-0.13.1:
@@ -122,6 +125,7 @@ Bug Fixes
- Recent changes in IPython cause warnings to be emitted when using previous versions
of pandas in QTConsole, now fixed. If you're using an older version and
need to supress the warnings, see (:issue:`5922`).
+ - Bug in merging ``timedelta`` dtypes (:issue:`5695`)
pandas 0.13.0
-------------
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 31004d24e56a6..08c8eb76caaf8 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -3,7 +3,7 @@
v0.13.1 (???)
-------------
-This is a major release from 0.13.0 and includes a number of API changes, several new features and
+This is a minor release from 0.13.0 and includes a number of API changes, several new features and
enhancements along with a large number of bug fixes.
Highlights include:
@@ -29,6 +29,27 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+- The ``ArrayFormatter`` for ``datetime`` and ``timedelta64`` now intelligently
+ limit precision based on the values in the array (:issue:`3401`)
+
+ Previously output might look like:
+
+ .. code-block:: python
+
+ age today diff
+ 0 2001-01-01 00:00:00 2013-04-19 00:00:00 4491 days, 00:00:00
+ 1 2004-06-01 00:00:00 2013-04-19 00:00:00 3244 days, 00:00:00
+
+ Now the output looks like:
+
+ .. ipython:: python
+
+ df = DataFrame([ Timestamp('20010101'),
+ Timestamp('20040601') ], columns=['age'])
+ df['today'] = Timestamp('20130419')
+ df['diff'] = df['today']-df['age']
+ df
+
- ``Panel.apply`` will work on non-ufuncs. See :ref:`the docs<basics.apply_panel>`.
.. ipython:: python
@@ -83,27 +104,6 @@ Enhancements
result
result.loc[:,:,'ItemA']
-- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
- limit precision based on the values in the array (:issue:`3401`)
-
- Previously output might look like:
-
- .. code-block:: python
-
- age today diff
- 0 2001-01-01 00:00:00 2013-04-19 00:00:00 4491 days, 00:00:00
- 1 2004-06-01 00:00:00 2013-04-19 00:00:00 3244 days, 00:00:00
-
- Now the output looks like:
-
- .. ipython:: python
-
- df = DataFrame([ Timestamp('20010101'),
- Timestamp('20040601') ], columns=['age'])
- df['today'] = Timestamp('20130419')
- df['diff'] = df['today']-df['age']
- df
-
Experimental
~~~~~~~~~~~~
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 774ef02b594f3..5b585c44ca3b8 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1514,7 +1514,8 @@ def _values_from_object(o):
def _possibly_convert_objects(values, convert_dates=True,
- convert_numeric=True):
+ convert_numeric=True,
+ convert_timedeltas=True):
""" if we have an object dtype, try to coerce dates and/or numbers """
# if we have passed in a list or scalar
@@ -1539,6 +1540,22 @@ def _possibly_convert_objects(values, convert_dates=True,
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 \
+ _possibly_cast_to_timedelta
+ values = _possibly_cast_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:
@@ -1624,7 +1641,7 @@ def _possibly_cast_to_datetime(value, dtype, coerce=False):
elif is_timedelta64:
from pandas.tseries.timedeltas import \
_possibly_cast_to_timedelta
- value = _possibly_cast_to_timedelta(value)
+ value = _possibly_cast_to_timedelta(value, coerce='compat')
except:
pass
@@ -1655,7 +1672,7 @@ def _possibly_cast_to_datetime(value, dtype, coerce=False):
elif inferred_type in ['timedelta', 'timedelta64']:
from pandas.tseries.timedeltas import \
_possibly_cast_to_timedelta
- value = _possibly_cast_to_timedelta(value)
+ value = _possibly_cast_to_timedelta(value, coerce='compat')
return value
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 82bc3ac25f68a..fbd49dbe6eeaf 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3626,7 +3626,7 @@ def append(self, other, ignore_index=False, verify_integrity=False):
index = None if other.name is None else [other.name]
other = other.reindex(self.columns, copy=False)
other = DataFrame(other.values.reshape((1, len(other))),
- index=index, columns=self.columns)
+ index=index, columns=self.columns).convert_objects()
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
other = DataFrame(other)
if (self.columns.get_indexer(other.columns) >= 0).all():
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4bf27c08cb253..f1e890216830a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1844,16 +1844,18 @@ def copy(self, deep=True):
return self._constructor(data).__finalize__(self)
def convert_objects(self, convert_dates=True, convert_numeric=False,
- copy=True):
+ convert_timedeltas=True, copy=True):
"""
Attempt to infer better dtype for object columns
Parameters
----------
- convert_dates : if True, attempt to soft convert_dates, if 'coerce',
+ convert_dates : if True, attempt to soft convert dates, if 'coerce',
force conversion (and non-convertibles get NaT)
convert_numeric : if True attempt to coerce to numbers (including
strings), non-convertibles get NaN
+ convert_timedeltas : if True, attempt to soft convert timedeltas, if 'coerce',
+ force conversion (and non-convertibles get NaT)
copy : Boolean, if True, return copy, default is True
Returns
@@ -1863,6 +1865,7 @@ def convert_objects(self, convert_dates=True, convert_numeric=False,
return self._constructor(
self._data.convert(convert_dates=convert_dates,
convert_numeric=convert_numeric,
+ convert_timedeltas=convert_timedeltas,
copy=copy)).__finalize__(self)
#----------------------------------------------------------------------
@@ -3174,23 +3177,22 @@ def abs(self):
-------
abs: type of caller
"""
- obj = np.abs(self)
# suprimo numpy 1.6 hacking
+ # for timedeltas
if _np_version_under1p7:
+
+ def _convert_timedeltas(x):
+ if x.dtype.kind == 'm':
+ return np.abs(x.view('i8')).astype(x.dtype)
+ return np.abs(x)
+
if self.ndim == 1:
- if obj.dtype == 'm8[us]':
- obj = obj.astype('m8[ns]')
+ return _convert_timedeltas(self)
elif self.ndim == 2:
- def f(x):
- if x.dtype == 'm8[us]':
- x = x.astype('m8[ns]')
- return x
-
- if 'm8[us]' in obj.dtypes.values:
- obj = obj.apply(f)
+ return self.apply(_convert_timedeltas)
- return obj
+ return np.abs(self)
def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None,
**kwds):
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index fbea40eb76a0d..0603746cf9dc5 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1315,8 +1315,8 @@ def is_bool(self):
"""
return lib.is_bool_array(self.values.ravel())
- def convert(self, convert_dates=True, convert_numeric=True, copy=True,
- by_item=True):
+ def convert(self, convert_dates=True, convert_numeric=True, convert_timedeltas=True,
+ copy=True, by_item=True):
""" attempt to coerce any object types to better types
return a copy of the block (if copy = True)
by definition we ARE an ObjectBlock!!!!!
@@ -1334,7 +1334,8 @@ def convert(self, convert_dates=True, convert_numeric=True, copy=True,
values = com._possibly_convert_objects(
values.ravel(), convert_dates=convert_dates,
- convert_numeric=convert_numeric
+ convert_numeric=convert_numeric,
+ convert_timedeltas=convert_timedeltas,
).reshape(values.shape)
values = _block_shape(values, ndim=self.ndim)
items = self.items.take([i])
diff --git a/pandas/lib.pyx b/pandas/lib.pyx
index afd8ac87589be..ea5071eab976c 100644
--- a/pandas/lib.pyx
+++ b/pandas/lib.pyx
@@ -14,7 +14,7 @@ from cpython cimport (PyDict_New, PyDict_GetItem, PyDict_SetItem,
Py_INCREF, PyTuple_SET_ITEM,
PyList_Check, PyFloat_Check,
PyString_Check,
- PyBytes_Check,
+ PyBytes_Check,
PyTuple_SetItem,
PyTuple_New,
PyObject_SetAttrString)
@@ -31,7 +31,7 @@ from datetime import datetime as pydatetime
# this is our tseries.pxd
from datetime cimport *
-from tslib cimport convert_to_tsobject
+from tslib cimport convert_to_tsobject, convert_to_timedelta64
import tslib
from tslib import NaT, Timestamp, repr_timedelta64
diff --git a/pandas/src/datetime.pxd b/pandas/src/datetime.pxd
index 3e11c9d20fb0d..abd3bc3333adb 100644
--- a/pandas/src/datetime.pxd
+++ b/pandas/src/datetime.pxd
@@ -37,6 +37,7 @@ cdef extern from "datetime.h":
bint PyDateTime_Check(object o)
bint PyDate_Check(object o)
bint PyTime_Check(object o)
+ bint PyDelta_Check(object o)
object PyDateTime_FromDateAndTime(int year, int month, int day, int hour,
int minute, int second, int us)
diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx
index 84f1f3cb4904d..e23afad278ee7 100644
--- a/pandas/src/inference.pyx
+++ b/pandas/src/inference.pyx
@@ -1,4 +1,7 @@
cimport util
+from tslib import NaT
+from datetime import datetime, timedelta
+iNaT = util.get_nat()
_TYPE_MAP = {
np.int8: 'integer',
@@ -55,15 +58,26 @@ def infer_dtype(object _values):
val = util.get_value_1d(values, 0)
- if util.is_datetime64_object(val):
+ if util.is_datetime64_object(val) or val is NaT:
if is_datetime64_array(values):
return 'datetime64'
+ elif is_timedelta_or_timedelta64_array(values):
+ return 'timedelta'
+
elif util.is_integer_object(val):
+ # a timedelta will show true here as well
+ if is_timedelta(val):
+ if is_timedelta_or_timedelta64_array(values):
+ return 'timedelta'
+
if is_integer_array(values):
return 'integer'
elif is_integer_float_array(values):
return 'mixed-integer-float'
+ elif is_timedelta_or_timedelta64_array(values):
+ return 'timedelta'
return 'mixed-integer'
+
elif is_datetime(val):
if is_datetime_array(values):
return 'datetime'
@@ -115,6 +129,9 @@ def infer_dtype_list(list values):
pass
+cdef inline bint is_null_datetimelike(v):
+ return util._checknull(v) or (util.is_integer_object(v) and v == iNaT) or v is NaT
+
cdef inline bint is_datetime(object o):
return PyDateTime_Check(o)
@@ -124,6 +141,9 @@ cdef inline bint is_date(object o):
cdef inline bint is_time(object o):
return PyTime_Check(o)
+cdef inline bint is_timedelta(object o):
+ return PyDelta_Check(o) or util.is_timedelta64_object(o)
+
def is_bool_array(ndarray values):
cdef:
Py_ssize_t i, n = len(values)
@@ -258,53 +278,58 @@ def is_unicode_array(ndarray values):
def is_datetime_array(ndarray[object] values):
cdef int i, n = len(values)
+ cdef object v
if n == 0:
return False
for i in range(n):
- if not is_datetime(values[i]):
+ v = values[i]
+ if not (is_datetime(v) or is_null_datetimelike(v)):
return False
return True
def is_datetime64_array(ndarray values):
cdef int i, n = len(values)
+ cdef object v
if n == 0:
return False
for i in range(n):
- if not util.is_datetime64_object(values[i]):
+ v = values[i]
+ if not (util.is_datetime64_object(v) or is_null_datetimelike(v)):
return False
return True
-def is_timedelta(object o):
- import datetime
- return isinstance(o,datetime.timedelta) or isinstance(o,np.timedelta64)
-
def is_timedelta_array(ndarray values):
- import datetime
cdef int i, n = len(values)
+ cdef object v
if n == 0:
return False
for i in range(n):
- if not isinstance(values[i],datetime.timedelta):
+ v = values[i]
+ if not (PyDelta_Check(v) or is_null_datetimelike(v)):
return False
return True
def is_timedelta64_array(ndarray values):
cdef int i, n = len(values)
+ cdef object v
if n == 0:
return False
for i in range(n):
- if not isinstance(values[i],np.timedelta64):
+ v = values[i]
+ if not (util.is_timedelta64_object(v) or is_null_datetimelike(v)):
return False
return True
def is_timedelta_or_timedelta64_array(ndarray values):
- import datetime
+ """ infer with timedeltas and/or nat/none """
cdef int i, n = len(values)
+ cdef object v
if n == 0:
return False
for i in range(n):
- if not (isinstance(values[i],datetime.timedelta) or isinstance(values[i],np.timedelta64)):
+ v = values[i]
+ if not (is_timedelta(v) or is_null_datetimelike(v)):
return False
return True
@@ -427,7 +452,7 @@ def maybe_convert_numeric(ndarray[object] values, set na_values,
return ints
def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
- bint safe=0, bint convert_datetime=0):
+ bint safe=0, bint convert_datetime=0, bint convert_timedelta=0):
'''
Type inference function-- convert object array to proper dtype
'''
@@ -438,9 +463,11 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
ndarray[int64_t] ints
ndarray[uint8_t] bools
ndarray[int64_t] idatetimes
+ ndarray[int64_t] itimedeltas
bint seen_float = 0
bint seen_complex = 0
bint seen_datetime = 0
+ bint seen_timedelta = 0
bint seen_int = 0
bint seen_bool = 0
bint seen_object = 0
@@ -455,8 +482,14 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
complexes = np.empty(n, dtype='c16')
ints = np.empty(n, dtype='i8')
bools = np.empty(n, dtype=np.uint8)
- datetimes = np.empty(n, dtype='M8[ns]')
- idatetimes = datetimes.view(np.int64)
+
+ if convert_datetime:
+ datetimes = np.empty(n, dtype='M8[ns]')
+ idatetimes = datetimes.view(np.int64)
+
+ if convert_timedelta:
+ timedeltas = np.empty(n, dtype='m8[ns]')
+ itimedeltas = timedeltas.view(np.int64)
onan = np.nan
fnan = np.nan
@@ -481,9 +514,13 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
seen_object = 1
# objects[i] = val.astype('O')
break
- elif util.is_timedelta64_object(val):
- seen_object = 1
- break
+ elif is_timedelta(val):
+ if convert_timedelta:
+ itimedeltas[i] = convert_to_timedelta64(val, 'ns', False)
+ seen_timedelta = 1
+ else:
+ seen_object = 1
+ break
elif util.is_integer_object(val):
seen_int = 1
floats[i] = <float64_t> val
@@ -523,7 +560,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
if not safe:
if seen_null:
- if not seen_bool and not seen_datetime:
+ if not seen_bool and not seen_datetime and not seen_timedelta:
if seen_complex:
return complexes
elif seen_float or seen_int:
@@ -533,6 +570,9 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
if seen_datetime:
if not seen_numeric:
return datetimes
+ elif seen_timedelta:
+ if not seen_numeric:
+ return timedeltas
else:
if seen_complex:
return complexes
@@ -540,13 +580,13 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
return floats
elif seen_int:
return ints
- elif not seen_datetime and not seen_numeric:
+ elif not seen_datetime and not seen_numeric and not seen_timedelta:
return bools.view(np.bool_)
else:
# don't cast int to float, etc.
if seen_null:
- if not seen_bool and not seen_datetime:
+ if not seen_bool and not seen_datetime and not seen_timedelta:
if seen_complex:
if not seen_int:
return complexes
@@ -558,6 +598,9 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
if seen_datetime:
if not seen_numeric:
return datetimes
+ elif seen_timedelta:
+ if not seen_numeric:
+ return timedeltas
else:
if seen_complex:
if not seen_int:
@@ -567,7 +610,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0,
return floats
elif seen_int:
return ints
- elif not seen_datetime and not seen_numeric:
+ elif not seen_datetime and not seen_numeric and not seen_timedelta:
return bools.view(np.bool_)
return objects
@@ -582,8 +625,6 @@ def try_parse_dates(ndarray[object] values, parser=None,
Py_ssize_t i, n
ndarray[object] result
- from datetime import datetime, timedelta
-
n = len(values)
result = np.empty(n, dtype='O')
@@ -841,8 +882,10 @@ def map_infer_mask(ndarray arr, object f, ndarray[uint8_t] mask,
result[i] = val
if convert:
- return maybe_convert_objects(result, try_float=0,
- convert_datetime=0)
+ return maybe_convert_objects(result,
+ try_float=0,
+ convert_datetime=0,
+ convert_timedelta=0)
return result
@@ -877,8 +920,10 @@ def map_infer(ndarray arr, object f, bint convert=1):
result[i] = val
if convert:
- return maybe_convert_objects(result, try_float=0,
- convert_datetime=0)
+ return maybe_convert_objects(result,
+ try_float=0,
+ convert_datetime=0,
+ convert_timedelta=0)
return result
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 6b4a9a2bc4c22..f3f3127bbe875 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2246,23 +2246,46 @@ def test_operators_empty_int_corner(self):
def test_constructor_dtype_timedelta64(self):
+ # basic
td = Series([timedelta(days=i) for i in range(3)])
self.assert_(td.dtype == 'timedelta64[ns]')
+ td = Series([timedelta(days=1)])
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
+ if not _np_version_under1p7:
+ td = Series([timedelta(days=1),timedelta(days=2),np.timedelta64(1,'s')])
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
# mixed with NaT
from pandas import tslib
- td = Series([timedelta(days=i)
- for i in range(3)] + [tslib.NaT ], dtype='m8[ns]' )
+ td = Series([timedelta(days=1),tslib.NaT ], dtype='m8[ns]' )
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
+ td = Series([timedelta(days=1),np.nan ], dtype='m8[ns]' )
self.assert_(td.dtype == 'timedelta64[ns]')
- td = Series([timedelta(days=i)
- for i in range(3)] + [tslib.iNaT ], dtype='m8[ns]' )
+ td = Series([np.timedelta64(300000000), pd.NaT],dtype='m8[ns]')
self.assert_(td.dtype == 'timedelta64[ns]')
- td = Series([timedelta(days=i)
- for i in range(3)] + [np.nan ], dtype='m8[ns]' )
+ # improved inference
+ # GH5689
+ td = Series([np.timedelta64(300000000), pd.NaT])
self.assert_(td.dtype == 'timedelta64[ns]')
+ td = Series([np.timedelta64(300000000), tslib.iNaT])
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
+ td = Series([np.timedelta64(300000000), np.nan])
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
+ td = Series([pd.NaT, np.timedelta64(300000000)])
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
+ if not _np_version_under1p7:
+ td = Series([np.timedelta64(1,'s')])
+ self.assert_(td.dtype == 'timedelta64[ns]')
+
# these are frequency conversion astypes
#for t in ['s', 'D', 'us', 'ms']:
# self.assertRaises(TypeError, td.astype, 'm8[%s]' % t)
@@ -2270,11 +2293,14 @@ def test_constructor_dtype_timedelta64(self):
# valid astype
td.astype('int64')
- # this is an invalid casting
- self.assertRaises(Exception, Series, [timedelta(days=i)
- for i in range(3)] + ['foo' ], dtype='m8[ns]' )
+ # invalid casting
self.assertRaises(TypeError, td.astype, 'int32')
+ # this is an invalid casting
+ def f():
+ Series([timedelta(days=1), 'foo'],dtype='m8[ns]')
+ self.assertRaises(Exception, f)
+
# leave as object here
td = Series([timedelta(days=i) for i in range(3)] + ['foo'])
self.assert_(td.dtype == 'object')
@@ -2854,6 +2880,9 @@ def test_bfill(self):
assert_series_equal(ts.bfill(), ts.fillna(method='bfill'))
def test_sub_of_datetime_from_TimeSeries(self):
+ if _np_version_under1p7:
+ raise nose.SkipTest("timedelta broken in np 1.6.1")
+
from pandas.tseries.timedeltas import _possibly_cast_to_timedelta
from datetime import datetime
a = Timestamp(datetime(1993, 0o1, 0o7, 13, 30, 00))
diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py
index dd7ab65869303..41a4cf9984c14 100644
--- a/pandas/tools/merge.py
+++ b/pandas/tools/merge.py
@@ -14,7 +14,7 @@
from pandas.core.index import (Index, MultiIndex, _get_combined_index,
_ensure_index, _get_consensus_names,
_all_indexes_same)
-from pandas.core.internals import (IntBlock, BoolBlock, BlockManager,
+from pandas.core.internals import (TimeDeltaBlock, IntBlock, BoolBlock, BlockManager,
make_block, _consolidate)
from pandas.util.decorators import cache_readonly, Appender, Substitution
from pandas.core.common import (PandasError, ABCSeries,
@@ -816,7 +816,7 @@ def reindex_block(self, block, axis, ref_items, copy=True):
def _may_need_upcasting(blocks):
for block in blocks:
- if isinstance(block, (IntBlock, BoolBlock)):
+ if isinstance(block, (IntBlock, BoolBlock)) and not isinstance(block, TimeDeltaBlock):
return True
return False
@@ -827,7 +827,10 @@ def _upcast_blocks(blocks):
"""
new_blocks = []
for block in blocks:
- if isinstance(block, IntBlock):
+ if isinstance(block, TimeDeltaBlock):
+ # these are int blocks underlying, but are ok
+ newb = block
+ elif isinstance(block, IntBlock):
newb = make_block(block.values.astype(float), block.items,
block.ref_items, placement=block._ref_locs)
elif isinstance(block, BoolBlock):
diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py
index e3b448b650767..a0d90ac0920eb 100644
--- a/pandas/tools/tests/test_merge.py
+++ b/pandas/tools/tests/test_merge.py
@@ -9,7 +9,7 @@
import random
from pandas.compat import range, lrange, lzip, zip
-from pandas import compat
+from pandas import compat, _np_version_under1p7
from pandas.tseries.index import DatetimeIndex
from pandas.tools.merge import merge, concat, ordered_merge, MergeError
from pandas.util.testing import (assert_frame_equal, assert_series_equal,
@@ -791,6 +791,34 @@ def test_append_dtype_coerce(self):
result = df1.append(df2,ignore_index=True)
assert_frame_equal(result, expected)
+ def test_join_append_timedeltas(self):
+
+ import datetime as dt
+ from pandas import NaT
+
+ # timedelta64 issues with join/merge
+ # GH 5695
+ if _np_version_under1p7:
+ raise nose.SkipTest("numpy < 1.7")
+
+ d = {'d': dt.datetime(2013, 11, 5, 5, 56), 't': dt.timedelta(0, 22500)}
+ df = DataFrame(columns=list('dt'))
+ df = df.append(d, ignore_index=True)
+ result = df.append(d, ignore_index=True)
+ expected = DataFrame({'d': [dt.datetime(2013, 11, 5, 5, 56),
+ dt.datetime(2013, 11, 5, 5, 56) ],
+ 't': [ dt.timedelta(0, 22500),
+ dt.timedelta(0, 22500) ]})
+ assert_frame_equal(result, expected)
+
+ td = np.timedelta64(300000000)
+ lhs = DataFrame(Series([td,td],index=["A","B"]))
+ rhs = DataFrame(Series([td],index=["A"]))
+
+ from pandas import NaT
+ result = lhs.join(rhs,rsuffix='r', how="left")
+ expected = DataFrame({ '0' : Series([td,td],index=list('AB')), '0r' : Series([td,NaT],index=list('AB')) })
+ assert_frame_equal(result, expected)
def test_overlapping_columns_error_message(self):
# #2649
@@ -1763,7 +1791,24 @@ def test_concat_datetime64_block(self):
df = DataFrame({'time': rng})
result = concat([df, df])
- self.assert_((result[:10]['time'] == rng).all())
+ self.assert_((result.iloc[:10]['time'] == rng).all())
+ self.assert_((result.iloc[10:]['time'] == rng).all())
+
+ def test_concat_timedelta64_block(self):
+
+ # not friendly for < 1.7
+ if _np_version_under1p7:
+ raise nose.SkipTest("numpy < 1.7")
+
+ from pandas import to_timedelta
+
+ rng = to_timedelta(np.arange(10),unit='s')
+
+ df = DataFrame({'time': rng})
+
+ result = concat([df, df])
+ self.assert_((result.iloc[:10]['time'] == rng).all())
+ self.assert_((result.iloc[10:]['time'] == rng).all())
def test_concat_keys_with_none(self):
# #1649
diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py
index 1d34c5b91d5ed..3d8ee87f6c42f 100644
--- a/pandas/tseries/tests/test_timedeltas.py
+++ b/pandas/tseries/tests/test_timedeltas.py
@@ -165,11 +165,24 @@ def conv(v):
# single element conversion
v = timedelta(seconds=1)
result = to_timedelta(v,box=False)
- expected = to_timedelta([v])
+ expected = np.timedelta64(timedelta(seconds=1))
+ self.assert_(result == expected)
v = np.timedelta64(timedelta(seconds=1))
result = to_timedelta(v,box=False)
- expected = to_timedelta([v])
+ expected = np.timedelta64(timedelta(seconds=1))
+ self.assert_(result == expected)
+
+ def test_to_timedelta_via_apply(self):
+ _skip_if_numpy_not_friendly()
+
+ # GH 5458
+ expected = Series([np.timedelta64(1,'s')])
+ result = Series(['00:00:01']).apply(to_timedelta)
+ tm.assert_series_equal(result, expected)
+
+ result = Series([to_timedelta('00:00:01')])
+ tm.assert_series_equal(result, expected)
def test_timedelta_ops(self):
_skip_if_numpy_not_friendly()
diff --git a/pandas/tseries/timedeltas.py b/pandas/tseries/timedeltas.py
index 835401a13403f..4a522d9874c4f 100644
--- a/pandas/tseries/timedeltas.py
+++ b/pandas/tseries/timedeltas.py
@@ -70,42 +70,16 @@ def _convert_listlike(arg, box):
_whitespace = re.compile('^\s*$')
def _coerce_scalar_to_timedelta_type(r, unit='ns'):
- # kludgy here until we have a timedelta scalar
- # handle the numpy < 1.7 case
-
- def conv(v):
- if _np_version_under1p7:
- return timedelta(microseconds=v/1000.0)
- return np.timedelta64(v)
+ """ convert strings to timedelta; coerce to np.timedelta64"""
if isinstance(r, compat.string_types):
+
+ # we are already converting to nanoseconds
converter = _get_string_converter(r, unit=unit)
r = converter()
- r = conv(r)
- elif r == tslib.iNaT:
- return r
- elif isnull(r):
- return np.timedelta64('NaT')
- elif isinstance(r, np.timedelta64):
- r = r.astype("m8[{0}]".format(unit.lower()))
- elif is_integer(r):
- r = tslib.cast_from_unit(r, unit)
- r = conv(r)
+ unit='ns'
- if _np_version_under1p7:
- if not isinstance(r, timedelta):
- raise AssertionError("Invalid type for timedelta scalar: %s" % type(r))
- if compat.PY3:
- # convert to microseconds in timedelta64
- r = np.timedelta64(int(r.total_seconds()*1e9 + r.microseconds*1000))
- else:
- return r
-
- if isinstance(r, timedelta):
- r = np.timedelta64(r)
- elif not isinstance(r, np.timedelta64):
- raise AssertionError("Invalid type for timedelta scalar: %s" % type(r))
- return r.astype('timedelta64[ns]')
+ return tslib.convert_to_timedelta(r,unit)
def _get_string_converter(r, unit='ns'):
""" return a string converter for r to process the timedelta format """
@@ -189,7 +163,7 @@ def convert(td, dtype):
td *= 1000
return td
- if td == tslib.compat_NaT:
+ if isnull(td) or td == tslib.compat_NaT or td == tslib.iNaT:
return tslib.iNaT
# convert td value to a nanosecond value
diff --git a/pandas/tslib.pxd b/pandas/tslib.pxd
index a70f9883c5bb1..1452dbdca03ee 100644
--- a/pandas/tslib.pxd
+++ b/pandas/tslib.pxd
@@ -1,3 +1,4 @@
from numpy cimport ndarray, int64_t
cdef convert_to_tsobject(object, object, object)
+cdef convert_to_timedelta64(object, object, object)
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index e303df23003cb..c2a727d7d3394 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -38,6 +38,12 @@ from pandas.compat import parse_date
from sys import version_info
+# numpy compat
+from distutils.version import LooseVersion
+_np_version = np.version.short_version
+_np_version_under1p6 = LooseVersion(_np_version) < '1.6'
+_np_version_under1p7 = LooseVersion(_np_version) < '1.7'
+
# GH3363
cdef bint PY2 = version_info[0] == 2
@@ -1149,48 +1155,80 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
return oresult
-def array_to_timedelta64(ndarray[object] values, coerce=True):
+def array_to_timedelta64(ndarray[object] values, coerce=False):
""" convert an ndarray to an array of ints that are timedeltas
force conversion if coerce = True,
- else return an object array """
+ else will raise if cannot convert """
cdef:
Py_ssize_t i, n
- object val
- ndarray[int64_t] result
+ ndarray[int64_t] iresult
n = values.shape[0]
- result = np.empty(n, dtype='i8')
+ result = np.empty(n, dtype='m8[ns]')
+ iresult = result.view('i8')
+
for i in range(n):
- val = values[i]
+ result[i] = convert_to_timedelta64(values[i], 'ns', coerce)
+ return iresult
- # in py3 this is already an int, don't convert
- if is_integer_object(val):
- result[i] = val
+def convert_to_timedelta(object ts, object unit='ns', coerce=False):
+ return convert_to_timedelta64(ts, unit, coerce)
- elif isinstance(val,timedelta) or isinstance(val,np.timedelta64):
+cdef convert_to_timedelta64(object ts, object unit, object coerce):
+ """
+ Convert an incoming object to a timedelta64 if possible
- if isinstance(val, np.timedelta64):
- if val.dtype != 'm8[ns]':
- val = val.astype('m8[ns]')
- val = val.item()
- else:
- val = _delta_to_nanoseconds(np.timedelta64(val).item())
+ Handle these types of objects:
+ - timedelta
+ - timedelta64
+ - np.int64 (with unit providing a possible modifier)
+ - None/NaT
- result[i] = val
+ if coerce, set a non-valid value to NaT
- elif _checknull_with_nat(val):
- result[i] = iNaT
+ Return a ns based int64
+ # kludgy here until we have a timedelta scalar
+ # handle the numpy < 1.7 case
+ """
+ if _checknull_with_nat(ts):
+ ts = np.timedelta64(iNaT)
+ elif util.is_datetime64_object(ts):
+ # only accept a NaT here
+ if ts.astype('int64') == iNaT:
+ ts = np.timedelta64(iNaT)
+ elif isinstance(ts, np.timedelta64):
+ ts = ts.astype("m8[{0}]".format(unit.lower()))
+ elif is_integer_object(ts):
+ if ts == iNaT:
+ ts = np.timedelta64(iNaT)
else:
+ if util.is_array(ts):
+ ts = ts.astype('int64').item()
+ ts = cast_from_unit(ts, unit)
+ if _np_version_under1p7:
+ ts = timedelta(microseconds=ts/1000.0)
+ else:
+ ts = np.timedelta64(ts)
- # just return, don't convert
- if not coerce:
- return values.copy()
-
- result[i] = iNaT
-
- return result
+ if _np_version_under1p7:
+ if not isinstance(ts, timedelta):
+ if coerce:
+ return np.timedelta64(iNaT)
+ raise ValueError("Invalid type for timedelta scalar: %s" % type(ts))
+ if not PY2:
+ # convert to microseconds in timedelta64
+ ts = np.timedelta64(int(ts.total_seconds()*1e9 + ts.microseconds*1000))
+ else:
+ return ts
+ if isinstance(ts, timedelta):
+ ts = np.timedelta64(ts)
+ elif not isinstance(ts, np.timedelta64):
+ if coerce:
+ return np.timedelta64(iNaT)
+ raise ValueError("Invalid type for timedelta scalar: %s" % type(ts))
+ return ts.astype('timedelta64[ns]')
def repr_timedelta64(object value, format=None):
"""
@@ -1206,6 +1244,7 @@ def repr_timedelta64(object value, format=None):
converted : Timestamp
"""
+ cdef object ivalue
ivalue = value.view('i8')
diff --git a/test.py b/test.py
new file mode 100644
index 0000000000000..a1cbac87ab2b3
--- /dev/null
+++ b/test.py
@@ -0,0 +1,12 @@
+import numpy as np
+import pandas
+from pandas import Series,DataFrame
+
+print pandas.__version__
+
+s = Series(np.arange(1028.))
+
+df = DataFrame({ i:s for i in range(1028) })
+
+import pdb; pdb.set_trace()
+df.apply(lambda x: np.corrcoef(x,s)[0,1])
| closes #5458
closes #5695
closes #5689
cleaned up / clarified timedelta inferences, bottom line is the following works, previously these would
return not-useful object dtypes
```
In [4]: Series([np.timedelta64(1,'s'),timedelta(days=1),pd.NaT])
Out[4]:
0 0 days, 00:00:01
1 1 days, 00:00:00
2 NaT
dtype: timedelta64[ns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5995 | 2014-01-18T21:00:18Z | 2014-01-20T23:37:17Z | 2014-01-20T23:37:17Z | 2014-06-16T22:59:26Z |
DOC: document read_csv fastpath for iso8601 datetime strings | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 48fe6e24dda9f..363a82ccbcf69 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -456,12 +456,22 @@ data columns:
index_col=0) #index is the nominal column
df
-**Note**: When passing a dict as the `parse_dates` argument, the order of
-the columns prepended is not guaranteed, because `dict` objects do not impose
-an ordering on their keys. On Python 2.7+ you may use `collections.OrderedDict`
-instead of a regular `dict` if this matters to you. Because of this, when using a
-dict for 'parse_dates' in conjunction with the `index_col` argument, it's best to
-specify `index_col` as a column label rather then as an index on the resulting frame.
+.. note::
+ read_csv has a fast_path for parsing datetime strings in iso8601 format,
+ e.g "2000-01-01T00:01:02+00:00" and similar variations. If you can arrange
+ for your data to store datetimes in this format, load times will be
+ significantly faster, ~20x has been observed.
+
+
+.. note::
+
+ When passing a dict as the `parse_dates` argument, the order of
+ the columns prepended is not guaranteed, because `dict` objects do not impose
+ an ordering on their keys. On Python 2.7+ you may use `collections.OrderedDict`
+ instead of a regular `dict` if this matters to you. Because of this, when using a
+ dict for 'parse_dates' in conjunction with the `index_col` argument, it's best to
+ specify `index_col` as a column label rather then as an index on the resulting frame.
+
Date Parsing Functions
~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 99b8bfc460068..1809ec5cccdba 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -1595,6 +1595,9 @@ Improvements to existing features
- Add methods ``neg`` and ``inv`` to Series
- Implement ``kind`` option in ``ExcelFile`` to indicate whether it's an XLS
or XLSX file (:issue:`2613`)
+ - Documented a fast-path in pd.read_Csv when parsing iso8601 datetime strings
+ yielding as much as a 20x speedup. (:issue:`5993`)
+
Bug Fixes
~~~~~~~~~
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 813b7e59e107a..52d4e6bbac50a 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -87,6 +87,7 @@
If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
{'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo'
+ A fast-path exists for iso8601-formatted dates.
keep_date_col : boolean, default False
If True and parse_dates specifies combining multiple columns then
keep the original columns.
| While investigating an optimization suggested in #5490 , I came
across a fast path in pd.read_csv that I was unaware of for parsing iso8601 datetimes.
It's undocumented as far as I can tell.
RIght the wrong.
```
N=10000
r=pd.date_range("2000-01-01","2013-01-01",freq="H")[:N]
df=pd.DataFrame(range(N),index=r)
df.to_csv("/tmp/1.csv")
def f1(s):
return dt.datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
def f2(s):
return dateutil.parser.parse(s)
%timeit x1=pd.read_csv("/tmp/1.csv",parse_dates=True,index_col=0) # fast-path for iso8601, fallback to dateutil.parser
%timeit x2=pd.read_csv("/tmp/1.csv",parse_dates=True,index_col=0,date_parser=f1)
%timeit x2=pd.read_csv("/tmp/1.csv",parse_dates=True,index_col=0,date_parser=f2)
100 loops, best of 3: 14.1 ms per loop
1 loops, best of 3: 259 ms per loop
1 loops, best of 3: 956 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5993 | 2014-01-18T20:04:00Z | 2014-01-18T20:07:12Z | 2014-01-18T20:07:12Z | 2014-06-12T13:16:50Z |
allow path to be an StringIO object and skip extension check for that case | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 151402a8b5370..ba27079b93b96 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -59,7 +59,7 @@ API Changes
- ``Series.sort`` will raise a ``ValueError`` (rather than a ``TypeError``) on sorting an
object that is a view of another (:issue:`5856`, :issue:`5853`)
- Raise/Warn ``SettingWithCopyError`` (according to the option ``chained_assignment`` in more cases,
- when detecting chained assignment, related (:issue:`5938`)
+ when detecting chained assignment, related (:issue:`5938`, :issue:`6025`)
- DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
- ``autocorrelation_plot`` now accepts ``**kwargs``. (:issue:`5623`)
- ``convert_objects`` now accepts a ``convert_timedeltas='coerce'`` argument to allow forced dtype conversion of
@@ -89,6 +89,7 @@ Improvements to existing features
- improved dtype inference for ``timedelta`` like passed to constructors (:issue:`5458`,:issue:`5689`)
- escape special characters when writing to latex (:issue: `5374`)
- perf improvements in ``DataFrame.apply`` (:issue:`6013`)
+ - ``Dataframe``s ``to_excel`` will now also accept file-like objects as output (:issue: `5992`)
.. _release.bug_fixes-0.13.1:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index adb7b2d2b2691..2d4fd2d792732 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1582,7 +1582,7 @@ def _ixs(self, i, axis=0, copy=False):
new_values, copy = self._data.fast_2d_xs(i, copy=copy)
result = Series(new_values, index=self.columns,
name=self.index[i], dtype=new_values.dtype)
- result.is_copy=copy
+ result._set_is_copy(self, copy=copy)
return result
# icol
@@ -1707,7 +1707,7 @@ def _getitem_multilevel(self, key):
if isinstance(result, Series):
result = Series(result, index=self.index, name=key)
- result.is_copy=True
+ result._set_is_copy(self)
return result
else:
return self._get_item_cache(key)
@@ -1878,6 +1878,7 @@ 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):
@@ -1912,6 +1913,7 @@ def _setitem_frame(self, key, value):
raise TypeError(
'Cannot do boolean setting on mixed-type frame')
+ self._check_setitem_copy()
self.where(-key, value, inplace=True)
def _ensure_valid_index(self, value):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index eb24301e5e603..63454d32a5fa1 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2,6 +2,7 @@
import warnings
import operator
import weakref
+import gc
import numpy as np
import pandas.lib as lib
@@ -97,7 +98,7 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
for i, ax in enumerate(axes):
data = data.reindex_axis(ax, axis=i)
- object.__setattr__(self, 'is_copy', False)
+ object.__setattr__(self, 'is_copy', None)
object.__setattr__(self, '_data', data)
object.__setattr__(self, '_item_cache', {})
@@ -994,6 +995,9 @@ def _get_item_cache(self, item):
res = self._box_item_values(item, values)
cache[item] = res
res._set_as_cached(item, self)
+
+ # for a chain
+ res.is_copy = self.is_copy
return res
def _set_as_cached(self, item, cacher):
@@ -1031,16 +1035,14 @@ def _maybe_update_cacher(self, clear=False):
# a copy
if ref is None:
del self._cacher
- self.is_copy = True
- self._check_setitem_copy(stacklevel=5, t='referant')
else:
try:
ref._maybe_cache_changed(cacher[0], self)
except:
pass
- if ref.is_copy:
- self.is_copy = True
- self._check_setitem_copy(stacklevel=5, t='referant')
+
+ # check if we are a copy
+ self._check_setitem_copy(stacklevel=5, t='referant')
if clear:
self._clear_item_cache()
@@ -1055,13 +1057,35 @@ def _set_item(self, key, value):
self._data.set(key, value)
self._clear_item_cache()
+ def _set_is_copy(self, ref=None, copy=True):
+ if not copy:
+ self.is_copy = None
+ else:
+ if ref is not None:
+ self.is_copy = weakref.ref(ref)
+ else:
+ self.is_copy = None
+
def _check_setitem_copy(self, stacklevel=4, t='setting'):
""" 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*"""
if 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
if t == 'referant':
t = ("A value is trying to be set on a copy of a slice from a "
@@ -1143,7 +1167,7 @@ def take(self, indices, axis=0, convert=True, is_copy=True):
# maybe set copy if we didn't actually change the index
if is_copy and not result._get_axis(axis).equals(self._get_axis(axis)):
- result.is_copy=is_copy
+ result._set_is_copy(self)
return result
@@ -1276,12 +1300,12 @@ def xs(self, key, axis=0, level=None, copy=True, drop_level=True):
new_values, copy = self._data.fast_2d_xs(loc, copy=copy)
result = Series(new_values, index=self.columns,
name=self.index[loc])
- result.is_copy=True
else:
result = self[loc]
result.index = new_index
+ result._set_is_copy(self)
return result
_xs = xs
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 474b5ae3ac6d6..9a67f5fe3854e 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -211,7 +211,7 @@ def _setitem_with_indexer(self, indexer, value):
labels = _safe_append_to_index(index, key)
self.obj._data = self.obj.reindex_axis(labels, i)._data
self.obj._maybe_update_cacher(clear=True)
- self.obj.is_copy=False
+ self.obj.is_copy=None
if isinstance(labels, MultiIndex):
self.obj.sortlevel(inplace=True)
@@ -418,6 +418,7 @@ def can_do_equal_len():
if isinstance(value, ABCPanel):
value = self._align_panel(indexer, value)
+ # actually do the set
self.obj._data = self.obj._data.setitem(indexer, value)
self.obj._maybe_update_cacher(clear=True)
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index ad7c37fba4c2f..63d5f57afe2c6 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -431,8 +431,9 @@ def save(self):
def __init__(self, path, engine=None, **engine_kwargs):
# validate that this engine can handle the extnesion
- ext = os.path.splitext(path)[-1]
- self.check_extension(ext)
+ if not hasattr(path, 'read'):
+ ext = os.path.splitext(path)[-1]
+ self.check_extension(ext)
self.path = path
self.sheets = {}
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 698f7777a1100..4ed325df9a747 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -60,7 +60,7 @@ def __init__(self, obj, orient, date_format, double_precision,
self.date_unit = date_unit
self.default_handler = default_handler
- self.is_copy = False
+ self.is_copy = None
self._format_axes()
def _format_axes(self):
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index edcb80ae74f6f..0062f0c514fe5 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -17,6 +17,7 @@
)
from pandas.util.testing import ensure_clean
from pandas.core.config import set_option, get_option
+from pandas.compat import BytesIO
import pandas.util.testing as tm
import pandas as pd
@@ -410,6 +411,22 @@ def test_excelwriter_contextmanager(self):
tm.assert_frame_equal(found_df, self.frame)
tm.assert_frame_equal(found_df2, self.frame2)
+ def test_stringio_writer(self):
+ _skip_if_no_xlsxwriter()
+ _skip_if_no_xlrd()
+
+ path = BytesIO()
+ with ExcelWriter(path, engine='xlsxwriter', **{'options': {'in-memory': True}}) as ew:
+ self.frame.to_excel(ew, 'test1', engine='xlsxwriter')
+ ew.save()
+ path.seek(0)
+ ef = ExcelFile(path)
+ found_df = ef.parse('test1')
+ tm.assert_frame_equal(self.frame, found_df)
+ path.close()
+
+
+
def test_roundtrip(self):
_skip_if_no_xlrd()
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index d0c783725f8bb..86627271c8e6a 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -181,7 +181,7 @@ def test_repr_should_return_str(self):
u("\u03c6")]
cols = [u("\u03c8")]
df = DataFrame(data, columns=cols, index=index1)
- self.assertTrue(type(df.__repr__() == str)) # both py2 / 3
+ self.assertTrue(type(df.__repr__()) == str) # both py2 / 3
def test_repr_no_backslash(self):
with option_context('mode.sim_interactive', True):
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 7daf95ac15a95..3270d80dc9dad 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1380,10 +1380,10 @@ def test_set_value_keeps_names(self):
columns=['one', 'two', 'three', 'four'],
index=idx)
df = df.sortlevel()
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
self.assertEqual(df.index.names, ('Name', 'Number'))
df = df.set_value(('grethe', '4'), 'one', 99.34)
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
self.assertEqual(df.index.names, ('Name', 'Number'))
def test_names(self):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index f80b0d36445cf..8c4572cf63dd1 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2022,7 +2022,7 @@ def test_detect_chained_assignment(self):
# work with the chain
expected = DataFrame([[-5,1],[-6,3]],columns=list('AB'))
df = DataFrame(np.arange(4).reshape(2,2),columns=list('AB'),dtype='int64')
- self.assert_(not df.is_copy)
+ self.assert_(df.is_copy is None)
df['A'][0] = -5
df['A'][1] = -6
@@ -2030,11 +2030,11 @@ def test_detect_chained_assignment(self):
expected = DataFrame([[-5,2],[np.nan,3.]],columns=list('AB'))
df = DataFrame({ 'A' : Series(range(2),dtype='int64'), 'B' : np.array(np.arange(2,4),dtype=np.float64)})
- self.assert_(not df.is_copy)
+ self.assert_(df.is_copy is None)
df['A'][0] = -5
df['A'][1] = np.nan
assert_frame_equal(df, expected)
- self.assert_(not df['A'].is_copy)
+ self.assert_(df['A'].is_copy is None)
# using a copy (the chain), fails
df = DataFrame({ 'A' : Series(range(2),dtype='int64'), 'B' : np.array(np.arange(2,4),dtype=np.float64)})
@@ -2046,7 +2046,7 @@ def f():
df = DataFrame({'a' : ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c' : Series(range(7),dtype='int64') })
- self.assert_(not df.is_copy)
+ self.assert_(df.is_copy is None)
expected = DataFrame({'a' : ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c' : [42,42,2,3,4,42,6]})
@@ -2075,7 +2075,7 @@ def f():
# make sure that is_copy is picked up reconstruction
# GH5475
df = DataFrame({"A": [1,2]})
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
with tm.ensure_clean('__tmp__pickle') as path:
df.to_pickle(path)
df2 = pd.read_pickle(path)
@@ -2100,25 +2100,34 @@ def random_text(nobs=100):
# always a copy
x = df.iloc[[0,1,2]]
- self.assert_(x.is_copy is True)
+ self.assert_(x.is_copy is not None)
x = df.iloc[[0,1,2,4]]
- self.assert_(x.is_copy is True)
+ self.assert_(x.is_copy is not None)
# explicity copy
indexer = df.letters.apply(lambda x : len(x) > 10)
df = df.ix[indexer].copy()
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
df['letters'] = df['letters'].apply(str.lower)
# implicity take
df = random_text(100000)
indexer = df.letters.apply(lambda x : len(x) > 10)
df = df.ix[indexer]
- self.assert_(df.is_copy is True)
+ self.assert_(df.is_copy is not None)
+ df['letters'] = df['letters'].apply(str.lower)
+
+ # implicity take 2
+ df = random_text(100000)
+ indexer = df.letters.apply(lambda x : len(x) > 10)
+ df = df.ix[indexer]
+ self.assert_(df.is_copy is not None)
df.loc[:,'letters'] = df['letters'].apply(str.lower)
- # this will raise
- #df['letters'] = df['letters'].apply(str.lower)
+ # should be ok even though its a copy!
+ self.assert_(df.is_copy is None)
+ df['letters'] = df['letters'].apply(str.lower)
+ self.assert_(df.is_copy is None)
df = random_text(100000)
indexer = df.letters.apply(lambda x : len(x) > 10)
@@ -2126,7 +2135,7 @@ def random_text(nobs=100):
# an identical take, so no copy
df = DataFrame({'a' : [1]}).dropna()
- self.assert_(df.is_copy is False)
+ self.assert_(df.is_copy is None)
df['a'] += 1
# inplace ops
@@ -2165,7 +2174,15 @@ def f():
df[['c']][mask] = df[['b']][mask]
self.assertRaises(com.SettingWithCopyError, f)
- pd.set_option('chained_assignment','warn')
+ # false positives GH6025
+ df = DataFrame ({'column1':['a', 'a', 'a'], 'column2': [4,8,9] })
+ str(df)
+ df['column1'] = df['column1'] + 'b'
+ str(df)
+ df = df [df['column2']!=8]
+ str(df)
+ df['column1'] = df['column1'] + 'c'
+ str(df)
def test_float64index_slicing_bug(self):
# GH 5557, related to slicing a float index
diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py
index 0ede6bd2bd46d..1571cf3bf6a7d 100644
--- a/pandas/tools/tests/test_pivot.py
+++ b/pandas/tools/tests/test_pivot.py
@@ -174,7 +174,7 @@ def _check_output(res, col, rows=['A', 'B'], cols=['C']):
exp = self.data.groupby(rows)[col].mean()
tm.assert_series_equal(cmarg, exp)
- res.sortlevel(inplace=True)
+ res = res.sortlevel()
rmarg = res.xs(('All', ''))[:-1]
exp = self.data.groupby(cols)[col].mean()
tm.assert_series_equal(rmarg, exp)
| this is to allow in-memory creation of excel-files from pandas
| https://api.github.com/repos/pandas-dev/pandas/pulls/5992 | 2014-01-18T19:40:50Z | 2014-04-06T15:17:13Z | null | 2014-07-02T07:07:23Z |
Change "methdo" to "method" in asfreq's docstring. | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index fdb12a79e0e08..00f2dd2ec2437 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -163,7 +163,7 @@ def asfreq(self, freq, method=None, how=None, normalize=False):
method : {'backfill', 'bfill', 'pad', 'ffill', None}
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
- backfill / bfill: use NEXT valid observation to fill methdo
+ backfill / bfill: use NEXT valid observation to fill method
how : {'start', 'end'}, default end
For PeriodIndex only, see PeriodIndex.asfreq
normalize : bool, default False
| Fixes a quick typo I noticed.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5989 | 2014-01-17T20:31:23Z | 2014-01-18T02:53:26Z | null | 2014-07-16T08:47:18Z |
DOC: in ReST, a sublabel defines it's parent. latex complains of dupe | diff --git a/doc/source/merging.rst b/doc/source/merging.rst
index 8f1eb0dc779be..d16b998f31ec1 100644
--- a/doc/source/merging.rst
+++ b/doc/source/merging.rst
@@ -580,8 +580,6 @@ them together on their indexes. The same is true for ``Panel.join``.
df1
df1.join([df2, df3])
-.. _merging.combine_first:
-
.. _merging.combine_first.update:
Merging together values within Series or DataFrame columns
| This fix allows us to bring back the pdf documentation, albeit with some warnings.
I've uploaded the pdf to GH releases, and eventually hope to get it on the website.
Also updated the [release checklist](https://github.com/pydata/pandas/wiki/Release-Checklist) to make pdf publishing a standard part of our release process.
closes #5433
related #3518
| https://api.github.com/repos/pandas-dev/pandas/pulls/5985 | 2014-01-17T13:37:10Z | 2014-01-17T13:37:15Z | 2014-01-17T13:37:15Z | 2014-06-22T08:33:03Z |
DOC: correction of docstring dtypes/ftypes | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bdd2e3a2683cc..9dcf5290d29b5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1748,24 +1748,27 @@ def get_values(self):
return self.as_matrix()
def get_dtype_counts(self):
- """ return the counts of dtypes in this object """
+ """ Return the counts of dtypes in this object """
from pandas import Series
return Series(self._data.get_dtype_counts())
def get_ftype_counts(self):
- """ return the counts of ftypes in this object """
+ """ Return the counts of ftypes in this object """
from pandas import Series
return Series(self._data.get_ftype_counts())
@property
def dtypes(self):
- """ return the counts of dtypes in this object """
+ """ Return the dtypes in this object """
from pandas import Series
return Series(self._data.get_dtypes(),index=self._info_axis)
@property
def ftypes(self):
- """ return the counts of ftypes in this object """
+ """
+ Return the ftypes (indication of sparse/dense and dtype)
+ in this object.
+ """
from pandas import Series
return Series(self._data.get_ftypes(),index=self._info_axis)
| @jreback
See #5970, you copied the docstring of `get_dtype_counts`. Only thing I was wondering: `columns` is maybe not generic enough?
| https://api.github.com/repos/pandas-dev/pandas/pulls/5984 | 2014-01-17T10:07:45Z | 2014-01-17T12:56:36Z | 2014-01-17T12:56:36Z | 2014-07-16T08:47:16Z |
API: Panel.dtypes to use generic method; add tests for Panel4D for same | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 79f5af74c3985..b21cd1456a5fd 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -249,8 +249,7 @@ Attributes and underlying data
Series.values
Series.dtype
- Series.isnull
- Series.notnull
+ Series.ftype
Conversion
~~~~~~~~~~
@@ -519,7 +518,9 @@ Attributes and underlying data
DataFrame.as_matrix
DataFrame.dtypes
+ DataFrame.ftypes
DataFrame.get_dtype_counts
+ DataFrame.get_ftype_counts
DataFrame.values
DataFrame.axes
DataFrame.ndim
@@ -786,6 +787,9 @@ Attributes and underlying data
Panel.ndim
Panel.shape
Panel.dtypes
+ Panel.ftypes
+ Panel.get_dtype_counts
+ Panel.get_ftype_counts
Conversion
~~~~~~~~~~
@@ -959,6 +963,49 @@ Serialization / IO / Conversion
Panel.to_frame
Panel.to_clipboard
+.. _api.panel4d:
+
+Panel4D
+-------
+
+Constructor
+~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Panel4D
+
+Attributes and underlying data
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+**Axes**
+
+ * **labels**: axis 1; each label corresponds to a Panel contained inside
+ * **items**: axis 2; each item corresponds to a DataFrame contained inside
+ * **major_axis**: axis 3; the index (rows) of each of the DataFrames
+ * **minor_axis**: axis 4; the columns of each of the DataFrames
+
+.. autosummary::
+ :toctree: generated/
+
+ Panel4D.values
+ Panel4D.axes
+ Panel4D.ndim
+ Panel4D.shape
+ Panel4D.dtypes
+ Panel4D.ftypes
+ Panel4D.get_dtype_counts
+ Panel4D.get_ftype_counts
+
+Conversion
+~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Panel4D.astype
+ Panel4D.copy
+ Panel4D.isnull
+ Panel4D.notnull
+
.. _api.index:
Index
diff --git a/doc/source/release.rst b/doc/source/release.rst
index c5dc55f260f64..99b8bfc460068 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -75,7 +75,7 @@ Improvements to existing features
- df.info() now honors option max_info_rows, disable null counts for large frames (:issue:`5974`)
- perf improvements in DataFrame ``count/dropna`` for ``axis=1``
- Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue:`5879`)
- - support ``dtypes`` on ``Panel``
+ - support ``dtypes`` property on ``Series/Panel/Panel4D``
- extend ``Panel.apply`` to allow arbitrary functions (rather than only ufuncs) (:issue:`1148`)
allow multiple axes to be used to operate on slabs of a ``Panel``
- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index ca16be1b52ca2..fbea40eb76a0d 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -3514,6 +3514,9 @@ def _post_setstate(self):
self._block = self.blocks[0]
self._values = self._block.values
+ def _get_counts(self, f):
+ return { f(self._block) : 1 }
+
@property
def shape(self):
if getattr(self, '_shape', None) is None:
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index 832874f08561b..fc4373764172f 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -441,10 +441,6 @@ def as_matrix(self):
self._consolidate_inplace()
return self._data.as_matrix()
- @property
- def dtypes(self):
- return self.apply(lambda x: x.dtype, axis='items')
-
#----------------------------------------------------------------------
# Getting and setting elements
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 2e1d95cf87b47..918043dcacd37 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -301,10 +301,20 @@ def flags(self):
def dtype(self):
return self._data.dtype
+ @property
+ def dtypes(self):
+ """ for compat """
+ return self._data.dtype
+
@property
def ftype(self):
return self._data.ftype
+ @property
+ def ftypes(self):
+ """ for compat """
+ return self._data.ftype
+
@property
def shape(self):
return self._data.shape
@@ -2094,7 +2104,7 @@ def isin(self, values):
----------
values : list-like
The sequence of values to test. Passing in a single string will
- raise a ``TypeError``. Instead, turn a single string into a
+ raise a ``TypeError``. Instead, turn a single string into a
``list`` of one element.
Returns
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 2589f7b82aedb..16a43f2f9e767 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -6,7 +6,7 @@
import numpy as np
-from pandas import DataFrame, Index, isnull, notnull, pivot, MultiIndex
+from pandas import Series, DataFrame, Index, isnull, notnull, pivot, MultiIndex
from pandas.core.datetools import bday
from pandas.core.frame import group_agg
from pandas.core.panel import Panel
@@ -1064,8 +1064,8 @@ def test_convert_objects(self):
def test_dtypes(self):
result = self.panel.dtypes
- expected = DataFrame(np.dtype('float64'),index=self.panel.major_axis,columns=self.panel.minor_axis)
- assert_frame_equal(result, expected)
+ expected = Series(np.dtype('float64'),index=self.panel.items)
+ assert_series_equal(result, expected)
def test_apply(self):
# GH1148
diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py
index ea6602dbb0be6..fb5030ac66831 100644
--- a/pandas/tests/test_panel4d.py
+++ b/pandas/tests/test_panel4d.py
@@ -6,7 +6,7 @@
import numpy as np
-from pandas import DataFrame, Index, isnull, notnull, pivot, MultiIndex
+from pandas import Series, DataFrame, Index, isnull, notnull, pivot, MultiIndex
from pandas.core.datetools import bday
from pandas.core.frame import group_agg
from pandas.core.panel import Panel
@@ -932,6 +932,12 @@ def test_filter(self):
def test_apply(self):
raise nose.SkipTest("skipping for now")
+ def test_dtypes(self):
+
+ result = self.panel4d.dtypes
+ expected = Series(np.dtype('float64'),index=self.panel4d.labels)
+ assert_series_equal(result, expected)
+
def test_compound(self):
raise nose.SkipTest("skipping for now")
# compounded = self.panel.compound()
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 699ffb592a63e..70dd38c2641ef 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -3620,6 +3620,15 @@ def test_count(self):
self.assertEqual(self.ts.count(), np.isfinite(self.ts).sum())
+ def test_dtype(self):
+
+ self.assert_(self.ts.dtype == np.dtype('float64'))
+ self.assert_(self.ts.dtypes == np.dtype('float64'))
+ self.assert_(self.ts.ftype == 'float64:dense')
+ self.assert_(self.ts.ftypes == 'float64:dense')
+ assert_series_equal(self.ts.get_dtype_counts(),Series(1,['float64']))
+ assert_series_equal(self.ts.get_ftype_counts(),Series(1,['float64:dense']))
+
def test_dot(self):
a = Series(np.random.randn(4), index=['p', 'q', 'r', 's'])
b = DataFrame(np.random.randn(3, 4), index=['1', '2', '3'],
| DOC: updated api docs for panel/panel4d
| https://api.github.com/repos/pandas-dev/pandas/pulls/5983 | 2014-01-17T00:42:42Z | 2014-01-17T13:42:13Z | 2014-01-17T13:42:13Z | 2014-07-16T08:47:14Z |
Modified test_pow function in computation/tests/test_eval.py to use asse... | diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py
index 073526f526abe..e6d2484a41019 100644
--- a/pandas/computation/tests/test_eval.py
+++ b/pandas/computation/tests/test_eval.py
@@ -405,13 +405,13 @@ def check_pow(self, lhs, arith1, rhs):
self.assertRaises(AssertionError, assert_array_equal, result,
expected)
else:
- assert_array_equal(result, expected)
+ assert_allclose(result, expected)
ex = '(lhs {0} rhs) {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = self.get_expected_pow_result(
self.get_expected_pow_result(lhs, rhs), rhs)
- assert_array_equal(result, expected)
+ assert_allclose(result, expected)
@skip_incompatible_operand
def check_single_invert_op(self, lhs, cmp1, rhs):
| ...rt_allclose rather than assert_all_equal to avoid machine precision failures in TestEvalNumexprPandas/Numpy. Fixes issue #5981.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5982 | 2014-01-16T23:36:12Z | 2014-01-17T12:54:59Z | 2014-01-17T12:54:59Z | 2014-07-16T08:47:12Z |
DOC: add a couple plt.close('all') to avoid warning | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 27e1e8df6bfe1..c5dc55f260f64 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -71,10 +71,10 @@ Improvements to existing features
- perf improvements in Series datetime/timedelta binary operations (:issue:`5801`)
- `option_context` context manager now available as top-level API (:issue:`5752`)
- - df.info() view now display dtype info per column (:issue: `5682`)
- - df.info() now honors option max_info_rows, disable null counts for large frames (:issue: `5974`)
+ - df.info() view now display dtype info per column (:issue:`5682`)
+ - df.info() now honors option max_info_rows, disable null counts for large frames (:issue:`5974`)
- perf improvements in DataFrame ``count/dropna`` for ``axis=1``
- - Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue: `5879`)
+ - Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue:`5879`)
- support ``dtypes`` on ``Panel``
- extend ``Panel.apply`` to allow arbitrary functions (rather than only ufuncs) (:issue:`1148`)
allow multiple axes to be used to operate on slabs of a ``Panel``
@@ -114,9 +114,9 @@ Bug Fixes
``MultiIndex`` (:issue:`5402`).
- Bug in ``pd.read_msgpack`` with inferring a ``DateTimeIndex`` frequencey
incorrectly (:issue:`5947`)
- - Fixed ``to_datetime`` for array with both Tz-aware datetimes and ``NaT``s (:issue:`5961`)
+ - Fixed ``to_datetime`` for array with both Tz-aware datetimes and ``NaT``'s (:issue:`5961`)
- Bug in rolling skew/kurtosis when passed a Series with bad data (:issue:`5749`)
- - Bug in scipy ``interpolate`` methods with a datetime index (:issue: `5975`)
+ - Bug in scipy ``interpolate`` methods with a datetime index (:issue:`5975`)
- Bug in NaT comparison if a mixed datetime/np.datetime64 with NaT were passed (:issue:`5968`)
pandas 0.13.0
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index 29f4cf2588c2f..aa7d4cf376e90 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -220,6 +220,11 @@ You can pass an ``ax`` argument to ``Series.plot`` to plot on a particular axis:
@savefig series_plot_multi.png
df['D'].plot(ax=axes[1,1]); axes[1,1].set_title('D')
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.other:
@@ -361,6 +366,11 @@ columns:
@savefig box_plot_ex3.png
bp = df.boxplot(column=['Col1','Col2'], by=['X','Y'])
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
+
.. _visualization.scatter_matrix:
Scatter plot matrix
@@ -595,3 +605,8 @@ Andrews curves charts:
@savefig andrews_curve_winter.png
andrews_curves(data, 'Name', colormap='winter')
+
+.. ipython:: python
+ :suppress:
+
+ plt.close('all')
| Some small doc fixes:
- added some `plt.close('all')` calls to avoid the matplotlib warning that there are more than 20 figures open.
- some style errors in release.rst. Apparantly sphinx complains about something like ```NaN``s`.because there may not be a character directly after the closing ````
| https://api.github.com/repos/pandas-dev/pandas/pulls/5980 | 2014-01-16T21:52:15Z | 2014-01-17T10:47:13Z | 2014-01-17T10:47:13Z | 2014-07-02T01:21:00Z |
VBENCH: rename parser.py to parser_vb.py | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index acebe369c428f..82bc3ac25f68a 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1444,7 +1444,7 @@ def info(self, verbose=True, buf=None, max_cols=None):
count= ""
if show_counts:
- count = counts[i]
+ count = counts.iloc[i]
lines.append(_put_str(col, space) +
tmpl % (count, dtype))
diff --git a/vb_suite/parser.py b/vb_suite/parser_vb.py
similarity index 100%
rename from vb_suite/parser.py
rename to vb_suite/parser_vb.py
diff --git a/vb_suite/suite.py b/vb_suite/suite.py
index 26091d83f7c34..1b845e88a9d79 100644
--- a/vb_suite/suite.py
+++ b/vb_suite/suite.py
@@ -17,12 +17,12 @@
'miscellaneous',
'panel_ctor',
'packers',
- 'parser',
+ 'parser_vb',
'plotting',
'reindex',
'replace',
'sparse',
- 'strings',
+ 'strings',
'reshape',
'stat_ops',
'timeseries',
| closes #5972
@dsm054, does this resolve the issue for you?
| https://api.github.com/repos/pandas-dev/pandas/pulls/5979 | 2014-01-16T19:38:24Z | 2014-01-17T09:48:52Z | 2014-01-17T09:48:52Z | 2014-06-21T02:57:58Z |
ENH: series rank has a percentage rank option | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 341450410f1e5..9988ffc2f1bdd 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -66,6 +66,7 @@ API Changes
- ``df['col'] = value`` and ``df.loc[:,'col'] = value`` are now completely equivalent;
previously the ``.loc`` would not necessarily coerce the dtype of the resultant series (:issue:`6149`)
+
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
@@ -83,6 +84,8 @@ Improvements to existing features
- implement joining a single-level indexed DataFrame on a matching column of a multi-indexed DataFrame (:issue:`3662`)
- Performance improvement in indexing into a multi-indexed Series (:issue:`5567`)
- Testing statements updated to use specialized asserts (:issue: `6175`)
+- ``Series.rank()`` now has a percentage rank option (:issue: `5971`)
+
.. _release.bug_fixes-0.14.0:
diff --git a/pandas/algos.pyx b/pandas/algos.pyx
index 0be238117fe4e..7f406611c82f7 100644
--- a/pandas/algos.pyx
+++ b/pandas/algos.pyx
@@ -131,7 +131,7 @@ cdef _take_2d_object(ndarray[object, ndim=2] values,
def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
- na_option='keep'):
+ na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
@@ -144,6 +144,7 @@ def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
float64_t sum_ranks = 0
int tiebreak = 0
bint keep_na = 0
+ float count = 0.0
tiebreak = tiebreakers[ties_method]
values = np.asarray(in_arr).copy()
@@ -182,6 +183,7 @@ def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
if (val == nan_value) and keep_na:
ranks[argsorted[i]] = nan
continue
+ count += 1.0
if i == n - 1 or fabs(sorted_data[i + 1] - val) > FP_ERR:
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
@@ -199,11 +201,14 @@ def rank_1d_float64(object in_arr, ties_method='average', ascending=True,
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = 2 * i - j - dups + 2
sum_ranks = dups = 0
- return ranks
+ if pct:
+ return ranks / count
+ else:
+ return ranks
def rank_1d_int64(object in_arr, ties_method='average', ascending=True,
- na_option='keep'):
+ na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
@@ -216,6 +221,7 @@ def rank_1d_int64(object in_arr, ties_method='average', ascending=True,
int64_t val
float64_t sum_ranks = 0
int tiebreak = 0
+ float count = 0.0
tiebreak = tiebreakers[ties_method]
values = np.asarray(in_arr)
@@ -242,6 +248,7 @@ def rank_1d_int64(object in_arr, ties_method='average', ascending=True,
sum_ranks += i + 1
dups += 1
val = sorted_data[i]
+ count += 1.0
if i == n - 1 or fabs(sorted_data[i + 1] - val) > 0:
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
@@ -259,7 +266,10 @@ def rank_1d_int64(object in_arr, ties_method='average', ascending=True,
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = 2 * i - j - dups + 2
sum_ranks = dups = 0
- return ranks
+ if pct:
+ return ranks / count
+ else:
+ return ranks
def rank_2d_float64(object in_arr, axis=0, ties_method='average',
@@ -414,7 +424,7 @@ def rank_2d_int64(object in_arr, axis=0, ties_method='average',
def rank_1d_generic(object in_arr, bint retry=1, ties_method='average',
- ascending=True, na_option='keep'):
+ ascending=True, na_option='keep', pct=False):
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
@@ -428,6 +438,8 @@ def rank_1d_generic(object in_arr, bint retry=1, ties_method='average',
float64_t sum_ranks = 0
int tiebreak = 0
bint keep_na = 0
+ float count = 0.0
+
tiebreak = tiebreakers[ties_method]
@@ -469,7 +481,6 @@ def rank_1d_generic(object in_arr, bint retry=1, ties_method='average',
sorted_data = values.take(_as)
argsorted = _as.astype('i8')
-
for i in range(n):
sum_ranks += i + 1
dups += 1
@@ -479,6 +490,7 @@ def rank_1d_generic(object in_arr, bint retry=1, ties_method='average',
continue
if (i == n - 1 or
are_diff(util.get_value_at(sorted_data, i + 1), val)):
+ count += 1.0
if tiebreak == TIEBREAK_AVERAGE:
for j in range(i - dups + 1, i + 1):
ranks[argsorted[j]] = sum_ranks / dups
@@ -491,7 +503,10 @@ def rank_1d_generic(object in_arr, bint retry=1, ties_method='average',
elif tiebreak == TIEBREAK_FIRST:
raise ValueError('first not supported for non-numeric data')
sum_ranks = dups = 0
- return ranks
+ if pct:
+ ranks / count
+ else:
+ return ranks
cdef inline are_diff(object left, object right):
try:
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 44cd2d8906a5b..9c972c9795c47 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -285,14 +285,14 @@ def mode(values):
def rank(values, axis=0, method='average', na_option='keep',
- ascending=True):
+ ascending=True, pct=False):
"""
"""
if values.ndim == 1:
f, values = _get_data_algo(values, _rank1d_functions)
ranks = f(values, ties_method=method, ascending=ascending,
- na_option=na_option)
+ na_option=na_option, pct=pct)
elif values.ndim == 2:
f, values = _get_data_algo(values, _rank2d_functions)
ranks = f(values, axis=axis, ties_method=method,
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 2ede2dfc130da..35acfffe5b598 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1707,7 +1707,8 @@ def argsort(self, axis=0, kind='quicksort', order=None):
np.argsort(values, kind=kind), index=self.index,
dtype='int64').__finalize__(self)
- def rank(self, method='average', na_option='keep', ascending=True):
+ def rank(self, method='average', na_option='keep', ascending=True,
+ pct=False):
"""
Compute data ranks (1 through n). Equal values are assigned a rank that
is the average of the ranks of those values
@@ -1723,14 +1724,16 @@ def rank(self, method='average', na_option='keep', ascending=True):
keep: leave NA values where they are
ascending : boolean, default True
False for ranks by high (1) to low (N)
-
+ pct : boolean, defeault False
+ Computes percentage rank of data
+
Returns
-------
ranks : Series
"""
from pandas.core.algorithms import rank
ranks = rank(self.values, method=method, na_option=na_option,
- ascending=ascending)
+ ascending=ascending, pct=pct)
return self._constructor(ranks, index=self.index).__finalize__(self)
def order(self, na_last=True, ascending=True, kind='mergesort'):
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index fa7a2b2d24636..2c8b60ea25a6e 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2348,7 +2348,15 @@ def test_rank_apply(self):
expected.append(piece.value.rank())
expected = concat(expected, axis=0)
expected = expected.reindex(result.index)
+ assert_series_equal(result, expected)
+
+ result = df.groupby(['key1', 'key2']).value.rank(pct=True)
+ expected = []
+ for key, piece in df.groupby(['key1', 'key2']):
+ expected.append(piece.value.rank(pct=True))
+ expected = concat(expected, axis=0)
+ expected = expected.reindex(result.index)
assert_series_equal(result, expected)
def test_dont_clobber_name_column(self):
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 79ef285d7c5c2..74cbb956663ce 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -3955,6 +3955,48 @@ def test_rank(self):
iranks = iseries.rank()
exp = iseries.astype(float).rank()
assert_series_equal(iranks, exp)
+ iseries = Series(np.arange(5)) + 1.0
+ exp = iseries / 5.0
+ iranks = iseries.rank(pct=True)
+
+ assert_series_equal(iranks, exp)
+
+ iseries = Series(np.repeat(1, 100))
+ exp = Series(np.repeat(0.505, 100))
+ iranks = iseries.rank(pct=True)
+ assert_series_equal(iranks, exp)
+
+ iseries[1] = np.nan
+ exp = Series(np.repeat(50.0 / 99.0, 100))
+ exp[1] = np.nan
+ iranks = iseries.rank(pct=True)
+ assert_series_equal(iranks, exp)
+
+ iseries = Series(np.arange(5)) + 1.0
+ iseries[4] = np.nan
+ exp = iseries / 4.0
+ iranks = iseries.rank(pct=True)
+ assert_series_equal(iranks, exp)
+
+ iseries = Series(np.repeat(np.nan, 100))
+ exp = iseries.copy()
+ iranks = iseries.rank(pct=True)
+ assert_series_equal(iranks, exp)
+
+ iseries = Series(np.arange(5)) + 1
+ iseries[4] = np.nan
+ exp = iseries / 4.0
+ iranks = iseries.rank(pct=True)
+ assert_series_equal(iranks, exp)
+ rng = date_range('1/1/1990', periods=5)
+
+ iseries = Series(np.arange(5), rng) + 1
+ iseries.ix[4] = np.nan
+ exp = iseries / 4.0
+ iranks = iseries.rank(pct=True)
+ assert_series_equal(iranks, exp)
+
+
def test_from_csv(self):
diff --git a/vb_suite/groupby.py b/vb_suite/groupby.py
index 4b2f097c212f8..01b44cbd5351c 100644
--- a/vb_suite/groupby.py
+++ b/vb_suite/groupby.py
@@ -47,6 +47,11 @@ def f():
Benchmark('simple_series.groupby(key1).sum()', setup,
start_date=datetime(2011, 3, 1))
+
+stmt4 = "df.groupby('key1').rank(pct=True)"
+groupby_series_simple_cython = Benchmark(stmt4, setup,
+ start_date=datetime(2014, 1, 16))
+
#----------------------------------------------------------------------
# 2d grouping, aggregate many columns
diff --git a/vb_suite/stat_ops.py b/vb_suite/stat_ops.py
index 91741eb3c3759..a3a1df70dc248 100644
--- a/vb_suite/stat_ops.py
+++ b/vb_suite/stat_ops.py
@@ -85,6 +85,10 @@
stats_rank_average = Benchmark('s.rank()', setup,
start_date=datetime(2011, 12, 12))
+stats_rank_pct_average = Benchmark('s.rank(pct=True)', setup,
+ start_date=datetime(2014, 01, 16))
+stats_rank_pct_average_old = Benchmark('s.rank() / s.size()', setup,
+ start_date=datetime(2014, 01, 16))
setup = common_setup + """
values = np.random.randint(0, 100000, size=200000)
s = Series(values)
| closes #5971
This pull allows people to compute percentage ranks in cython for a series. I found myself computing this all the time and it will make this calculation much faster.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5978 | 2014-01-16T19:05:10Z | 2014-02-16T21:23:12Z | 2014-02-16T21:23:12Z | 2014-06-12T15:46:42Z |
BUG: Allow DatetimeIndex for scipy interpolate | diff --git a/doc/source/release.rst b/doc/source/release.rst
index a5555744b99b1..4c94be56db363 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -114,6 +114,7 @@ Bug Fixes
incorrectly (:issue:`5947`)
- Fixed ``to_datetime`` for array with both Tz-aware datetimes and ``NaT``s (:issue:`5961`)
- Bug in rolling skew/kurtosis when passed a Series with bad data (:issue:`5749`)
+ - Bug in scipy ``interpolate`` methods with a datetime index (:issue: `5975`)
pandas 0.13.0
-------------
diff --git a/pandas/core/common.py b/pandas/core/common.py
index fc0532364eb42..e8bcfa71fe32a 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1401,6 +1401,7 @@ def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
"""
try:
from scipy import interpolate
+ from pandas import DatetimeIndex
except ImportError:
raise ImportError('{0} interpolation requires Scipy'.format(method))
@@ -1413,6 +1414,10 @@ def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
'piecewise_polynomial': interpolate.piecewise_polynomial_interpolate,
}
+ if hasattr(x, 'asi8'):
+ # GH 5975, scipy.interp1d can't hande datetime64s
+ x, new_x = x.values.view('i8'), new_x.view('i8')
+
try:
alt_methods['pchip'] = interpolate.pchip_interpolate
except AttributeError:
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 5ba2a4519db0f..e0f4dde99560d 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -587,6 +587,13 @@ def test_interp_nonmono_raise(self):
with tm.assertRaises(ValueError):
s.interpolate(method='krogh')
+ def test_interp_datetime64(self):
+ _skip_if_no_scipy()
+ df = Series([1, np.nan, 3], index=date_range('1/1/2000', periods=3))
+ result = df.interpolate(method='nearest')
+ expected = Series([1, 1, 3], index=date_range('1/1/2000', periods=3))
+ assert_series_equal(result, expected)
+
class TestDataFrame(tm.TestCase, Generic):
_typ = DataFrame
_comparator = lambda self, x, y: assert_frame_equal(x,y)
| Closes #5975
Is there a better way to check for a DatetimeIndex than with an `isinstance()`?
| https://api.github.com/repos/pandas-dev/pandas/pulls/5977 | 2014-01-16T18:43:21Z | 2014-01-16T21:08:52Z | 2014-01-16T21:08:52Z | 2016-11-03T12:37:42Z |
ENH: make show_versions available in the top_level api | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 775850cb6c892..a764f9c1a5439 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -26,6 +26,11 @@ looking for a quick way to help out.
>>> show_versions()
```
+ and in 0.13.1 onwards:
+ ```python
+ >>> pd.show_versions()
+ ```
+
- Explain what the expected behavior was, and what you saw instead.
#### Pull Requests
diff --git a/doc/source/release.rst b/doc/source/release.rst
index a5555744b99b1..ad904980dd749 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -80,6 +80,7 @@ Improvements to existing features
allow multiple axes to be used to operate on slabs of a ``Panel``
- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
limit precision based on the values in the array (:issue:`3401`)
+ - pd.show_versions() is now available for convenience when reporting issues.
- perf improvements to Series.str.extract (:issue:`5944`)
- perf improvments in ``dtypes/ftypes`` methods (:issue:`5968`)
diff --git a/pandas/__init__.py b/pandas/__init__.py
index b33150cc64079..0fdcf655ca47a 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -49,3 +49,4 @@
from pandas.tools.plotting import scatter_matrix, plot_params
from pandas.tools.tile import cut, qcut
from pandas.core.reshape import melt
+from pandas.util.print_versions import show_versions
| comfy for everyone.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5976 | 2014-01-16T18:34:01Z | 2014-01-16T18:35:51Z | 2014-01-16T18:35:51Z | 2014-07-16T08:47:02Z |
ENH: revamp null count supression for large frames in df.info() | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 0666eb7f88675..bd141d4d905e1 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -72,6 +72,7 @@ Improvements to existing features
- perf improvements in Series datetime/timedelta binary operations (:issue:`5801`)
- `option_context` context manager now available as top-level API (:issue:`5752`)
- df.info() view now display dtype info per column (:issue: `5682`)
+ - df.info() now honors option max_info_rows, disable null counts for large frames (:issue: `5974`)
- perf improvements in DataFrame ``count/dropna`` for ``axis=1``
- Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue: `5879`)
- support ``dtypes`` on ``Panel``
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index e4d4ea74ac169..c617c58c527a8 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -166,11 +166,9 @@
pc_max_info_rows_doc = """
: int or None
- Deprecated.
-"""
-
-pc_max_info_rows_deprecation_warning = """\
-max_info_rows has been deprecated, as reprs no longer use the info view.
+ df.info() will usually show null-counts for each column.
+ For large frames this can be quite slow. max_info_rows and max_info_cols
+ limit this null check only to frames with smaller dimensions then specified.
"""
pc_large_repr_doc = """
@@ -266,9 +264,6 @@ def mpl_style_cb(key):
msg=pc_height_deprecation_warning,
rkey='display.max_rows')
-cf.deprecate_option('display.max_info_rows',
- msg=pc_max_info_rows_deprecation_warning)
-
tc_sim_interactive_doc = """
: boolean
Whether to simulate interactive mode for purposes of testing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 61d59e8f93c83..01f854aabb8d8 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1419,20 +1419,35 @@ def info(self, verbose=True, buf=None, max_cols=None):
max_cols = get_option(
'display.max_info_columns', len(self.columns) + 1)
- if verbose and len(self.columns) <= max_cols:
+ max_rows = get_option('display.max_info_rows', len(self) + 1)
+
+ show_counts = ((len(self.columns) <= max_cols) and
+ (len(self) < max_rows))
+ if verbose:
lines.append('Data columns (total %d columns):' %
len(self.columns))
space = max([len(com.pprint_thing(k)) for k in self.columns]) + 4
- counts = self.count()
- if len(cols) != len(counts): # pragma: no cover
- raise AssertionError('Columns must equal counts (%d != %d)' %
- (len(cols), len(counts)))
+ counts = None
+
+ tmpl = "%s%s"
+ if show_counts:
+ counts = self.count()
+ if len(cols) != len(counts): # pragma: no cover
+ raise AssertionError('Columns must equal counts (%d != %d)' %
+ (len(cols), len(counts)))
+ tmpl = "%s non-null %s"
+
dtypes = self.dtypes
- for col, count in compat.iteritems(counts):
+ for i, col in enumerate(self.columns):
dtype = dtypes[col]
col = com.pprint_thing(col)
+
+ count= ""
+ if show_counts:
+ count = counts[i]
+
lines.append(_put_str(col, space) +
- '%d non-null %s' % (count, dtype))
+ tmpl % (count, dtype))
else:
lines.append(self.columns.summary(name='Columns'))
| #5550 deprecated options.display.max_info_rows, but df.info is still there
for the user to invoke and the null count can be very slow.
Un-deprecte the option and revamp `df.info` to do the right thing.
Now that @cpcloud add per column dtypes it will always show them,
and just supress the counts if needed, where previously if max_info_rows was
exceeded, it didn't even print the column names.
```
In [4]: df.info()
<class 'pandas.core.frame.DataFrame'>
Index: 1000000 entries, C00410118 to C00431445
Data columns (total 18 columns):
cmte_id 1000000 non-null object
cand_id 1000000 non-null object
cand_nm 1000000 non-null object
contbr_nm 999975 non-null object
contbr_city 1000000 non-null object
contbr_st 999850 non-null object
contbr_zip 992087 non-null object
contbr_employer 994533 non-null object
contbr_occupation 1000000 non-null float64
contb_receipt_amt 1000000 non-null object
contb_receipt_dt 18038 non-null object
receipt_desc 383960 non-null object
memo_cd 391290 non-null object
memo_text 1000000 non-null object
form_tp 1000000 non-null int64
file_num 1000000 non-null object
tran_id 999998 non-null object
election_tp 0 non-null float64
dtypes: float64(2), int64(1), object(15)
In [5]: pd.options.display.max_info_rows
Out[5]: 1690785
In [6]: pd.options.display.max_info_rows=999999
In [7]: df.info()
<class 'pandas.core.frame.DataFrame'>
Index: 1000000 entries, C00410118 to C00431445
Data columns (total 18 columns):
cmte_id object
cand_id object
cand_nm object
contbr_nm object
contbr_city object
contbr_st object
contbr_zip object
contbr_employer object
contbr_occupation float64
contb_receipt_amt object
contb_receipt_dt object
receipt_desc object
memo_cd object
memo_text object
form_tp int64
file_num object
tran_id object
election_tp float64
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5974 | 2014-01-16T17:52:57Z | 2014-01-16T18:06:13Z | 2014-01-16T18:06:13Z | 2014-06-12T19:14:09Z |
PERF: perf improvments in indexing with object dtypes (GH5968) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index f1d13645f863e..27e1e8df6bfe1 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -83,6 +83,7 @@ Improvements to existing features
- pd.show_versions() is now available for convenience when reporting issues.
- perf improvements to Series.str.extract (:issue:`5944`)
- perf improvments in ``dtypes/ftypes`` methods (:issue:`5968`)
+ - perf improvments in indexing with object dtypes (:issue:`5968`)
.. _release.bug_fixes-0.13.1:
@@ -116,6 +117,7 @@ Bug Fixes
- Fixed ``to_datetime`` for array with both Tz-aware datetimes and ``NaT``s (:issue:`5961`)
- Bug in rolling skew/kurtosis when passed a Series with bad data (:issue:`5749`)
- Bug in scipy ``interpolate`` methods with a datetime index (:issue: `5975`)
+ - Bug in NaT comparison if a mixed datetime/np.datetime64 with NaT were passed (:issue:`5968`)
pandas 0.13.0
-------------
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 354eadc7c7ba1..ca16be1b52ca2 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1889,7 +1889,10 @@ def make_block(values, items, ref_items, klass=None, ndim=None, dtype=None,
if np.prod(values.shape):
flat = values.ravel()
- inferred_type = lib.infer_dtype(flat)
+
+ # try with just the first element; we just need to see if
+ # this is a datetime or not
+ inferred_type = lib.infer_dtype(flat[0:1])
if inferred_type in ['datetime', 'datetime64']:
# we have an object array that has been inferred as
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index 5a842adb561b1..eb3f518b0dd4b 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -4,9 +4,12 @@
import os
import warnings
import nose
+import sys
+from distutils.version import LooseVersion
import numpy as np
+import pandas as pd
from pandas.core.frame import DataFrame, Series
from pandas.io.parsers import read_csv
from pandas.io.stata import read_stata, StataReader
@@ -66,6 +69,9 @@ def test_read_dta1(self):
tm.assert_frame_equal(parsed_13, expected)
def test_read_dta2(self):
+ if LooseVersion(sys.version) < '2.7':
+ raise nose.SkipTest('datetime interp under 2.6 is faulty')
+
expected = DataFrame.from_records(
[
(
@@ -89,14 +95,14 @@ def test_read_dta2(self):
datetime(2, 1, 1)
),
(
- np.datetime64('NaT'),
- np.datetime64('NaT'),
- np.datetime64('NaT'),
- np.datetime64('NaT'),
- np.datetime64('NaT'),
- np.datetime64('NaT'),
- np.datetime64('NaT'),
- np.datetime64('NaT')
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
+ pd.NaT,
)
],
columns=['datetime_c', 'datetime_big_c', 'date', 'weekly_date',
diff --git a/pandas/src/util.pxd b/pandas/src/util.pxd
index d6f3c4caea306..7a30f018e623e 100644
--- a/pandas/src/util.pxd
+++ b/pandas/src/util.pxd
@@ -67,7 +67,7 @@ cdef inline is_array(object o):
cdef inline bint _checknull(object val):
try:
- return val is None or (cpython.PyFloat_Check(val) and val != val)
+ return val is None or (cpython.PyFloat_Check(val) and val != val)
except ValueError:
return False
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 4fb8bc7deddb4..bae93602cb840 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -829,6 +829,11 @@ def test_to_datetime_mixed(self):
expected = Series([NaT,Timestamp('20130408'),Timestamp('20130409')])
assert_series_equal(result,expected)
+ # mixed datetime/np.datetime64('NaT')
+ result = Series(to_datetime([dt.datetime(2000,1,1),np.datetime64('NaT')]))
+ expected = Series([dt.datetime(2000,1,1),NaT])
+ assert_series_equal(result, expected)
+
def test_dayfirst(self):
# GH 3341
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index c118a9660b5e7..e303df23003cb 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -8,6 +8,7 @@ import numpy as np
from cpython cimport (
PyTypeObject,
PyFloat_Check,
+ PyLong_Check,
PyObject_RichCompareBool,
PyObject_RichCompare,
PyString_Check,
@@ -55,6 +56,9 @@ cdef int64_t NPY_NAT = util.get_nat()
# < numpy 1.7 compat for NaT
compat_NaT = np.array([NPY_NAT]).astype('m8[ns]').item()
+# numpy actual nat object
+np_NaT = np.datetime64('NaT',dtype='M8')
+
try:
basestring
except NameError: # py3
@@ -416,6 +420,11 @@ 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 _cmp_nat_dt(_NaT lhs, _Timestamp rhs, int op) except -1:
return _nat_scalar_rules[op]
@@ -761,7 +770,7 @@ cdef convert_to_tsobject(object ts, object tz, object unit):
obj = _TSObject()
- if ts is None or ts is NaT:
+ if ts is None or ts is NaT or ts is np_NaT:
obj.value = NPY_NAT
elif is_datetime64_object(ts):
obj.value = _get_datetime64_nanos(ts)
@@ -933,7 +942,7 @@ def datetime_to_datetime64(ndarray[object] values):
iresult = result.view('i8')
for i in range(n):
val = values[i]
- if util._checknull(val) or val is NaT:
+ if _checknull_with_nat(val):
iresult[i] = iNaT
elif PyDateTime_Check(val):
if val.tzinfo is not None:
@@ -999,7 +1008,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
iresult = result.view('i8')
for i in range(n):
val = values[i]
- if util._checknull(val) or val is NaT:
+ if _checknull_with_nat(val):
iresult[i] = iNaT
elif PyDateTime_Check(val):
if val.tzinfo is not None:
@@ -1038,13 +1047,16 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
continue
raise
elif util.is_datetime64_object(val):
- try:
- iresult[i] = _get_datetime64_nanos(val)
- except ValueError:
- if coerce:
- iresult[i] = iNaT
- continue
- raise
+ if val == np_NaT:
+ iresult[i] = iNaT
+ else:
+ try:
+ iresult[i] = _get_datetime64_nanos(val)
+ except ValueError:
+ if coerce:
+ iresult[i] = iNaT
+ continue
+ raise
# if we are coercing, dont' allow integers
elif util.is_integer_object(val) and not coerce:
@@ -1114,7 +1126,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
for i in range(n):
val = values[i]
- if util._checknull(val):
+ if _checknull_with_nat(val):
oresult[i] = val
elif util.is_string_object(val):
if len(val) == 0:
@@ -1166,7 +1178,7 @@ def array_to_timedelta64(ndarray[object] values, coerce=True):
result[i] = val
- elif util._checknull(val) or val == iNaT or val is NaT:
+ elif _checknull_with_nat(val):
result[i] = iNaT
else:
@@ -1316,7 +1328,7 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False):
iresult[i] = iNaT
continue
else:
- if util._checknull(val) or val is NaT:
+ if _checknull_with_nat(val):
iresult[i] = iNaT
continue
else:
diff --git a/vb_suite/indexing.py b/vb_suite/indexing.py
index beefec256ed81..dcfda997fabd6 100644
--- a/vb_suite/indexing.py
+++ b/vb_suite/indexing.py
@@ -167,3 +167,10 @@
frame_loc_dups = Benchmark('df2.loc[idx]', setup,
start_date=datetime(2013, 1, 1))
+
+setup = common_setup + """
+df = DataFrame(dict( A = [ 'foo'] * 1000000))
+"""
+
+frame_iloc_big = Benchmark('df.iloc[:100,0]', setup,
+ start_date=datetime(2013, 1, 1))
| closes #5968
```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
frame_iloc_big | 0.2836 | 2.8454 | 0.0997 |
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5973 | 2014-01-16T17:47:39Z | 2014-01-16T21:14:35Z | 2014-01-16T21:14:35Z | 2014-06-13T17:04:51Z |
PERF: perf improvments in dtypes/ftypes methods (GH5968) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 0666eb7f88675..6cef0a040485b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -80,6 +80,7 @@ Improvements to existing features
- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
limit precision based on the values in the array (:issue:`3401`)
- perf improvements to Series.str.extract (:issue:`5944`)
+ - perf improvments in ``dtypes/ftypes`` methods (:issue:`5968`)
.. _release.bug_fixes-0.13.1:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 61d59e8f93c83..624921f573fbd 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1441,14 +1441,6 @@ def info(self, verbose=True, buf=None, max_cols=None):
lines.append('dtypes: %s' % ', '.join(dtypes))
_put_lines(buf, lines)
- @property
- def dtypes(self):
- return self.apply(lambda x: x.dtype, reduce=False)
-
- @property
- def ftypes(self):
- return self.apply(lambda x: x.ftype, reduce=False)
-
def transpose(self):
"""Transpose index and columns"""
return super(DataFrame, self).transpose(1, 0)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 549a199e9e3dd..bdd2e3a2683cc 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1748,15 +1748,27 @@ def get_values(self):
return self.as_matrix()
def get_dtype_counts(self):
- """ return the counts of dtypes in this frame """
+ """ return the counts of dtypes in this object """
from pandas import Series
return Series(self._data.get_dtype_counts())
def get_ftype_counts(self):
- """ return the counts of ftypes in this frame """
+ """ return the counts of ftypes in this object """
from pandas import Series
return Series(self._data.get_ftype_counts())
+ @property
+ def dtypes(self):
+ """ return the counts of dtypes in this object """
+ from pandas import Series
+ return Series(self._data.get_dtypes(),index=self._info_axis)
+
+ @property
+ def ftypes(self):
+ """ return the counts of ftypes in this object """
+ from pandas import Series
+ return Series(self._data.get_ftypes(),index=self._info_axis)
+
def as_blocks(self, columns=None):
"""
Convert the frame to a dict of dtype -> Constructor Types that each has
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 5c77930a206b7..354eadc7c7ba1 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -2157,21 +2157,43 @@ def _get_items(self):
return self.axes[0]
items = property(fget=_get_items)
- def get_dtype_counts(self):
- """ return a dict of the counts of dtypes in BlockManager """
+ def _get_counts(self, f):
+ """ return a dict of the counts of the function in BlockManager """
self._consolidate_inplace()
counts = dict()
for b in self.blocks:
- counts[b.dtype.name] = counts.get(b.dtype.name, 0) + b.shape[0]
+ v = f(b)
+ counts[v] = counts.get(v, 0) + b.shape[0]
return counts
- def get_ftype_counts(self):
- """ return a dict of the counts of dtypes in BlockManager """
+ def _get_types(self, f):
+ """ return a list of the f per item """
self._consolidate_inplace()
- counts = dict()
- for b in self.blocks:
- counts[b.ftype] = counts.get(b.ftype, 0) + b.shape[0]
- return counts
+
+ # unique
+ if self.items.is_unique:
+ l = [ None ] * len(self.items)
+ for b in self.blocks:
+ v = f(b)
+ for rl in b.ref_locs:
+ l[rl] = v
+ return l
+
+ # non-unique
+ ref_locs = self._set_ref_locs()
+ return [ f(ref_locs[i][0]) for i, item in enumerate(self.items) ]
+
+ def get_dtype_counts(self):
+ return self._get_counts(lambda b: b.dtype.name)
+
+ def get_ftype_counts(self):
+ return self._get_counts(lambda b: b.ftype)
+
+ def get_dtypes(self):
+ return self._get_types(lambda b: b.dtype)
+
+ def get_ftypes(self):
+ return self._get_types(lambda b: b.ftype)
def __getstate__(self):
block_values = [b.values for b in self.blocks]
diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py
index fd03d512125e7..88d773319817d 100644
--- a/vb_suite/frame_methods.py
+++ b/vb_suite/frame_methods.py
@@ -326,3 +326,12 @@ def f(K=100):
frame_apply_user_func = Benchmark('df.apply(lambda x: np.corrcoef(x,s)[0,1])', setup,
start_date=datetime(2012,1,1))
+#----------------------------------------------------------------------
+# dtypes
+
+setup = common_setup + """
+df = DataFrame(np.random.randn(1000,1000))
+"""
+frame_dtypes = Benchmark('df.dtypes', setup,
+ start_date=datetime(2012,1,1))
+
| closes #5968
```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
frame_dtypes | 0.2654 | 51.2140 | 0.0052 |
frame_wide_repr | 17.1947 | 525.7313 | 0.0327 |
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
Ratio < 1.0 means the target commit is faster then the baseline.
Seed used: 1234
Target [6a7bfc1] : PERF: perf improvments in dtypes/ftypes methods (GH5968)
Base [2081fcc] : Merge pull request #5951 from y-p/PR_latest_ipython_rep_fixes
CLN: repr_html raises NotImplementedError rather then ValueError in qtconsole
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5970 | 2014-01-16T16:35:58Z | 2014-01-16T17:04:02Z | 2014-01-16T17:04:02Z | 2014-06-15T18:39:31Z |
Travis checks that tarball can be installed without cython installed. | diff --git a/ci/install.sh b/ci/install.sh
index edd6d0690d3c8..660b05932a5ec 100755
--- a/ci/install.sh
+++ b/ci/install.sh
@@ -28,12 +28,6 @@ function edit_init()
edit_init
-# Install Dependencies
-# as of pip 1.4rc2, wheel files are still being broken regularly, this is a
-# known good commit. should revert to pypi when a final release is out
-pip_commit=42102e9deaea99db08b681d06906c2945f6f95e2
-pip install -I git+https://github.com/pypa/pip@$pip_commit#egg=pip
-
python_major_version="${TRAVIS_PYTHON_VERSION:0:1}"
[ "$python_major_version" == "2" ] && python_major_version=""
@@ -96,6 +90,8 @@ fi
# build and install pandas
-time python setup.py build_ext install
+time python setup.py sdist
+pip uninstall cython -y
+time pip install $(find dist | grep gz | head -n 1)
true
| Catch stuff like #5965 in the future.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5966 | 2014-01-16T11:49:06Z | 2014-01-16T11:49:17Z | 2014-01-16T11:49:17Z | 2014-07-16T08:46:54Z |
DOC: Clarified documentation for MultiIndexes | diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 8813e9d838d22..9c3412d35d286 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -1638,6 +1638,10 @@ completely analogous way to selecting a column in a regular DataFrame:
df['bar']['one']
s['qux']
+See :ref:`Cross-section with hierarchical index <indexing.xs>` for how to select
+on a deeper level.
+
+
Data alignment and using ``reindex``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1674,11 +1678,17 @@ following works as you would expect:
df.ix['bar']
df.ix['bar', 'two']
-"Partial" slicing also works quite nicely:
+"Partial" slicing also works quite nicely for the topmost level:
.. ipython:: python
df.ix['baz':'foo']
+
+But lower levels cannot be sliced in this way, because the MultiIndex uses
+its multiple index dimensions to slice along one dimension of your object:
+
+.. ipython:: python
+
df.ix[('baz', 'two'):('qux', 'one')]
df.ix[('baz', 'two'):'foo']
diff --git a/pandas/core/index.py b/pandas/core/index.py
index ed964e76dd470..86344b1cc2161 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2472,7 +2472,9 @@ def from_arrays(cls, arrays, sortorder=None, names=None):
Parameters
----------
- arrays : list / sequence
+ arrays : list / sequence of array-likes
+ Each array-like gives one level's value for each data point.
+ len(arrays) is the number of levels.
sortorder : int or None
Level of sortedness (must be lexicographically sorted by that
level)
@@ -2480,6 +2482,15 @@ def from_arrays(cls, arrays, sortorder=None, names=None):
Returns
-------
index : MultiIndex
+
+ Examples
+ --------
+ >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
+ >>> MultiIndex.from_arrays(arrays, names=('number', 'color'))
+
+ See Also
+ --------
+ MultiIndex.from_tuples : Convert list of tuples to MultiIndex
"""
from pandas.core.categorical import Categorical
@@ -2504,7 +2515,8 @@ def from_tuples(cls, tuples, sortorder=None, names=None):
Parameters
----------
- tuples : array-like
+ tuples : list / sequence of tuple-likes
+ Each tuple is the index of one row/column.
sortorder : int or None
Level of sortedness (must be lexicographically sorted by that
level)
@@ -2512,6 +2524,16 @@ def from_tuples(cls, tuples, sortorder=None, names=None):
Returns
-------
index : MultiIndex
+
+ Examples
+ --------
+ >>> tuples = [(1, u'red'), (1, u'blue'),
+ (2, u'red'), (2, u'blue')]
+ >>> MultiIndex.from_tuples(tuples, names=('number', 'color'))
+
+ See Also
+ --------
+ MultiIndex.from_arrays : Convert list of arrays to MultiIndex
"""
if len(tuples) == 0:
# I think this is right? Not quite sure...
| Clarify some quirks regarding slicing on MultiIndexes
| https://api.github.com/repos/pandas-dev/pandas/pulls/5964 | 2014-01-16T04:51:47Z | 2014-01-20T09:27:50Z | 2014-01-20T09:27:50Z | 2014-07-16T08:46:52Z |
BUG: Fixed to_datetime for array with both Tz-aware datetimes and NaTs | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 2ee9c7338889e..8de8929c5fa7a 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -110,6 +110,7 @@ Bug Fixes
``MultiIndex`` (:issue:`5402`).
- Bug in ``pd.read_msgpack`` with inferring a ``DateTimeIndex`` frequencey
incorrectly (:issue:`5947`)
+ - Fixed ``to_datetime`` for array with both Tz-aware datetimes and ``NaT``s (:issue:`5961`)
pandas 0.13.0
-------------
diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py
index 8f0c817d33a2b..6b571aca20afc 100644
--- a/pandas/tseries/tests/test_timezones.py
+++ b/pandas/tseries/tests/test_timezones.py
@@ -10,7 +10,7 @@
from pandas import (Index, Series, TimeSeries, DataFrame, isnull,
date_range, Timestamp)
-from pandas import DatetimeIndex, Int64Index, to_datetime
+from pandas import DatetimeIndex, Int64Index, to_datetime, NaT
from pandas.core.daterange import DateRange
import pandas.core.datetools as datetools
@@ -671,6 +671,12 @@ def test_datetimeindex_tz(self):
for other in [idx2, idx3, idx4]:
self.assert_(idx1.equals(other))
+ def test_datetimeindex_tz_nat(self):
+ idx = to_datetime([Timestamp("2013-1-1", tz='US/Eastern'), NaT])
+
+ self.assertTrue(isnull(idx[1]))
+ self.assertTrue(idx[0].tzinfo is not None)
+
class TestTimeZones(tm.TestCase):
_multiprocess_can_split_ = True
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 0bac159404e34..c118a9660b5e7 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -933,7 +933,7 @@ def datetime_to_datetime64(ndarray[object] values):
iresult = result.view('i8')
for i in range(n):
val = values[i]
- if util._checknull(val):
+ if util._checknull(val) or val is NaT:
iresult[i] = iNaT
elif PyDateTime_Check(val):
if val.tzinfo is not None:
| Closes #5961
| https://api.github.com/repos/pandas-dev/pandas/pulls/5962 | 2014-01-16T03:52:27Z | 2014-01-16T11:54:39Z | 2014-01-16T11:54:39Z | 2014-06-22T06:32:18Z |
PERF: add np.max and np.min to _cython_table (GH5927) | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index fb9b5e7831c88..1d3d4717c6bdb 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -2994,7 +2994,9 @@ def _reorder_by_uniques(uniques, labels):
np.prod: 'prod',
np.std: 'std',
np.var: 'var',
- np.median: 'median'
+ np.median: 'median',
+ np.max: 'max',
+ np.min: 'min'
}
diff --git a/vb_suite/timeseries.py b/vb_suite/timeseries.py
index 0850499f42480..c43d2fb76dbdb 100644
--- a/vb_suite/timeseries.py
+++ b/vb_suite/timeseries.py
@@ -243,3 +243,29 @@ def date_range(start=None, end=None, periods=None, freq=None):
setup, start_date=datetime(2013, 9, 30))
+#----------------------------------------------------------------------
+# Resampling: fast-path various functions
+
+setup = common_setup + """
+rng = date_range('20130101',periods=100000,freq='50L')
+df = DataFrame(np.random.randn(100000,2),index=rng)
+"""
+
+dataframe_resample_mean_string = \
+ Benchmark("df.resample('1s', how='mean')", setup)
+
+dataframe_resample_mean_numpy = \
+ Benchmark("df.resample('1s', how=np.mean)", setup)
+
+dataframe_resample_min_string = \
+ Benchmark("df.resample('1s', how='min')", setup)
+
+dataframe_resample_min_numpy = \
+ Benchmark("df.resample('1s', how=np.min)", setup)
+
+dataframe_resample_max_string = \
+ Benchmark("df.resample('1s', how='max')", setup)
+
+dataframe_resample_max_numpy = \
+ Benchmark("df.resample('1s', how=np.max)", setup)
+
| closes #5927
Fixes numpy max/min slow path on resample and adds tests to vbench.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5960 | 2014-01-16T02:24:51Z | 2014-01-16T14:28:12Z | 2014-01-16T14:28:12Z | 2014-06-21T03:08:27Z |
BUG: use the "join" string in Appender decorator | diff --git a/pandas/util/decorators.py b/pandas/util/decorators.py
index d83b1eb778763..56a90b9ba1d17 100644
--- a/pandas/util/decorators.py
+++ b/pandas/util/decorators.py
@@ -102,7 +102,7 @@ def __call__(self, func):
func.__doc__ = func.__doc__ if func.__doc__ else ''
self.addendum = self.addendum if self.addendum else ''
docitems = [func.__doc__, self.addendum]
- func.__doc__ = ''.join(docitems)
+ func.__doc__ = self.join.join(docitems)
return func
| The docstring for Appender decorator says that "join" parameter is used to join the docstring and addendum. This commit brings the code in line with the documentation.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5959 | 2014-01-16T01:40:05Z | 2014-01-18T03:08:06Z | 2014-01-18T03:08:06Z | 2014-07-06T10:27:41Z |
BUG: Fix to_datetime to properly deal with tz offsets #3944 | diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py
index 9a8c19bdc00ab..8c31254d26c02 100644
--- a/pandas/tseries/tests/test_tslib.py
+++ b/pandas/tseries/tests/test_tslib.py
@@ -189,6 +189,29 @@ def test_coerce_of_invalid_datetimes(self):
)
)
+ def test_parsing_timezone_offsets(self):
+ # All of these datetime strings with offsets are equivalent
+ # to the same datetime after the timezone offset is added
+ dt_strings = [
+ '01-01-2013 08:00:00+08:00',
+ '2013-01-01T08:00:00.000000000+0800',
+ '2012-12-31T16:00:00.000000000-0800',
+ '12-31-2012 23:00:00-01:00',
+ ]
+
+ expected_output = tslib.array_to_datetime(
+ np.array(['01-01-2013 00:00:00'], dtype=object)
+ )
+
+ for dt_string in dt_strings:
+ self.assert_(
+ np.array_equal(
+ tslib.array_to_datetime(
+ np.array([dt_string], dtype=object)
+ ),
+ expected_output
+ )
+ )
class TestTimestampNsOperations(tm.TestCase):
def setUp(self):
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index e303df23003cb..94c78ca466b3a 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -995,7 +995,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
format=None, utc=None, coerce=False, unit=None):
cdef:
Py_ssize_t i, n = len(values)
- object val
+ object val, py_dt
ndarray[int64_t] iresult
ndarray[object] oresult
pandas_datetimestruct dts
@@ -1085,10 +1085,7 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
_check_dts_bounds(&dts)
except ValueError:
try:
- iresult[i] = _pydatetime_to_dts(
- parse_datetime_string(val, dayfirst=dayfirst),
- &dts
- )
+ py_dt = parse_datetime_string(val, dayfirst=dayfirst)
except Exception:
if coerce:
iresult[i] = iNaT
@@ -1096,7 +1093,8 @@ def array_to_datetime(ndarray[object] values, raise_=False, dayfirst=False,
raise TypeError
try:
- _check_dts_bounds(&dts)
+ _ts = convert_to_tsobject(py_dt, None, None)
+ iresult[i] = _ts.value
except ValueError:
if coerce:
iresult[i] = iNaT
| Currently for certain formats of datetime strings, the tz offset will
just be ignored.
#3944
| https://api.github.com/repos/pandas-dev/pandas/pulls/5958 | 2014-01-15T23:30:56Z | 2014-02-04T09:24:37Z | 2014-02-04T09:24:36Z | 2014-06-13T22:41:44Z |
API: add reads_json, reads_msgpack, reads_csv, reads_pickle as convience functions which accept a string | diff --git a/pandas/io/api.py b/pandas/io/api.py
index cf3615cd822cd..9235497d0d608 100644
--- a/pandas/io/api.py
+++ b/pandas/io/api.py
@@ -2,14 +2,14 @@
Data IO api
"""
-from pandas.io.parsers import read_csv, read_table, read_fwf
+from pandas.io.parsers import read_csv, reads_csv, read_table, read_fwf
from pandas.io.clipboard import read_clipboard
from pandas.io.excel import ExcelFile, ExcelWriter, read_excel
from pandas.io.pytables import HDFStore, Term, get_store, read_hdf
-from pandas.io.json import read_json
+from pandas.io.json import read_json, reads_json
from pandas.io.html import read_html
from pandas.io.sql import read_sql
from pandas.io.stata import read_stata
-from pandas.io.pickle import read_pickle, to_pickle
-from pandas.io.packers import read_msgpack, to_msgpack
+from pandas.io.pickle import read_pickle, reads_pickle, to_pickle
+from pandas.io.packers import read_msgpack, reads_msgpack, to_msgpack
from pandas.io.gbq import read_gbq
diff --git a/pandas/io/common.py b/pandas/io/common.py
index d6b2827f94d36..a4bcaa2016b28 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -6,7 +6,7 @@
from pandas.compat import StringIO
from pandas import compat
-
+from functools import wraps
if compat.PY3:
from urllib.request import urlopen, pathname2url
@@ -45,6 +45,37 @@ class PerformanceWarning(Warning):
class DtypeWarning(Warning):
pass
+def _create_string_file_reader(func):
+ """
+ create and return a new function that takes string input and
+ passed to a file-like reader function,
+ e.g. read_json
+
+ Parameters
+ ----------
+ func : the function with a file-like interface
+
+ Returns
+ -------
+ new function that transform input to file-like
+ """
+
+ @wraps(func)
+ def f(path_or_buf, *args, **kwargs):
+ if not hasattr(path_or_buf,'read'):
+ if isinstance(path_or_buf, compat.string_types):
+ path_or_buf = StringIO(path_or_buf)
+ elif isinstance(path_or_buf, compat.binary_type):
+ path_or_buf = compat.BytesIO(path_or_buf)
+ try:
+ return func(path_or_buf, *args, **kwargs)
+ finally:
+ if not ('iterator' in kwargs or 'chunksize' in kwargs):
+ path_or_buf.close()
+
+ return func(path_or_buf, *args, **kwargs)
+
+ return f
def _is_url(url):
"""Check to see if a URL has a valid protocol.
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 698f7777a1100..c41f1759b4d7f 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -10,7 +10,7 @@
from pandas.compat import long, u
from pandas import compat, isnull
from pandas import Series, DataFrame, to_datetime
-from pandas.io.common import get_filepath_or_buffer
+from pandas.io.common import get_filepath_or_buffer, _create_string_file_reader
import pandas.core.common as com
loads = _json.loads
@@ -109,7 +109,7 @@ 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_buffer : a valid file-like
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``
@@ -171,25 +171,14 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
result : Series or DataFrame
"""
- filepath_or_buffer, _ = get_filepath_or_buffer(path_or_buf)
- if isinstance(filepath_or_buffer, compat.string_types):
- try:
- exists = os.path.exists(filepath_or_buffer)
-
- # if the filepath is too long will raise here
- # 5874
- except (TypeError,ValueError):
- exists = False
-
- if exists:
- with open(filepath_or_buffer, 'r') as fh:
- json = fh.read()
- else:
- json = filepath_or_buffer
- elif hasattr(filepath_or_buffer, 'read'):
- json = filepath_or_buffer.read()
+ path_or_buffer, _ = get_filepath_or_buffer(path_or_buf)
+ if isinstance(path_or_buffer, compat.string_types):
+ with open(path_or_buffer, 'r') as fh:
+ json = fh.read()
+ elif hasattr(path_or_buffer, 'read'):
+ json = path_or_buffer.read()
else:
- json = filepath_or_buffer
+ raise ValueError("path_or_buffer must be a file or file-like buffer")
obj = None
if typ == 'frame':
@@ -206,6 +195,7 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
return obj
+reads_json = _create_string_file_reader(read_json)
class Parser(object):
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index 105bea92124fd..8475972f493e6 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -56,7 +56,7 @@
from pandas.sparse.array import BlockIndex, IntIndex
from pandas.core.generic import NDFrame
from pandas.core.common import needs_i8_conversion
-from pandas.io.common import get_filepath_or_buffer
+from pandas.io.common import get_filepath_or_buffer, _create_string_file_reader
from pandas.core.internals import BlockManager, make_block
import pandas.core.internals as internals
@@ -124,7 +124,7 @@ def read_msgpack(path_or_buf, iterator=False, **kwargs):
Parameters
----------
- path_or_buf : string File path, BytesIO like or string
+ path_or_buf : string File path or buffer
iterator : boolean, if True, return an iterator to the unpacker
(default is False)
@@ -146,26 +146,15 @@ def read(fh):
# see if we have an actual file
if isinstance(path_or_buf, compat.string_types):
- try:
- exists = os.path.exists(path_or_buf)
- except (TypeError,ValueError):
- exists = False
-
- if exists:
- with open(path_or_buf, 'rb') as fh:
- return read(fh)
-
- # treat as a string-like
- if not hasattr(path_or_buf, 'read'):
-
- try:
- fh = compat.BytesIO(path_or_buf)
+ with open(path_or_buf, 'rb') as fh:
return read(fh)
- finally:
- fh.close()
- # a buffer like
- return read(path_or_buf)
+ elif hasattr(path_or_buf, 'read'):
+ return read(path_or_buf)
+ else:
+ raise ValueError("path_or_buffer must be a file or file-like buffer")
+
+reads_msgpack = _create_string_file_reader(read_msgpack)
dtype_dict = {21: np.dtype('M8[ns]'),
u('datetime64[ns]'): np.dtype('M8[ns]'),
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 813b7e59e107a..8dbf2b39063d6 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -15,7 +15,7 @@
import pandas.core.common as com
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, _create_string_file_reader
from pandas.util.decorators import Appender
@@ -417,6 +417,7 @@ def parser_f(filepath_or_buffer,
read_csv = _make_parser_function('read_csv', sep=',')
read_csv = Appender(_read_csv_doc)(read_csv)
+reads_csv = _create_string_file_reader(read_csv)
read_table = _make_parser_function('read_table', sep='\t')
read_table = Appender(_read_table_doc)(read_table)
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index 915c1e9ae1574..de191f1df5475 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -1,5 +1,5 @@
from pandas.compat import cPickle as pkl, pickle_compat as pc, PY3
-
+from pandas.io.common import _create_string_file_reader
def to_pickle(obj, path):
"""
@@ -51,3 +51,5 @@ def try_read(path, encoding=None):
if PY3:
return try_read(path, encoding='latin1')
raise
+
+reads_pickle= _create_string_file_reader(read_pickle)
diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py
index 084bc63188e2b..5b710771b88e5 100644
--- a/pandas/io/tests/test_json/test_pandas.py
+++ b/pandas/io/tests/test_json/test_pandas.py
@@ -7,7 +7,7 @@
from pandas import Series, DataFrame, DatetimeIndex, Timestamp
import pandas as pd
-read_json = pd.read_json
+from pandas import reads_json
from pandas.util.testing import (assert_almost_equal, assert_frame_equal,
assert_series_equal, network,
@@ -72,13 +72,13 @@ def test_frame_double_encoded_labels(self):
index=['index " 1', 'index / 2'],
columns=['a \\ b', 'y / z'])
- assert_frame_equal(df, read_json(df.to_json(orient='split'),
+ assert_frame_equal(df, reads_json(df.to_json(orient='split'),
orient='split'))
- assert_frame_equal(df, read_json(df.to_json(orient='columns'),
+ assert_frame_equal(df, reads_json(df.to_json(orient='columns'),
orient='columns'))
- assert_frame_equal(df, read_json(df.to_json(orient='index'),
+ assert_frame_equal(df, reads_json(df.to_json(orient='index'),
orient='index'))
- df_unser = read_json(df.to_json(orient='records'), orient='records')
+ df_unser = reads_json(df.to_json(orient='records'), orient='records')
assert_index_equal(df.columns, df_unser.columns)
np.testing.assert_equal(df.values, df_unser.values)
@@ -89,12 +89,12 @@ def test_frame_non_unique_index(self):
self.assertRaises(ValueError, df.to_json, orient='index')
self.assertRaises(ValueError, df.to_json, orient='columns')
- assert_frame_equal(df, read_json(df.to_json(orient='split'),
+ assert_frame_equal(df, reads_json(df.to_json(orient='split'),
orient='split'))
- unser = read_json(df.to_json(orient='records'), orient='records')
+ unser = reads_json(df.to_json(orient='records'), orient='records')
self.assertTrue(df.columns.equals(unser.columns))
np.testing.assert_equal(df.values, unser.values)
- unser = read_json(df.to_json(orient='values'), orient='values')
+ unser = reads_json(df.to_json(orient='values'), orient='values')
np.testing.assert_equal(df.values, unser.values)
def test_frame_non_unique_columns(self):
@@ -105,18 +105,18 @@ def test_frame_non_unique_columns(self):
self.assertRaises(ValueError, df.to_json, orient='columns')
self.assertRaises(ValueError, df.to_json, orient='records')
- assert_frame_equal(df, read_json(df.to_json(orient='split'),
+ assert_frame_equal(df, reads_json(df.to_json(orient='split'),
orient='split', dtype=False))
- unser = read_json(df.to_json(orient='values'), orient='values')
+ unser = reads_json(df.to_json(orient='values'), orient='values')
np.testing.assert_equal(df.values, unser.values)
# GH4377; duplicate columns not processing correctly
df = DataFrame([['a','b'],['c','d']], index=[1,2], columns=['x','y'])
- result = read_json(df.to_json(orient='split'), orient='split')
+ result = reads_json(df.to_json(orient='split'), orient='split')
assert_frame_equal(result, df)
def _check(df):
- result = read_json(df.to_json(orient='split'), orient='split',
+ result = reads_json(df.to_json(orient='split'), orient='split',
convert_dates=['x'])
assert_frame_equal(result, df)
@@ -133,7 +133,7 @@ def _check_orient(df, orient, dtype=None, numpy=False,
dfjson = df.to_json(orient=orient)
try:
- unser = read_json(dfjson, orient=orient, dtype=dtype,
+ unser = reads_json(dfjson, orient=orient, dtype=dtype,
numpy=numpy, convert_axes=convert_axes)
except Exception as detail:
if raise_ok is not None:
@@ -259,20 +259,20 @@ def _check_all_orients(df, dtype=None, convert_axes=True, raise_ok=None):
_check_orient(df.transpose().transpose(), "index", dtype=False)
def test_frame_from_json_bad_data(self):
- self.assertRaises(ValueError, read_json, StringIO('{"key":b:a:d}'))
+ self.assertRaises(ValueError, reads_json, StringIO('{"key":b:a:d}'))
# too few indices
json = StringIO('{"columns":["A","B"],'
'"index":["2","3"],'
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}')
- self.assertRaises(ValueError, read_json, json,
+ self.assertRaises(ValueError, reads_json, json,
orient="split")
# too many columns
json = StringIO('{"columns":["A","B","C"],'
'"index":["1","2","3"],'
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}')
- self.assertRaises(AssertionError, read_json, json,
+ self.assertRaises(AssertionError, reads_json, json,
orient="split")
# bad key
@@ -280,41 +280,41 @@ def test_frame_from_json_bad_data(self):
'"index":["2","3"],'
'"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}')
with tm.assertRaisesRegexp(ValueError, r"unexpected key\(s\): badkey"):
- read_json(json, orient="split")
+ reads_json(json, orient="split")
def test_frame_from_json_nones(self):
df = DataFrame([[1, 2], [4, 5, 6]])
- unser = read_json(df.to_json())
+ unser = reads_json(df.to_json())
self.assertTrue(np.isnan(unser[2][0]))
df = DataFrame([['1', '2'], ['4', '5', '6']])
- unser = read_json(df.to_json())
+ unser = reads_json(df.to_json())
self.assertTrue(np.isnan(unser[2][0]))
- unser = read_json(df.to_json(),dtype=False)
+ unser = reads_json(df.to_json(),dtype=False)
self.assertTrue(unser[2][0] is None)
- unser = read_json(df.to_json(),convert_axes=False,dtype=False)
+ unser = reads_json(df.to_json(),convert_axes=False,dtype=False)
self.assertTrue(unser['2']['0'] is None)
- unser = read_json(df.to_json(), numpy=False)
+ unser = reads_json(df.to_json(), numpy=False)
self.assertTrue(np.isnan(unser[2][0]))
- unser = read_json(df.to_json(), numpy=False, dtype=False)
+ unser = reads_json(df.to_json(), numpy=False, dtype=False)
self.assertTrue(unser[2][0] is None)
- unser = read_json(df.to_json(), numpy=False, convert_axes=False, dtype=False)
+ unser = reads_json(df.to_json(), numpy=False, convert_axes=False, dtype=False)
self.assertTrue(unser['2']['0'] is None)
# infinities get mapped to nulls which get mapped to NaNs during
# deserialisation
df = DataFrame([[1, 2], [4, 5, 6]])
df[2][0] = np.inf
- unser = read_json(df.to_json())
+ unser = reads_json(df.to_json())
self.assertTrue(np.isnan(unser[2][0]))
- unser = read_json(df.to_json(), dtype=False)
+ unser = reads_json(df.to_json(), dtype=False)
self.assertTrue(np.isnan(unser[2][0]))
df[2][0] = np.NINF
- unser = read_json(df.to_json())
+ unser = reads_json(df.to_json())
self.assertTrue(np.isnan(unser[2][0]))
- unser = read_json(df.to_json(),dtype=False)
+ unser = reads_json(df.to_json(),dtype=False)
self.assertTrue(np.isnan(unser[2][0]))
def test_frame_to_json_except(self):
@@ -350,9 +350,9 @@ def test_series_non_unique_index(self):
self.assertRaises(ValueError, s.to_json, orient='index')
- assert_series_equal(s, read_json(s.to_json(orient='split'),
+ assert_series_equal(s, reads_json(s.to_json(orient='split'),
orient='split', typ='series'))
- unser = read_json(s.to_json(orient='records'),
+ unser = reads_json(s.to_json(orient='records'),
orient='records', typ='series')
np.testing.assert_equal(s.values, unser.values)
@@ -360,7 +360,7 @@ def test_series_from_json_to_json(self):
def _check_orient(series, orient, dtype=None, numpy=False):
series = series.sort_index()
- unser = read_json(series.to_json(orient=orient),
+ unser = reads_json(series.to_json(orient=orient),
typ='series', orient=orient, numpy=numpy,
dtype=dtype)
unser = unser.sort_index()
@@ -410,24 +410,24 @@ def test_series_to_json_except(self):
def test_series_from_json_precise_float(self):
s = Series([4.56, 4.56, 4.56])
- result = read_json(s.to_json(), typ='series', precise_float=True)
+ result = reads_json(s.to_json(), typ='series', precise_float=True)
assert_series_equal(result, s)
def test_frame_from_json_precise_float(self):
df = DataFrame([[4.56, 4.56, 4.56], [4.56, 4.56, 4.56]])
- result = read_json(df.to_json(), precise_float=True)
+ result = reads_json(df.to_json(), precise_float=True)
assert_frame_equal(result, df)
def test_typ(self):
s = Series(lrange(6), index=['a','b','c','d','e','f'], dtype='int64')
- result = read_json(s.to_json(),typ=None)
+ result = reads_json(s.to_json(),typ=None)
assert_series_equal(result,s)
def test_reconstruction_index(self):
df = DataFrame([[1, 2, 3], [4, 5, 6]])
- result = read_json(df.to_json())
+ result = reads_json(df.to_json())
# the index is serialized as strings....correct?
assert_frame_equal(result, df)
@@ -437,18 +437,18 @@ def test_path(self):
for df in [self.frame, self.frame2, self.intframe, self.tsframe,
self.mixed_frame]:
df.to_json(path)
- read_json(path)
+ pd.read_json(path)
def test_axis_dates(self):
# frame
json = self.tsframe.to_json()
- result = read_json(json)
+ result = reads_json(json)
assert_frame_equal(result, self.tsframe)
# series
json = self.ts.to_json()
- result = read_json(json, typ='series')
+ result = reads_json(json, typ='series')
assert_series_equal(result, self.ts)
def test_convert_dates(self):
@@ -458,12 +458,12 @@ def test_convert_dates(self):
df['date'] = Timestamp('20130101')
json = df.to_json()
- result = read_json(json)
+ result = reads_json(json)
assert_frame_equal(result, df)
df['foo'] = 1.
json = df.to_json(date_unit='ns')
- result = read_json(json, convert_dates=False)
+ result = reads_json(json, convert_dates=False)
expected = df.copy()
expected['date'] = expected['date'].values.view('i8')
expected['foo'] = expected['foo'].astype('int64')
@@ -472,7 +472,7 @@ def test_convert_dates(self):
# series
ts = Series(Timestamp('20130101'), index=self.ts.index)
json = ts.to_json()
- result = read_json(json, typ='series')
+ result = reads_json(json, typ='series')
assert_series_equal(result, ts)
def test_date_format_frame(self):
@@ -486,7 +486,7 @@ def test_w_date(date, date_unit=None):
json = df.to_json(date_format='iso', date_unit=date_unit)
else:
json = df.to_json(date_format='iso')
- result = read_json(json)
+ result = reads_json(json)
assert_frame_equal(result, df)
test_w_date('20130101 20:43:42.123')
@@ -507,7 +507,7 @@ def test_w_date(date, date_unit=None):
json = ts.to_json(date_format='iso', date_unit=date_unit)
else:
json = ts.to_json(date_format='iso')
- result = read_json(json, typ='series')
+ result = reads_json(json, typ='series')
assert_series_equal(result, ts)
test_w_date('20130101 20:43:42.123')
@@ -531,11 +531,11 @@ def test_date_unit(self):
json = df.to_json(date_format='epoch', date_unit=unit)
# force date unit
- result = read_json(json, date_unit=unit)
+ result = reads_json(json, date_unit=unit)
assert_frame_equal(result, df)
# detect date unit
- result = read_json(json, date_unit=None)
+ result = reads_json(json, date_unit=None)
assert_frame_equal(result, df)
def test_weird_nested_json(self):
@@ -558,7 +558,7 @@ def test_weird_nested_json(self):
}
}'''
- read_json(s)
+ reads_json(s)
def test_doc_example(self):
dfj2 = DataFrame(np.random.randn(5, 2), columns=list('AB'))
@@ -568,19 +568,19 @@ def test_doc_example(self):
dfj2.index = pd.date_range('20130101',periods=5)
json = dfj2.to_json()
- result = read_json(json,dtype={'ints' : np.int64, 'bools' : np.bool_})
+ result = reads_json(json,dtype={'ints' : np.int64, 'bools' : np.bool_})
assert_frame_equal(result,result)
def test_misc_example(self):
# parsing unordered input fails
- result = read_json('[{"a": 1, "b": 2}, {"b":2, "a" :1}]',numpy=True)
+ result = reads_json('[{"a": 1, "b": 2}, {"b":2, "a" :1}]',numpy=True)
expected = DataFrame([[1,2],[1,2]],columns=['a','b'])
with tm.assertRaisesRegexp(AssertionError,
'\[index\] left \[.+\], right \[.+\]'):
assert_frame_equal(result, expected)
- result = read_json('[{"a": 1, "b": 2}, {"b":2, "a" :1}]')
+ result = reads_json('[{"a": 1, "b": 2}, {"b":2, "a" :1}]')
expected = DataFrame([[1,2],[1,2]],columns=['a','b'])
assert_frame_equal(result,expected)
@@ -590,13 +590,13 @@ def test_round_trip_exception_(self):
csv = 'https://raw.github.com/hayd/lahman2012/master/csvs/Teams.csv'
df = pd.read_csv(csv)
s = df.to_json()
- result = pd.read_json(s)
+ result = pd.reads_json(s)
assert_frame_equal(result.reindex(index=df.index,columns=df.columns),df)
@network
def test_url(self):
url = 'https://api.github.com/repos/pydata/pandas/issues?per_page=5'
- result = read_json(url, convert_dates=True)
+ result = pd.read_json(url, convert_dates=True)
for c in ['created_at', 'closed_at', 'updated_at']:
self.assertEqual(result[c].dtype, 'datetime64[ns]')
@@ -606,7 +606,7 @@ def test_default_handler(self):
self.assertRaises(OverflowError, frame.to_json)
expected = DataFrame([str(timedelta(23)), str(timedelta(seconds=5))])
assert_frame_equal(
- expected, pd.read_json(frame.to_json(default_handler=str)))
+ expected, pd.reads_json(frame.to_json(default_handler=str)))
def my_handler_raises(obj):
raise TypeError("raisin")
diff --git a/pandas/io/tests/test_packers.py b/pandas/io/tests/test_packers.py
index 8cab9a65995bf..957cde34cf616 100644
--- a/pandas/io/tests/test_packers.py
+++ b/pandas/io/tests/test_packers.py
@@ -16,13 +16,13 @@
from pandas.tests.test_frame import assert_frame_equal
from pandas.tests.test_panel import assert_panel_equal
-import pandas
+import pandas as pd
from pandas.sparse.tests.test_sparse import assert_sp_series_equal, assert_sp_frame_equal
from pandas import Timestamp, tslib
nan = np.nan
-from pandas.io.packers import to_msgpack, read_msgpack
+from pandas.io.packers import to_msgpack, read_msgpack, reads_msgpack
_multiprocess_can_split_ = False
@@ -62,19 +62,19 @@ def test_string_io(self):
df = DataFrame(np.random.randn(10,2))
s = df.to_msgpack(None)
- result = read_msgpack(s)
+ result = reads_msgpack(s)
tm.assert_frame_equal(result,df)
s = df.to_msgpack()
- result = read_msgpack(s)
+ result = reads_msgpack(s)
tm.assert_frame_equal(result,df)
s = df.to_msgpack()
- result = read_msgpack(compat.BytesIO(s))
+ result = reads_msgpack(compat.BytesIO(s))
tm.assert_frame_equal(result,df)
s = to_msgpack(None,df)
- result = read_msgpack(s)
+ result = reads_msgpack(s)
tm.assert_frame_equal(result, df)
with ensure_clean(self.path) as p:
@@ -90,7 +90,7 @@ def test_iterator_with_string_io(self):
dfs = [ DataFrame(np.random.randn(10,2)) for i in range(5) ]
s = to_msgpack(None,*dfs)
- for i, result in enumerate(read_msgpack(s,iterator=True)):
+ for i, result in enumerate(reads_msgpack(s,iterator=True)):
tm.assert_frame_equal(result,dfs[i])
class TestNumpy(TestPackers):
| related #5655
related #5874
closes #5924
todo:
```
[ ] update io.rst docs / whatsnew
[ ] more tests (esp pickle/csv) for passing string to ``read_csv`` or file-handle to ``reads_csv``
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5957 | 2014-01-15T23:25:21Z | 2014-01-16T11:12:09Z | null | 2014-06-26T01:49:36Z |
CLN: break read_json, read_msgpack API, disallow string data input | diff --git a/pandas/io/json.py b/pandas/io/json.py
index 698f7777a1100..b5409ef41aeef 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -109,11 +109,14 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
Parameters
----------
- filepath_or_buffer : a valid JSON string or file-like
- The string could be a URL. Valid URL schemes include http, ftp, s3, and
+ path_or_buf : a url, filepath or file-like/StringIO
+ 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``
+ Note: read_json no longer directly accepts a json string as input,
+ If required, wrap it in a BytesIO/StringIO call.
+
orient
* `Series`
@@ -171,25 +174,17 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
result : Series or DataFrame
"""
- filepath_or_buffer, _ = get_filepath_or_buffer(path_or_buf)
- if isinstance(filepath_or_buffer, compat.string_types):
- try:
- exists = os.path.exists(filepath_or_buffer)
-
- # if the filepath is too long will raise here
- # 5874
- except (TypeError,ValueError):
- exists = False
-
- if exists:
- with open(filepath_or_buffer, 'r') as fh:
+ io, _ = get_filepath_or_buffer(path_or_buf)
+ if isinstance(io, compat.string_types):
+ if os.path.exists(io):
+ with open(io, 'r') as fh:
json = fh.read()
else:
- json = filepath_or_buffer
- elif hasattr(filepath_or_buffer, 'read'):
- json = filepath_or_buffer.read()
+ json = io
+ elif hasattr(io, 'read'):
+ json = io.read()
else:
- json = filepath_or_buffer
+ raise ValueError("path_or_buf must be a a url, filepath or file-like/StringIO")
obj = None
if typ == 'frame':
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index 105bea92124fd..4d9de0246d630 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -124,7 +124,11 @@ def read_msgpack(path_or_buf, iterator=False, **kwargs):
Parameters
----------
- path_or_buf : string File path, BytesIO like or string
+ path_or_buf : a url, filepath or BytesIO like
+
+ Note: read_msgpack no longer directly accepts an str/bytes object
+ as input, If required, wrap it in a BytesIO call.
+
iterator : boolean, if True, return an iterator to the unpacker
(default is False)
@@ -145,24 +149,8 @@ def read(fh):
# see if we have an actual file
if isinstance(path_or_buf, compat.string_types):
-
- try:
- exists = os.path.exists(path_or_buf)
- except (TypeError,ValueError):
- exists = False
-
- if exists:
- with open(path_or_buf, 'rb') as fh:
- return read(fh)
-
- # treat as a string-like
- if not hasattr(path_or_buf, 'read'):
-
- try:
- fh = compat.BytesIO(path_or_buf)
- return read(fh)
- finally:
- fh.close()
+ if not os.path.exists(path_or_buf):
+ raise ValueError("path_or_buf must be a a url, filepath or BytesIO like.")
# a buffer like
return read(path_or_buf)
diff --git a/pandas/io/tests/test_packers.py b/pandas/io/tests/test_packers.py
index 8cab9a65995bf..7461745704e52 100644
--- a/pandas/io/tests/test_packers.py
+++ b/pandas/io/tests/test_packers.py
@@ -54,19 +54,19 @@ def tearDown(self):
def encode_decode(self, x, **kwargs):
with ensure_clean(self.path) as p:
to_msgpack(p, x, **kwargs)
- return read_msgpack(p, **kwargs)
+ with open(p, "rb") as f:
+ return read_msgpack(f, **kwargs)
class TestAPI(TestPackers):
def test_string_io(self):
-
df = DataFrame(np.random.randn(10,2))
s = df.to_msgpack(None)
- result = read_msgpack(s)
+ result = read_msgpack(compat.BytesIO(s))
tm.assert_frame_equal(result,df)
s = df.to_msgpack()
- result = read_msgpack(s)
+ result = read_msgpack(compat.BytesIO(s))
tm.assert_frame_equal(result,df)
s = df.to_msgpack()
@@ -74,7 +74,7 @@ def test_string_io(self):
tm.assert_frame_equal(result,df)
s = to_msgpack(None,df)
- result = read_msgpack(s)
+ result = read_msgpack(compat.BytesIO(s))
tm.assert_frame_equal(result, df)
with ensure_clean(self.path) as p:
@@ -83,7 +83,8 @@ def test_string_io(self):
fh = open(p,'wb')
fh.write(s)
fh.close()
- result = read_msgpack(p)
+ with open(p) as f:
+ result = read_msgpack(f)
tm.assert_frame_equal(result, df)
def test_iterator_with_string_io(self):
| revisiting #5655 due to recent #5874, it's just not right.
most pandas read_\* methods take a path/url of file like. the newish read_json/read_msgpack
also accept a (byte)string of data, and tries to guess whether it's data or a filepath.
That creates weird corner cases and is sufficently wrong IMO that it's worth
making a breaking change. Users will now have to wrap their data in BytesIO/StringIO.
not much of a problem, except perhaps the lost convenience of `pd.read_json(j)`. But since json
usually comes from a file or url which are supported directly I'm hoping it won't be
that disruptive.
0.14.0 ofcourse.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5954 | 2014-01-15T20:26:44Z | 2014-01-16T11:26:40Z | null | 2014-06-15T09:42:36Z |
Misc fixes to doc build | diff --git a/doc/source/_templates/autosummary/class.rst b/doc/_templates/autosummary/class.rst
similarity index 100%
rename from doc/source/_templates/autosummary/class.rst
rename to doc/_templates/autosummary/class.rst
diff --git a/doc/source/conf.py b/doc/source/conf.py
index c3c946a5180ba..30d47d0a306a0 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -52,13 +52,13 @@
]
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ['../_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
-# source_encoding = 'utf-8'
+source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
diff --git a/doc/source/dsintro.rst b/doc/source/dsintro.rst
index 3cc93d2f3e122..7d49e26759dd4 100644
--- a/doc/source/dsintro.rst
+++ b/doc/source/dsintro.rst
@@ -11,6 +11,7 @@
np.set_printoptions(precision=4, suppress=True)
set_option('display.precision', 4, 'display.max_columns', 8)
options.display.max_rows=15
+ import pandas as pd
************************
@@ -488,6 +489,12 @@ TimeSeries (which it will be automatically if the index contains datetime
objects), and the DataFrame index also contains dates, the broadcasting will be
column-wise:
+.. ipython:: python
+ :suppress:
+
+ import warnings
+ warnings.filterwarnings("ignore",message='TimeSeries broadcasting',category=FutureWarning)
+
.. ipython:: python
index = date_range('1/1/2000', periods=8)
diff --git a/doc/source/faq.rst b/doc/source/faq.rst
index c826d95e9c1d7..68f6e3d53cdca 100644
--- a/doc/source/faq.rst
+++ b/doc/source/faq.rst
@@ -81,7 +81,7 @@ life easier is missing. In that case you have several options:
For example, here is an example of adding an ``just_foo_cols()``
method to the dataframe class:
-.. ipython:: python
+::
import pandas as pd
def just_foo_cols(self):
| The more innocous bits and pieces of #5925, no sense in waiting.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5953 | 2014-01-15T19:47:05Z | 2014-01-15T19:47:11Z | 2014-01-15T19:47:11Z | 2014-06-22T18:22:35Z |
CLN: repr_html raises NotImplementedError rather then ValueError in qtconsole | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8f1916141b572..61d59e8f93c83 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -474,7 +474,7 @@ def _repr_html_(self):
# behaves badly when outputting an HTML table
# that doesn't fit the window, so disable it.
if com.in_qtconsole():
- raise ValueError('Disable HTML output in QtConsole')
+ raise NotImplementedError('HTML output is disabled in QtConsole')
if self._info_repr():
buf = StringIO(u(""))
| #5922. No word from ipython yet but the change makes sense regardless.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5951 | 2014-01-15T19:03:35Z | 2014-01-15T20:49:18Z | 2014-01-15T20:49:18Z | 2014-07-16T08:22:47Z |
ENH: sql support via SQLAlchemy, with legacy fallback | diff --git a/README.md b/README.md
index 3b5f69912823b..ec7b8b07f3e89 100644
--- a/README.md
+++ b/README.md
@@ -106,6 +106,7 @@ pip install pandas
- [Cython](http://www.cython.org): Only necessary to build development version. Version 0.17.1 or higher.
- [SciPy](http://www.scipy.org): miscellaneous statistical functions
- [PyTables](http://www.pytables.org): necessary for HDF5-based storage
+- [SQLAlchemy](http://www.sqlalchemy.org): for SQL database support. Version 0.8.1 or higher recommended.
- [matplotlib](http://matplotlib.sourceforge.net/): for plotting
- [statsmodels](http://statsmodels.sourceforge.net/)
- Needed for parts of `pandas.stats`
diff --git a/ci/requirements-2.6.txt b/ci/requirements-2.6.txt
index 8199fdd9b9648..183d0a2d888f0 100644
--- a/ci/requirements-2.6.txt
+++ b/ci/requirements-2.6.txt
@@ -5,4 +5,5 @@ pytz==2013b
http://www.crummy.com/software/BeautifulSoup/bs4/download/4.2/beautifulsoup4-4.2.0.tar.gz
html5lib==1.0b2
bigquery==2.0.17
+sqlalchemy==0.8.1
numexpr==1.4.2
diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt
index c7cf69bc92927..f9ccc54fbbcb6 100644
--- a/ci/requirements-2.7.txt
+++ b/ci/requirements-2.7.txt
@@ -19,3 +19,4 @@ scipy==0.10.0
beautifulsoup4==4.2.1
statsmodels==0.5.0
bigquery==2.0.17
+sqlalchemy==0.8.1
diff --git a/ci/requirements-2.7_LOCALE.txt b/ci/requirements-2.7_LOCALE.txt
index 06574cdd6b299..e45c27141c907 100644
--- a/ci/requirements-2.7_LOCALE.txt
+++ b/ci/requirements-2.7_LOCALE.txt
@@ -7,8 +7,6 @@ xlrd==0.9.2
numpy==1.6.1
cython==0.19.1
bottleneck==0.6.0
-numexpr==2.1
-tables==2.3.1
matplotlib==1.3.0
patsy==0.1.0
html5lib==1.0b2
@@ -17,3 +15,4 @@ scipy==0.10.0
beautifulsoup4==4.2.1
statsmodels==0.5.0
bigquery==2.0.17
+sqlalchemy==0.8.1
diff --git a/ci/requirements-3.3.txt b/ci/requirements-3.3.txt
index 480fde477d88b..73009b572c4c2 100644
--- a/ci/requirements-3.3.txt
+++ b/ci/requirements-3.3.txt
@@ -14,3 +14,4 @@ lxml==3.2.1
scipy==0.12.0
beautifulsoup4==4.2.1
statsmodels==0.4.3
+sqlalchemy==0.9.1
diff --git a/doc/source/install.rst b/doc/source/install.rst
index 631973934cc3b..f67bdc10a457f 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -95,6 +95,7 @@ Optional Dependencies
version. Version 0.17.1 or higher.
* `SciPy <http://www.scipy.org>`__: miscellaneous statistical functions
* `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage
+ * `SQLAlchemy <http://www.sqlalchemy.org>`__: for SQL database support. Version 0.8.1 or higher recommended.
* `matplotlib <http://matplotlib.sourceforge.net/>`__: for plotting
* `statsmodels <http://statsmodels.sourceforge.net/>`__
* Needed for parts of :mod:`pandas.stats`
diff --git a/doc/source/io.rst b/doc/source/io.rst
index 34af31747ca4a..cc354b6d134d8 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -3068,13 +3068,48 @@ SQL Queries
-----------
The :mod:`pandas.io.sql` module provides a collection of query wrappers to both
-facilitate data retrieval and to reduce dependency on DB-specific API. These
-wrappers only support the Python database adapters which respect the `Python
-DB-API <http://www.python.org/dev/peps/pep-0249/>`__. See some
-:ref:`cookbook examples <cookbook.sql>` for some advanced strategies
+facilitate data retrieval and to reduce dependency on DB-specific API. Database abstraction
+is provided by SQLAlchemy if installed, in addition you will need a driver library for
+your database.
-For example, suppose you want to query some data with different types from a
-table such as:
+.. versionadded:: 0.14.0
+
+
+If SQLAlchemy is not installed a legacy fallback is provided for sqlite and mysql.
+These legacy modes require Python database adapters which respect the `Python
+DB-API <http://www.python.org/dev/peps/pep-0249/>`__.
+
+See also some :ref:`cookbook examples <cookbook.sql>` for some advanced strategies.
+
+The key functions are:
+:func:`~pandas.io.sql.to_sql`
+:func:`~pandas.io.sql.read_sql`
+:func:`~pandas.io.sql.read_table`
+
+
+In the following example, we use the `SQlite <http://www.sqlite.org/>`__ SQL database
+engine. You can use a temporary SQLite database where data are stored in
+"memory".
+
+To connect with SQLAlchemy you use the :func:`create_engine` function to create an engine
+object from database URI. You only need to create the engine once per database you are
+connecting to.
+
+For more information on :func:`create_engine` and the URI formatting, see the examples
+below and the SQLAlchemy `documentation <http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html>`__
+
+.. code-block:: python
+
+ from sqlalchemy import create_engine
+ from pandas.io import sql
+ # Create your connection.
+ engine = create_engine('sqlite:///:memory:')
+
+Writing DataFrames
+~~~~~~~~~~~~~~~~~~
+
+Assuming the following data is in a DataFrame ``data``, we can insert it into
+the database using :func:`~pandas.io.sql.to_sql`.
+-----+------------+-------+-------+-------+
@@ -3088,81 +3123,144 @@ table such as:
+-----+------------+-------+-------+-------+
-Functions from :mod:`pandas.io.sql` can extract some data into a DataFrame. In
-the following example, we use the `SQlite <http://www.sqlite.org/>`__ SQL database
-engine. You can use a temporary SQLite database where data are stored in
-"memory". Just do:
-
-.. code-block:: python
+.. ipython:: python
+ :suppress:
- import sqlite3
+ from sqlalchemy import create_engine
from pandas.io import sql
- # Create your connection.
- cnx = sqlite3.connect(':memory:')
+ engine = create_engine('sqlite:///:memory:')
.. ipython:: python
:suppress:
+
+ c = ['id', 'Date', 'Col_1', 'Col_2', 'Col_3']
+ d = [(26, datetime.datetime(2010,10,18), 'X', 27.5, True),
+ (42, datetime.datetime(2010,10,19), 'Y', -12.5, False),
+ (63, datetime.datetime(2010,10,20), 'Z', 5.73, True)]
- import sqlite3
- from pandas.io import sql
- cnx = sqlite3.connect(':memory:')
+ data = DataFrame(d, columns=c)
.. ipython:: python
- :suppress:
+
+ sql.to_sql(data, 'data', engine)
+
+Reading Tables
+~~~~~~~~~~~~~~
+
+:func:`~pandas.io.sql.read_table` will read a databse table given the
+table name and optionally a subset of columns to read.
- cu = cnx.cursor()
- # Create a table named 'data'.
- cu.execute("""CREATE TABLE data(id integer,
- date date,
- Col_1 string,
- Col_2 float,
- Col_3 bool);""")
- cu.executemany('INSERT INTO data VALUES (?,?,?,?,?)',
- [(26, datetime.datetime(2010,10,18), 'X', 27.5, True),
- (42, datetime.datetime(2010,10,19), 'Y', -12.5, False),
- (63, datetime.datetime(2010,10,20), 'Z', 5.73, True)])
+.. note::
+
+ In order to use :func:`~pandas.io.sql.read_table`, you **must** have the
+ SQLAlchemy optional dependency installed.
+.. ipython:: python
+
+ sql.read_table('data', engine)
-Let ``data`` be the name of your SQL table. With a query and your database
-connection, just use the :func:`~pandas.io.sql.read_sql` function to get the
-query results into a DataFrame:
+You can also specify the name of the column as the DataFrame index,
+and specify a subset of columns to be read.
.. ipython:: python
- sql.read_sql("SELECT * FROM data;", cnx)
+ sql.read_table('data', engine, index_col='id')
+ sql.read_table('data', engine, columns=['Col_1', 'Col_2'])
-You can also specify the name of the column as the DataFrame index:
+And you can explicitly force columns to be parsed as dates:
.. ipython:: python
- sql.read_sql("SELECT * FROM data;", cnx, index_col='id')
- sql.read_sql("SELECT * FROM data;", cnx, index_col='date')
+ sql.read_table('data', engine, parse_dates=['Date'])
-Of course, you can specify a more "complex" query.
+If needed you can explicitly specifiy a format string, or a dict of arguments
+to pass to :func:`pandas.tseries.tools.to_datetime`.
+
+.. code-block:: python
+
+ sql.read_table('data', engine, parse_dates={'Date': '%Y-%m-%d'})
+ sql.read_table('data', engine, parse_dates={'Date': {'format': '%Y-%m-%d %H:%M:%S'}})
+
+
+You can check if a table exists using :func:`~pandas.io.sql.has_table`
+
+In addition, the class :class:`~pandas.io.sql.PandasSQLWithEngine` can be
+instantiated directly for more manual control over the SQL interaction.
+
+Querying
+~~~~~~~~
+
+You can query using raw SQL in the :func:`~pandas.io.sql.read_sql` function.
+In this case you must use the SQL variant appropriate for your database.
+When using SQLAlchemy, you can also pass SQLAlchemy Expression language constructs,
+which are database-agnostic.
.. ipython:: python
+
+ sql.read_sql('SELECT * FROM data', engine)
- sql.read_sql("SELECT id, Col_1, Col_2 FROM data WHERE id = 42;", cnx)
+Of course, you can specify a more "complex" query.
.. ipython:: python
- :suppress:
- cu.close()
- cnx.close()
+ sql.read_frame("SELECT id, Col_1, Col_2 FROM data WHERE id = 42;", engine)
-There are a few other available functions:
+You can also run a plain query without creating a dataframe with
+:func:`~pandas.io.sql.execute`. This is useful for queries that don't return values,
+such as INSERT. This is functionally equivalent to calling ``execute`` on the
+SQLAlchemy engine or db connection object. Again, ou must use the SQL syntax
+variant appropriate for your database.
- - ``tquery`` returns a list of tuples corresponding to each row.
- - ``uquery`` does the same thing as tquery, but instead of returning results
- it returns the number of related rows.
- - ``write_frame`` writes records stored in a DataFrame into the SQL table.
- - ``has_table`` checks if a given SQLite table exists.
+.. code-block:: python
-.. note::
+ sql.execute('SELECT * FROM table_name', engine)
+
+ sql.execute('INSERT INTO table_name VALUES(?, ?, ?)', engine, params=[('id', 1, 12.2, True)])
+
+
+Engine connection examples
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. code-block:: python
+
+ from sqlalchemy import create_engine
+
+ engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
+
+ engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')
+
+ engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
+
+ engine = create_engine('mssql+pyodbc://mydsn')
+
+ # sqlite://<nohostname>/<path>
+ # where <path> is relative:
+ engine = create_engine('sqlite:///foo.db')
+
+ # or absolute, starting with a slash:
+ engine = create_engine('sqlite:////absolute/path/to/foo.db')
+
+
+Legacy
+~~~~~~
+To use the sqlite support without SQLAlchemy, you can create connections like so:
+
+.. code-block:: python
+
+ import sqlite3
+ from pandas.io import sql
+ cnx = sqlite3.connect(':memory:')
+
+And then issue the following queries, remembering to also specify the flavor of SQL
+you are using.
+
+.. code-block:: python
+
+ sql.to_sql(data, 'data', cnx, flavor='sqlite')
+
+ sql.read_sql("SELECT * FROM data", cnx, flavor='sqlite')
- For now, writing your DataFrame into a database works only with
- **SQLite**. Moreover, the **index** will currently be **dropped**.
.. _io.bigquery:
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 5e83a0921189b..e705a3b20585a 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -4,20 +4,77 @@
"""
from __future__ import print_function
from datetime import datetime, date
-
-from pandas.compat import range, lzip, map, zip
-import pandas.compat as compat
+import warnings
+from pandas.compat import lzip, map, zip, raise_with_traceback, string_types
import numpy as np
-import traceback
-from pandas.core.datetools import format as date_format
+
from pandas.core.api import DataFrame
+from pandas.core.base import PandasObject
+from pandas.tseries.tools import to_datetime
+
+
+class SQLAlchemyRequired(ImportError):
+ pass
+
+
+class DatabaseError(IOError):
+ pass
+
#------------------------------------------------------------------------------
-# Helper execution function
+# Helper functions
+
+def _convert_params(sql, params):
+ """convert sql and params args to DBAPI2.0 compliant format"""
+ args = [sql]
+ if params is not None:
+ args += list(params)
+ return args
+
+def _safe_col_name(col_name):
+ #TODO: probably want to forbid database reserved names, such as "database"
+ return col_name.strip().replace(' ', '_')
-def execute(sql, con, retry=True, cur=None, params=None):
+
+def _handle_date_column(col, format=None):
+ if isinstance(format, dict):
+ return to_datetime(col, **format)
+ else:
+ if format in ['D', 's', 'ms', 'us', 'ns']:
+ return to_datetime(col, coerce=True, unit=format)
+ elif issubclass(col.dtype.type, np.floating) or issubclass(col.dtype.type, np.integer):
+ # parse dates as timestamp
+ format = 's' if format is None else format
+ return to_datetime(col, coerce=True, unit=format)
+ else:
+ return to_datetime(col, coerce=True, format=format)
+
+
+def _parse_date_columns(data_frame, parse_dates):
+ """ Force non-datetime columns to be read as such.
+ Supports both string formatted and integer timestamp columns
+ """
+ # handle non-list entries for parse_dates gracefully
+ if parse_dates is True or parse_dates is None or parse_dates is False:
+ parse_dates = []
+
+ if not hasattr(parse_dates, '__iter__'):
+ parse_dates = [parse_dates]
+
+ for col_name in parse_dates:
+ df_col = data_frame[col_name]
+ try:
+ fmt = parse_dates[col_name]
+ except TypeError:
+ fmt = None
+ data_frame[col_name] = _handle_date_column(df_col, format=fmt)
+
+ return data_frame
+
+
+def execute(sql, con, cur=None, params=None, flavor='sqlite'):
"""
Execute the given SQL query using the provided connection object.
@@ -25,52 +82,26 @@ def execute(sql, con, retry=True, cur=None, params=None):
----------
sql: string
Query to be executed
- con: database connection instance
- Database connection. Must implement PEP249 (Database API v2.0).
- retry: bool
- Not currently implemented
- cur: database cursor, optional
- Must implement PEP249 (Datbase API v2.0). If cursor is not provided,
- one will be obtained from the database connection.
+ con: SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ If a DBAPI2 object, a supported SQL flavor must also be provided
+ cur: depreciated, cursor is obtained from connection
params: list or tuple, optional
List of parameters to pass to execute method.
-
+ flavor : string "sqlite", "mysql"
+ Specifies the flavor of SQL to use.
+ Ignored when using SQLAlchemy engine. Required when using DBAPI2 connection.
Returns
-------
- Cursor object
+ Results Iterable
"""
- try:
- if cur is None:
- cur = con.cursor()
-
- if params is None:
- cur.execute(sql)
- else:
- cur.execute(sql, params)
- return cur
- except Exception:
- try:
- con.rollback()
- except Exception: # pragma: no cover
- pass
-
- print('Error on sql %s' % sql)
- raise
-
-
-def _safe_fetch(cur):
- try:
- result = cur.fetchall()
- if not isinstance(result, list):
- result = list(result)
- return result
- except Exception as e: # pragma: no cover
- excName = e.__class__.__name__
- if excName == 'OperationalError':
- return []
+ pandas_sql = pandasSQL_builder(con, flavor=flavor)
+ args = _convert_params(sql, params)
+ return pandas_sql.execute(*args)
-def tquery(sql, con=None, cur=None, retry=True):
+def tquery(sql, con, cur=None, params=None, flavor='sqlite'):
"""
Returns list of tuples corresponding to each row in given sql
query.
@@ -81,102 +112,118 @@ def tquery(sql, con=None, cur=None, retry=True):
----------
sql: string
SQL query to be executed
- con: SQLConnection or DB API 2.0-compliant connection
- cur: DB API 2.0 cursor
-
- Provide a specific connection or a specific cursor if you are executing a
- lot of sequential statements and want to commit outside.
+ con: SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ If a DBAPI2 object is given, a supported SQL flavor must also be provided
+ cur: depreciated, cursor is obtained from connection
+ params: list or tuple, optional
+ List of parameters to pass to execute method.
+ flavor : string "sqlite", "mysql"
+ Specifies the flavor of SQL to use.
+ Ignored when using SQLAlchemy engine. Required when using DBAPI2
+ connection.
+ Returns
+ -------
+ Results Iterable
"""
- cur = execute(sql, con, cur=cur)
- result = _safe_fetch(cur)
-
- if con is not None:
- try:
- cur.close()
- con.commit()
- except Exception as e:
- excName = e.__class__.__name__
- if excName == 'OperationalError': # pragma: no cover
- print('Failed to commit, may need to restart interpreter')
- else:
- raise
-
- traceback.print_exc()
- if retry:
- return tquery(sql, con=con, retry=False)
-
- if result and len(result[0]) == 1:
- # python 3 compat
- result = list(lzip(*result)[0])
- elif result is None: # pragma: no cover
- result = []
+ warnings.warn(
+ "tquery is depreciated, and will be removed in future versions",
+ DeprecationWarning)
- return result
+ pandas_sql = pandasSQL_builder(con, flavor=flavor)
+ args = _convert_params(sql, params)
+ return pandas_sql.tquery(*args)
-def uquery(sql, con=None, cur=None, retry=True, params=None):
+def uquery(sql, con, cur=None, params=None, engine=None, flavor='sqlite'):
"""
Does the same thing as tquery, but instead of returning results, it
returns the number of rows affected. Good for update queries.
+
+ Parameters
+ ----------
+ sql: string
+ SQL query to be executed
+ con: SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ If a DBAPI2 object is given, a supported SQL flavor must also be provided
+ cur: depreciated, cursor is obtained from connection
+ params: list or tuple, optional
+ List of parameters to pass to execute method.
+ flavor : string "sqlite", "mysql"
+ Specifies the flavor of SQL to use.
+ Ignored when using SQLAlchemy engine. Required when using DBAPI2
+ connection.
+ Returns
+ -------
+ Number of affected rows
"""
- cur = execute(sql, con, cur=cur, retry=retry, params=params)
+ warnings.warn(
+ "uquery is depreciated, and will be removed in future versions",
+ DeprecationWarning)
+ pandas_sql = pandasSQL_builder(con, flavor=flavor)
+ args = _convert_params(sql, params)
+ return pandas_sql.uquery(*args)
- result = cur.rowcount
- try:
- con.commit()
- except Exception as e:
- excName = e.__class__.__name__
- if excName != 'OperationalError':
- raise
- traceback.print_exc()
- if retry:
- print('Looks like your connection failed, reconnecting...')
- return uquery(sql, con, retry=False)
- return result
+#------------------------------------------------------------------------------
+# Read and write to DataFrames
-def read_frame(sql, con, index_col=None, coerce_float=True, params=None):
+def read_sql(sql, con, index_col=None, flavor='sqlite', coerce_float=True,
+ params=None, parse_dates=None):
"""
Returns a DataFrame corresponding to the result set of the query
string.
Optionally provide an index_col parameter to use one of the
- columns as the index. Otherwise will be 0 to len(results) - 1.
+ columns as the index, otherwise default integer index will be used
Parameters
----------
sql: string
SQL query to be executed
- con: DB connection object, optional
+ con: SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ If a DBAPI2 object is given, a supported SQL flavor must also be provided
index_col: string, optional
column name to use for the returned DataFrame object.
+ flavor : string specifying the flavor of SQL to use. Ignored when using
+ SQLAlchemy engine. Required when using DBAPI2 connection.
coerce_float : boolean, default True
Attempt to convert values to non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
+ cur: depreciated, cursor is obtained from connection
params: list or tuple, optional
List of parameters to pass to execute method.
- """
- cur = execute(sql, con, params=params)
- rows = _safe_fetch(cur)
- columns = [col_desc[0] for col_desc in cur.description]
-
- cur.close()
- con.commit()
-
- result = DataFrame.from_records(rows, columns=columns,
- coerce_float=coerce_float)
+ parse_dates: list or dict
+ List of column names to parse as dates
+ Or
+ Dict of {column_name: format string} where format string is
+ strftime compatible in case of parsing string times or is one of
+ (D, s, ns, ms, us) in case of parsing integer timestamps
+ Or
+ Dict of {column_name: arg dict}, where the arg dict corresponds
+ to the keyword arguments of :func:`pandas.tseries.tools.to_datetime`
+ Especially useful with databases without native Datetime support,
+ such as SQLite
- if index_col is not None:
- result = result.set_index(index_col)
-
- return result
-
-frame_query = read_frame
-read_sql = read_frame
+ Returns
+ -------
+ DataFrame
+ """
+ pandas_sql = pandasSQL_builder(con, flavor=flavor)
+ return pandas_sql.read_sql(sql,
+ index_col=index_col,
+ params=params,
+ coerce_float=coerce_float,
+ parse_dates=parse_dates)
-def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs):
+def to_sql(frame, name, con, flavor='sqlite', if_exists='fail', index=True):
"""
Write records stored in a DataFrame to a SQL database.
@@ -184,162 +231,689 @@ def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs):
----------
frame: DataFrame
name: name of SQL table
- con: an open SQL database connection object
- flavor: {'sqlite', 'mysql', 'oracle'}, default 'sqlite'
+ con: SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ If a DBAPI2 object is given, a supported SQL flavor must also be provided
+ flavor: {'sqlite', 'mysql', 'postgres'}, default 'sqlite'
+ ignored when SQLAlchemy engine. Required when using DBAPI2 connection.
if_exists: {'fail', 'replace', 'append'}, default 'fail'
fail: If table exists, do nothing.
replace: If table exists, drop it, recreate it, and insert data.
append: If table exists, insert data. Create if does not exist.
+ index : boolean, default True
+ Write DataFrame index as an column
"""
+ pandas_sql = pandasSQL_builder(con, flavor=flavor)
+ pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index)
- if 'append' in kwargs:
- import warnings
- warnings.warn("append is deprecated, use if_exists instead",
- FutureWarning)
- if kwargs['append']:
- if_exists = 'append'
- else:
- if_exists = 'fail'
-
- if if_exists not in ('fail', 'replace', 'append'):
- raise ValueError("'%s' is not valid for if_exists" % if_exists)
-
- exists = table_exists(name, con, flavor)
- if if_exists == 'fail' and exists:
- raise ValueError("Table '%s' already exists." % name)
-
- # creation/replacement dependent on the table existing and if_exist criteria
- create = None
- if exists:
- if if_exists == 'fail':
- raise ValueError("Table '%s' already exists." % name)
- elif if_exists == 'replace':
- cur = con.cursor()
- cur.execute("DROP TABLE %s;" % name)
- cur.close()
- create = get_schema(frame, name, flavor)
+
+def has_table(table_name, con, meta=None, flavor='sqlite'):
+ """
+ Check if DB has named table
+
+ Parameters
+ ----------
+ frame: DataFrame
+ name: name of SQL table
+ con: SQLAlchemy engine or DBAPI2 connection (legacy mode)
+ Using SQLAlchemy makes it possible to use any DB supported by that
+ library.
+ If a DBAPI2 object is given, a supported SQL flavor name must also be provided
+ flavor: {'sqlite', 'mysql'}, default 'sqlite', ignored when using engine
+ Returns
+ -------
+ boolean
+ """
+ pandas_sql = pandasSQL_builder(con, flavor=flavor)
+ return pandas_sql.has_table(table_name)
+
+
+def read_table(table_name, con, meta=None, index_col=None, coerce_float=True,
+ parse_dates=None, columns=None):
+ """Given a table name and SQLAlchemy engine, return a DataFrame.
+ Type convertions will be done automatically
+
+ Parameters
+ ----------
+ table_name: name of SQL table in database
+ con: SQLAlchemy engine. Legacy mode not supported
+ meta: SQLAlchemy meta, optional. If omitted MetaData is reflected from engine
+ index_col: column to set as index, optional
+ coerce_float : boolean, default True
+ Attempt to convert values to non-string, non-numeric objects (like
+ decimal.Decimal) to floating point. Can result in loss of Precision.
+ parse_dates: list or dict
+ List of column names to parse as dates
+ Or
+ Dict of {column_name: format string} where format string is
+ strftime compatible in case of parsing string times or is one of
+ (D, s, ns, ms, us) in case of parsing integer timestamps
+ Or
+ Dict of {column_name: arg dict}, where the arg dict corresponds
+ to the keyword arguments of :func:`pandas.tseries.tools.to_datetime`
+ Especially useful with databases without native Datetime support,
+ such as SQLite
+ columns: list
+ List of column names to select from sql table
+ Returns
+ -------
+ DataFrame
+ """
+ pandas_sql = PandasSQLAlchemy(con, meta=meta)
+ table = pandas_sql.read_table(table_name,
+ index_col=index_col,
+ coerce_float=coerce_float,
+ parse_dates=parse_dates)
+
+ if table is not None:
+ return table
else:
- create = get_schema(frame, name, flavor)
+ raise ValueError("Table %s not found" % table_name, con)
+
- if create is not None:
- cur = con.cursor()
- cur.execute(create)
+def pandasSQL_builder(con, flavor=None, meta=None):
+ """
+ Convenience function to return the correct PandasSQL subclass based on the
+ provided parameters
+ """
+ try:
+ import sqlalchemy
+
+ if isinstance(con, sqlalchemy.engine.Engine):
+ return PandasSQLAlchemy(con, meta=meta)
+ else:
+ warnings.warn(
+ """Not an SQLAlchemy engine,
+ attempting to use as legacy DBAPI connection""")
+ if flavor is None:
+ raise ValueError(
+ """PandasSQL must be created with an SQLAlchemy engine
+ or a DBAPI2 connection and SQL flavour""")
+ else:
+ return PandasSQLLegacy(con, flavor)
+
+ except ImportError:
+ warnings.warn("SQLAlchemy not installed, using legacy mode")
+ if flavor is None:
+ raise SQLAlchemyRequired
+ else:
+ return PandasSQLLegacy(con, flavor)
+
+
+class PandasSQLTable(PandasObject):
+ """ For mapping Pandas tables to SQL tables.
+ Uses fact that table is reflected by SQLAlchemy to
+ do better type convertions.
+ Also holds various flags needed to avoid having to
+ pass them between functions all the time.
+ """
+ # TODO: support for multiIndex
+ def __init__(self, name, pandas_sql_engine, frame=None, index=True,
+ if_exists='fail', prefix='pandas'):
+ self.name = name
+ self.pd_sql = pandas_sql_engine
+ self.prefix = prefix
+ self.frame = frame
+ self.index = self._index_name(index)
+
+ if frame is not None:
+ # We want to write a frame
+ if self.pd_sql.has_table(self.name):
+ if if_exists == 'fail':
+ raise ValueError("Table '%s' already exists." % name)
+ elif if_exists == 'replace':
+ self.pd_sql.drop_table(self.name)
+ self.table = self._create_table_statement()
+ self.create()
+ elif if_exists == 'append':
+ self.table = self.pd_sql.get_table(self.name)
+ if self.table is None:
+ self.table = self._create_table_statement()
+ else:
+ self.table = self._create_table_statement()
+ self.create()
+ else:
+ # no data provided, read-only mode
+ self.table = self.pd_sql.get_table(self.name)
+
+ if self.table is None:
+ raise ValueError("Could not init table '%s'" % name)
+
+ def exists(self):
+ return self.pd_sql.has_table(self.name)
+
+ def sql_schema(self):
+ return str(self.table.compile())
+
+ def create(self):
+ self.table.create()
+
+ def insert_statement(self):
+ return self.table.insert()
+
+ def maybe_asscalar(self, i):
+ try:
+ return np.asscalar(i)
+ except AttributeError:
+ return i
+
+ def insert(self):
+ ins = self.insert_statement()
+
+ for t in self.frame.iterrows():
+ data = dict((k, self.maybe_asscalar(v))
+ for k, v in t[1].iteritems())
+ if self.index is not None:
+ data[self.index] = self.maybe_asscalar(t[0])
+ self.pd_sql.execute(ins, **data)
+
+ def read(self, coerce_float=True, parse_dates=None, columns=None):
+
+ if columns is not None and len(columns) > 0:
+ from sqlalchemy import select
+ cols = [self.table.c[n] for n in columns]
+ if self.index is not None:
+ cols.insert(0, self.table.c[self.index])
+ sql_select = select(cols)
+ else:
+ sql_select = self.table.select()
+
+ result = self.pd_sql.execute(sql_select)
+ data = result.fetchall()
+ column_names = result.keys()
+
+ self.frame = DataFrame.from_records(
+ data, columns=column_names, coerce_float=coerce_float)
+
+ self._harmonize_columns(parse_dates=parse_dates)
+
+ if self.index is not None:
+ self.frame.set_index(self.index, inplace=True)
+
+ # Assume if the index in prefix_index format, we gave it a name
+ # and should return it nameless
+ if self.index == self.prefix + '_index':
+ self.frame.index.name = None
+
+ return self.frame
+
+ def _index_name(self, index):
+ if index is True:
+ if self.frame.index.name is not None:
+ return _safe_col_name(self.frame.index.name)
+ else:
+ return self.prefix + '_index'
+ elif isinstance(index, string_types):
+ return index
+ else:
+ return None
+
+ def _create_table_statement(self):
+ from sqlalchemy import Table, Column
+
+ safe_columns = map(_safe_col_name, self.frame.dtypes.index)
+ column_types = map(self._sqlalchemy_type, self.frame.dtypes)
+
+ columns = [Column(name, typ)
+ for name, typ in zip(safe_columns, column_types)]
+
+ if self.index is not None:
+ columns.insert(0, Column(self.index,
+ self._sqlalchemy_type(
+ self.frame.index.dtype),
+ index=True))
+
+ return Table(self.name, self.pd_sql.meta, *columns)
+
+ def _harmonize_columns(self, parse_dates=None):
+ """ Make a data_frame's column type align with an sql_table
+ column types
+ Need to work around limited NA value support.
+ Floats are always fine, ints must always
+ be floats if there are Null values.
+ Booleans are hard because converting bool column with None replaces
+ all Nones with false. Therefore only convert bool if there are no
+ NA values.
+ Datetimes should already be converted
+ to np.datetime if supported, but here we also force conversion
+ if required
+ """
+ # handle non-list entries for parse_dates gracefully
+ if parse_dates is True or parse_dates is None or parse_dates is False:
+ parse_dates = []
+
+ if not hasattr(parse_dates, '__iter__'):
+ parse_dates = [parse_dates]
+
+ for sql_col in self.table.columns:
+ col_name = sql_col.name
+ try:
+ df_col = self.frame[col_name]
+ # the type the dataframe column should have
+ col_type = self._numpy_type(sql_col.type)
+
+ if col_type is datetime or col_type is date:
+ if not issubclass(df_col.dtype.type, np.datetime64):
+ self.frame[col_name] = _handle_date_column(df_col)
+
+ elif col_type is float:
+ # floats support NA, can always convert!
+ self.frame[col_name].astype(col_type, copy=False)
+
+ elif len(df_col) == df_col.count():
+ # No NA values, can convert ints and bools
+ if col_type is int or col_type is bool:
+ self.frame[col_name].astype(col_type, copy=False)
+
+ # Handle date parsing
+ if col_name in parse_dates:
+ try:
+ fmt = parse_dates[col_name]
+ except TypeError:
+ fmt = None
+ self.frame[col_name] = _handle_date_column(
+ df_col, format=fmt)
+
+ except KeyError:
+ pass # this column not in results
+
+ def _sqlalchemy_type(self, dtype):
+ from sqlalchemy.types import Integer, Float, Text, Boolean, DateTime, Date
+
+ pytype = dtype.type
+
+ if pytype is date:
+ return Date
+ if issubclass(pytype, np.datetime64) or pytype is datetime:
+ # Caution: np.datetime64 is also a subclass of np.number.
+ return DateTime
+ if issubclass(pytype, np.floating):
+ return Float
+ if issubclass(pytype, np.integer):
+ # TODO: Refine integer size.
+ return Integer
+ if issubclass(pytype, np.bool_):
+ return Boolean
+ return Text
+
+ def _numpy_type(self, sqltype):
+ from sqlalchemy.types import Integer, Float, Boolean, DateTime, Date
+
+ if isinstance(sqltype, Float):
+ return float
+ if isinstance(sqltype, Integer):
+ # TODO: Refine integer size.
+ return int
+ if isinstance(sqltype, DateTime):
+ # Caution: np.datetime64 is also a subclass of np.number.
+ return datetime
+ if isinstance(sqltype, Date):
+ return date
+ if isinstance(sqltype, Boolean):
+ return bool
+ return object
+
+
+class PandasSQL(PandasObject):
+
+ """
+ Subclasses Should define read_sql and to_sql
+ """
+
+ def read_sql(self, *args, **kwargs):
+ raise ValueError(
+ "PandasSQL must be created with an SQLAlchemy engine or connection+sql flavor")
+
+ def to_sql(self, *args, **kwargs):
+ raise ValueError(
+ "PandasSQL must be created with an SQLAlchemy engine or connection+sql flavor")
+
+
+class PandasSQLAlchemy(PandasSQL):
+
+ """
+ This class enables convertion between DataFrame and SQL databases
+ using SQLAlchemy to handle DataBase abstraction
+ """
+
+ def __init__(self, engine, meta=None):
+ self.engine = engine
+ if not meta:
+ from sqlalchemy.schema import MetaData
+ meta = MetaData(self.engine)
+ meta.reflect(self.engine)
+
+ self.meta = meta
+
+ def execute(self, *args, **kwargs):
+ """Simple passthrough to SQLAlchemy engine"""
+ return self.engine.execute(*args, **kwargs)
+
+ def tquery(self, *args, **kwargs):
+ result = self.execute(*args, **kwargs)
+ return result.fetchall()
+
+ def uquery(self, *args, **kwargs):
+ result = self.execute(*args, **kwargs)
+ return result.rowcount
+
+ def read_sql(self, sql, index_col=None, coerce_float=True,
+ parse_dates=None, params=None):
+ args = _convert_params(sql, params)
+
+ result = self.execute(*args)
+ data = result.fetchall()
+ columns = result.keys()
+
+ data_frame = DataFrame.from_records(
+ data, columns=columns, coerce_float=coerce_float)
+
+ _parse_date_columns(data_frame, parse_dates)
+
+ if index_col is not None:
+ data_frame.set_index(index_col, inplace=True)
+
+ return data_frame
+
+ def to_sql(self, frame, name, if_exists='fail', index=True):
+ table = PandasSQLTable(
+ name, self, frame=frame, index=index, if_exists=if_exists)
+ table.insert()
+
+ def has_table(self, name):
+ return self.engine.has_table(name)
+
+ def get_table(self, table_name):
+ if self.engine.has_table(table_name):
+ return self.meta.tables[table_name]
+ else:
+ return None
+
+ def read_table(self, table_name, index_col=None, coerce_float=True,
+ parse_dates=None, columns=None):
+
+ table = PandasSQLTable(table_name, self, index=index_col)
+ return table.read(coerce_float=parse_dates,
+ parse_dates=parse_dates, columns=columns)
+
+ def drop_table(self, table_name):
+ if self.engine.has_table(table_name):
+ self.get_table(table_name).drop()
+ self.meta.clear()
+ self.meta.reflect()
+
+ def _create_sql_schema(self, frame, table_name):
+ table = PandasSQLTable(table_name, self, frame=frame)
+ return str(table.compile())
+
+
+# ---- SQL without SQLAlchemy ---
+# Flavour specific sql strings and handler class for access to DBs without
+# SQLAlchemy installed
+# SQL type convertions for each DB
+_SQL_TYPES = {
+ 'text': {
+ 'mysql': 'VARCHAR (63)',
+ 'sqlite': 'TEXT',
+ },
+ 'float': {
+ 'mysql': 'FLOAT',
+ 'sqlite': 'REAL',
+ },
+ 'int': {
+ 'mysql': 'BIGINT',
+ 'sqlite': 'INTEGER',
+ },
+ 'datetime': {
+ 'mysql': 'DATETIME',
+ 'sqlite': 'TIMESTAMP',
+ },
+ 'date': {
+ 'mysql': 'DATE',
+ 'sqlite': 'TIMESTAMP',
+ },
+ 'bool': {
+ 'mysql': 'BOOLEAN',
+ 'sqlite': 'INTEGER',
+ }
+}
+
+# SQL enquote and wildcard symbols
+_SQL_SYMB = {
+ 'mysql': {
+ 'br_l': '`',
+ 'br_r': '`',
+ 'wld': '%s'
+ },
+ 'sqlite': {
+ 'br_l': '[',
+ 'br_r': ']',
+ 'wld': '?'
+ }
+}
+
+
+class PandasSQLTableLegacy(PandasSQLTable):
+ """Patch the PandasSQLTable for legacy support.
+ Instead of a table variable just use the Create Table
+ statement"""
+ def sql_schema(self):
+ return str(self.table)
+
+ def create(self):
+ self.pd_sql.execute(self.table)
+
+ def insert_statement(self):
+ # Replace spaces in DataFrame column names with _.
+ safe_names = [_safe_col_name(n) for n in self.frame.dtypes.index]
+ flv = self.pd_sql.flavor
+ br_l = _SQL_SYMB[flv]['br_l'] # left val quote char
+ br_r = _SQL_SYMB[flv]['br_r'] # right val quote char
+ wld = _SQL_SYMB[flv]['wld'] # wildcard char
+
+ if self.index is not None:
+ safe_names.insert(0, self.index)
+
+ bracketed_names = [br_l + column + br_r for column in safe_names]
+ col_names = ','.join(bracketed_names)
+ wildcards = ','.join([wld] * len(safe_names))
+ insert_statement = 'INSERT INTO %s (%s) VALUES (%s)' % (
+ self.name, col_names, wildcards)
+ return insert_statement
+
+ def insert(self):
+ ins = self.insert_statement()
+ cur = self.pd_sql.con.cursor()
+ for r in self.frame.iterrows():
+ data = [self.maybe_asscalar(v) for v in r[1].values]
+ if self.index is not None:
+ data.insert(0, self.maybe_asscalar(r[0]))
+ print(type(data[2]))
+ print(type(r[0]))
+ cur.execute(ins, tuple(data))
cur.close()
- cur = con.cursor()
- # Replace spaces in DataFrame column names with _.
- safe_names = [s.replace(' ', '_').strip() for s in frame.columns]
- flavor_picker = {'sqlite': _write_sqlite,
- 'mysql': _write_mysql}
-
- func = flavor_picker.get(flavor, None)
- if func is None:
- raise NotImplementedError
- func(frame, name, safe_names, cur)
- cur.close()
- con.commit()
-
-
-def _write_sqlite(frame, table, names, cur):
- bracketed_names = ['[' + column + ']' for column in names]
- col_names = ','.join(bracketed_names)
- wildcards = ','.join(['?'] * len(names))
- insert_query = 'INSERT INTO %s (%s) VALUES (%s)' % (
- table, col_names, wildcards)
- # pandas types are badly handled if there is only 1 column ( Issue #3628 )
- if not len(frame.columns) == 1:
- data = [tuple(x) for x in frame.values]
- else:
- data = [tuple(x) for x in frame.values.tolist()]
- cur.executemany(insert_query, data)
-
-
-def _write_mysql(frame, table, names, cur):
- bracketed_names = ['`' + column + '`' for column in names]
- col_names = ','.join(bracketed_names)
- wildcards = ','.join([r'%s'] * len(names))
- insert_query = "INSERT INTO %s (%s) VALUES (%s)" % (
- table, col_names, wildcards)
- data = [tuple(x) for x in frame.values]
- cur.executemany(insert_query, data)
-
-
-def table_exists(name, con, flavor):
- flavor_map = {
- 'sqlite': ("SELECT name FROM sqlite_master "
- "WHERE type='table' AND name='%s';") % name,
- 'mysql': "SHOW TABLES LIKE '%s'" % name}
- query = flavor_map.get(flavor, None)
- if query is None:
- raise NotImplementedError
- return len(tquery(query, con)) > 0
-
-
-def get_sqltype(pytype, flavor):
- sqltype = {'mysql': 'VARCHAR (63)',
- 'sqlite': 'TEXT'}
-
- if issubclass(pytype, np.floating):
- sqltype['mysql'] = 'FLOAT'
- sqltype['sqlite'] = 'REAL'
-
- if issubclass(pytype, np.integer):
- #TODO: Refine integer size.
- sqltype['mysql'] = 'BIGINT'
- sqltype['sqlite'] = 'INTEGER'
-
- if issubclass(pytype, np.datetime64) or pytype is datetime:
- # Caution: np.datetime64 is also a subclass of np.number.
- sqltype['mysql'] = 'DATETIME'
- sqltype['sqlite'] = 'TIMESTAMP'
-
- if pytype is datetime.date:
- sqltype['mysql'] = 'DATE'
- sqltype['sqlite'] = 'TIMESTAMP'
-
- if issubclass(pytype, np.bool_):
- sqltype['sqlite'] = 'INTEGER'
-
- return sqltype[flavor]
-
-
-def get_schema(frame, name, flavor, keys=None):
- "Return a CREATE TABLE statement to suit the contents of a DataFrame."
- lookup_type = lambda dtype: get_sqltype(dtype.type, flavor)
- # Replace spaces in DataFrame column names with _.
- safe_columns = [s.replace(' ', '_').strip() for s in frame.dtypes.index]
- column_types = lzip(safe_columns, map(lookup_type, frame.dtypes))
- if flavor == 'sqlite':
- columns = ',\n '.join('[%s] %s' % x for x in column_types)
- else:
- columns = ',\n '.join('`%s` %s' % x for x in column_types)
-
- keystr = ''
- if keys is not None:
- if isinstance(keys, compat.string_types):
- keys = (keys,)
- keystr = ', PRIMARY KEY (%s)' % ','.join(keys)
- template = """CREATE TABLE %(name)s (
- %(columns)s
- %(keystr)s
- );"""
- create_statement = template % {'name': name, 'columns': columns,
- 'keystr': keystr}
- return create_statement
-
-
-def sequence2dict(seq):
- """Helper function for cx_Oracle.
-
- For each element in the sequence, creates a dictionary item equal
- to the element and keyed by the position of the item in the list.
- >>> sequence2dict(("Matt", 1))
- {'1': 'Matt', '2': 1}
-
- Source:
- http://www.gingerandjohn.com/archives/2004/02/26/cx_oracle-executemany-example/
+ def _create_table_statement(self):
+ "Return a CREATE TABLE statement to suit the contents of a DataFrame."
+
+ # Replace spaces in DataFrame column names with _.
+ safe_columns = [_safe_col_name(n) for n in self.frame.dtypes.index]
+ column_types = [self._sql_type_name(typ) for typ in self.frame.dtypes]
+
+ if self.index is not None:
+ safe_columns.insert(0, self.index)
+ column_types.insert(0, self._sql_type_name(self.frame.index.dtype))
+ flv = self.pd_sql.flavor
+
+ br_l = _SQL_SYMB[flv]['br_l'] # left val quote char
+ br_r = _SQL_SYMB[flv]['br_r'] # right val quote char
+
+ col_template = br_l + '%s' + br_r + ' %s'
+
+ columns = ',\n '.join(col_template %
+ x for x in zip(safe_columns, column_types))
+ template = """CREATE TABLE %(name)s (
+ %(columns)s
+ );"""
+ create_statement = template % {'name': self.name, 'columns': columns}
+ return create_statement
+
+ def _sql_type_name(self, dtype):
+ pytype = dtype.type
+ pytype_name = "text"
+ if issubclass(pytype, np.floating):
+ pytype_name = "float"
+ elif issubclass(pytype, np.integer):
+ pytype_name = "int"
+ elif issubclass(pytype, np.datetime64) or pytype is datetime:
+ # Caution: np.datetime64 is also a subclass of np.number.
+ pytype_name = "datetime"
+ elif pytype is datetime.date:
+ pytype_name = "date"
+ elif issubclass(pytype, np.bool_):
+ pytype_name = "bool"
+
+ return _SQL_TYPES[pytype_name][self.pd_sql.flavor]
+
+
+class PandasSQLLegacy(PandasSQL):
+
+ def __init__(self, con, flavor):
+ self.con = con
+ if flavor not in ['sqlite', 'mysql']:
+ raise NotImplementedError
+ else:
+ self.flavor = flavor
+
+ def execute(self, *args, **kwargs):
+ try:
+ cur = self.con.cursor()
+ if kwargs:
+ cur.execute(*args, **kwargs)
+ else:
+ cur.execute(*args)
+ return cur
+ except Exception as e:
+ try:
+ self.con.rollback()
+ except Exception: # pragma: no cover
+ ex = DatabaseError(
+ "Execution failed on sql: %s\n%s\nunable to rollback" % (args[0], e))
+ raise_with_traceback(ex)
+
+ ex = DatabaseError("Execution failed on sql: %s" % args[0])
+ raise_with_traceback(ex)
+
+ def tquery(self, *args):
+ cur = self.execute(*args)
+ result = self._fetchall_as_list(cur)
+
+ # This makes into tuples
+ if result and len(result[0]) == 1:
+ # python 3 compat
+ result = list(lzip(*result)[0])
+ elif result is None: # pragma: no cover
+ result = []
+ return result
+
+ def uquery(self, *args):
+ cur = self.execute(*args)
+ return cur.rowcount
+
+ def read_sql(self, sql, index_col=None, coerce_float=True, params=None,
+ parse_dates=None):
+ args = _convert_params(sql, params)
+ cursor = self.execute(*args)
+ columns = [col_desc[0] for col_desc in cursor.description]
+ data = self._fetchall_as_list(cursor)
+ cursor.close()
+
+ data_frame = DataFrame.from_records(
+ data, columns=columns, coerce_float=coerce_float)
+
+ _parse_date_columns(data_frame, parse_dates)
+
+ if index_col is not None:
+ data_frame.set_index(index_col, inplace=True)
+ return data_frame
+
+ def _fetchall_as_list(self, cur):
+ result = cur.fetchall()
+ if not isinstance(result, list):
+ result = list(result)
+ return result
+
+ def to_sql(self, frame, name, if_exists='fail', index=True):
+ """
+ Write records stored in a DataFrame to a SQL database.
+
+ Parameters
+ ----------
+ frame: DataFrame
+ name: name of SQL table
+ flavor: {'sqlite', 'mysql', 'postgres'}, default 'sqlite'
+ if_exists: {'fail', 'replace', 'append'}, default 'fail'
+ fail: If table exists, do nothing.
+ replace: If table exists, drop it, recreate it, and insert data.
+ append: If table exists, insert data. Create if does not exist.
+ """
+ table = PandasSQLTableLegacy(
+ name, self, frame=frame, index=index, if_exists=if_exists)
+ table.insert()
+
+ def has_table(self, name):
+ flavor_map = {
+ 'sqlite': ("SELECT name FROM sqlite_master "
+ "WHERE type='table' AND name='%s';") % name,
+ 'mysql': "SHOW TABLES LIKE '%s'" % name}
+ query = flavor_map.get(self.flavor)
+
+ return len(self.tquery(query)) > 0
+
+ def get_table(self, table_name):
+ return None # not supported in Legacy mode
+
+ def drop_table(self, name):
+ drop_sql = "DROP TABLE %s" % name
+ self.execute(drop_sql)
+
+
+# legacy names, with depreciation warnings and copied docs
+def get_schema(frame, name, con, flavor='sqlite'):
+ """
+ Get the SQL db table schema for the given frame
+
+ Parameters
+ ----------
+ frame: DataFrame
+ name: name of SQL table
+ con: an open SQL database connection object
+ engine: an SQLAlchemy engine - replaces connection and flavor
+ flavor: {'sqlite', 'mysql', 'postgres'}, default 'sqlite'
+
+ """
+ warnings.warn(
+ "get_schema is depreciated", DeprecationWarning)
+ pandas_sql = pandasSQL_builder(con=con, flavor=flavor)
+ return pandas_sql._create_sql_schema(frame, name)
+
+
+def read_frame(*args, **kwargs):
+ """DEPRECIATED - use read_sql
"""
- d = {}
- for k, v in zip(range(1, 1 + len(seq)), seq):
- d[str(k)] = v
- return d
+ warnings.warn(
+ "read_frame is depreciated, use read_sql", DeprecationWarning)
+ return read_sql(*args, **kwargs)
+
+
+def write_frame(*args, **kwargs):
+ """DEPRECIATED - use to_sql
+ """
+ warnings.warn("write_frame is depreciated, use to_sql", DeprecationWarning)
+ return to_sql(*args, **kwargs)
+
+
+# Append wrapped function docstrings
+read_frame.__doc__ += read_sql.__doc__
+write_frame.__doc__ += to_sql.__doc__
diff --git a/pandas/io/tests/data/iris.csv b/pandas/io/tests/data/iris.csv
new file mode 100644
index 0000000000000..c19b9c3688515
--- /dev/null
+++ b/pandas/io/tests/data/iris.csv
@@ -0,0 +1,151 @@
+SepalLength,SepalWidth,PetalLength,PetalWidth,Name
+5.1,3.5,1.4,0.2,Iris-setosa
+4.9,3.0,1.4,0.2,Iris-setosa
+4.7,3.2,1.3,0.2,Iris-setosa
+4.6,3.1,1.5,0.2,Iris-setosa
+5.0,3.6,1.4,0.2,Iris-setosa
+5.4,3.9,1.7,0.4,Iris-setosa
+4.6,3.4,1.4,0.3,Iris-setosa
+5.0,3.4,1.5,0.2,Iris-setosa
+4.4,2.9,1.4,0.2,Iris-setosa
+4.9,3.1,1.5,0.1,Iris-setosa
+5.4,3.7,1.5,0.2,Iris-setosa
+4.8,3.4,1.6,0.2,Iris-setosa
+4.8,3.0,1.4,0.1,Iris-setosa
+4.3,3.0,1.1,0.1,Iris-setosa
+5.8,4.0,1.2,0.2,Iris-setosa
+5.7,4.4,1.5,0.4,Iris-setosa
+5.4,3.9,1.3,0.4,Iris-setosa
+5.1,3.5,1.4,0.3,Iris-setosa
+5.7,3.8,1.7,0.3,Iris-setosa
+5.1,3.8,1.5,0.3,Iris-setosa
+5.4,3.4,1.7,0.2,Iris-setosa
+5.1,3.7,1.5,0.4,Iris-setosa
+4.6,3.6,1.0,0.2,Iris-setosa
+5.1,3.3,1.7,0.5,Iris-setosa
+4.8,3.4,1.9,0.2,Iris-setosa
+5.0,3.0,1.6,0.2,Iris-setosa
+5.0,3.4,1.6,0.4,Iris-setosa
+5.2,3.5,1.5,0.2,Iris-setosa
+5.2,3.4,1.4,0.2,Iris-setosa
+4.7,3.2,1.6,0.2,Iris-setosa
+4.8,3.1,1.6,0.2,Iris-setosa
+5.4,3.4,1.5,0.4,Iris-setosa
+5.2,4.1,1.5,0.1,Iris-setosa
+5.5,4.2,1.4,0.2,Iris-setosa
+4.9,3.1,1.5,0.1,Iris-setosa
+5.0,3.2,1.2,0.2,Iris-setosa
+5.5,3.5,1.3,0.2,Iris-setosa
+4.9,3.1,1.5,0.1,Iris-setosa
+4.4,3.0,1.3,0.2,Iris-setosa
+5.1,3.4,1.5,0.2,Iris-setosa
+5.0,3.5,1.3,0.3,Iris-setosa
+4.5,2.3,1.3,0.3,Iris-setosa
+4.4,3.2,1.3,0.2,Iris-setosa
+5.0,3.5,1.6,0.6,Iris-setosa
+5.1,3.8,1.9,0.4,Iris-setosa
+4.8,3.0,1.4,0.3,Iris-setosa
+5.1,3.8,1.6,0.2,Iris-setosa
+4.6,3.2,1.4,0.2,Iris-setosa
+5.3,3.7,1.5,0.2,Iris-setosa
+5.0,3.3,1.4,0.2,Iris-setosa
+7.0,3.2,4.7,1.4,Iris-versicolor
+6.4,3.2,4.5,1.5,Iris-versicolor
+6.9,3.1,4.9,1.5,Iris-versicolor
+5.5,2.3,4.0,1.3,Iris-versicolor
+6.5,2.8,4.6,1.5,Iris-versicolor
+5.7,2.8,4.5,1.3,Iris-versicolor
+6.3,3.3,4.7,1.6,Iris-versicolor
+4.9,2.4,3.3,1.0,Iris-versicolor
+6.6,2.9,4.6,1.3,Iris-versicolor
+5.2,2.7,3.9,1.4,Iris-versicolor
+5.0,2.0,3.5,1.0,Iris-versicolor
+5.9,3.0,4.2,1.5,Iris-versicolor
+6.0,2.2,4.0,1.0,Iris-versicolor
+6.1,2.9,4.7,1.4,Iris-versicolor
+5.6,2.9,3.6,1.3,Iris-versicolor
+6.7,3.1,4.4,1.4,Iris-versicolor
+5.6,3.0,4.5,1.5,Iris-versicolor
+5.8,2.7,4.1,1.0,Iris-versicolor
+6.2,2.2,4.5,1.5,Iris-versicolor
+5.6,2.5,3.9,1.1,Iris-versicolor
+5.9,3.2,4.8,1.8,Iris-versicolor
+6.1,2.8,4.0,1.3,Iris-versicolor
+6.3,2.5,4.9,1.5,Iris-versicolor
+6.1,2.8,4.7,1.2,Iris-versicolor
+6.4,2.9,4.3,1.3,Iris-versicolor
+6.6,3.0,4.4,1.4,Iris-versicolor
+6.8,2.8,4.8,1.4,Iris-versicolor
+6.7,3.0,5.0,1.7,Iris-versicolor
+6.0,2.9,4.5,1.5,Iris-versicolor
+5.7,2.6,3.5,1.0,Iris-versicolor
+5.5,2.4,3.8,1.1,Iris-versicolor
+5.5,2.4,3.7,1.0,Iris-versicolor
+5.8,2.7,3.9,1.2,Iris-versicolor
+6.0,2.7,5.1,1.6,Iris-versicolor
+5.4,3.0,4.5,1.5,Iris-versicolor
+6.0,3.4,4.5,1.6,Iris-versicolor
+6.7,3.1,4.7,1.5,Iris-versicolor
+6.3,2.3,4.4,1.3,Iris-versicolor
+5.6,3.0,4.1,1.3,Iris-versicolor
+5.5,2.5,4.0,1.3,Iris-versicolor
+5.5,2.6,4.4,1.2,Iris-versicolor
+6.1,3.0,4.6,1.4,Iris-versicolor
+5.8,2.6,4.0,1.2,Iris-versicolor
+5.0,2.3,3.3,1.0,Iris-versicolor
+5.6,2.7,4.2,1.3,Iris-versicolor
+5.7,3.0,4.2,1.2,Iris-versicolor
+5.7,2.9,4.2,1.3,Iris-versicolor
+6.2,2.9,4.3,1.3,Iris-versicolor
+5.1,2.5,3.0,1.1,Iris-versicolor
+5.7,2.8,4.1,1.3,Iris-versicolor
+6.3,3.3,6.0,2.5,Iris-virginica
+5.8,2.7,5.1,1.9,Iris-virginica
+7.1,3.0,5.9,2.1,Iris-virginica
+6.3,2.9,5.6,1.8,Iris-virginica
+6.5,3.0,5.8,2.2,Iris-virginica
+7.6,3.0,6.6,2.1,Iris-virginica
+4.9,2.5,4.5,1.7,Iris-virginica
+7.3,2.9,6.3,1.8,Iris-virginica
+6.7,2.5,5.8,1.8,Iris-virginica
+7.2,3.6,6.1,2.5,Iris-virginica
+6.5,3.2,5.1,2.0,Iris-virginica
+6.4,2.7,5.3,1.9,Iris-virginica
+6.8,3.0,5.5,2.1,Iris-virginica
+5.7,2.5,5.0,2.0,Iris-virginica
+5.8,2.8,5.1,2.4,Iris-virginica
+6.4,3.2,5.3,2.3,Iris-virginica
+6.5,3.0,5.5,1.8,Iris-virginica
+7.7,3.8,6.7,2.2,Iris-virginica
+7.7,2.6,6.9,2.3,Iris-virginica
+6.0,2.2,5.0,1.5,Iris-virginica
+6.9,3.2,5.7,2.3,Iris-virginica
+5.6,2.8,4.9,2.0,Iris-virginica
+7.7,2.8,6.7,2.0,Iris-virginica
+6.3,2.7,4.9,1.8,Iris-virginica
+6.7,3.3,5.7,2.1,Iris-virginica
+7.2,3.2,6.0,1.8,Iris-virginica
+6.2,2.8,4.8,1.8,Iris-virginica
+6.1,3.0,4.9,1.8,Iris-virginica
+6.4,2.8,5.6,2.1,Iris-virginica
+7.2,3.0,5.8,1.6,Iris-virginica
+7.4,2.8,6.1,1.9,Iris-virginica
+7.9,3.8,6.4,2.0,Iris-virginica
+6.4,2.8,5.6,2.2,Iris-virginica
+6.3,2.8,5.1,1.5,Iris-virginica
+6.1,2.6,5.6,1.4,Iris-virginica
+7.7,3.0,6.1,2.3,Iris-virginica
+6.3,3.4,5.6,2.4,Iris-virginica
+6.4,3.1,5.5,1.8,Iris-virginica
+6.0,3.0,4.8,1.8,Iris-virginica
+6.9,3.1,5.4,2.1,Iris-virginica
+6.7,3.1,5.6,2.4,Iris-virginica
+6.9,3.1,5.1,2.3,Iris-virginica
+5.8,2.7,5.1,1.9,Iris-virginica
+6.8,3.2,5.9,2.3,Iris-virginica
+6.7,3.3,5.7,2.5,Iris-virginica
+6.7,3.0,5.2,2.3,Iris-virginica
+6.3,2.5,5.0,1.9,Iris-virginica
+6.5,3.0,5.2,2.0,Iris-virginica
+6.2,3.4,5.4,2.3,Iris-virginica
+5.9,3.0,5.1,1.8,Iris-virginica
\ No newline at end of file
diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py
index ef9917c9a02f7..c11d64302d955 100644
--- a/pandas/io/tests/test_sql.py
+++ b/pandas/io/tests/test_sql.py
@@ -1,608 +1,701 @@
from __future__ import print_function
+import unittest
import sqlite3
-import sys
-
-import warnings
+import csv
+import os
import nose
-
import numpy as np
-from pandas.core.datetools import format as date_format
-from pandas.core.api import DataFrame, isnull
-from pandas.compat import StringIO, range, lrange
-import pandas.compat as compat
+from pandas import DataFrame
+from pandas.compat import range, lrange, iteritems
+#from pandas.core.datetools import format as date_format
import pandas.io.sql as sql
import pandas.util.testing as tm
-from pandas import Series, Index, DataFrame
-from datetime import datetime
-
-_formatters = {
- datetime: lambda dt: "'%s'" % date_format(dt),
- str: lambda x: "'%s'" % x,
- np.str_: lambda x: "'%s'" % x,
- compat.text_type: lambda x: "'%s'" % x,
- compat.binary_type: lambda x: "'%s'" % x,
- float: lambda x: "%.8f" % x,
- int: lambda x: "%s" % x,
- type(None): lambda x: "NULL",
- np.float64: lambda x: "%.10f" % x,
- bool: lambda x: "'%s'" % x,
+
+
+try:
+ import sqlalchemy
+ SQLALCHEMY_INSTALLED = True
+except ImportError:
+ SQLALCHEMY_INSTALLED = False
+
+SQL_STRINGS = {
+ 'create_iris': {
+ 'sqlite': """CREATE TABLE iris (
+ `SepalLength` REAL,
+ `SepalWidth` REAL,
+ `PetalLength` REAL,
+ `PetalWidth` REAL,
+ `Name` TEXT
+ )""",
+ 'mysql': """CREATE TABLE iris (
+ `SepalLength` DOUBLE,
+ `SepalWidth` DOUBLE,
+ `PetalLength` DOUBLE,
+ `PetalWidth` DOUBLE,
+ `Name` VARCHAR(200)
+ )"""
+ },
+ 'insert_iris': {
+ 'sqlite': """INSERT INTO iris VALUES(?, ?, ?, ?, ?)""",
+ 'mysql': """INSERT INTO iris VALUES(%s, %s, %s, %s, "%s");"""
+ },
+ 'create_test_types': {
+ 'sqlite': """CREATE TABLE types_test_data (
+ `TextCol` TEXT,
+ `DateCol` TEXT,
+ `IntDateCol` INTEGER,
+ `FloatCol` REAL,
+ `IntCol` INTEGER,
+ `BoolCol` INTEGER,
+ `IntColWithNull` INTEGER,
+ `BoolColWithNull` INTEGER
+ )""",
+ 'mysql': """CREATE TABLE types_test_data (
+ `TextCol` TEXT,
+ `DateCol` DATETIME,
+ `IntDateCol` INTEGER,
+ `FloatCol` DOUBLE,
+ `IntCol` INTEGER,
+ `BoolCol` BOOLEAN,
+ `IntColWithNull` INTEGER,
+ `BoolColWithNull` BOOLEAN
+ )"""
+ },
+ 'insert_test_types': {
+ 'sqlite': """
+ INSERT INTO types_test_data
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ 'mysql': """
+ INSERT INTO types_test_data
+ VALUES("%s", %s, %s, %s, %s, %s, %s, %s)
+ """
+ }
}
-def format_query(sql, *args):
+
+class PandasSQLTest(unittest.TestCase):
+
+ """Base class with common private methods for
+ SQLAlchemy and fallback cases.
"""
+ def drop_table(self, table_name):
+ self._get_exec().execute("DROP TABLE IF EXISTS %s" % table_name)
+
+ def _get_exec(self):
+ if hasattr(self.conn, 'execute'):
+ return self.conn
+ else:
+ return self.conn.cursor()
+
+ def _load_iris_data(self):
+ iris_csv_file = os.path.join(tm.get_data_path(), 'iris.csv')
+
+ self.drop_table('iris')
+ self._get_exec().execute(SQL_STRINGS['create_iris'][self.flavor])
+
+ with open(iris_csv_file, 'rU') as iris_csv:
+ r = csv.reader(iris_csv)
+ next(r) # skip header row
+ ins = SQL_STRINGS['insert_iris'][self.flavor]
+
+ for row in r:
+ self._get_exec().execute(ins, row)
+
+ def _check_iris_loaded_frame(self, iris_frame):
+ pytype = iris_frame.dtypes[0].type
+ row = iris_frame.iloc[0]
+
+ self.assertTrue(
+ issubclass(pytype, np.floating), 'Loaded frame has incorrect type')
+ tm.equalContents(row.values, [5.1, 3.5, 1.4, 0.2, 'Iris-setosa'])
+
+ def _load_test1_data(self):
+ columns = ['index', 'A', 'B', 'C', 'D']
+ data = [(
+ '2000-01-03 00:00:00', 0.980268513777, 3.68573087906, -0.364216805298, -1.15973806169),
+ ('2000-01-04 00:00:00', 1.04791624281, -
+ 0.0412318367011, -0.16181208307, 0.212549316967),
+ ('2000-01-05 00:00:00', 0.498580885705,
+ 0.731167677815, -0.537677223318, 1.34627041952),
+ ('2000-01-06 00:00:00', 1.12020151869, 1.56762092543, 0.00364077397681, 0.67525259227)]
+
+ self.test_frame1 = DataFrame(data, columns=columns)
+
+ def _load_raw_sql(self):
+ self.drop_table('types_test_data')
+ self._get_exec().execute(SQL_STRINGS['create_test_types'][self.flavor])
+ ins = SQL_STRINGS['insert_test_types'][self.flavor]
+
+ data = [(
+ 'first', '2000-01-03 00:00:00', 535852800, 10.10, 1, False, 1, False),
+ ('first', '2000-01-04 00:00:00', 1356998400, 10.10, 1, False, None, None)]
+ for d in data:
+ self._get_exec().execute(ins, d)
+
+ def _count_rows(self, table_name):
+ result = self._get_exec().execute(
+ "SELECT count(*) AS count_1 FROM %s" % table_name).fetchone()
+ return result[0]
+
+ def _read_sql_iris(self):
+ iris_frame = self.pandasSQL.read_sql("SELECT * FROM iris")
+ self._check_iris_loaded_frame(iris_frame)
+
+ def _to_sql(self):
+ self.drop_table('test_frame1')
+
+ self.pandasSQL.to_sql(self.test_frame1, 'test_frame1')
+ self.assertTrue(self.pandasSQL.has_table(
+ 'test_frame1'), 'Table not written to DB')
+
+ # Nuke table
+ self.drop_table('test_frame1')
+
+ def _to_sql_fail(self):
+ self.drop_table('test_frame1')
+
+ self.pandasSQL.to_sql(
+ self.test_frame1, 'test_frame1', if_exists='fail')
+ self.assertTrue(self.pandasSQL.has_table(
+ 'test_frame1'), 'Table not written to DB')
+
+ self.assertRaises(ValueError, self.pandasSQL.to_sql,
+ self.test_frame1, 'test_frame1', if_exists='fail')
+
+ self.drop_table('test_frame1')
+
+ def _to_sql_replace(self):
+ self.drop_table('test_frame1')
+
+ self.pandasSQL.to_sql(
+ self.test_frame1, 'test_frame1', if_exists='fail')
+ # Add to table again
+ self.pandasSQL.to_sql(
+ self.test_frame1, 'test_frame1', if_exists='replace')
+ self.assertTrue(self.pandasSQL.has_table(
+ 'test_frame1'), 'Table not written to DB')
+
+ num_entries = len(self.test_frame1)
+ num_rows = self._count_rows('test_frame1')
+
+ self.assertEqual(
+ num_rows, num_entries, "not the same number of rows as entries")
+
+ self.drop_table('test_frame1')
+
+ def _to_sql_append(self):
+ # Nuke table just in case
+ self.drop_table('test_frame1')
+
+ self.pandasSQL.to_sql(
+ self.test_frame1, 'test_frame1', if_exists='fail')
+
+ # Add to table again
+ self.pandasSQL.to_sql(
+ self.test_frame1, 'test_frame1', if_exists='append')
+ self.assertTrue(self.pandasSQL.has_table(
+ 'test_frame1'), 'Table not written to DB')
+
+ num_entries = 2 * len(self.test_frame1)
+ num_rows = self._count_rows('test_frame1')
+
+ self.assertEqual(
+ num_rows, num_entries, "not the same number of rows as entries")
+
+ self.drop_table('test_frame1')
+
+ def _roundtrip(self):
+ self.drop_table('test_frame_roundtrip')
+ self.pandasSQL.to_sql(self.test_frame1, 'test_frame_roundtrip')
+ result = self.pandasSQL.read_sql('SELECT * FROM test_frame_roundtrip')
+
+ result.set_index('pandas_index', inplace=True)
+ # result.index.astype(int)
+
+ result.index.name = None
+
+ tm.assert_frame_equal(result, self.test_frame1)
+
+ def _execute_sql(self):
+ # drop_sql = "DROP TABLE IF EXISTS test" # should already be done
+ iris_results = self.pandasSQL.execute("SELECT * FROM iris")
+ row = iris_results.fetchone()
+ tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, 'Iris-setosa'])
+
+ def _tquery(self):
+ iris_results = self.pandasSQL.tquery("SELECT * FROM iris")
+ row = iris_results[0]
+ tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, 'Iris-setosa'])
+
+
+class TestSQLApi(PandasSQLTest):
+
+ """Test the public API as it would be used
+ directly, including legacy names
+
+ Notes:
+ flavor can always be passed even in SQLAlchemy mode,
+ should be correctly ignored.
+
+ we don't use drop_table because that isn't part of the public api
+
"""
- processed_args = []
- for arg in args:
- if isinstance(arg, float) and isnull(arg):
- arg = None
+ flavor = 'sqlite'
- formatter = _formatters[type(arg)]
- processed_args.append(formatter(arg))
+ def connect(self):
+ if SQLALCHEMY_INSTALLED:
+ return sqlalchemy.create_engine('sqlite:///:memory:')
+ else:
+ return sqlite3.connect(':memory:')
- return sql % tuple(processed_args)
+ def setUp(self):
+ self.conn = self.connect()
+ self._load_iris_data()
+ self._load_test1_data()
+ self._load_raw_sql()
+
+ def test_read_sql_iris(self):
+ iris_frame = sql.read_sql(
+ "SELECT * FROM iris", self.conn, flavor='sqlite')
+ self._check_iris_loaded_frame(iris_frame)
+
+ def test_legacy_read_frame(self):
+ """Test legacy name read_frame"""
+ iris_frame = sql.read_frame(
+ "SELECT * FROM iris", self.conn, flavor='sqlite')
+ self._check_iris_loaded_frame(iris_frame)
+
+ def test_to_sql(self):
+ sql.to_sql(self.test_frame1, 'test_frame1', self.conn, flavor='sqlite')
+ self.assertTrue(
+ sql.has_table('test_frame1', self.conn, flavor='sqlite'), 'Table not written to DB')
+
+ def test_to_sql_fail(self):
+ sql.to_sql(self.test_frame1, 'test_frame2',
+ self.conn, flavor='sqlite', if_exists='fail')
+ self.assertTrue(
+ sql.has_table('test_frame2', self.conn, flavor='sqlite'), 'Table not written to DB')
+
+ self.assertRaises(ValueError, sql.to_sql, self.test_frame1,
+ 'test_frame2', self.conn, flavor='sqlite', if_exists='fail')
+
+ def test_to_sql_replace(self):
+ sql.to_sql(self.test_frame1, 'test_frame3',
+ self.conn, flavor='sqlite', if_exists='fail')
+ # Add to table again
+ sql.to_sql(self.test_frame1, 'test_frame3',
+ self.conn, flavor='sqlite', if_exists='replace')
+ self.assertTrue(
+ sql.has_table('test_frame3', self.conn, flavor='sqlite'), 'Table not written to DB')
+
+ num_entries = len(self.test_frame1)
+ num_rows = self._count_rows('test_frame3')
+
+ self.assertEqual(
+ num_rows, num_entries, "not the same number of rows as entries")
+
+ def test_to_sql_append(self):
+ sql.to_sql(self.test_frame1, 'test_frame4',
+ self.conn, flavor='sqlite', if_exists='fail')
+
+ # Add to table again
+ sql.to_sql(self.test_frame1, 'test_frame4',
+ self.conn, flavor='sqlite', if_exists='append')
+ self.assertTrue(
+ sql.has_table('test_frame4', self.conn, flavor='sqlite'), 'Table not written to DB')
+
+ num_entries = 2 * len(self.test_frame1)
+ num_rows = self._count_rows('test_frame4')
+
+ self.assertEqual(
+ num_rows, num_entries, "not the same number of rows as entries")
+
+ def test_legacy_write_frame(self):
+ """Test legacy write frame name.
+ Assume that functionality is already tested above so just do quick check that it basically works"""
+ sql.write_frame(
+ self.test_frame1, 'test_frame_legacy', self.conn, flavor='sqlite')
+ self.assertTrue(
+ sql.has_table('test_frame_legacy', self.conn, flavor='sqlite'), 'Table not written to DB')
+
+ def test_roundtrip(self):
+ sql.to_sql(self.test_frame1, 'test_frame_roundtrip',
+ con=self.conn, flavor='sqlite')
+ result = sql.read_sql(
+ 'SELECT * FROM test_frame_roundtrip',
+ con=self.conn,
+ flavor='sqlite')
+
+ # HACK!
+ result.index = self.test_frame1.index
+ result.set_index('pandas_index', inplace=True)
+ result.index.astype(int)
+ result.index.name = None
+ tm.assert_frame_equal(result, self.test_frame1)
+
+ def test_execute_sql(self):
+ # drop_sql = "DROP TABLE IF EXISTS test" # should already be done
+ iris_results = sql.execute(
+ "SELECT * FROM iris", con=self.conn, flavor='sqlite')
+ row = iris_results.fetchone()
+ tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, 'Iris-setosa'])
+
+ def test_tquery(self):
+ iris_results = sql.tquery(
+ "SELECT * FROM iris", con=self.conn, flavor='sqlite')
+ row = iris_results[0]
+ tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, 'Iris-setosa'])
+
+ def test_date_parsing(self):
+ """ Test date parsing in read_sql """
+ # No Parsing
+ df = sql.read_sql(
+ "SELECT * FROM types_test_data", self.conn, flavor='sqlite')
+ self.assertFalse(
+ issubclass(df.DateCol.dtype.type, np.datetime64),
+ "DateCol loaded with incorrect type")
+
+ df = sql.read_sql("SELECT * FROM types_test_data",
+ self.conn, flavor='sqlite', parse_dates=['DateCol'])
+ self.assertTrue(
+ issubclass(df.DateCol.dtype.type, np.datetime64),
+ "DateCol loaded with incorrect type")
+
+ df = sql.read_sql("SELECT * FROM types_test_data", self.conn,
+ flavor='sqlite',
+ parse_dates={'DateCol': '%Y-%m-%d %H:%M:%S'})
+ self.assertTrue(
+ issubclass(df.DateCol.dtype.type, np.datetime64),
+ "DateCol loaded with incorrect type")
+
+ df = sql.read_sql("SELECT * FROM types_test_data",
+ self.conn, flavor='sqlite',
+ parse_dates=['IntDateCol'])
+
+ self.assertTrue(issubclass(df.IntDateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
+
+ df = sql.read_sql("SELECT * FROM types_test_data",
+ self.conn, flavor='sqlite',
+ parse_dates={'IntDateCol': 's'})
+
+ self.assertTrue(issubclass(df.IntDateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
+
+ def test_date_and_index(self):
+ """ Test case where same column appears in parse_date and index_col"""
+
+ df = sql.read_sql("SELECT * FROM types_test_data",
+ self.conn, flavor='sqlite',
+ parse_dates=['DateCol', 'IntDateCol'],
+ index_col='DateCol')
+ self.assertTrue(
+ issubclass(df.index.dtype.type, np.datetime64),
+ "DateCol loaded with incorrect type")
+
+ self.assertTrue(
+ issubclass(df.IntDateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
-def _skip_if_no_MySQLdb():
- try:
- import MySQLdb
- except ImportError:
- raise nose.SkipTest('MySQLdb not installed, skipping')
-class TestSQLite(tm.TestCase):
+class TestSQLAlchemy(PandasSQLTest):
+
+ '''
+ Test the sqlalchemy backend against an in-memory sqlite database.
+ Assume that sqlalchemy takes case of the DB specifics
+ '''
+ flavor = 'sqlite'
+
+ def connect(self):
+ return sqlalchemy.create_engine('sqlite:///:memory:')
def setUp(self):
- self.db = sqlite3.connect(':memory:')
-
- def test_basic(self):
- frame = tm.makeTimeDataFrame()
- self._check_roundtrip(frame)
-
- def test_write_row_by_row(self):
- frame = tm.makeTimeDataFrame()
- frame.ix[0, 0] = np.nan
- create_sql = sql.get_schema(frame, 'test', 'sqlite')
- cur = self.db.cursor()
- cur.execute(create_sql)
-
- cur = self.db.cursor()
-
- ins = "INSERT INTO test VALUES (%s, %s, %s, %s)"
- for idx, row in frame.iterrows():
- fmt_sql = format_query(ins, *row)
- sql.tquery(fmt_sql, cur=cur)
-
- self.db.commit()
-
- result = sql.read_frame("select * from test", con=self.db)
- result.index = frame.index
- tm.assert_frame_equal(result, frame)
-
- def test_execute(self):
- frame = tm.makeTimeDataFrame()
- create_sql = sql.get_schema(frame, 'test', 'sqlite')
- cur = self.db.cursor()
- cur.execute(create_sql)
- ins = "INSERT INTO test VALUES (?, ?, ?, ?)"
-
- row = frame.ix[0]
- sql.execute(ins, self.db, params=tuple(row))
- self.db.commit()
-
- result = sql.read_frame("select * from test", self.db)
- result.index = frame.index[:1]
- tm.assert_frame_equal(result, frame[:1])
-
- def test_schema(self):
- frame = tm.makeTimeDataFrame()
- create_sql = sql.get_schema(frame, 'test', 'sqlite')
- lines = create_sql.splitlines()
- for l in lines:
- tokens = l.split(' ')
- if len(tokens) == 2 and tokens[0] == 'A':
- self.assert_(tokens[1] == 'DATETIME')
-
- frame = tm.makeTimeDataFrame()
- create_sql = sql.get_schema(frame, 'test', 'sqlite', keys=['A', 'B'],)
- lines = create_sql.splitlines()
- self.assert_('PRIMARY KEY (A,B)' in create_sql)
- cur = self.db.cursor()
- cur.execute(create_sql)
-
- def test_execute_fail(self):
- create_sql = """
- CREATE TABLE test
- (
- a TEXT,
- b TEXT,
- c REAL,
- PRIMARY KEY (a, b)
- );
- """
- cur = self.db.cursor()
- cur.execute(create_sql)
-
- sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.db)
- sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)', self.db)
+ # Skip this test if SQLAlchemy not available
+ if not SQLALCHEMY_INSTALLED:
+ raise nose.SkipTest('SQLAlchemy not installed')
- try:
- sys.stdout = StringIO()
- self.assertRaises(Exception, sql.execute,
- 'INSERT INTO test VALUES("foo", "bar", 7)',
- self.db)
- finally:
- sys.stdout = sys.__stdout__
-
- def test_execute_closed_connection(self):
- create_sql = """
- CREATE TABLE test
- (
- a TEXT,
- b TEXT,
- c REAL,
- PRIMARY KEY (a, b)
- );
- """
- cur = self.db.cursor()
- cur.execute(create_sql)
-
- sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.db)
- self.db.close()
- try:
- sys.stdout = StringIO()
- self.assertRaises(Exception, sql.tquery, "select * from test",
- con=self.db)
- finally:
- sys.stdout = sys.__stdout__
-
- def test_na_roundtrip(self):
- pass
-
- def _check_roundtrip(self, frame):
- sql.write_frame(frame, name='test_table', con=self.db)
- result = sql.read_frame("select * from test_table", self.db)
-
- # HACK! Change this once indexes are handled properly.
- result.index = frame.index
-
- expected = frame
- tm.assert_frame_equal(result, expected)
-
- frame['txt'] = ['a'] * len(frame)
- frame2 = frame.copy()
- frame2['Idx'] = Index(lrange(len(frame2))) + 10
- sql.write_frame(frame2, name='test_table2', con=self.db)
- result = sql.read_frame("select * from test_table2", self.db,
- index_col='Idx')
- expected = frame.copy()
- expected.index = Index(lrange(len(frame2))) + 10
- expected.index.name = 'Idx'
- print(expected.index.names)
- print(result.index.names)
- tm.assert_frame_equal(expected, result)
+ self.conn = self.connect()
+ self.pandasSQL = sql.PandasSQLAlchemy(self.conn)
- def test_tquery(self):
- frame = tm.makeTimeDataFrame()
- sql.write_frame(frame, name='test_table', con=self.db)
- result = sql.tquery("select A from test_table", self.db)
- expected = frame.A
- result = Series(result, frame.index)
- tm.assert_series_equal(result, expected)
+ self._load_iris_data()
+ self._load_raw_sql()
- try:
- sys.stdout = StringIO()
- self.assertRaises(sqlite3.OperationalError, sql.tquery,
- 'select * from blah', con=self.db)
+ self._load_test1_data()
- self.assertRaises(sqlite3.OperationalError, sql.tquery,
- 'select * from blah', con=self.db, retry=True)
- finally:
- sys.stdout = sys.__stdout__
+ def test_read_sql(self):
+ self._read_sql_iris()
- def test_uquery(self):
- frame = tm.makeTimeDataFrame()
- sql.write_frame(frame, name='test_table', con=self.db)
- stmt = 'INSERT INTO test_table VALUES(2.314, -123.1, 1.234, 2.3)'
- self.assertEqual(sql.uquery(stmt, con=self.db), 1)
+ def test_to_sql(self):
+ self._to_sql()
- try:
- sys.stdout = StringIO()
-
- self.assertRaises(sqlite3.OperationalError, sql.tquery,
- 'insert into blah values (1)', con=self.db)
-
- self.assertRaises(sqlite3.OperationalError, sql.tquery,
- 'insert into blah values (1)', con=self.db,
- retry=True)
- finally:
- sys.stdout = sys.__stdout__
-
- def test_keyword_as_column_names(self):
- '''
- '''
- df = DataFrame({'From':np.ones(5)})
- sql.write_frame(df, con = self.db, name = 'testkeywords')
-
- def test_onecolumn_of_integer(self):
- # GH 3628
- # a column_of_integers dataframe should transfer well to sql
-
- mono_df=DataFrame([1 , 2], columns=['c0'])
- sql.write_frame(mono_df, con = self.db, name = 'mono_df')
- # computing the sum via sql
- con_x=self.db
- the_sum=sum([my_c0[0] for my_c0 in con_x.execute("select * from mono_df")])
- # it should not fail, and gives 3 ( Issue #3628 )
- self.assertEqual(the_sum , 3)
-
- result = sql.read_frame("select * from mono_df",con_x)
- tm.assert_frame_equal(result,mono_df)
-
- def test_if_exists(self):
- df_if_exists_1 = DataFrame({'col1': [1, 2], 'col2': ['A', 'B']})
- df_if_exists_2 = DataFrame({'col1': [3, 4, 5], 'col2': ['C', 'D', 'E']})
- table_name = 'table_if_exists'
- sql_select = "SELECT * FROM %s" % table_name
-
- def clean_up(test_table_to_drop):
- """
- Drops tables created from individual tests
- so no dependencies arise from sequential tests
- """
- if sql.table_exists(test_table_to_drop, self.db, flavor='sqlite'):
- cur = self.db.cursor()
- cur.execute("DROP TABLE %s" % test_table_to_drop)
- cur.close()
-
- # test if invalid value for if_exists raises appropriate error
- self.assertRaises(ValueError,
- sql.write_frame,
- frame=df_if_exists_1,
- con=self.db,
- name=table_name,
- flavor='sqlite',
- if_exists='notvalidvalue')
- clean_up(table_name)
-
- # test if_exists='fail'
- sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
- flavor='sqlite', if_exists='fail')
- self.assertRaises(ValueError,
- sql.write_frame,
- frame=df_if_exists_1,
- con=self.db,
- name=table_name,
- flavor='sqlite',
- if_exists='fail')
-
- # test if_exists='replace'
- sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
- flavor='sqlite', if_exists='replace')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(1, 'A'), (2, 'B')])
- sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name,
- flavor='sqlite', if_exists='replace')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(3, 'C'), (4, 'D'), (5, 'E')])
- clean_up(table_name)
-
- # test if_exists='append'
- sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
- flavor='sqlite', if_exists='fail')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(1, 'A'), (2, 'B')])
- sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name,
- flavor='sqlite', if_exists='append')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')])
- clean_up(table_name)
-
-
-class TestMySQL(tm.TestCase):
+ def test_to_sql_fail(self):
+ self._to_sql_fail()
+
+ def test_to_sql_replace(self):
+ self._to_sql_replace()
+
+ def test_to_sql_append(self):
+ self._to_sql_append()
+
+ def test_create_table(self):
+ temp_conn = self.connect()
+ temp_frame = DataFrame(
+ {'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]})
+
+ pandasSQL = sql.PandasSQLAlchemy(temp_conn)
+ pandasSQL.to_sql(temp_frame, 'temp_frame')
+
+ self.assertTrue(
+ temp_conn.has_table('temp_frame'), 'Table not written to DB')
+
+ def test_drop_table(self):
+ temp_conn = self.connect()
+
+ temp_frame = DataFrame(
+ {'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]})
+
+ pandasSQL = sql.PandasSQLAlchemy(temp_conn)
+ pandasSQL.to_sql(temp_frame, 'temp_frame')
+
+ self.assertTrue(
+ temp_conn.has_table('temp_frame'), 'Table not written to DB')
+
+ pandasSQL.drop_table('temp_frame')
+
+ self.assertFalse(
+ temp_conn.has_table('temp_frame'), 'Table not deleted from DB')
+
+ def test_roundtrip(self):
+ self._roundtrip()
+
+ def test_execute_sql(self):
+ self._execute_sql()
+
+ def test_read_table(self):
+ iris_frame = sql.read_table("iris", con=self.conn)
+ self._check_iris_loaded_frame(iris_frame)
+
+ def test_read_table_columns(self):
+ iris_frame = sql.read_table(
+ "iris", con=self.conn, columns=['SepalLength', 'SepalLength'])
+ tm.equalContents(
+ iris_frame.columns.values, ['SepalLength', 'SepalLength'])
+
+ def test_read_table_absent(self):
+ self.assertRaises(
+ ValueError, sql.read_table, "this_doesnt_exist", con=self.conn)
+
+ def test_default_type_convertion(self):
+ """ Test default type conversion"""
+ df = sql.read_table("types_test_data", self.conn)
+ self.assertTrue(
+ issubclass(df.FloatCol.dtype.type, np.floating), "FloatCol loaded with incorrect type")
+ self.assertTrue(
+ issubclass(df.IntCol.dtype.type, np.integer), "IntCol loaded with incorrect type")
+ self.assertTrue(
+ issubclass(df.BoolCol.dtype.type, np.integer), "BoolCol loaded with incorrect type")
+
+ # Int column with NA values stays as float
+ self.assertTrue(issubclass(df.IntColWithNull.dtype.type, np.floating),
+ "IntColWithNull loaded with incorrect type")
+ # Non-native Bool column with NA values stays as float
+ self.assertTrue(
+ issubclass(df.BoolColWithNull.dtype.type, np.floating), "BoolCol loaded with incorrect type")
+
+ def test_default_date_load(self):
+ df = sql.read_table("types_test_data", self.conn)
+
+ # IMPORTANT - sqlite has no native date type, so shouldn't parse, but
+ # MySQL SHOULD be converted.
+ self.assertFalse(
+ issubclass(df.DateCol.dtype.type, np.datetime64), "DateCol loaded with incorrect type")
+
+ def test_date_parsing(self):
+ """ Test date parsing """
+ # No Parsing
+ df = sql.read_table("types_test_data", self.conn)
+
+ df = sql.read_table(
+ "types_test_data", self.conn, parse_dates=['DateCol'])
+ self.assertTrue(
+ issubclass(df.DateCol.dtype.type, np.datetime64), "DateCol loaded with incorrect type")
+
+ df = sql.read_table(
+ "types_test_data", self.conn, parse_dates={'DateCol': '%Y-%m-%d %H:%M:%S'})
+ self.assertTrue(
+ issubclass(df.DateCol.dtype.type, np.datetime64), "DateCol loaded with incorrect type")
+
+ df = sql.read_table("types_test_data", self.conn, parse_dates={
+ 'DateCol': {'format': '%Y-%m-%d %H:%M:%S'}})
+ self.assertTrue(issubclass(df.DateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
+
+ df = sql.read_table(
+ "types_test_data", self.conn, parse_dates=['IntDateCol'])
+ self.assertTrue(issubclass(df.IntDateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
+
+ df = sql.read_table(
+ "types_test_data", self.conn, parse_dates={'IntDateCol': 's'})
+ self.assertTrue(issubclass(df.IntDateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
+
+ df = sql.read_table(
+ "types_test_data", self.conn, parse_dates={'IntDateCol': {'unit': 's'}})
+ self.assertTrue(issubclass(df.IntDateCol.dtype.type, np.datetime64),
+ "IntDateCol loaded with incorrect type")
+
+
+# --- Test SQLITE fallback
+class TestSQLite(PandasSQLTest):
+
+ '''
+ Test the sqlalchemy backend against an in-memory sqlite database.
+ Assume that sqlalchemy takes case of the DB specifics
+ '''
+ flavor = 'sqlite'
+
+ def connect(self):
+ return sqlite3.connect(':memory:')
+
+ def drop_table(self, table_name):
+ cur = self.conn.cursor()
+ cur.execute("DROP TABLE IF EXISTS %s" % table_name)
+ self.conn.commit()
def setUp(self):
- _skip_if_no_MySQLdb()
- import MySQLdb
- try:
- # Try Travis defaults.
- # No real user should allow root access with a blank password.
- self.db = MySQLdb.connect(host='localhost', user='root', passwd='',
- db='pandas_nosetest')
- except:
- pass
- else:
- return
- try:
- self.db = MySQLdb.connect(read_default_group='pandas')
- except MySQLdb.ProgrammingError as e:
- raise nose.SkipTest(
- "Create a group of connection parameters under the heading "
- "[pandas] in your system's mysql default file, "
- "typically located at ~/.my.cnf or /etc/.my.cnf. ")
- except MySQLdb.Error as e:
- raise nose.SkipTest(
- "Cannot connect to database. "
- "Create a group of connection parameters under the heading "
- "[pandas] in your system's mysql default file, "
- "typically located at ~/.my.cnf or /etc/.my.cnf. ")
-
- def test_basic(self):
- _skip_if_no_MySQLdb()
- frame = tm.makeTimeDataFrame()
- self._check_roundtrip(frame)
-
- def test_write_row_by_row(self):
- _skip_if_no_MySQLdb()
- frame = tm.makeTimeDataFrame()
- frame.ix[0, 0] = np.nan
- drop_sql = "DROP TABLE IF EXISTS test"
- create_sql = sql.get_schema(frame, 'test', 'mysql')
- cur = self.db.cursor()
- cur.execute(drop_sql)
- cur.execute(create_sql)
- ins = "INSERT INTO test VALUES (%s, %s, %s, %s)"
- for idx, row in frame.iterrows():
- fmt_sql = format_query(ins, *row)
- sql.tquery(fmt_sql, cur=cur)
-
- self.db.commit()
-
- result = sql.read_frame("select * from test", con=self.db)
- result.index = frame.index
- tm.assert_frame_equal(result, frame)
-
- def test_execute(self):
- _skip_if_no_MySQLdb()
- frame = tm.makeTimeDataFrame()
- drop_sql = "DROP TABLE IF EXISTS test"
- create_sql = sql.get_schema(frame, 'test', 'mysql')
- cur = self.db.cursor()
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", "Unknown table.*")
- cur.execute(drop_sql)
- cur.execute(create_sql)
- ins = "INSERT INTO test VALUES (%s, %s, %s, %s)"
-
- row = frame.ix[0]
- sql.execute(ins, self.db, params=tuple(row))
- self.db.commit()
-
- result = sql.read_frame("select * from test", self.db)
- result.index = frame.index[:1]
- tm.assert_frame_equal(result, frame[:1])
-
- def test_schema(self):
- _skip_if_no_MySQLdb()
- frame = tm.makeTimeDataFrame()
- create_sql = sql.get_schema(frame, 'test', 'mysql')
- lines = create_sql.splitlines()
- for l in lines:
- tokens = l.split(' ')
- if len(tokens) == 2 and tokens[0] == 'A':
- self.assert_(tokens[1] == 'DATETIME')
-
- frame = tm.makeTimeDataFrame()
- drop_sql = "DROP TABLE IF EXISTS test"
- create_sql = sql.get_schema(frame, 'test', 'mysql', keys=['A', 'B'],)
- lines = create_sql.splitlines()
- self.assert_('PRIMARY KEY (A,B)' in create_sql)
- cur = self.db.cursor()
- cur.execute(drop_sql)
- cur.execute(create_sql)
-
- def test_execute_fail(self):
- _skip_if_no_MySQLdb()
- drop_sql = "DROP TABLE IF EXISTS test"
- create_sql = """
- CREATE TABLE test
- (
- a TEXT,
- b TEXT,
- c REAL,
- PRIMARY KEY (a(5), b(5))
- );
- """
- cur = self.db.cursor()
- cur.execute(drop_sql)
- cur.execute(create_sql)
-
- sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.db)
- sql.execute('INSERT INTO test VALUES("foo", "baz", 2.567)', self.db)
+ self.conn = self.connect()
+ self.pandasSQL = sql.PandasSQLLegacy(self.conn, 'sqlite')
- try:
- sys.stdout = StringIO()
- self.assertRaises(Exception, sql.execute,
- 'INSERT INTO test VALUES("foo", "bar", 7)',
- self.db)
- finally:
- sys.stdout = sys.__stdout__
-
- def test_execute_closed_connection(self):
- _skip_if_no_MySQLdb()
- drop_sql = "DROP TABLE IF EXISTS test"
- create_sql = """
- CREATE TABLE test
- (
- a TEXT,
- b TEXT,
- c REAL,
- PRIMARY KEY (a(5), b(5))
- );
- """
- cur = self.db.cursor()
- cur.execute(drop_sql)
- cur.execute(create_sql)
-
- sql.execute('INSERT INTO test VALUES("foo", "bar", 1.234)', self.db)
- self.db.close()
- try:
- sys.stdout = StringIO()
- self.assertRaises(Exception, sql.tquery, "select * from test",
- con=self.db)
- finally:
- sys.stdout = sys.__stdout__
-
- def test_na_roundtrip(self):
- _skip_if_no_MySQLdb()
- pass
-
- def _check_roundtrip(self, frame):
- _skip_if_no_MySQLdb()
- drop_sql = "DROP TABLE IF EXISTS test_table"
- cur = self.db.cursor()
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", "Unknown table.*")
- cur.execute(drop_sql)
- sql.write_frame(frame, name='test_table', con=self.db, flavor='mysql')
- result = sql.read_frame("select * from test_table", self.db)
-
- # HACK! Change this once indexes are handled properly.
- result.index = frame.index
- result.index.name = frame.index.name
-
- expected = frame
- tm.assert_frame_equal(result, expected)
-
- frame['txt'] = ['a'] * len(frame)
- frame2 = frame.copy()
- index = Index(lrange(len(frame2))) + 10
- frame2['Idx'] = index
- drop_sql = "DROP TABLE IF EXISTS test_table2"
- cur = self.db.cursor()
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", "Unknown table.*")
- cur.execute(drop_sql)
- sql.write_frame(frame2, name='test_table2', con=self.db, flavor='mysql')
- result = sql.read_frame("select * from test_table2", self.db,
- index_col='Idx')
- expected = frame.copy()
-
- # HACK! Change this once indexes are handled properly.
- expected.index = index
- expected.index.names = result.index.names
- tm.assert_frame_equal(expected, result)
+ self._load_iris_data()
+
+ self._load_test1_data()
+
+ def test_invalid_flavor(self):
+ self.assertRaises(
+ NotImplementedError, sql.PandasSQLLegacy, self.conn, 'oracle')
+
+ def test_read_sql(self):
+ self._read_sql_iris()
+
+ def test_to_sql(self):
+ self._to_sql()
+
+ def test_to_sql_fail(self):
+ self._to_sql_fail()
+
+ def test_to_sql_replace(self):
+ self._to_sql_replace()
+
+ def test_to_sql_append(self):
+ self._to_sql_append()
+
+ def test_create_and_drop_table(self):
+ temp_frame = DataFrame(
+ {'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]})
+
+ self.pandasSQL.to_sql(temp_frame, 'drop_test_frame')
+
+ self.assertTrue(self.pandasSQL.has_table(
+ 'drop_test_frame'), 'Table not written to DB')
+
+ self.pandasSQL.drop_table('drop_test_frame')
+
+ self.assertFalse(self.pandasSQL.has_table(
+ 'drop_test_frame'), 'Table not deleted from DB')
+
+ def test_roundtrip(self):
+ self._roundtrip()
+
+ def test_execute_sql(self):
+ self._execute_sql()
def test_tquery(self):
- try:
- import MySQLdb
- except ImportError:
- raise nose.SkipTest("no MySQLdb")
- frame = tm.makeTimeDataFrame()
- drop_sql = "DROP TABLE IF EXISTS test_table"
- cur = self.db.cursor()
- cur.execute(drop_sql)
- sql.write_frame(frame, name='test_table', con=self.db, flavor='mysql')
- result = sql.tquery("select A from test_table", self.db)
- expected = frame.A
- result = Series(result, frame.index)
- tm.assert_series_equal(result, expected)
+ self._tquery()
- try:
- sys.stdout = StringIO()
- self.assertRaises(MySQLdb.ProgrammingError, sql.tquery,
- 'select * from blah', con=self.db)
- self.assertRaises(MySQLdb.ProgrammingError, sql.tquery,
- 'select * from blah', con=self.db, retry=True)
- finally:
- sys.stdout = sys.__stdout__
+class TestMySQL(TestSQLite):
+ flavor = 'mysql'
- def test_uquery(self):
+ def drop_table(self, table_name):
+ cur = self.conn.cursor()
+ cur.execute("DROP TABLE IF EXISTS %s" % table_name)
+ self.conn.commit()
+
+ def _count_rows(self, table_name):
+ cur = self._get_exec()
+ cur.execute(
+ "SELECT count(*) AS count_1 FROM %s" % table_name)
+ rows = cur.fetchall()
+ return rows[0][0]
+
+ def connect(self):
+ return self.driver.connect(host='127.0.0.1', user='root', passwd='', db='pandas_nosetest')
+
+ def setUp(self):
try:
- import MySQLdb
+ import pymysql
+ self.driver = pymysql
+
except ImportError:
- raise nose.SkipTest("no MySQLdb")
- frame = tm.makeTimeDataFrame()
- drop_sql = "DROP TABLE IF EXISTS test_table"
- cur = self.db.cursor()
- cur.execute(drop_sql)
- sql.write_frame(frame, name='test_table', con=self.db, flavor='mysql')
- stmt = 'INSERT INTO test_table VALUES(2.314, -123.1, 1.234, 2.3)'
- self.assertEqual(sql.uquery(stmt, con=self.db), 1)
+ raise nose.SkipTest
- try:
- sys.stdout = StringIO()
-
- self.assertRaises(MySQLdb.ProgrammingError, sql.tquery,
- 'insert into blah values (1)', con=self.db)
-
- self.assertRaises(MySQLdb.ProgrammingError, sql.tquery,
- 'insert into blah values (1)', con=self.db,
- retry=True)
- finally:
- sys.stdout = sys.__stdout__
-
- def test_keyword_as_column_names(self):
- '''
- '''
- _skip_if_no_MySQLdb()
- df = DataFrame({'From':np.ones(5)})
- sql.write_frame(df, con = self.db, name = 'testkeywords',
- if_exists='replace', flavor='mysql')
-
- def test_if_exists(self):
- _skip_if_no_MySQLdb()
- df_if_exists_1 = DataFrame({'col1': [1, 2], 'col2': ['A', 'B']})
- df_if_exists_2 = DataFrame({'col1': [3, 4, 5], 'col2': ['C', 'D', 'E']})
- table_name = 'table_if_exists'
- sql_select = "SELECT * FROM %s" % table_name
-
- def clean_up(test_table_to_drop):
- """
- Drops tables created from individual tests
- so no dependencies arise from sequential tests
- """
- if sql.table_exists(test_table_to_drop, self.db, flavor='mysql'):
- cur = self.db.cursor()
- cur.execute("DROP TABLE %s" % test_table_to_drop)
- cur.close()
-
- # test if invalid value for if_exists raises appropriate error
- self.assertRaises(ValueError,
- sql.write_frame,
- frame=df_if_exists_1,
- con=self.db,
- name=table_name,
- flavor='mysql',
- if_exists='notvalidvalue')
- clean_up(table_name)
-
- # test if_exists='fail'
- sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
- flavor='mysql', if_exists='fail')
- self.assertRaises(ValueError,
- sql.write_frame,
- frame=df_if_exists_1,
- con=self.db,
- name=table_name,
- flavor='mysql',
- if_exists='fail')
-
- # test if_exists='replace'
- sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
- flavor='mysql', if_exists='replace')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(1, 'A'), (2, 'B')])
- sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name,
- flavor='mysql', if_exists='replace')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(3, 'C'), (4, 'D'), (5, 'E')])
- clean_up(table_name)
-
- # test if_exists='append'
- sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
- flavor='mysql', if_exists='fail')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(1, 'A'), (2, 'B')])
- sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name,
- flavor='mysql', if_exists='append')
- self.assertEqual(sql.tquery(sql_select, con=self.db),
- [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')])
- clean_up(table_name)
-
-
-if __name__ == '__main__':
- nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
- exit=False)
+ self.conn = self.connect()
+ self.pandasSQL = sql.PandasSQLLegacy(self.conn, 'mysql')
+
+ self._load_iris_data()
+
+ self._load_test1_data()
+
+ def tearDown(self):
+ c = self.conn.cursor()
+ c.execute('SHOW TABLES')
+ for table in c.fetchall():
+ c.execute('DROP TABLE %s' % table[0])
+ self.conn.commit()
+ self.conn.close()
+
+
+class TestMySQLAlchemy(TestSQLAlchemy):
+ flavor = 'mysql'
+
+ def connect(self):
+ return sqlalchemy.create_engine(
+ 'mysql+{driver}://root@localhost/pandas_nosetest'.format(driver=self.driver))
+
+ def setUp(self):
+ if not SQLALCHEMY_INSTALLED:
+ raise nose.SkipTest('SQLAlchemy not installed')
+
+ try:
+ import pymysql
+ self.driver = 'pymysql'
+
+ except ImportError:
+ raise nose.SkipTest
+
+ self.conn = self.connect()
+ self.pandasSQL = sql.PandasSQLAlchemy(self.conn)
+
+ self._load_iris_data()
+ self._load_raw_sql()
+
+ self._load_test1_data()
+
+ def tearDown(self):
+ c = self.conn.execute('SHOW TABLES')
+ for table in c.fetchall():
+ self.conn.execute('DROP TABLE %s' % table[0])
+
+ def test_default_date_load(self):
+ df = sql.read_table("types_test_data", self.conn)
+
+ # IMPORTANT - sqlite has no native date type, so shouldn't parse,
+ # but MySQL SHOULD be converted.
+ self.assertTrue(
+ issubclass(df.DateCol.dtype.type, np.datetime64), "DateCol loaded with incorrect type")
| Code, tests, and docs for an updated io.sql module which uses SQLAlchemy as a DB abstraction layer. A legacy fallback is provided for SQLite and MySQL. The api should be backwards compatible, with depreciated names marked as such.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5950 | 2014-01-15T17:35:55Z | 2014-02-06T21:35:56Z | null | 2014-06-12T12:35:36Z |
BUG: Bug in pd.read_msgpack with inferring a DateTimeIndex frequency incorrectly (GH5947) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index eb40b9474f41b..d567d3557dc8f 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -107,6 +107,8 @@ Bug Fixes
- ``pd.match`` not returning passed sentinel
- ``Panel.to_frame()`` no longer fails when ``major_axis`` is a
``MultiIndex`` (:issue:`5402`).
+ - Bug in ``pd.read_msgpack`` with inferring a ``DateTimeIndex`` frequencey
+ incorrectly (:issue:`5947`)
pandas 0.13.0
-------------
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index eba2579e80ea8..105bea92124fd 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -458,18 +458,19 @@ def decode(obj):
return globals()[obj['klass']].from_tuples(data, names=obj['names'])
elif typ == 'period_index':
data = unconvert(obj['data'], np.int64, obj.get('compress'))
- return globals()[obj['klass']](data, name=obj['name'],
- freq=obj['freq'])
+ d = dict(name=obj['name'], freq=obj['freq'])
+ return globals()[obj['klass']](data, **d)
elif typ == 'datetime_index':
data = unconvert(obj['data'], np.int64, obj.get('compress'))
- result = globals()[obj['klass']](data, freq=obj['freq'],
- name=obj['name'])
+ d = dict(name=obj['name'], freq=obj['freq'], verify_integrity=False)
+ result = globals()[obj['klass']](data, **d)
tz = obj['tz']
# reverse tz conversion
if tz is not None:
result = result.tz_localize('UTC').tz_convert(tz)
return result
+
elif typ == 'series':
dtype = dtype_for(obj['dtype'])
index = obj['index']
diff --git a/pandas/io/tests/test_packers.py b/pandas/io/tests/test_packers.py
index 1563406b1f8af..8cab9a65995bf 100644
--- a/pandas/io/tests/test_packers.py
+++ b/pandas/io/tests/test_packers.py
@@ -372,6 +372,17 @@ def test_iterator(self):
for i, packed in enumerate(read_msgpack(path, iterator=True)):
check_arbitrary(packed, l[i])
+ def tests_datetimeindex_freq_issue(self):
+
+ # GH 5947
+ # inferring freq on the datetimeindex
+ df = DataFrame([1, 2, 3], index=date_range('1/1/2013', '1/3/2013'))
+ result = self.encode_decode(df)
+ assert_frame_equal(result, df)
+
+ df = DataFrame([1, 2], index=date_range('1/1/2013', '1/2/2013'))
+ result = self.encode_decode(df)
+ assert_frame_equal(result, df)
class TestSparse(TestPackers):
| closes #5947
| https://api.github.com/repos/pandas-dev/pandas/pulls/5948 | 2014-01-15T16:41:07Z | 2014-01-15T19:25:07Z | 2014-01-15T19:25:07Z | 2014-07-16T08:46:41Z |
ENH: Improve perf of str_extract | diff --git a/doc/source/release.rst b/doc/source/release.rst
index eb40b9474f41b..75b9581a32ba6 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -79,6 +79,7 @@ Improvements to existing features
allow multiple axes to be used to operate on slabs of a ``Panel``
- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
limit precision based on the values in the array (:issue:`3401`)
+ - perf improvements to Series.str.extract (:issue:`5944`)
.. _release.bug_fixes-0.13.1:
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 77abd82b7ecc3..588a81e3cf80d 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -439,41 +439,28 @@ def str_extract(arr, pat, flags=0):
"""
regex = re.compile(pat, flags=flags)
-
# just to be safe, check this
if regex.groups == 0:
raise ValueError("This pattern contains no groups to capture.")
- elif regex.groups == 1:
- def f(x):
- if not isinstance(x, compat.string_types):
- return None
- m = regex.search(x)
- if m:
- return m.groups()[0] # may be None
- else:
- return None
+ empty_row = [np.nan]*regex.groups
+ def f(x):
+ if not isinstance(x, compat.string_types):
+ return empty_row
+ m = regex.search(x)
+ if m:
+ return [np.nan if item is None else item for item in m.groups()]
+ else:
+ return empty_row
+ if regex.groups == 1:
+ result = Series([f(val)[0] for val in arr], name=regex.groupindex.get(1))
else:
- empty_row = Series(regex.groups * [None])
-
- def f(x):
- if not isinstance(x, compat.string_types):
- return empty_row
- m = regex.search(x)
- if m:
- return Series(list(m.groups())) # may contain None
- else:
- return empty_row
- result = arr.apply(f)
- result.replace({None: np.nan}, inplace=True)
- if regex.groups > 1:
- result = DataFrame(result) # Don't rely on the wrapper; name columns.
names = dict(zip(regex.groupindex.values(), regex.groupindex.keys()))
- result.columns = [names.get(1 + i, i) for i in range(regex.groups)]
- else:
- result.name = regex.groupindex.get(0)
+ columns = [names.get(1 + i, i) for i in range(regex.groups)]
+ result = DataFrame([f(val) for val in arr], columns=columns)
return result
+
def str_join(arr, sep):
"""
Join lists contained as elements in array, a la str.join
| Building the result from a list of strings or a list of lists seems to improve performance over building the result via `arr.apply(f)`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5944 | 2014-01-15T13:19:13Z | 2014-01-15T22:17:33Z | 2014-01-15T22:17:33Z | 2014-06-14T23:57:13Z |
BUG: pd.match not returning passed sentinel | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 6d550d4f0b588..9a0854494a897 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -103,6 +103,7 @@ Bug Fixes
- Bug in propogating metadata on ``resample`` (:issue:`5862`)
- Fixed string-representation of ``NaT`` to be "NaT" (:issue:`5708`)
- Fixed string-representation for Timestamp to show nanoseconds if present (:issue:`5912`)
+ - ``pd.match`` not returning passed sentinel
pandas 0.13.0
-------------
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 24c14a5d7f215..f76f952c53d1d 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -11,7 +11,6 @@
import pandas.hashtable as htable
import pandas.compat as compat
-
def match(to_match, values, na_sentinel=-1):
"""
Compute locations of to_match into values
@@ -37,7 +36,16 @@ def match(to_match, values, na_sentinel=-1):
values = np.array(values, dtype='O')
f = lambda htype, caster: _match_generic(to_match, values, htype, caster)
- return _hashtable_algo(f, values.dtype)
+ result = _hashtable_algo(f, values.dtype)
+
+ if na_sentinel != -1:
+
+ # replace but return a numpy array
+ # use a Series because it handles dtype conversions properly
+ from pandas.core.series import Series
+ result = Series(result.ravel()).replace(-1,na_sentinel).values.reshape(result.shape)
+
+ return result
def unique(values):
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 2cbccbaf5c66b..027e7c5fab191 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -8,7 +8,6 @@
import pandas.core.algorithms as algos
import pandas.util.testing as tm
-
class TestMatch(tm.TestCase):
_multiprocess_can_split_ = True
@@ -20,6 +19,19 @@ def test_ints(self):
expected = np.array([0, 2, 1, 1, 0, 2, -1, 0])
self.assert_(np.array_equal(result, expected))
+ result = Series(algos.match(to_match, values, np.nan))
+ expected = Series(np.array([0, 2, 1, 1, 0, 2, np.nan, 0]))
+ tm.assert_series_equal(result,expected)
+
+ s = pd.Series(np.arange(5),dtype=np.float32)
+ result = algos.match(s, [2,4])
+ expected = np.array([-1, -1, 0, -1, 1])
+ self.assert_(np.array_equal(result, expected))
+
+ result = Series(algos.match(s, [2,4], np.nan))
+ expected = Series(np.array([np.nan, np.nan, 0, np.nan, 1]))
+ tm.assert_series_equal(result,expected)
+
def test_strings(self):
values = ['foo', 'bar', 'baz']
to_match = ['bar', 'foo', 'qux', 'foo', 'bar', 'baz', 'qux']
@@ -28,6 +40,9 @@ def test_strings(self):
expected = np.array([1, 0, -1, 0, 1, 2, -1])
self.assert_(np.array_equal(result, expected))
+ result = Series(algos.match(to_match, values, np.nan))
+ expected = Series(np.array([1, 0, np.nan, 0, 1, 2, np.nan]))
+ tm.assert_series_equal(result,expected)
class TestUnique(tm.TestCase):
_multiprocess_can_split_ = True
| https://api.github.com/repos/pandas-dev/pandas/pulls/5943 | 2014-01-15T02:50:17Z | 2014-01-15T03:07:47Z | 2014-01-15T03:07:47Z | 2014-07-16T08:46:35Z | |
BUG: Bug in propogating metadata on resample (GH5862) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index aa772ef437355..9f0b42dd5b741 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -95,6 +95,7 @@ Bug Fixes
- Bug in assigning to chained series with a series via ix (:issue:`5928`)
- Bug in creating an empty DataFrame, copying, then assigning (:issue:`5932`)
- Bug in DataFrame.tail with empty frame (:issue:`5846`)
+ - Bug in propogating metadata on ``resample`` (:issue:`5862`)
pandas 0.13.0
-------------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index a5a7021d9f4b7..549a199e9e3dd 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2562,7 +2562,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
axis=axis, kind=kind, loffset=loffset,
fill_method=fill_method, convention=convention,
limit=limit, base=base)
- return sampler.resample(self)
+ return sampler.resample(self).__finalize__(self)
def first(self, offset):
"""
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 14082486f80a0..5ba2a4519db0f 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -285,7 +285,6 @@ def test_metadata_propagation(self):
except (AttributeError):
pass
-
# ---------------------------
# non-preserving (by default)
# ---------------------------
@@ -428,6 +427,19 @@ def test_metadata_propagation_indiv(self):
result = o.T
self.check_metadata(o,result)
+ # resample
+ ts = Series(np.random.rand(1000),
+ index=date_range('20130101',periods=1000,freq='s'),
+ name='foo')
+ result = ts.resample('1T')
+ self.check_metadata(ts,result)
+
+ result = ts.resample('1T',how='min')
+ self.check_metadata(ts,result)
+
+ result = ts.resample('1T',how=lambda x: x.sum())
+ self.check_metadata(ts,result)
+
def test_interpolate(self):
ts = Series(np.arange(len(self.ts), dtype=float), self.ts.index)
@@ -768,6 +780,23 @@ def test_spline(self):
expected = Series([1, 2, 3, 4, 5, 6, 7])
assert_series_equal(result, expected)
+ def test_metadata_propagation_indiv(self):
+
+ # groupby
+ df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
+ 'foo', 'bar', 'foo', 'foo'],
+ 'B': ['one', 'one', 'two', 'three',
+ 'two', 'two', 'one', 'three'],
+ 'C': np.random.randn(8),
+ 'D': np.random.randn(8)})
+ result = df.groupby('A').sum()
+ self.check_metadata(df,result)
+
+ # resample
+ df = DataFrame(np.random.randn(1000,2), index=date_range('20130101',periods=1000,freq='s'))
+ result = df.resample('1T')
+ self.check_metadata(df,result)
+
class TestPanel(tm.TestCase, Generic):
_typ = Panel
_comparator = lambda self, x, y: assert_panel_equal(x, y)
| closes #5862
| https://api.github.com/repos/pandas-dev/pandas/pulls/5942 | 2014-01-15T00:56:48Z | 2014-01-15T02:08:37Z | 2014-01-15T02:08:37Z | 2014-06-22T19:02:47Z |
API: add read_gbq to top-level api, closes (GH5843) | diff --git a/pandas/io/api.py b/pandas/io/api.py
index dc9ea290eb45e..cf3615cd822cd 100644
--- a/pandas/io/api.py
+++ b/pandas/io/api.py
@@ -12,3 +12,4 @@
from pandas.io.stata import read_stata
from pandas.io.pickle import read_pickle, to_pickle
from pandas.io.packers import read_msgpack, to_msgpack
+from pandas.io.gbq import read_gbq
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 010277533589c..7b0c3137e79ac 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -13,8 +13,9 @@
import pandas as pd
import numpy as np
-from pandas import DataFrame, concat
from pandas.core.common import PandasError
+from pandas.core.frame import DataFrame
+from pandas.tools.merge import concat
try:
import bq
| closes #5843
| https://api.github.com/repos/pandas-dev/pandas/pulls/5941 | 2014-01-15T00:41:22Z | 2014-01-15T02:51:22Z | 2014-01-15T02:51:22Z | 2014-07-16T08:46:33Z |
API: Raise/Warn SettingWithCopyError in more cases | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 589dcca154a10..aa772ef437355 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -58,8 +58,9 @@ API Changes
- ``Series.sort`` will raise a ``ValueError`` (rather than a ``TypeError``) on sorting an
object that is a view of another (:issue:`5856`, :issue:`5853`)
-
-.. _release.bug_fixes-0.13.1:
+ - Raise/Warn ``SettingWithCopyError`` (according to the option ``chained_assignment`` in more cases,
+ when detecting chained assignment, related (:issue:`5938`)
+ - DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
@@ -72,7 +73,8 @@ Improvements to existing features
- df.info() view now display dtype info per column (:issue: `5682`)
- perf improvements in DataFrame ``count/dropna`` for ``axis=1``
- Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue: `5879`)
- - DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
+
+.. _release.bug_fixes-0.13.1:
Bug Fixes
~~~~~~~~~
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 47ec392a1135a..8f1916141b572 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1856,6 +1856,7 @@ def _box_col_values(self, values, items):
name=items, fastpath=True)
def __setitem__(self, key, value):
+
# see if we can slice the rows
indexer = _convert_to_index_sliceable(self, key)
if indexer is not None:
@@ -1880,6 +1881,7 @@ 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):
@@ -1889,6 +1891,7 @@ 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):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 1a7359eed45fc..8f3f122fefb88 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2061,6 +2061,14 @@ def f():
assert_series_equal(s,df.iloc[:,0].order())
assert_series_equal(s,df[0].order())
+ # operating on a copy
+ df = pd.DataFrame({'a': list(range(4)), 'b': list('ab..'), 'c': ['a', 'b', np.nan, 'd']})
+ mask = pd.isnull(df.c)
+
+ def f():
+ df[['c']][mask] = df[['b']][mask]
+ self.assertRaises(com.SettingWithCopyError, f)
+
pd.set_option('chained_assignment','warn')
def test_float64index_slicing_bug(self):
| when detecting chained assignment, related, #5938
| https://api.github.com/repos/pandas-dev/pandas/pulls/5939 | 2014-01-14T21:31:09Z | 2014-01-15T00:37:31Z | 2014-01-15T00:37:31Z | 2014-07-16T08:46:31Z |
BUG: Bug in creating an empty DataFrame, copying, then assigning (GH5932) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 6967c096ae90a..9ab175c07f169 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -89,6 +89,7 @@ Bug Fixes
- Bug in idxmin/max with object dtypes (:issue:`5914`)
- Bug in ``BusinessDay`` when adding n days to a date not on offset when n>5 and n%5==0 (:issue:`5890`)
- Bug in assigning to chained series with a series via ix (:issue:`5928`)
+ - Bug in creating an empty DataFrame, copying, then assigning (:issue:`5932`)
pandas 0.13.0
-------------
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 7f49f7c1993bd..5c77930a206b7 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1961,8 +1961,11 @@ def make_empty(self, axes=None):
]
# preserve dtype if possible
- dtype = self.dtype if self.ndim == 1 else object
- return self.__class__(np.array([], dtype=dtype), axes)
+ if self.ndim == 1:
+ blocks = np.array([], dtype=self.dtype)
+ else:
+ blocks = []
+ return self.__class__(blocks, axes)
def __nonzero__(self):
return True
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index a420dcc7b68e4..1a7359eed45fc 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1843,6 +1843,14 @@ def f():
df = DataFrame(Series(name='foo'))
assert_frame_equal(df, DataFrame({ 'foo' : Series() }))
+ # GH 5932
+ # copy on empty with assignment fails
+ df = DataFrame(index=[0])
+ df = df.copy()
+ df['a'] = 0
+ expected = DataFrame(0,index=[0],columns=['a'])
+ assert_frame_equal(df, expected)
+
def test_cache_updating(self):
# GH 4939, make sure to update the cache on setitem
| closes #5932
| https://api.github.com/repos/pandas-dev/pandas/pulls/5935 | 2014-01-14T13:10:28Z | 2014-01-14T13:45:01Z | 2014-01-14T13:45:01Z | 2014-06-15T15:32:47Z |
BUG: bug in chained assignment with ix and another chained series (GH5928) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index d025baa66aa88..6967c096ae90a 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -88,6 +88,7 @@ Bug Fixes
- Bug in fully reindexing a Panel (:issue:`5905`)
- Bug in idxmin/max with object dtypes (:issue:`5914`)
- Bug in ``BusinessDay`` when adding n days to a date not on offset when n>5 and n%5==0 (:issue:`5890`)
+ - Bug in assigning to chained series with a series via ix (:issue:`5928`)
pandas 0.13.0
-------------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 0697f9d826f97..751c020fecc27 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -421,7 +421,7 @@ def can_do_equal_len():
def _align_series(self, indexer, ser):
# indexer to assign Series can be tuple, slice, scalar
- if isinstance(indexer, slice):
+ if isinstance(indexer, (slice, np.ndarray, list)):
indexer = tuple([indexer])
if isinstance(indexer, tuple):
@@ -453,8 +453,12 @@ def _align_series(self, indexer, ser):
all([com._is_sequence(_) for _ in indexer])):
ser = ser.reindex(obj.axes[0][indexer[0].ravel()],
copy=True).values
- l = len(indexer[1].ravel())
- ser = np.tile(ser, l).reshape(l, -1).T
+
+ # single indexer
+ if len(indexer) > 1:
+ l = len(indexer[1].ravel())
+ ser = np.tile(ser, l).reshape(l, -1).T
+
return ser
for i, idx in enumerate(indexer):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index bf1709c78822f..a420dcc7b68e4 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -476,6 +476,20 @@ def test_loc_setitem(self):
expected = Series([1,1,0],index=[4,5,6])
assert_series_equal(s, expected)
+ # GH 5928
+ # chained indexing assignment
+ df = DataFrame({'a' : [0,1,2] })
+ expected = df.copy()
+ expected.ix[[0,1,2],'a'] = -expected.ix[[0,1,2],'a']
+
+ df['a'].ix[[0,1,2]] = -df['a'].ix[[0,1,2]]
+ assert_frame_equal(df,expected)
+
+ df = DataFrame({'a' : [0,1,2], 'b' :[0,1,2] })
+ df['a'].ix[[0,1,2]] = -df['a'].ix[[0,1,2]].astype('float64') + 0.5
+ expected = DataFrame({'a' : [0.5,-0.5,-1.5], 'b' : [0,1,2] })
+ assert_frame_equal(df,expected)
+
def test_loc_getitem_int(self):
# int label
| closes #5928
| https://api.github.com/repos/pandas-dev/pandas/pulls/5930 | 2014-01-13T23:21:18Z | 2014-01-14T00:24:21Z | 2014-01-14T00:24:21Z | 2014-06-22T07:37:28Z |
Tutorials | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 79f5af74c3985..b21cd1456a5fd 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -249,8 +249,7 @@ Attributes and underlying data
Series.values
Series.dtype
- Series.isnull
- Series.notnull
+ Series.ftype
Conversion
~~~~~~~~~~
@@ -519,7 +518,9 @@ Attributes and underlying data
DataFrame.as_matrix
DataFrame.dtypes
+ DataFrame.ftypes
DataFrame.get_dtype_counts
+ DataFrame.get_ftype_counts
DataFrame.values
DataFrame.axes
DataFrame.ndim
@@ -786,6 +787,9 @@ Attributes and underlying data
Panel.ndim
Panel.shape
Panel.dtypes
+ Panel.ftypes
+ Panel.get_dtype_counts
+ Panel.get_ftype_counts
Conversion
~~~~~~~~~~
@@ -959,6 +963,49 @@ Serialization / IO / Conversion
Panel.to_frame
Panel.to_clipboard
+.. _api.panel4d:
+
+Panel4D
+-------
+
+Constructor
+~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Panel4D
+
+Attributes and underlying data
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+**Axes**
+
+ * **labels**: axis 1; each label corresponds to a Panel contained inside
+ * **items**: axis 2; each item corresponds to a DataFrame contained inside
+ * **major_axis**: axis 3; the index (rows) of each of the DataFrames
+ * **minor_axis**: axis 4; the columns of each of the DataFrames
+
+.. autosummary::
+ :toctree: generated/
+
+ Panel4D.values
+ Panel4D.axes
+ Panel4D.ndim
+ Panel4D.shape
+ Panel4D.dtypes
+ Panel4D.ftypes
+ Panel4D.get_dtype_counts
+ Panel4D.get_ftype_counts
+
+Conversion
+~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Panel4D.astype
+ Panel4D.copy
+ Panel4D.isnull
+ Panel4D.notnull
+
.. _api.index:
Index
diff --git a/doc/source/release.rst b/doc/source/release.rst
index c5dc55f260f64..99b8bfc460068 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -75,7 +75,7 @@ Improvements to existing features
- df.info() now honors option max_info_rows, disable null counts for large frames (:issue:`5974`)
- perf improvements in DataFrame ``count/dropna`` for ``axis=1``
- Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue:`5879`)
- - support ``dtypes`` on ``Panel``
+ - support ``dtypes`` property on ``Series/Panel/Panel4D``
- extend ``Panel.apply`` to allow arbitrary functions (rather than only ufuncs) (:issue:`1148`)
allow multiple axes to be used to operate on slabs of a ``Panel``
- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
diff --git a/doc/source/tutorials.rst b/doc/source/tutorials.rst
index 4ad9082b0cb9b..b742767205685 100644
--- a/doc/source/tutorials.rst
+++ b/doc/source/tutorials.rst
@@ -55,4 +55,61 @@ repository <http://github.com/jvns/pandas-cookbook>`_.
* | `Chapter 8: <http://nbviewer.ipython.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%208%20-%20How%20to%20deal%20with%20timestamps.ipynb>`_
Parsing Unix timestamps is confusing at first but it turns out
to be really easy.
+
+
+
+Lessons for New Pandas Users
+----------------------------
+
+For more resources, please visit the main `repository <https://bitbucket.org/hrojas/learn-pandas>`_.
+
+* | `01 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/01%20-%20Lesson.ipynb>`_
+
+ * Importing libraries
+ * Creating data sets
+ * Creating data frames
+ * Reading from CSV
+ * Exporting to CSV
+ * Finding maximums
+ * Plotting data
+* | `02 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/02%20-%20Lesson.ipynb>`_
+
+ * Reading from TXT
+ * Exporting to TXT
+ * Selecting top/bottom records
+ * Descriptive statistics
+ * Grouping/sorting data
+* | `03 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/03%20-%20Lesson.ipynb>`_
+
+ * Creating functions
+ * Reading from EXCEL
+ * Exporting to EXCEL
+ * Outliers
+ * Lambda functions
+ * Slice and dice data
+* | `04 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/04%20-%20Lesson.ipynb>`_
+
+ * Adding/deleting columns
+ * Index operations
+* | `05 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/05%20-%20Lesson.ipynb>`_
+
+ * Stack/Unstack/Transpose functions
+* | `06 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/06%20-%20Lesson.ipynb>`_
+
+ * GroupBy function
+* | `07 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/07%20-%20Lesson.ipynb>`_
+
+ * Ways to calculate outliers
+* | `08 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/08%20-%20Lesson.ipynb>`_
+
+ * Read from Microsoft SQL databases
+* | `09 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/09%20-%20Lesson.ipynb>`_
+
+ * Export to CSV/EXCEL/TXT
+* | `10 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/10%20-%20Lesson.ipynb>`_
+
+ * Converting between different kinds of formats
+* | `11 - Lesson: <http://nbviewer.ipython.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/11%20-%20Lesson.ipynb>`_
+
+ * Combining data from various sources
diff --git a/doc/source/whatsnew.rst b/doc/source/whatsnew.rst
index ad2af07d3d723..e36428e96301a 100644
--- a/doc/source/whatsnew.rst
+++ b/doc/source/whatsnew.rst
@@ -17,6 +17,8 @@ What's New
These are new features and improvements of note in each release.
+.. include:: v0.13.1.txt
+
.. include:: v0.13.0.txt
.. include:: v0.12.0.txt
diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py
index 073526f526abe..e6d2484a41019 100644
--- a/pandas/computation/tests/test_eval.py
+++ b/pandas/computation/tests/test_eval.py
@@ -405,13 +405,13 @@ def check_pow(self, lhs, arith1, rhs):
self.assertRaises(AssertionError, assert_array_equal, result,
expected)
else:
- assert_array_equal(result, expected)
+ assert_allclose(result, expected)
ex = '(lhs {0} rhs) {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = self.get_expected_pow_result(
self.get_expected_pow_result(lhs, rhs), rhs)
- assert_array_equal(result, expected)
+ assert_allclose(result, expected)
@skip_incompatible_operand
def check_single_invert_op(self, lhs, cmp1, rhs):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bdd2e3a2683cc..9dcf5290d29b5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1748,24 +1748,27 @@ def get_values(self):
return self.as_matrix()
def get_dtype_counts(self):
- """ return the counts of dtypes in this object """
+ """ Return the counts of dtypes in this object """
from pandas import Series
return Series(self._data.get_dtype_counts())
def get_ftype_counts(self):
- """ return the counts of ftypes in this object """
+ """ Return the counts of ftypes in this object """
from pandas import Series
return Series(self._data.get_ftype_counts())
@property
def dtypes(self):
- """ return the counts of dtypes in this object """
+ """ Return the dtypes in this object """
from pandas import Series
return Series(self._data.get_dtypes(),index=self._info_axis)
@property
def ftypes(self):
- """ return the counts of ftypes in this object """
+ """
+ Return the ftypes (indication of sparse/dense and dtype)
+ in this object.
+ """
from pandas import Series
return Series(self._data.get_ftypes(),index=self._info_axis)
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index ca16be1b52ca2..fbea40eb76a0d 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -3514,6 +3514,9 @@ def _post_setstate(self):
self._block = self.blocks[0]
self._values = self._block.values
+ def _get_counts(self, f):
+ return { f(self._block) : 1 }
+
@property
def shape(self):
if getattr(self, '_shape', None) is None:
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index 832874f08561b..fc4373764172f 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -441,10 +441,6 @@ def as_matrix(self):
self._consolidate_inplace()
return self._data.as_matrix()
- @property
- def dtypes(self):
- return self.apply(lambda x: x.dtype, axis='items')
-
#----------------------------------------------------------------------
# Getting and setting elements
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 2e1d95cf87b47..918043dcacd37 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -301,10 +301,20 @@ def flags(self):
def dtype(self):
return self._data.dtype
+ @property
+ def dtypes(self):
+ """ for compat """
+ return self._data.dtype
+
@property
def ftype(self):
return self._data.ftype
+ @property
+ def ftypes(self):
+ """ for compat """
+ return self._data.ftype
+
@property
def shape(self):
return self._data.shape
@@ -2094,7 +2104,7 @@ def isin(self, values):
----------
values : list-like
The sequence of values to test. Passing in a single string will
- raise a ``TypeError``. Instead, turn a single string into a
+ raise a ``TypeError``. Instead, turn a single string into a
``list`` of one element.
Returns
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 2589f7b82aedb..16a43f2f9e767 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -6,7 +6,7 @@
import numpy as np
-from pandas import DataFrame, Index, isnull, notnull, pivot, MultiIndex
+from pandas import Series, DataFrame, Index, isnull, notnull, pivot, MultiIndex
from pandas.core.datetools import bday
from pandas.core.frame import group_agg
from pandas.core.panel import Panel
@@ -1064,8 +1064,8 @@ def test_convert_objects(self):
def test_dtypes(self):
result = self.panel.dtypes
- expected = DataFrame(np.dtype('float64'),index=self.panel.major_axis,columns=self.panel.minor_axis)
- assert_frame_equal(result, expected)
+ expected = Series(np.dtype('float64'),index=self.panel.items)
+ assert_series_equal(result, expected)
def test_apply(self):
# GH1148
diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py
index ea6602dbb0be6..fb5030ac66831 100644
--- a/pandas/tests/test_panel4d.py
+++ b/pandas/tests/test_panel4d.py
@@ -6,7 +6,7 @@
import numpy as np
-from pandas import DataFrame, Index, isnull, notnull, pivot, MultiIndex
+from pandas import Series, DataFrame, Index, isnull, notnull, pivot, MultiIndex
from pandas.core.datetools import bday
from pandas.core.frame import group_agg
from pandas.core.panel import Panel
@@ -932,6 +932,12 @@ def test_filter(self):
def test_apply(self):
raise nose.SkipTest("skipping for now")
+ def test_dtypes(self):
+
+ result = self.panel4d.dtypes
+ expected = Series(np.dtype('float64'),index=self.panel4d.labels)
+ assert_series_equal(result, expected)
+
def test_compound(self):
raise nose.SkipTest("skipping for now")
# compounded = self.panel.compound()
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 699ffb592a63e..70dd38c2641ef 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -3620,6 +3620,15 @@ def test_count(self):
self.assertEqual(self.ts.count(), np.isfinite(self.ts).sum())
+ def test_dtype(self):
+
+ self.assert_(self.ts.dtype == np.dtype('float64'))
+ self.assert_(self.ts.dtypes == np.dtype('float64'))
+ self.assert_(self.ts.ftype == 'float64:dense')
+ self.assert_(self.ts.ftypes == 'float64:dense')
+ assert_series_equal(self.ts.get_dtype_counts(),Series(1,['float64']))
+ assert_series_equal(self.ts.get_ftype_counts(),Series(1,['float64:dense']))
+
def test_dot(self):
a = Series(np.random.randn(4), index=['p', 'q', 'r', 's'])
b = DataFrame(np.random.randn(3, 4), index=['1', '2', '3'],
| added tutorials, let me know if you guys would like the output in a different format.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5929 | 2014-01-13T22:25:52Z | 2014-01-17T22:17:13Z | null | 2014-07-16T08:46:22Z |
DOC: make io.rst utf8 only | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 48fe6e24dda9f..3d099bc291244 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -326,7 +326,8 @@ result in byte strings being decoded to unicode in the result:
.. ipython:: python
- data = 'word,length\nTr\xe4umen,7\nGr\xfc\xdfe,5'
+ # a latin-1 encoded bytestring
+ data='word,length\nTr\xc3\xa4umen,7\nGr\xc3\xbc\xc3\x9fe,5'.decode('utf8').encode('latin-1')
df = pd.read_csv(StringIO(data), encoding='latin-1')
df
df['word'][1]
| https://github.com/pydata/pandas/issues/5142
@JanSchulz , can you test whether this solves the problem for you?
| https://api.github.com/repos/pandas-dev/pandas/pulls/5926 | 2014-01-13T18:30:02Z | 2014-01-13T20:40:57Z | null | 2014-07-06T12:35:17Z |
Rebase ipython_directive on top of recent ipython updated version | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 48fe6e24dda9f..f8ae4e6282ec5 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -326,7 +326,7 @@ result in byte strings being decoded to unicode in the result:
.. ipython:: python
- data = 'word,length\nTr\xe4umen,7\nGr\xfc\xdfe,5'
+ data = b'word,length\nTr\xc3\xa4umen,7\nGr\xc3\xbc\xc3\x9fe,5'.decode('utf8').encode('latin-1')
df = pd.read_csv(StringIO(data), encoding='latin-1')
df
df['word'][1]
diff --git a/doc/sphinxext/ipython_directive.py b/doc/sphinxext/ipython_directive.py
index 114a3d56f36c8..e228542b64b4d 100644
--- a/doc/sphinxext/ipython_directive.py
+++ b/doc/sphinxext/ipython_directive.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
-"""Sphinx directive to support embedded IPython code.
+"""
+Sphinx directive to support embedded IPython code.
This directive allows pasting of entire interactive IPython sessions, prompts
and all, and their code will actually get re-executed at doc build time, with
@@ -9,11 +10,17 @@
To enable this directive, simply list it in your Sphinx ``conf.py`` file
(making sure the directory where you placed it is visible to sphinx, as is
-needed for all Sphinx directives).
+needed for all Sphinx directives). For example, to enable syntax highlighting
+and the IPython directive::
+
+ extensions = ['IPython.sphinxext.ipython_console_highlighting',
+ 'IPython.sphinxext.ipython_directive']
-By default this directive assumes that your prompts are unchanged IPython ones,
-but this can be customized. The configurable options that can be placed in
-conf.py are
+The IPython directive outputs code-blocks with the language 'ipython'. So
+if you do not have the syntax highlighting extension enabled as well, then
+all rendered code-blocks will be uncolored. By default this directive assumes
+that your prompts are unchanged IPython ones, but this can be customized.
+The configurable options that can be placed in conf.py are:
ipython_savefig_dir:
The directory in which to save the figures. This is relative to the
@@ -31,10 +38,50 @@
The default is 'In [%d]:'. This expects that the line numbers are used
in the prompt.
ipython_promptout:
-
The string to represent the IPython prompt in the generated ReST. The
default is 'Out [%d]:'. This expects that the line numbers are used
in the prompt.
+ipython_mplbackend:
+ The string which specifies if the embedded Sphinx shell should import
+ Matplotlib and set the backend. The value specifies a backend that is
+ passed to `matplotlib.use()` before any lines in `ipython_execlines` are
+ executed. If not specified in conf.py, then the default value of 'agg' is
+ used. To use the IPython directive without matplotlib as a dependency, set
+ the value to `None`. It may end up that matplotlib is still imported
+ if the user specifies so in `ipython_execlines` or makes use of the
+ @savefig pseudo decorator.
+ipython_execlines:
+ A list of strings to be exec'd in the embedded Sphinx shell. Typical
+ usage is to make certain packages always available. Set this to an empty
+ list if you wish to have no imports always available. If specified in
+ conf.py as `None`, then it has the effect of making no imports available.
+ If omitted from conf.py altogether, then the default value of
+ ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
+ipython_holdcount
+ When the @suppress pseudo-decorator is used, the execution count can be
+ incremented or not. The default behavior is to hold the execution count,
+ corresponding to a value of `True`. Set this to `False` to increment
+ the execution count after each suppressed command.
+
+As an example, to use the IPython directive when `matplotlib` is not available,
+one sets the backend to `None`::
+
+ ipython_mplbackend = None
+
+An example usage of the directive is:
+
+.. code-block:: rst
+
+ .. ipython::
+
+ In [1]: x = 1
+
+ In [2]: y = x**2
+
+ In [3]: print(y)
+
+See http://matplotlib.org/sampledoc/ipython_directive.html for additional
+documentation.
ToDo
----
@@ -48,47 +95,56 @@
- John D Hunter: orignal author.
- Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
-- VĂĄclavĹ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
+- VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
- Skipper Seabold, refactoring, cleanups, pure python addition
"""
+from __future__ import print_function
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Stdlib
-import ast
-import cStringIO
import os
import re
import sys
import tempfile
+import ast
+from pandas.compat import zip, range, map, lmap, u, cStringIO as StringIO
+
+# To keep compatibility with various python versions
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
# Third-party
-import matplotlib
+import sphinx
from docutils.parsers.rst import directives
from docutils import nodes
from sphinx.util.compat import Directive
-matplotlib.use('Agg')
-
# Our own
from IPython import Config, InteractiveShell
from IPython.core.profiledir import ProfileDir
from IPython.utils import io
+from IPython.utils.py3compat import PY3
+if PY3:
+ from io import StringIO
+else:
+ from StringIO import StringIO
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
# for tokenizing blocks
-COMMENT, INPUT, OUTPUT = range(3)
+COMMENT, INPUT, OUTPUT = range(3)
#-----------------------------------------------------------------------------
# Functions and class declarations
#-----------------------------------------------------------------------------
-
def block_parser(part, rgxin, rgxout, fmtin, fmtout):
"""
part is a string of ipython text, comprised of at most one
@@ -107,10 +163,9 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
INPUT_LINE: the input as string (possibly multi-line)
REST : any stdout generated by the input line (not OUTPUT)
-
OUTPUT: the output string, possibly multi-line
- """
+ """
block = []
lines = part.split('\n')
N = len(lines)
@@ -118,7 +173,7 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
decorator = None
while 1:
- if i == N:
+ if i==N:
# nothing left to parse -- the last line
break
@@ -141,7 +196,7 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
lineno, inputline = int(matchin.group(1)), matchin.group(2)
# the ....: continuation string
- continuation = ' %s:' % ''.join(['.'] * (len(str(lineno)) + 2))
+ continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
Nc = len(continuation)
# input lines can continue on for more than one line, if
# we have a '\' line continuation char or a function call
@@ -151,22 +206,26 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
# multiline as well as any echo text
rest = []
- while i < N:
+ while i<N:
# look ahead; if the next line is blank, or a comment, or
# an output line, we're done
nextline = lines[i]
matchout = rgxout.match(nextline)
- # print("nextline=%s, continuation=%s, starts=%s"%(nextline,
- # continuation, nextline.startswith(continuation)))
+ #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation))
if matchout or nextline.startswith('#'):
break
elif nextline.startswith(continuation):
- inputline += '\n' + nextline[Nc:]
+ nextline = nextline[Nc:]
+ if nextline and nextline[0] == ' ':
+ nextline = nextline[1:]
+
+ inputline += '\n' + nextline
+
else:
rest.append(nextline)
- i += 1
+ i+= 1
block.append((INPUT, (decorator, inputline, '\n'.join(rest))))
continue
@@ -176,7 +235,7 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
matchout = rgxout.match(line)
if matchout:
lineno, output = int(matchout.group(1)), matchout.group(2)
- if i < N - 1:
+ if i<N-1:
output = '\n'.join([output] + lines[i:])
block.append((OUTPUT, output))
@@ -186,42 +245,39 @@ def block_parser(part, rgxin, rgxout, fmtin, fmtout):
class EmbeddedSphinxShell(object):
-
"""An embedded IPython instance to run inside Sphinx"""
- def __init__(self):
+ def __init__(self, exec_lines=None):
+
+ self.cout = StringIO()
- self.cout = cStringIO.StringIO()
+ if exec_lines is None:
+ exec_lines = []
# Create config object for IPython
config = Config()
- config.Global.display_banner = False
- config.Global.exec_lines = ['import numpy as np',
- 'from pylab import *'
- ]
config.InteractiveShell.autocall = False
config.InteractiveShell.autoindent = False
config.InteractiveShell.colors = 'NoColor'
- config.InteractiveShell.cache_size = 0
# create a profile so instance history isn't saved
tmp_profile_dir = tempfile.mkdtemp(prefix='profile_')
profname = 'auto_profile_sphinx_build'
- pdir = os.path.join(tmp_profile_dir, profname)
+ pdir = os.path.join(tmp_profile_dir,profname)
profile = ProfileDir.create_profile_dir(pdir)
- # Create and initialize ipython, but don't start its mainloop
+ # Create and initialize global ipython, but don't start its mainloop.
+ # This will persist across different EmbededSphinxShell instances.
IP = InteractiveShell.instance(config=config, profile_dir=profile)
- # io.stdout redirect must be done *after* instantiating
- # InteractiveShell
+ # io.stdout redirect must be done after instantiating InteractiveShell
io.stdout = self.cout
io.stderr = self.cout
# For debugging, so we can see normal output, use this:
- # from IPython.utils.io import Tee
- # io.stdout = Tee(self.cout, channel='stdout') # dbg
- # io.stderr = Tee(self.cout, channel='stderr') # dbg
+ #from IPython.utils.io import Tee
+ #io.stdout = Tee(self.cout, channel='stdout') # dbg
+ #io.stderr = Tee(self.cout, channel='stderr') # dbg
# Store a few parts of IPython we'll need.
self.IP = IP
@@ -235,17 +291,24 @@ def __init__(self):
self.is_doctest = False
self.is_suppress = False
+ # Optionally, provide more detailed information to shell.
+ self.directive = None
+
# on the first call to the savefig decorator, we'll import
# pyplot as plt so we can make a call to the plt.gcf().savefig
self._pyplot_imported = False
+ # Prepopulate the namespace.
+ for line in exec_lines:
+ self.process_input_line(line, store_history=False)
+
def clear_cout(self):
self.cout.seek(0)
self.cout.truncate(0)
def process_input_line(self, line, store_history=True):
"""process the input, capturing stdout"""
- # print("input='%s'"%self.input)
+
stdout = sys.stdout
splitter = self.IP.input_splitter
try:
@@ -257,6 +320,14 @@ def process_input_line(self, line, store_history=True):
self.IP.run_cell(source_raw, store_history=store_history)
finally:
sys.stdout = stdout
+ buflist = self.cout.buflist
+ for i in range(len(buflist)):
+ try:
+ # print(buflist[i])
+ if not isinstance(buflist[i], unicode):
+ buflist[i] = buflist[i].decode('utf8','replace')
+ except:
+ pass
def process_image(self, decorator):
"""
@@ -272,127 +343,160 @@ def process_image(self, decorator):
saveargs = decorator.split(' ')
filename = saveargs[1]
# insert relative path to image file in source
- outfile = os.path.relpath(os.path.join(savefig_dir, filename),
- source_dir)
+ outfile = os.path.relpath(os.path.join(savefig_dir,filename),
+ source_dir)
- imagerows = ['.. image:: %s' % outfile]
+ imagerows = ['.. image:: %s'%outfile]
for kwarg in saveargs[2:]:
arg, val = kwarg.split('=')
arg = arg.strip()
val = val.strip()
- imagerows.append(' :%s: %s' % (arg, val))
+ imagerows.append(' :%s: %s'%(arg, val))
- image_file = os.path.basename(outfile) # only return file name
+ image_file = os.path.basename(outfile) # only return file name
image_directive = '\n'.join(imagerows)
return image_file, image_directive
# Callbacks for each type of token
def process_input(self, data, input_prompt, lineno):
- """Process data block for INPUT token."""
+ """
+ Process data block for INPUT token.
+
+ """
decorator, input, rest = data
image_file = None
image_directive = None
- # print('INPUT:', data) # dbg
- is_verbatim = decorator == '@verbatim' or self.is_verbatim
- is_doctest = decorator == '@doctest' or self.is_doctest
- is_suppress = decorator == '@suppress' or self.is_suppress
- is_okexcept = decorator == '@okexcept' or self.is_okexcept
+
+ is_verbatim = decorator=='@verbatim' or self.is_verbatim
+ is_doctest = (decorator is not None and \
+ decorator.startswith('@doctest')) or self.is_doctest
+ is_suppress = decorator=='@suppress' or self.is_suppress
+ is_okexcept = decorator=='@okexcept' or self.is_okexcept
is_savefig = decorator is not None and \
- decorator.startswith('@savefig')
+ decorator.startswith('@savefig')
- def _remove_first_space_if_any(line):
- return line[1:] if line.startswith(' ') else line
+ # #>>> required for cython magic to work
+ # def _remove_first_space_if_any(line):
+ # return line[1:] if line.startswith(' ') else line
- input_lines = map(_remove_first_space_if_any, input.split('\n'))
+ # input_lines = lmap(_remove_first_space_if_any, input.split('\n'))
+ input_lines = input.split('\n')
- self.datacontent = data
+ if len(input_lines) > 1:
+ if input_lines[-1] != "":
+ input_lines.append('') # make sure there's a blank line
+ # so splitter buffer gets reset
- continuation = ' %s: ' % ''.join(['.'] * (len(str(lineno)) + 2))
+ continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
if is_savefig:
image_file, image_directive = self.process_image(decorator)
ret = []
is_semicolon = False
- store_history = True
+
+ # Hold the execution count, if requested to do so.
+ if is_suppress and self.hold_count:
+ store_history = False
+ else:
+ store_history = True
for i, line in enumerate(input_lines):
if line.endswith(';'):
is_semicolon = True
- if is_semicolon or is_suppress:
- store_history = False
if i == 0:
# process the first input line
if is_verbatim:
self.process_input_line('')
- self.IP.execution_count += 1 # increment it anyway
+ self.IP.execution_count += 1 # increment it anyway
else:
# only submit the line in non-verbatim mode
self.process_input_line(line, store_history=store_history)
- formatted_line = '%s %s' % (input_prompt, line)
+ formatted_line = '%s %s'%(input_prompt, line)
else:
# process a continuation line
if not is_verbatim:
self.process_input_line(line, store_history=store_history)
- formatted_line = '%s%s' % (continuation, line)
+ formatted_line = '%s %s'%(continuation, line)
if not is_suppress:
ret.append(formatted_line)
- if not is_suppress:
- if len(rest.strip()):
- if is_verbatim:
- # the "rest" is the standard output of the
- # input, which needs to be added in
- # verbatim mode
- ret.append(rest)
+ if not is_suppress and len(rest.strip()) and is_verbatim:
+ # the "rest" is the standard output of the
+ # input, which needs to be added in
+ # verbatim mode
+ ret.append(rest)
self.cout.seek(0)
output = self.cout.read()
if not is_suppress and not is_semicolon:
- ret.append(output.decode('utf-8'))
+ ret.append(output)
+ elif is_semicolon: # get spacing right
+ ret.append('')
if not is_okexcept and "Traceback" in output:
sys.stdout.write(output)
self.cout.truncate(0)
- return (ret, input_lines, output, is_doctest, image_file,
- image_directive)
- # print('OUTPUT', output) # dbg
+ return (ret, input_lines, output, is_doctest, decorator, image_file,
+ image_directive)
+
def process_output(self, data, output_prompt,
- input_lines, output, is_doctest, image_file):
- """Process data block for OUTPUT token."""
- if is_doctest:
- submitted = data.strip()
- found = output
- if found is not None:
- found = found.strip()
+ input_lines, output, is_doctest, decorator, image_file):
+ """
+ Process data block for OUTPUT token.
- # XXX - fperez: in 0.11, 'output' never comes with the prompt
- # in it, just the actual output text. So I think all this code
- # can be nuked...
+ """
+ TAB = ' ' * 4
- # the above comment does not appear to be accurate... (minrk)
+ if is_doctest and output is not None:
- ind = found.find(output_prompt)
- if ind < 0:
- e = 'output prompt="%s" does not match out line=%s' % \
- (output_prompt, found)
- raise RuntimeError(e)
- found = found[len(output_prompt):].strip()
+ found = output
+ found = found.strip()
+ submitted = data.strip()
+ if self.directive is None:
+ source = 'Unavailable'
+ content = 'Unavailable'
+ else:
+ source = self.directive.state.document.current_source
+ content = self.directive.content
+ # Add tabs and join into a single string.
+ content = '\n'.join([TAB + line for line in content])
+
+ # Make sure the output contains the output prompt.
+ ind = found.find(output_prompt)
+ if ind < 0:
+ e = ('output does not contain output prompt\n\n'
+ 'Document source: {0}\n\n'
+ 'Raw content: \n{1}\n\n'
+ 'Input line(s):\n{TAB}{2}\n\n'
+ 'Output line(s):\n{TAB}{3}\n\n')
+ e = e.format(source, content, '\n'.join(input_lines),
+ repr(found), TAB=TAB)
+ raise RuntimeError(e)
+ found = found[len(output_prompt):].strip()
+
+ # Handle the actual doctest comparison.
+ if decorator.strip() == '@doctest':
+ # Standard doctest
if found != submitted:
- e = ('doctest failure for input_lines="%s" with '
- 'found_output="%s" and submitted output="%s"' %
- (input_lines, found, submitted))
+ e = ('doctest failure\n\n'
+ 'Document source: {0}\n\n'
+ 'Raw content: \n{1}\n\n'
+ 'On input line(s):\n{TAB}{2}\n\n'
+ 'we found output:\n{TAB}{3}\n\n'
+ 'instead of the expected:\n{TAB}{4}\n\n')
+ e = e.format(source, content, '\n'.join(input_lines),
+ repr(found), repr(submitted), TAB=TAB)
raise RuntimeError(e)
- # print('''doctest PASSED for input_lines="%s" with
- # found_output="%s" and submitted output="%s"''' % (input_lines,
- # found, submitted))
+ else:
+ self.custom_doctest(decorator, input_lines, found, submitted)
def process_comment(self, data):
"""Process data fPblock for COMMENT token."""
@@ -406,7 +510,8 @@ def save_image(self, image_file):
self.ensure_pyplot()
command = ('plt.gcf().savefig("%s", bbox_inches="tight", '
'dpi=100)' % image_file)
- # print('SAVEFIG', command) # dbg
+
+ #print 'SAVEFIG', command # dbg
self.process_input_line('bookmark ipy_thisdir', store_history=False)
self.process_input_line('cd -b ipy_savedir', store_history=False)
self.process_input_line(command, store_history=False)
@@ -432,14 +537,14 @@ def process_block(self, block):
if token == COMMENT:
out_data = self.process_comment(data)
elif token == INPUT:
- (out_data, input_lines, output, is_doctest, image_file,
- image_directive) = \
- self.process_input(data, input_prompt, lineno)
+ (out_data, input_lines, output, is_doctest, decorator,
+ image_file, image_directive) = \
+ self.process_input(data, input_prompt, lineno)
elif token == OUTPUT:
out_data = \
self.process_output(data, output_prompt,
input_lines, output, is_doctest,
- image_file)
+ decorator, image_file)
if out_data:
ret.extend(out_data)
@@ -450,110 +555,47 @@ def process_block(self, block):
return ret, image_directive
def ensure_pyplot(self):
- if self._pyplot_imported:
- return
- self.process_input_line('import matplotlib.pyplot as plt',
- store_history=False)
-
- def process_pure_python(self, content):
"""
- content is a list of strings. it is unedited directive conent
-
- This runs it line by line in the InteractiveShell, prepends
- prompts as needed capturing stderr and stdout, then returns
- the content as a list as if it were ipython code
- """
- output = []
- savefig = False # keep up with this to clear figure
- multiline = False # to handle line continuation
- fmtin = self.promptin
-
- for lineno, line in enumerate(content):
-
- line_stripped = line.strip()
-
- if not len(line):
- output.append(line) # preserve empty lines in output
- continue
-
- # handle decorators
- if line_stripped.startswith('@'):
- output.extend([line])
- if 'savefig' in line:
- savefig = True # and need to clear figure
- continue
-
- # handle comments
- if line_stripped.startswith('#'):
- output.extend([line])
- continue
+ Ensures that pyplot has been imported into the embedded IPython shell.
- # deal with multilines
- if not multiline: # not currently on a multiline
+ Also, makes sure to set the backend appropriately if not set already.
- if line_stripped.endswith('\\'): # now we are
- multiline = True
- cont_len = len(str(lineno)) + 2
- line_to_process = line.strip('\\')
- output.extend([u"%s %s" % (fmtin % lineno, line)])
- continue
- else: # no we're still not
- line_to_process = line.strip('\\')
- else: # we are currently on a multiline
- line_to_process += line.strip('\\')
- if line_stripped.endswith('\\'): # and we still are
- continuation = '.' * cont_len
- output.extend(
- [(u' %s: ' + line_stripped) % continuation])
- continue
- # else go ahead and run this multiline then carry on
-
- # get output of line
- self.process_input_line(unicode(line_to_process.strip()),
+ """
+ # We are here if the @figure pseudo decorator was used. Thus, it's
+ # possible that we could be here even if python_mplbackend were set to
+ # `None`. That's also strange and perhaps worthy of raising an
+ # exception, but for now, we just set the backend to 'agg'.
+
+ if not self._pyplot_imported:
+ if 'matplotlib.backends' not in sys.modules:
+ # Then ipython_matplotlib was set to None but there was a
+ # call to the @figure decorator (and ipython_execlines did
+ # not set a backend).
+ #raise Exception("No backend was set, but @figure was used!")
+ import matplotlib
+ matplotlib.use('agg')
+
+ # Always import pyplot into embedded shell.
+ self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
- out_line = self.cout.getvalue()
- self.clear_cout()
-
- # clear current figure if plotted
- if savefig:
- self.ensure_pyplot()
- self.process_input_line('plt.clf()', store_history=False)
- self.clear_cout()
- savefig = False
-
- # line numbers don't actually matter, they're replaced later
- if not multiline:
- in_line = u"%s %s" % (fmtin % lineno, line)
-
- output.extend([in_line])
- else:
- output.extend([(u' %s: ' + line_stripped) % continuation])
- multiline = False
- if len(out_line):
- output.extend([out_line])
- output.extend([u''])
-
- return output
+ self._pyplot_imported = True
- def process_pure_python2(self, content):
+ def process_pure_python(self, content):
"""
- content is a list of strings. it is unedited directive conent
+ content is a list of strings. it is unedited directive content
This runs it line by line in the InteractiveShell, prepends
prompts as needed capturing stderr and stdout, then returns
the content as a list as if it were ipython code
"""
output = []
- savefig = False # keep up with this to clear figure
- multiline = False # to handle line continuation
+ savefig = False # keep up with this to clear figure
+ multiline = False # to handle line continuation
multiline_start = None
fmtin = self.promptin
ct = 0
- # nuke empty lines
- content = [line for line in content if len(line.strip()) > 0]
-
for lineno, line in enumerate(content):
line_stripped = line.strip()
@@ -565,7 +607,7 @@ def process_pure_python2(self, content):
if line_stripped.startswith('@'):
output.extend([line])
if 'savefig' in line:
- savefig = True # and need to clear figure
+ savefig = True # and need to clear figure
continue
# handle comments
@@ -573,7 +615,8 @@ def process_pure_python2(self, content):
output.extend([line])
continue
- continuation = u' %s:' % ''.join(['.'] * (len(str(ct)) + 2))
+ # deal with lines checking for multiline
+ continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2))
if not multiline:
modified = u"%s %s" % (fmtin % ct, line_stripped)
output.append(modified)
@@ -581,54 +624,70 @@ def process_pure_python2(self, content):
try:
ast.parse(line_stripped)
output.append(u'')
- except Exception:
+ except Exception: # on a multiline
multiline = True
multiline_start = lineno
- else:
+ else: # still on a multiline
modified = u'%s %s' % (continuation, line)
output.append(modified)
- try:
- ast.parse('\n'.join(content[multiline_start:lineno + 1]))
-
- if (lineno < len(content) - 1 and
- _count_indent(content[multiline_start]) <
- _count_indent(content[lineno + 1])):
-
+ # if the next line is indented, it should be part of multiline
+ if len(content) > lineno + 1:
+ nextline = content[lineno + 1]
+ if len(nextline) - len(nextline.lstrip()) > 3:
continue
-
- output.extend([continuation, u''])
- multiline = False
+ try:
+ mod = ast.parse(
+ '\n'.join(content[multiline_start:lineno+1]))
+ if isinstance(mod.body[0], ast.FunctionDef):
+ # check to see if we have the whole function
+ for element in mod.body[0].body:
+ if isinstance(element, ast.Return):
+ multiline = False
+ else:
+ output.append(u'')
+ multiline = False
except Exception:
pass
- continue
+ if savefig: # clear figure if plotted
+ self.ensure_pyplot()
+ self.process_input_line('plt.clf()', store_history=False)
+ self.clear_cout()
+ savefig = False
return output
+ def custom_doctest(self, decorator, input_lines, found, submitted):
+ """
+ Perform a specialized doctest.
+
+ """
+ from .custom_doctests import doctests
-def _count_indent(x):
- import re
- m = re.match('(\s+)(.*)', x)
- if not m:
- return 0
- return len(m.group(1))
+ args = decorator.split()
+ doctest_type = args[1]
+ if doctest_type in doctests:
+ doctests[doctest_type](self, args, input_lines, found, submitted)
+ else:
+ e = "Invalid option to @doctest: {0}".format(doctest_type)
+ raise Exception(e)
-class IpythonDirective(Directive):
+class IPythonDirective(Directive):
has_content = True
required_arguments = 0
- optional_arguments = 4 # python, suppress, verbatim, doctest
+ optional_arguments = 4 # python, suppress, verbatim, doctest
final_argumuent_whitespace = True
- option_spec = {'python': directives.unchanged,
- 'suppress': directives.flag,
- 'verbatim': directives.flag,
- 'doctest': directives.flag,
- 'okexcept': directives.flag,
- }
+ option_spec = { 'python': directives.unchanged,
+ 'suppress' : directives.flag,
+ 'verbatim' : directives.flag,
+ 'doctest' : directives.flag,
+ 'okexcept': directives.flag
+ }
- shell = EmbeddedSphinxShell()
+ shell = None
seen_docs = set()
@@ -643,28 +702,53 @@ def get_config_options(self):
if savefig_dir is None:
savefig_dir = config.html_static_path
if isinstance(savefig_dir, list):
- savefig_dir = savefig_dir[0] # safe to assume only one path?
+ savefig_dir = savefig_dir[0] # safe to assume only one path?
savefig_dir = os.path.join(confdir, savefig_dir)
# get regex and prompt stuff
- rgxin = config.ipython_rgxin
- rgxout = config.ipython_rgxout
- promptin = config.ipython_promptin
- promptout = config.ipython_promptout
+ rgxin = config.ipython_rgxin
+ rgxout = config.ipython_rgxout
+ promptin = config.ipython_promptin
+ promptout = config.ipython_promptout
+ mplbackend = config.ipython_mplbackend
+ exec_lines = config.ipython_execlines
+ hold_count = config.ipython_holdcount
- return savefig_dir, source_dir, rgxin, rgxout, promptin, promptout
+ return (savefig_dir, source_dir, rgxin, rgxout,
+ promptin, promptout, mplbackend, exec_lines, hold_count)
def setup(self):
-
+ # Get configuration values.
+ (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout,
+ mplbackend, exec_lines, hold_count) = self.get_config_options()
+
+ if self.shell is None:
+ # We will be here many times. However, when the
+ # EmbeddedSphinxShell is created, its interactive shell member
+ # is the same for each instance.
+
+ if mplbackend:
+ import matplotlib
+ # Repeated calls to use() will not hurt us since `mplbackend`
+ # is the same each time.
+ matplotlib.use(mplbackend)
+
+ # Must be called after (potentially) importing matplotlib and
+ # setting its backend since exec_lines might import pylab.
+ self.shell = EmbeddedSphinxShell(exec_lines)
+
+ # Store IPython directive to enable better error messages
+ self.shell.directive = self
+
+ # reset the execution count if we haven't processed this doc
+ #NOTE: this may be borked if there are multiple seen_doc tmp files
+ #check time stamp?
if not self.state.document.current_source in self.seen_docs:
self.shell.IP.history_manager.reset()
self.shell.IP.execution_count = 1
+ self.shell.IP.prompt_manager.width = 0
self.seen_docs.add(self.state.document.current_source)
- # get config values
- (savefig_dir, source_dir, rgxin,
- rgxout, promptin, promptout) = self.get_config_options()
-
# and attach to shell so we don't have to pass them around
self.shell.rgxin = rgxin
self.shell.rgxout = rgxout
@@ -672,10 +756,10 @@ def setup(self):
self.shell.promptout = promptout
self.shell.savefig_dir = savefig_dir
self.shell.source_dir = source_dir
+ self.shell.hold_count = hold_count
# setup bookmark for saving figures directory
-
- self.shell.process_input_line('bookmark ipy_savedir %s' % savefig_dir,
+ self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir,
store_history=False)
self.shell.clear_cout()
@@ -690,7 +774,7 @@ def teardown(self):
def run(self):
debug = False
- # TODO, any reason block_parser can't be a method of embeddable shell
+ #TODO, any reason block_parser can't be a method of embeddable shell
# then we wouldn't have to carry these around
rgxin, rgxout, promptin, promptout = self.setup()
@@ -699,12 +783,11 @@ def run(self):
self.shell.is_doctest = 'doctest' in options
self.shell.is_verbatim = 'verbatim' in options
self.shell.is_okexcept = 'okexcept' in options
- self.shell.current_content = self.content
# handle pure python code
if 'python' in self.arguments:
content = self.content
- self.content = self.shell.process_pure_python2(content)
+ self.content = self.shell.process_pure_python(content)
parts = '\n'.join(self.content).split('\n\n')
@@ -712,65 +795,60 @@ def run(self):
figures = []
for part in parts:
-
block = block_parser(part, rgxin, rgxout, promptin, promptout)
-
if len(block):
rows, figure = self.shell.process_block(block)
for row in rows:
- # hack
- # if row == '':
- # continue
-
- # lines.extend([' %s'% row.strip()])
- lines.extend([' %s' % line
- for line in re.split('[\n]+', row)])
+ lines.extend([' %s'%line for line in row.split('\n')])
if figure is not None:
figures.append(figure)
- # text = '\n'.join(lines)
- # figs = '\n'.join(figures)
-
for figure in figures:
lines.append('')
lines.extend(figure.split('\n'))
lines.append('')
- # print(lines)
- if len(lines) > 2:
+ if len(lines)>2:
if debug:
print('\n'.join(lines))
- else: # NOTE: this raises some errors, what's it for?
- # print('INSERTING %d lines' % len(lines))
+ else:
+ # This has to do with input, not output. But if we comment
+ # these lines out, then no IPython code will appear in the
+ # final output.
self.state_machine.insert_input(
lines, self.state_machine.input_lines.source(0))
- text = '\n'.join(lines)
- txtnode = nodes.literal_block(text, text)
- txtnode['language'] = 'ipython'
- # imgnode = nodes.image(figs)
-
# cleanup
self.teardown()
- return [] # , imgnode]
+ return []
# Enable as a proper Sphinx directive
-
-
def setup(app):
setup.app = app
- app.add_directive('ipython', IpythonDirective)
- app.add_config_value('ipython_savefig_dir', None, True)
+ app.add_directive('ipython', IPythonDirective)
+ app.add_config_value('ipython_savefig_dir', None, 'env')
app.add_config_value('ipython_rgxin',
- re.compile('In \[(\d+)\]:\s?(.*)\s*'), True)
+ re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env')
app.add_config_value('ipython_rgxout',
- re.compile('Out\[(\d+)\]:\s?(.*)\s*'), True)
- app.add_config_value('ipython_promptin', 'In [%d]:', True)
- app.add_config_value('ipython_promptout', 'Out[%d]:', True)
+ re.compile('Out\[(\d+)\]:\s?(.*)\s*'), 'env')
+ app.add_config_value('ipython_promptin', 'In [%d]:', 'env')
+ app.add_config_value('ipython_promptout', 'Out[%d]:', 'env')
+
+ # We could just let matplotlib pick whatever is specified as the default
+ # backend in the matplotlibrc file, but this would cause issues if the
+ # backend didn't work in headless environments. For this reason, 'agg'
+ # is a good default backend choice.
+ app.add_config_value('ipython_mplbackend', 'agg', 'env')
+ # If the user sets this config value to `None`, then EmbeddedSphinxShell's
+ # __init__ method will treat it as [].
+ execlines = ['import numpy as np', 'import matplotlib.pyplot as plt']
+ app.add_config_value('ipython_execlines', execlines, 'env')
+
+ app.add_config_value('ipython_holdcount', True, 'env')
# Simple smoke test, needs to be converted to a proper automatic test.
def test():
@@ -808,18 +886,18 @@ def test():
In [3]: x.st<TAB>
x.startswith x.strip
""",
- r"""
+ r"""
In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
.....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
-In [131]: print(url.split('&'))
+In [131]: print url.split('&')
['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
In [60]: import urllib
""",
- r"""\
+ r"""\
In [133]: import numpy.random
@@ -842,13 +920,12 @@ def test():
""",
- r"""
-In [106]: print(x)
+ r"""
+In [106]: print x
jdh
In [109]: for i in range(10):
- n
-.....: print(i)
+ .....: print i
.....:
.....:
0
@@ -889,7 +966,7 @@ def test():
In [151]: hist(np.random.randn(10000), 100);
""",
- r"""
+ r"""
# update the current fig
In [151]: ylabel('number')
@@ -899,24 +976,51 @@ def test():
@savefig hist_with_text.png
In [153]: grid(True)
+@doctest float
+In [154]: 0.1 + 0.2
+Out[154]: 0.3
+
+@doctest float
+In [155]: np.arange(16).reshape(4,4)
+Out[155]:
+array([[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11],
+ [12, 13, 14, 15]])
+
+In [1]: x = np.arange(16, dtype=float).reshape(4,4)
+
+In [2]: x[0,0] = np.inf
+
+In [3]: x[0,1] = np.nan
+
+@doctest float
+In [4]: x
+Out[4]:
+array([[ inf, nan, 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [ 12., 13., 14., 15.]])
+
+
""",
- ]
+ ]
# skip local-file depending first example:
examples = examples[1:]
- # ipython_directive.DEBUG = True # dbg
- # options = dict(suppress=True) # dbg
+ #ipython_directive.DEBUG = True # dbg
+ #options = dict(suppress=True) # dbg
options = dict()
for example in examples:
content = example.split('\n')
- ipython_directive('debug', arguments=None, options=options,
+ IPythonDirective('debug', arguments=None, options=options,
content=content, lineno=0,
content_offset=None, block_text=None,
state=None, state_machine=None,
)
# Run test suite as a script
-if __name__ == '__main__':
+if __name__=='__main__':
if not os.path.isdir('_static'):
os.mkdir('_static')
test()
| https://github.com/ipython/ipython/pull/4570
We'd prefer to get rid of the duplication, but we have some tweaks in place
which ipython does not.
I rebased everythingon top of ipython to generae a clean diff, if they pick it up
we can make the transition, otherwise we synched for now.
cc @takluyver, if you're interested, check the diff between 2e3c608 and 82b8c3a
for an unobstructed view.
@jorisvandenbossche, can you check this out and let me know if I missed anything?
I included the cython magic fixes you pointed out.
related https://github.com/pydata/pandas/issues/5221
| https://api.github.com/repos/pandas-dev/pandas/pulls/5925 | 2014-01-13T18:15:06Z | 2014-01-18T16:30:29Z | 2014-01-18T16:30:28Z | 2014-06-16T03:52:02Z |
Fixes to docs, eliminate scikits.timeseries docs dep, sphinx 1.2, update copyright years | diff --git a/doc/source/_templates/autosummary/class.rst b/doc/source/_templates/autosummary/class.rst
deleted file mode 100644
index a9c9bd2b6507f..0000000000000
--- a/doc/source/_templates/autosummary/class.rst
+++ /dev/null
@@ -1,33 +0,0 @@
-{% extends "!autosummary/class.rst" %}
-
-{% block methods %}
-{% if methods %}
-
-..
- HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages.
- .. autosummary::
- :toctree:
- {% for item in all_methods %}
- {%- if not item.startswith('_') or item in ['__call__'] %}
- {{ name }}.{{ item }}
- {%- endif -%}
- {%- endfor %}
-
-{% endif %}
-{% endblock %}
-
-{% block attributes %}
-{% if attributes %}
-
-..
- HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages.
- .. autosummary::
- :toctree:
- {% for item in all_attributes %}
- {%- if not item.startswith('_') %}
- {{ name }}.{{ item }}
- {%- endif -%}
- {%- endfor %}
-
-{% endif %}
-{% endblock %}
diff --git a/doc/source/conf.py b/doc/source/conf.py
index 8e8ac4a61acf5..c3c946a5180ba 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -12,6 +12,7 @@
import sys
import os
+from pandas.compat import u
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
@@ -63,8 +64,8 @@
master_doc = 'index'
# General information about the project.
-project = u'pandas'
-copyright = u'2008-2012, the pandas development team'
+project = u('pandas')
+copyright = u('2008-2014, the pandas development team')
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -211,8 +212,8 @@
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'pandas.tex',
- u'pandas: powerful Python data analysis toolkit',
- u'Wes McKinney\n\& PyData Development Team', 'manual'),
+ u('pandas: powerful Python data analysis toolkit'),
+ u('Wes McKinney\n\& PyData Development Team'), 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
diff --git a/doc/source/faq.rst b/doc/source/faq.rst
index d64b799a865d1..c826d95e9c1d7 100644
--- a/doc/source/faq.rst
+++ b/doc/source/faq.rst
@@ -181,17 +181,7 @@ Frequency conversion
Frequency conversion is implemented using the ``resample`` method on TimeSeries
and DataFrame objects (multiple time series). ``resample`` also works on panels
-(3D). Here is some code that resamples daily data to montly with
-scikits.timeseries:
-
-.. ipython:: python
-
- import scikits.timeseries as ts
- data = ts.time_series(np.random.randn(50), start_date='Jan-2000', freq='M')
- data
- data.convert('A', func=np.mean)
-
-Here is the equivalent pandas code:
+(3D). Here is some code that resamples daily data to montly:
.. ipython:: python
| closes #5836
closes #5899, following @jorisvandenbossche's advice
| https://api.github.com/repos/pandas-dev/pandas/pulls/5921 | 2014-01-13T16:29:28Z | 2014-01-13T16:30:15Z | 2014-01-13T16:30:15Z | 2014-06-18T06:57:11Z |
BUG: Bug in idxmin/max with object dtypes (GH5914) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 5db01e97531a5..83caba53375f0 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -86,6 +86,7 @@ Bug Fixes
- Testing bug in reading json/msgpack from a non-filepath on windows under py3 (:issue:`5874`)
- Bug when assigning to .ix[tuple(...)] (:issue:`5896`)
- Bug in fully reindexing a Panel (:issue:`5905`)
+ - Bug in idxmin/max with object dtypes (:issue:`5914`)
pandas 0.13.0
-------------
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 3b7320b848f9b..2722905bf49c0 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -171,6 +171,9 @@ def _get_values(values, skipna, fill_value=None, fill_value_typ=None,
def _isfinite(values):
if issubclass(values.dtype.type, (np.timedelta64, np.datetime64)):
return isnull(values)
+ elif isinstance(values.dtype, object):
+ return -np.isfinite(values.astype('float64'))
+
return -np.isfinite(values)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 5a4cbf1a6e16e..699ffb592a63e 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -3258,6 +3258,20 @@ def test_idxmax(self):
result = s.idxmax()
self.assert_(result == 4)
+ # Float64Index
+ # GH 5914
+ s = pd.Series([1,2,3],[1.1,2.1,3.1])
+ result = s.idxmax()
+ self.assert_(result == 3.1)
+ result = s.idxmin()
+ self.assert_(result == 1.1)
+
+ s = pd.Series(s.index, s.index)
+ result = s.idxmax()
+ self.assert_(result == 3.1)
+ result = s.idxmin()
+ self.assert_(result == 1.1)
+
def test_ndarray_compat(self):
# test numpy compat with Series as sub-class of NDFrame
| closes #5914
| https://api.github.com/repos/pandas-dev/pandas/pulls/5918 | 2014-01-13T12:57:39Z | 2014-01-13T13:16:06Z | 2014-01-13T13:16:06Z | 2014-06-26T01:25:52Z |
BLD: consider version tags only when using git-describe to gen version string | diff --git a/setup.py b/setup.py
index 4e9dd94a72abe..1c82da240af4d 100755
--- a/setup.py
+++ b/setup.py
@@ -203,7 +203,7 @@ def build_extensions(self):
pipe = None
for cmd in ['git','git.cmd']:
try:
- pipe = subprocess.Popen([cmd, "describe", "--always"],
+ pipe = subprocess.Popen([cmd, "describe", "--always", "--match", "v[0-9]*"],
stdout=subprocess.PIPE)
(so,serr) = pipe.communicate()
if pipe.returncode == 0:
| On master we use tags strictly to indicate releases.
In other clones, this may not be the case. Specifically, jenkins
sometimes likes to tags each build which can wreak [havoc](http://pandas.pydata.org/pandas-build/dev/) when
using git-describe naively to generate version strings.
git allows you to filter the tags to consider when constructing the version string. well then.
I tested this locally of course, but as always with changes to setup.py - duck and cover.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5916 | 2014-01-13T07:11:21Z | 2014-01-13T07:11:37Z | 2014-01-13T07:11:37Z | 2014-07-16T08:46:06Z |
BUG: dt+BDay(n) wrong if n>5, n%5==0 and dt not on offset (GH5890) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 83caba53375f0..d025baa66aa88 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -87,6 +87,7 @@ Bug Fixes
- Bug when assigning to .ix[tuple(...)] (:issue:`5896`)
- Bug in fully reindexing a Panel (:issue:`5905`)
- Bug in idxmin/max with object dtypes (:issue:`5914`)
+ - Bug in ``BusinessDay`` when adding n days to a date not on offset when n>5 and n%5==0 (:issue:`5890`)
pandas 0.13.0
-------------
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index b763fc6b11252..ab9f49ddd321e 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -397,7 +397,9 @@ def apply(self, other):
if n < 0 and result.weekday() > 4:
n += 1
n -= 5 * k
-
+ if n == 0 and result.weekday() > 4:
+ n -= 1
+
while n != 0:
k = n // abs(n)
result = result + timedelta(k)
diff --git a/pandas/tseries/tests/test_offsets.py b/pandas/tseries/tests/test_offsets.py
index 047bd244fef93..a3c63966948ee 100644
--- a/pandas/tseries/tests/test_offsets.py
+++ b/pandas/tseries/tests/test_offsets.py
@@ -317,6 +317,11 @@ def test_apply_large_n(self):
rs = st + off
xp = datetime(2011, 12, 26)
self.assertEqual(rs, xp)
+
+ off = BDay() * 10
+ rs = datetime(2014, 1, 5) + off # see #5890
+ xp = datetime(2014, 1, 17)
+ self.assertEqual(rs, xp)
def test_apply_corner(self):
self.assertRaises(TypeError, BDay().apply, BMonthEnd())
| closes #5890
| https://api.github.com/repos/pandas-dev/pandas/pulls/5911 | 2014-01-12T03:01:12Z | 2014-01-13T16:18:13Z | 2014-01-13T16:18:13Z | 2014-06-25T21:56:45Z |
docstring grammar. | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0f49c976d00a3..47ec392a1135a 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -718,7 +718,7 @@ def from_records(cls, data, index=None, exclude=None, columns=None,
exclude : sequence, default None
Columns or fields to exclude
columns : sequence, default None
- Column names to use. If the passed data do not have named
+ Column names to use. If the passed data do not have names
associated with them, this argument provides names for the
columns. Otherwise this argument indicates the order of the columns
in the result (any names not found in the data will become all-NA
| named should be names
| https://api.github.com/repos/pandas-dev/pandas/pulls/5910 | 2014-01-11T22:54:23Z | 2014-01-11T23:07:19Z | 2014-01-11T23:07:19Z | 2014-07-16T08:46:02Z |
DOC: Add "How to reduce a sequence (e.g. of Series) using a binary opera... | diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst
index 624a1188f5957..4cbee3e79a2f1 100644
--- a/doc/source/cookbook.rst
+++ b/doc/source/cookbook.rst
@@ -20,7 +20,7 @@
Cookbook
********
-This is a respository for *short and sweet* examples and links for useful pandas recipes.
+This is a repository for *short and sweet* examples and links for useful pandas recipes.
We encourage users to add to this documentation.
This is a great *First Pull Request* (to add interesting links and/or put short code inline
@@ -45,9 +45,13 @@ These are some neat pandas ``idioms``
`How to select from a frame with complex criteria?
<http://stackoverflow.com/questions/15315452/selecting-with-complex-criteria-from-pandas-dataframe>`__
-`Select rows closest to a user defined numer
+`Select rows closest to a user-defined number
<http://stackoverflow.com/questions/17758023/return-rows-in-a-dataframe-closest-to-a-user-defined-number>`__
+`How to reduce a sequence (e.g. of Series) using a binary operator
+<http://stackoverflow.com/questions/21058254/pandas-boolean-operation-in-a-python-list/21058331>`__
+
+
.. _cookbook.selection:
Selection
@@ -90,7 +94,7 @@ The :ref:`multindexing <indexing.hierarchical>` docs.
Arithmetic
~~~~~~~~~~
-`Performing arithmetic with a multi-index that needs broadcastin
+`Performing arithmetic with a multi-index that needs broadcasting
<http://stackoverflow.com/questions/19501510/divide-entire-pandas-multiindex-dataframe-by-dataframe-variable/19502176#19502176>`__
Slicing
@@ -221,7 +225,7 @@ The :ref:`Pivot <reshaping.pivot>` docs.
Apply
~~~~~
-`Turning embeded lists into a multi-index frame
+`Turning embedded lists into a multi-index frame
<http://stackoverflow.com/questions/17349981/converting-pandas-dataframe-with-categorical-values-into-binary-values>`__
`Rolling apply with a DataFrame returning a Series
@@ -242,8 +246,8 @@ Timeseries
`Vectorized Lookup
<http://stackoverflow.com/questions/13893227/vectorized-look-up-of-values-in-pandas-dataframe>`__
-Turn a matrix with hours in columns and days in rows into a continous row sequence in the form of a time series.
-`How to rearrange a python pandas dataframe?
+Turn a matrix with hours in columns and days in rows into a continuous row sequence in the form of a time series.
+`How to rearrange a python pandas DataFrame?
<http://stackoverflow.com/questions/15432659/how-to-rearrange-a-python-pandas-dataframe>`__
.. _cookbook.resample:
@@ -354,7 +358,7 @@ The :ref:`CSV <io.read_csv_table>` docs
`Reading the first few lines of a frame
<http://stackoverflow.com/questions/15008970/way-to-read-first-few-lines-for-pandas-dataframe>`__
-Reading a file that is compressed but not by ``gzip/bz2`` (the native compresed formats which ``read_csv`` understands).
+Reading a file that is compressed but not by ``gzip/bz2`` (the native compressed formats which ``read_csv`` understands).
This example shows a ``WinZipped`` file, but is a general application of opening the file within a context manager and
using that handle to read.
`See here
@@ -410,13 +414,13 @@ The :ref:`HDFStores <io.hdf5>` docs
`Simple Queries with a Timestamp Index
<http://stackoverflow.com/questions/13926089/selecting-columns-from-pandas-hdfstore-table>`__
-`Managing heteregenous data using a linked multiple table hierarchy
+`Managing heterogeneous data using a linked multiple table hierarchy
<http://github.com/pydata/pandas/issues/3032>`__
`Merging on-disk tables with millions of rows
<http://stackoverflow.com/questions/14614512/merging-two-tables-with-millions-of-rows-in-python/14617925#14617925>`__
-Deduplicating a large store by chunks, essentially a recusive reduction operation. Shows a function for taking in data from
+Deduplicating a large store by chunks, essentially a recursive reduction operation. Shows a function for taking in data from
csv file and creating a store by chunks, with date parsing as well.
`See here
<http://stackoverflow.com/questions/16110252/need-to-compare-very-large-files-around-1-5gb-in-python/16110391#16110391>`__
| ...tor"
MAINT: Fixed some typos
| https://api.github.com/repos/pandas-dev/pandas/pulls/5907 | 2014-01-11T17:39:55Z | 2014-01-11T18:29:52Z | 2014-01-11T18:29:52Z | 2014-06-14T21:09:21Z |
BUG: Bug in fully reindexing a Panel (GH5905) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 61e275b0eb0f6..5db01e97531a5 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -85,6 +85,7 @@ Bug Fixes
- Bug in internal caching, related to (:issue:`5727`)
- Testing bug in reading json/msgpack from a non-filepath on windows under py3 (:issue:`5874`)
- Bug when assigning to .ix[tuple(...)] (:issue:`5896`)
+ - Bug in fully reindexing a Panel (:issue:`5905`)
pandas 0.13.0
-------------
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index 84860b398c23b..b6cd643f47c5a 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -585,41 +585,8 @@ def tail(self, n=5):
raise NotImplementedError
def _needs_reindex_multi(self, axes, method, level):
- # only allowing multi-index on Panel (and not > dims)
- return (method is None and
- not self._is_mixed_type and
- self._AXIS_LEN <= 3 and
- com._count_not_none(*axes.values()) == 3)
-
- def _reindex_multi(self, axes, copy, fill_value):
- """ we are guaranteed non-Nones in the axes! """
- items = axes['items']
- major = axes['major_axis']
- minor = axes['minor_axis']
- a0, a1, a2 = len(items), len(major), len(minor)
-
- values = self.values
- new_values = np.empty((a0, a1, a2), dtype=values.dtype)
-
- new_items, indexer0 = self.items.reindex(items)
- new_major, indexer1 = self.major_axis.reindex(major)
- new_minor, indexer2 = self.minor_axis.reindex(minor)
-
- if indexer0 is None:
- indexer0 = lrange(len(new_items))
-
- if indexer1 is None:
- indexer1 = lrange(len(new_major))
-
- if indexer2 is None:
- indexer2 = lrange(len(new_minor))
-
- for i, ind in enumerate(indexer0):
- com.take_2d_multi(values[ind], (indexer1, indexer2),
- out=new_values[i])
-
- return Panel(new_values, items=new_items, major_axis=new_major,
- minor_axis=new_minor)
+ """ don't allow a multi reindex on Panel or above ndim """
+ return False
def dropna(self, axis=0, how='any', inplace=False, **kwargs):
"""
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 1122b4c7dcfb4..30500ac57a7f6 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1082,14 +1082,6 @@ def test_reindex(self):
result = self.panel.reindex(minor=new_minor)
assert_frame_equal(result['ItemB'], ref.reindex(columns=new_minor))
- result = self.panel.reindex(items=self.panel.items,
- major=self.panel.major_axis,
- minor=self.panel.minor_axis)
-
- self.assert_(result.items is self.panel.items)
- self.assert_(result.major_axis is self.panel.major_axis)
- self.assert_(result.minor_axis is self.panel.minor_axis)
-
# this ok
result = self.panel.reindex()
assert_panel_equal(result,self.panel)
@@ -1110,6 +1102,46 @@ def test_reindex(self):
assert_panel_equal(result,self.panel)
self.assert_((result is self.panel) == True)
+ def test_reindex_multi(self):
+
+ # with and without copy full reindexing
+ result = self.panel.reindex(items=self.panel.items,
+ major=self.panel.major_axis,
+ minor=self.panel.minor_axis,
+ copy = False)
+
+ self.assert_(result.items is self.panel.items)
+ self.assert_(result.major_axis is self.panel.major_axis)
+ self.assert_(result.minor_axis is self.panel.minor_axis)
+
+ result = self.panel.reindex(items=self.panel.items,
+ major=self.panel.major_axis,
+ minor=self.panel.minor_axis,
+ copy = False)
+ assert_panel_equal(result,self.panel)
+
+ # multi-axis indexing consistency
+ # GH 5900
+ df = DataFrame(np.random.randn(4,3))
+ p = Panel({ 'Item1' : df })
+ expected = Panel({ 'Item1' : df })
+ expected['Item2'] = np.nan
+
+ items = ['Item1','Item2']
+ major_axis = np.arange(4)
+ minor_axis = np.arange(3)
+
+ results = []
+ results.append(p.reindex(items=items, major_axis=major_axis, copy=True))
+ results.append(p.reindex(items=items, major_axis=major_axis, copy=False))
+ results.append(p.reindex(items=items, minor_axis=minor_axis, copy=True))
+ results.append(p.reindex(items=items, minor_axis=minor_axis, copy=False))
+ results.append(p.reindex(items=items, major_axis=major_axis, minor_axis=minor_axis, copy=True))
+ results.append(p.reindex(items=items, major_axis=major_axis, minor_axis=minor_axis, copy=False))
+
+ for i, r in enumerate(results):
+ assert_panel_equal(expected,r)
+
def test_reindex_like(self):
# reindex_like
smaller = self.panel.reindex(items=self.panel.items[:-1],
| closes #5905
| https://api.github.com/repos/pandas-dev/pandas/pulls/5906 | 2014-01-11T14:58:51Z | 2014-01-11T15:15:28Z | 2014-01-11T15:15:28Z | 2014-07-16T08:45:59Z |
DOC: remove usage of code-block directive in docstrings + fix some warnings | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index 5a4c5cd5e23a2..a86c1aa4c0258 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -19,7 +19,7 @@ We'd like to make it easier for users to find these project, if you know of othe
substantial projects that you feel should be on this list, please let us know.
`Statsmodels <http://statsmodels.sourceforge.net>`__
------------
+----------------------------------------------------
Statsmodels is the prominent python "statistics and econometrics library" and it has
a long-standing special relationship with pandas. Statsmodels provides powerful statistics,
@@ -27,14 +27,14 @@ econometrics, analysis and modeling functionality that is out of pandas' scope.
Statsmodels leverages pandas objects as the underlying data container for computation.
`Vincent <https://github.com/wrobstory/vincent>`__
--------
+--------------------------------------------------
The `Vincent <https://github.com/wrobstory/vincent>`__ project leverages `Vega <https://github.com/trifacta/vega>`__
(that in turn, leverages `d3 <http://d3js.org/>`__) to create plots . It has great support
for pandas data objects.
`yhat/ggplot <https://github.com/yhat/ggplot>`__
------------
+------------------------------------------------
Hadley Wickham's `ggplot2 <http://ggplot2.org/>`__ is a foundational exploratory visualization package for the R language.
Based on `"The Grammer of Graphics" <http://www.cs.uic.edu/~wilkinson/TheGrammarOfGraphics/GOG.html>`__ it
@@ -46,7 +46,7 @@ progressing quickly in that direction.
`Seaborn <https://github.com/mwaskom/seaborn>`__
--------
+------------------------------------------------
Although pandas has quite a bit of "just plot it" functionality built-in, visualization and
in particular statistical graphics is a vast field with a long tradition and lots of ground
@@ -56,7 +56,7 @@ more advanced types of plots then those offered by pandas.
`Geopandas <https://github.com/kjordahl/geopandas>`__
----------
+------------------------------------------------------
Geopandas extends pandas data objects to include geographic information which support
geometric operations. If your work entails maps and geographical coordinates, and
diff --git a/pandas/core/series.py b/pandas/core/series.py
index c310358ab58f9..2e1d95cf87b47 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2094,21 +2094,8 @@ def isin(self, values):
----------
values : list-like
The sequence of values to test. Passing in a single string will
- raise a ``TypeError``:
-
- .. code-block:: python
-
- from pandas import Series
- s = Series(list('abc'))
- s.isin('a')
-
- Instead, turn a single string into a ``list`` of one element:
-
- .. code-block:: python
-
- from pandas import Series
- s = Series(list('abc'))
- s.isin(['a'])
+ raise a ``TypeError``. Instead, turn a single string into a
+ ``list`` of one element.
Returns
-------
@@ -2122,6 +2109,26 @@ def isin(self, values):
See Also
--------
pandas.DataFrame.isin
+
+ Examples
+ --------
+
+ >>> s = pd.Series(list('abc'))
+ >>> s.isin(['a', 'c', 'e'])
+ 0 True
+ 1 False
+ 2 True
+ dtype: bool
+
+ Passing a single string as ``s.isin('a')`` will raise an error. Use
+ a list of one element instead:
+
+ >>> s.isin(['a'])
+ 0 True
+ 1 False
+ 2 False
+ dtype: bool
+
"""
if not com.is_list_like(values):
raise TypeError("only list-like objects are allowed to be passed"
diff --git a/pandas/io/html.py b/pandas/io/html.py
index f3cfa3a16807a..e60630204a8b9 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -759,20 +759,16 @@ def read_html(io, match='.+', flavor=None, header=None, index_col=None,
This is a dictionary of attributes that you can pass to use to identify
the table in the HTML. These are not checked for validity before being
passed to lxml or Beautiful Soup. However, these attributes must be
- valid HTML table attributes to work correctly. For example,
-
- .. code-block:: python
-
- attrs = {'id': 'table'}
-
+ valid HTML table attributes to work correctly. For example, ::
+
+ attrs = {'id': 'table'}
+
is a valid attribute dictionary because the 'id' HTML tag attribute is
a valid HTML attribute for *any* HTML tag as per `this document
- <http://www.w3.org/TR/html-markup/global-attributes.html>`__.
-
- .. code-block:: python
-
- attrs = {'asdf': 'table'}
-
+ <http://www.w3.org/TR/html-markup/global-attributes.html>`__. ::
+
+ attrs = {'asdf': 'table'}
+
is *not* a valid attribute dictionary because 'asdf' is not a valid
HTML attribute even if it is a valid XML attribute. Valid HTML 4.01
table attributes can be found `here
| Some docs things:
- remove remaining use of `code-block`, closes #3430 (@y-p, I think that were the last ones, so now it can be really closed)
- fix some headers to avoid useless warnings during doc build (if the line under the header is not as long as the header itself, sphinx complains about it although it renders fine)
| https://api.github.com/repos/pandas-dev/pandas/pulls/5903 | 2014-01-10T21:48:16Z | 2014-01-12T00:33:24Z | 2014-01-12T00:33:24Z | 2014-07-02T21:28:19Z |
ENH/API: Add count parameter to limit generator in Series, DataFrame, and DataFrame.from_records() | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0f49c976d00a3..74b64818c1ae7 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -16,6 +16,7 @@
import collections
import warnings
import types
+from itertools import islice, chain
from numpy import nan as NA
import numpy as np
@@ -159,6 +160,8 @@ class DataFrame(NDFrame):
Data type to force, otherwise infer
copy : boolean, default False
Copy data from inputs. Only affects DataFrame / 2d ndarray input
+ count : int or None, when data it's a generator, number of values to
+ read. If None reads the whole generator
Examples
--------
@@ -185,7 +188,7 @@ def _constructor(self):
_constructor_sliced = Series
def __init__(self, data=None, index=None, columns=None, dtype=None,
- copy=False):
+ copy=False, count=None):
if data is None:
data = {}
if dtype is not None:
@@ -232,7 +235,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
copy=copy)
elif isinstance(data, (list, types.GeneratorType)):
if isinstance(data, types.GeneratorType):
- data = list(data)
+ data = list(islice(data, count))
if len(data) > 0:
if index is None and isinstance(data[0], Series):
index = _get_names_from_index(data)
@@ -705,7 +708,7 @@ def to_gbq(self, destination_table, schema=None, col_order=None,
@classmethod
def from_records(cls, data, index=None, exclude=None, columns=None,
- coerce_float=False, nrows=None):
+ coerce_float=False, count=None, nrows=None):
"""
Convert structured or record ndarray to DataFrame
@@ -726,24 +729,29 @@ def from_records(cls, data, index=None, exclude=None, columns=None,
coerce_float : boolean, default False
Attempt to convert values to non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
+ count : int or None, number of records to read from a generator.
+ If None reads the whole generator
Returns
-------
df : DataFrame
"""
+ #Deprecate undocumented nrows
+ if nrows is not None:
+ warnings.warn("nrows is deprecated, use count",
+ FutureWarning)
+ count = nrows
+
# Make a copy of the input columns so we can modify it
if columns is not None:
columns = _ensure_index(columns)
if com.is_iterator(data):
- if nrows == 0:
+ if count == 0:
return cls()
try:
- if compat.PY3:
- first_row = next(data)
- else:
- first_row = next(data)
+ first_row = next(data)
except StopIteration:
return cls(index=index, columns=columns)
@@ -751,19 +759,8 @@ def from_records(cls, data, index=None, exclude=None, columns=None,
if hasattr(first_row, 'dtype') and first_row.dtype.names:
dtype = first_row.dtype
- values = [first_row]
-
- # if unknown length iterable (generator)
- if nrows is None:
- # consume whole generator
- values += list(data)
- else:
- i = 1
- for row in data:
- values.append(row)
- i += 1
- if i >= nrows:
- break
+ # put the generator in a list
+ values = list(islice(chain([first_row], data), count))
if dtype is not None:
data = np.array(values, dtype=dtype)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index c310358ab58f9..87c8183643795 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2,6 +2,7 @@
Data structure for 1-dimensional cross-sectional and time series data
"""
from __future__ import division
+from itertools import islice
# pylint: disable=E1101,E1103
# pylint: disable=W0703,W0622,W0613,W0201
@@ -118,11 +119,13 @@ class Series(generic.NDFrame):
dtype : numpy.dtype or None
If None, dtype will be inferred
copy : boolean, default False, copy input data
+ count : int or None, number of values to read from a generator.
+ If None reads the whole generator
"""
_metadata = ['name']
def __init__(self, data=None, index=None, dtype=None, name=None,
- copy=False, fastpath=False):
+ copy=False, count=None, fastpath=False):
# we are called internally, so short-circuit
if fastpath:
@@ -192,7 +195,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
name = data.name
data = np.asarray(data)
elif isinstance(data, types.GeneratorType):
- data = list(data)
+ data = list(islice(data, count))
elif isinstance(data, (set, frozenset)):
raise TypeError("{0!r} type is unordered"
"".format(data.__class__.__name__))
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index bded2fad36763..b6f18664d3e5b 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -2791,6 +2791,15 @@ def test_constructor_generator(self):
expected = DataFrame({ 0 : range(10), 1 : 'a' })
assert_frame_equal(result, expected, check_dtype=False)
+ def test_constructor_generator_count_limit(self):
+ generator_length = 10
+ expected_length = 5
+
+ #only works when data it'a a generator, not a collection
+ gen = ([ i, 'a'] for i in range(generator_length))
+ result = DataFrame(gen, count=expected_length)
+ self.assertEqual(len(result), expected_length)
+
def test_constructor_list_of_dicts(self):
data = [OrderedDict([['a', 1.5], ['b', 3], ['c', 4], ['d', 6]]),
OrderedDict([['a', 1.5], ['b', 3], ['d', 6]]),
@@ -3820,6 +3829,14 @@ def list_generator(length):
result = DataFrame.from_records(generator, columns=columns_names)
assert_frame_equal(result, expected)
+ def test_from_records_generator_count_limit(self):
+ def generator(length):
+ for i in range(length):
+ yield (i, i/2)
+ expected_length = 5
+ df = DataFrame.from_records(generator(10), count=expected_length)
+ self.assertEqual(len(df), expected_length)
+
def test_from_records_columns_not_modified(self):
tuples = [(1, 2, 3),
(1, 2, 3),
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 5a4cbf1a6e16e..fbc06f96b4249 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -403,6 +403,14 @@ def test_constructor_generator(self):
exp.index = lrange(10, 20)
assert_series_equal(result, exp)
+ def test_constructor_generator_count_limit(self):
+ generator_length = 10
+ expected_length = 5
+ gen = (i for i in range(generator_length))
+
+ result = Series(gen, count=expected_length)
+ self.assertEqual(len(result), expected_length)
+
def test_constructor_categorical(self):
cat = pd.Categorical([0, 1, 2, 0, 1, 2], ['a', 'b', 'c'])
res = Series(cat)
| When reading data from a generator type collection only reads the firsts number (count) of values.
First step to solve #2305, known the length of the data to allocate memory.
- Add count parameter to Series, DataFrame, and DataFrame.from_records().
- In DataFrame.from_records() deprecate the existing parameter nrows. Count it's more general and only refers to quantity of data units. Also exists on numpy API (fromiter).
- Some refactor in DataFrame.from_records().
- Add tests too.
- Lack of release docs for now.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5898 | 2014-01-10T02:08:01Z | 2014-01-18T03:34:46Z | null | 2014-07-10T14:59:30Z |
Fix bug where use of .ix[tuple(...)]=x fails to correctly check out of b... | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 071b6e77fc2eb..61e275b0eb0f6 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -84,6 +84,7 @@ Bug Fixes
- Regresssion in handling of empty Series as indexers to Series (:issue:`5877`)
- Bug in internal caching, related to (:issue:`5727`)
- Testing bug in reading json/msgpack from a non-filepath on windows under py3 (:issue:`5874`)
+ - Bug when assigning to .ix[tuple(...)] (:issue:`5896`)
pandas 0.13.0
-------------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index bfddd2e78c322..0697f9d826f97 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -903,7 +903,8 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
return {'key': obj}
# a positional
- if obj >= len(self.obj) and not isinstance(labels, MultiIndex):
+ if (obj >= self.obj.shape[axis] and
+ not isinstance(labels, MultiIndex)):
raise ValueError("cannot set by positional indexing with "
"enlargement")
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index d68ead4a69d9e..bf1709c78822f 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2352,6 +2352,14 @@ def check_slicing_positional(index):
#self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0])
#self.assertRaises(TypeError, lambda : s.iloc[2:5.0])
+ def test_set_ix_out_of_bounds_axis_0(self):
+ df = pd.DataFrame(randn(2, 5), index=["row%s" % i for i in range(2)], columns=["col%s" % i for i in range(5)])
+ self.assertRaises(ValueError, df.ix.__setitem__, (2, 0), 100)
+
+ def test_set_ix_out_of_bounds_axis_1(self):
+ df = pd.DataFrame(randn(5, 2), index=["row%s" % i for i in range(5)], columns=["col%s" % i for i in range(2)])
+ self.assertRaises(ValueError, df.ix.__setitem__, (0 , 2), 100)
+
if __name__ == '__main__':
import nose
| ...ounds index for columns. This is a regression as it used to work in pandas 0.12.0. The code incorrectly checks the column index against the len() of the dataframe to see if it is in bounds not against the number of columns. Have added 2 tests with non-square dataframes to test that the fix works.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5896 | 2014-01-09T17:45:23Z | 2014-01-09T23:26:26Z | 2014-01-09T23:26:26Z | 2014-06-23T20:21:50Z |
TST: Testing bug in reading json/msgpack from a non-filepath on windows under py3 (GH5874) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index d8e06c1ce9169..071b6e77fc2eb 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -83,6 +83,7 @@ Bug Fixes
- Bug in groupby dtype conversion with datetimelike (:issue:`5869`)
- Regresssion in handling of empty Series as indexers to Series (:issue:`5877`)
- Bug in internal caching, related to (:issue:`5727`)
+ - Testing bug in reading json/msgpack from a non-filepath on windows under py3 (:issue:`5874`)
pandas 0.13.0
-------------
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 83c503e7419e9..698f7777a1100 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -173,7 +173,15 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
filepath_or_buffer, _ = get_filepath_or_buffer(path_or_buf)
if isinstance(filepath_or_buffer, compat.string_types):
- if os.path.exists(filepath_or_buffer):
+ try:
+ exists = os.path.exists(filepath_or_buffer)
+
+ # if the filepath is too long will raise here
+ # 5874
+ except (TypeError,ValueError):
+ exists = False
+
+ if exists:
with open(filepath_or_buffer, 'r') as fh:
json = fh.read()
else:
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index 5d392e94106e9..eba2579e80ea8 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -147,11 +147,11 @@ def read(fh):
if isinstance(path_or_buf, compat.string_types):
try:
- path_exists = os.path.exists(path_or_buf)
- except (TypeError):
- path_exists = False
+ exists = os.path.exists(path_or_buf)
+ except (TypeError,ValueError):
+ exists = False
- if path_exists:
+ if exists:
with open(path_or_buf, 'rb') as fh:
return read(fh)
| closes #5874
| https://api.github.com/repos/pandas-dev/pandas/pulls/5894 | 2014-01-09T16:38:56Z | 2014-01-09T17:15:11Z | 2014-01-09T17:15:11Z | 2014-06-26T01:49:11Z |
BLD: Send Travis-CI results to ScatterCI | diff --git a/.travis.yml b/.travis.yml
index 477e81a956553..6dd459ac2d8f9 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,16 +6,37 @@ python:
matrix:
include:
- python: 2.6
- env: NOSE_ARGS="not slow" CLIPBOARD=xclip LOCALE_OVERRIDE="it_IT.UTF-8"
+ env:
+ - NOSE_ARGS="not slow and not network"
+ - CLIPBOARD=xclip
+ - LOCALE_OVERRIDE="it_IT.UTF-8"
+ - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ="
- python: 2.7
- env: NOSE_ARGS="slow and not network" LOCALE_OVERRIDE="zh_CN.GB18030" FULL_DEPS=true JOB_TAG=_LOCALE
+ env:
+ - NOSE_ARGS="slow and not network"
+ - LOCALE_OVERRIDE="zh_CN.GB18030"
+ - FULL_DEPS=true
+ - JOB_TAG=_LOCALE
+ - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ="
- python: 2.7
- env: NOSE_ARGS="not slow" FULL_DEPS=true CLIPBOARD_GUI=gtk2
+ env:
+ - NOSE_ARGS="not slow"
+ - FULL_DEPS=true
+ - CLIPBOARD_GUI=gtk2
+ - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ="
- python: 3.2
- env: NOSE_ARGS="not slow" FULL_DEPS=true CLIPBOARD_GUI=qt4
+ env:
+ - NOSE_ARGS="not slow"
+ - FULL_DEPS=true
+ - CLIPBOARD_GUI=qt4
+ - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ="
- python: 3.3
- env: NOSE_ARGS="not slow" FULL_DEPS=true CLIPBOARD=xsel
- exclude:
+ env:
+ - NOSE_ARGS="not slow"
+ - FULL_DEPS=true
+ - CLIPBOARD=xsel
+ - secure: "Bx5umgo6WjuGY+5XFa004xjCiX/vq0CyMZ/ETzcs7EIBI1BE/0fIDXOoWhoxbY9HPfdPGlDnDgB9nGqr5wArO2s+BavyKBWg6osZ3dmkfuJPMOWeyCa92EeP+sfKw8e5HSU5MizW9e319wHWOF/xkzdHR7T67Qd5erhv91x4DnQ="
+ exclude:
- python: 2.6
# allow importing from site-packages,
@@ -49,3 +70,5 @@ script:
after_script:
- ci/print_versions.py
- ci/print_skipped.py /tmp/nosetests.xml
+ - ci/print_versions.py -j /tmp/env.json
+ - ci/after_script.sh
\ No newline at end of file
diff --git a/ci/after_script.sh b/ci/after_script.sh
new file mode 100755
index 0000000000000..672b43d637b42
--- /dev/null
+++ b/ci/after_script.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+wget https://raw.github.com/y-p/ScatterCI-CLI/master/scatter_cli.py
+chmod u+x scatter_cli.py
+echo '' > /tmp/build.log
+pip install -I requests==2.1.0
+echo "${TRAVIS_PYTHON_VERSION:0:4}"
+if [ x"${TRAVIS_PYTHON_VERSION:0:4}" == x"2.6" ]; then
+ pip install simplejson;
+fi
+
+python scatter_cli.py --xunit-file /tmp/nosetests.xml --log-file /tmp/build.log --env-file /tmp/env.json --succeed
+
+true # never fail because bad things happened here
| Our CI situation could be better. Travis is great but doesn't do windows or 32 bit, the SPARC
buildbot provided by @yarikoptic lives in another location and the windows jenkins box isn't
publicly viewable. That means :red_circle: builds have been going unnoticed, sometimes for months
until it's time to do a release and we inevitably go spelunking through commits from 2 months
ago to find the problem.
Each platform features some uncorrelated failures so grabbing as much as we can will improve
our overall testing coverage.
To address these types of problems, I've started working on a side-project called ScatterCI.
You can check out the beta version here: [](http://scatterci.github.io/ScatterCI-Pandas/).
This PR should start getting travis jobs on the status page and the windows jenkins box already
submits results from it's nightlies.
If you hit problems with the status page, please open an issue up on the [ScatterCI-Pandas](http://scatterci.github.io/ScatterCI-Pandas/issues/new) repo, not here.
It's not a Pandas thing just a service useful to the project.
@yarikoptic, @neirbowj if you're interested, I can send you an API key and have you
and your favorite platform join the CI fun. It should just take a few minutes to setup and
a full-blown CI server is not even required, a nightly cron job would work just as well.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5893 | 2014-01-09T14:53:03Z | 2014-01-09T15:53:24Z | 2014-01-09T15:53:24Z | 2014-06-15T07:02:50Z |
BUG: Bug in internal caching, related to (GH5727) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 66fe5a353f1ca..d8e06c1ce9169 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -82,6 +82,7 @@ Bug Fixes
- Bug in ``to_datetime`` when passed a ``np.nan`` or integer datelike and a format string (:issue:`5863`)
- Bug in groupby dtype conversion with datetimelike (:issue:`5869`)
- Regresssion in handling of empty Series as indexers to Series (:issue:`5877`)
+ - Bug in internal caching, related to (:issue:`5727`)
pandas 0.13.0
-------------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 92539e7deb5d7..e5c5f362d7f58 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -77,8 +77,8 @@ class NDFrame(PandasObject):
axes : list
copy : boolean, default False
"""
- _internal_names = ['_data', 'name', '_cacher', 'is_copy', '_subtyp',
- '_index', '_default_kind', '_default_fill_value']
+ _internal_names = ['_data', '_cacher', '_item_cache', '_cache',
+ 'is_copy', '_subtyp', '_index', '_default_kind', '_default_fill_value']
_internal_names_set = set(_internal_names)
_metadata = []
is_copy = None
@@ -721,13 +721,14 @@ def __setstate__(self, state):
# to avoid definitional recursion
# e.g. say fill_value needing _data to be
# defined
- for k in self._internal_names_set:
+ meta = set(self._internal_names + self._metadata)
+ for k in list(meta):
if k in state:
v = state[k]
object.__setattr__(self, k, v)
for k, v in state.items():
- if k not in self._internal_names_set:
+ if k not in meta:
object.__setattr__(self, k, v)
else:
@@ -1607,16 +1608,23 @@ def __getattr__(self, name):
This allows simpler access to columns for interactive use.
"""
- if name in self._info_axis:
- return self[name]
- raise AttributeError("'%s' object has no attribute '%s'" %
- (type(self).__name__, name))
+ if name in self._internal_names_set:
+ return object.__getattribute__(self, name)
+ elif name in self._metadata:
+ return object.__getattribute__(self, name)
+ else:
+ if name in self._info_axis:
+ return self[name]
+ raise AttributeError("'%s' object has no attribute '%s'" %
+ (type(self).__name__, name))
def __setattr__(self, name, value):
"""After regular attribute access, try looking up the name of the info
This allows simpler access to columns for interactive use."""
if name in self._internal_names_set:
object.__setattr__(self, name, value)
+ elif name in self._metadata:
+ return object.__setattr__(self, name, value)
else:
try:
existing = getattr(self, name)
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index a5270fbbecf00..d68ead4a69d9e 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -258,6 +258,12 @@ def test_indexer_caching(self):
s = Series(np.zeros(n), index=index)
str(s)
+ # setitem
+ expected = Series(np.ones(n), index=index)
+ s = Series(np.zeros(n), index=index)
+ s[s==0] = 1
+ assert_series_equal(s,expected)
+
def test_at_and_iat_get(self):
def _check(f, func, values = False):
| related #5727
| https://api.github.com/repos/pandas-dev/pandas/pulls/5892 | 2014-01-09T13:04:20Z | 2014-01-09T15:22:22Z | 2014-01-09T15:22:22Z | 2014-07-12T14:28:53Z |
DOC: Add two examples to to_datetime | diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py
index d3c686cbfa4d2..2d4f27cb12ece 100644
--- a/pandas/tseries/tools.py
+++ b/pandas/tseries/tools.py
@@ -79,6 +79,20 @@ def to_datetime(arg, errors='ignore', dayfirst=False, utc=None, box=True,
Returns
-------
ret : datetime if parsing succeeded
+
+ Examples
+ --------
+ Take separate series and convert to datetime
+
+ >>> import pandas as pd
+ >>> i = pd.date_range('20000101',periods=100)
+ >>> df = pd.DataFrame(dict(year = i.year, month = i.month, day = i.day))
+ >>> pd.to_datetime(df.year*10000 + df.month*100 + df.day, format='%Y%m%d')
+
+ Or from strings
+
+ >>> df = df.astype(str)
+ >>> pd.to_datetime(df.day + df.month + df.year, format="%d%m%Y")
"""
from pandas import Timestamp
from pandas.core.series import Series
| https://api.github.com/repos/pandas-dev/pandas/pulls/5887 | 2014-01-09T00:11:10Z | 2014-01-09T00:59:17Z | 2014-01-09T00:59:17Z | 2014-06-26T01:33:53Z | |
BUG: Don't return the same thing twice. | diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py
index d3c686cbfa4d2..17c3e6b72bfa0 100644
--- a/pandas/tseries/tools.py
+++ b/pandas/tseries/tools.py
@@ -297,7 +297,7 @@ def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None):
if parsed is None:
raise DateParseError("Could not parse %s" % arg)
- return parsed, parsed, reso # datetime, resolution
+ return parsed, reso # datetime, resolution
def dateutil_parse(timestr, default,
| Surely this is a typo.
I noticed this because I was going add more robust parsing to datetools.parse [1], and I was surprised to find this function there. Two suggestions / questions. 1) Why not just roll this into the parse function like statsmodels instead of having it fall down on things like "1989Q1"? Extra function seems unneeded to me.
2) Why return the "resolution"? The parse function doesn't do this, and I'd expect them to have the same return signature. Optionally, the parse function should also try to infer a frequency.
[1] https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/base/datetools.py#L117
| https://api.github.com/repos/pandas-dev/pandas/pulls/5885 | 2014-01-08T19:46:08Z | 2014-01-08T20:03:17Z | null | 2014-01-08T21:28:34Z |
BUG: Regresssion in handling of empty Series as indexers to Series (GH5877) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 7ee3bdddce2ad..66fe5a353f1ca 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -81,6 +81,7 @@ Bug Fixes
- Bug in isnull handling ``NaT`` in an object array (:issue:`5443`)
- Bug in ``to_datetime`` when passed a ``np.nan`` or integer datelike and a format string (:issue:`5863`)
- Bug in groupby dtype conversion with datetimelike (:issue:`5869`)
+ - Regresssion in handling of empty Series as indexers to Series (:issue:`5877`)
pandas 0.13.0
-------------
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 4e964b2576845..fc0532364eb42 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1660,7 +1660,7 @@ def _is_bool_indexer(key):
if key.dtype == np.object_:
key = np.asarray(_values_from_object(key))
- if len(key) and not lib.is_bool_array(key):
+ if not lib.is_bool_array(key):
if isnull(key).any():
raise ValueError('cannot index with vector containing '
'NA / NaN values')
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index e8b421608fc0a..5a4cbf1a6e16e 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -16,6 +16,7 @@
from pandas import (Index, Series, DataFrame, isnull, notnull,
bdate_range, date_range, _np_version_under1p7)
from pandas.core.index import MultiIndex
+from pandas.core.indexing import IndexingError
from pandas.tseries.index import Timestamp, DatetimeIndex
import pandas.core.config as cf
import pandas.lib as lib
@@ -795,6 +796,28 @@ def test_getitem_boolean_empty(self):
self.assertEqual(s.index.name, 'index_name')
self.assertEqual(s.dtype, np.int64)
+ # GH5877
+ # indexing with empty series
+ s = Series(['A', 'B'])
+ expected = Series(np.nan,index=['C'],dtype=object)
+ result = s[Series(['C'], dtype=object)]
+ assert_series_equal(result, expected)
+
+ s = Series(['A', 'B'])
+ expected = Series(dtype=object)
+ result = s[Series([], dtype=object)]
+ assert_series_equal(result, expected)
+
+ # invalid because of the boolean indexer
+ # that's empty or not-aligned
+ def f():
+ s[Series([], dtype=bool)]
+ self.assertRaises(IndexingError, f)
+
+ def f():
+ s[Series([True], dtype=bool)]
+ self.assertRaises(IndexingError, f)
+
def test_getitem_generator(self):
gen = (x > 0 for x in self.series)
result = self.series[gen]
| closes #5877
```
In [1]: s = Series(['A', 'B'])
In [2]: s[Series(['C'], dtype=object)]
Out[2]:
C NaN
dtype: object
In [3]: s[Series([], dtype=object)]
Out[3]: Series([], dtype: object)
```
This didn't work in 0.12
```
In [4]: s[Series([], dtype=bool)]
Out[4]: Series([], dtype: object)
```
This raises though (in both 0.12 and 0.13)
```
In [5]: s[Series([True], dtype=bool)]
IndexingError: Unalignable boolean Series key provided
``
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5880 | 2014-01-08T15:19:02Z | 2014-01-08T17:23:12Z | 2014-01-08T17:23:12Z | 2014-06-16T09:26:31Z |
ENH: Add regex=True flag to str_contains | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9ab175c07f169..4cf5ce2304d55 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -71,6 +71,7 @@ Improvements to existing features
- `option_context` context manager now available as top-level API (:issue:`5752`)
- df.info() view now display dtype info per column (:issue: `5682`)
- perf improvements in DataFrame ``count/dropna`` for ``axis=1``
+ - Series.str.contains now has a `regex=False` keyword which can be faster for plain (non-regex) string patterns. (:issue: `5879`)
Bug Fixes
~~~~~~~~~
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 1d9139fa9a1c7..77abd82b7ecc3 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -148,7 +148,7 @@ def str_count(arr, pat, flags=0):
return _na_map(f, arr)
-def str_contains(arr, pat, case=True, flags=0, na=np.nan):
+def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):
"""
Check whether given pattern is contained in each string in the array
@@ -161,7 +161,9 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan):
flags : int, default 0 (no flags)
re module flags, e.g. re.IGNORECASE
na : default NaN, fill value for missing values.
-
+ regex : bool, default True
+ If True use re.search, otherwise use Python in operator
+
Returns
-------
Series of boolean values
@@ -171,17 +173,21 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan):
match : analagous, but stricter, relying on re.match instead of re.search
"""
- if not case:
- flags |= re.IGNORECASE
+ if regex:
+ if not case:
+ flags |= re.IGNORECASE
- regex = re.compile(pat, flags=flags)
+ regex = re.compile(pat, flags=flags)
- if regex.groups > 0:
- warnings.warn("This pattern has match groups. To actually get the"
- " groups, use str.extract.", UserWarning)
+ if regex.groups > 0:
+ warnings.warn("This pattern has match groups. To actually get the"
+ " groups, use str.extract.", UserWarning)
- f = lambda x: bool(regex.search(x))
+ f = lambda x: bool(regex.search(x))
+ else:
+ f = lambda x: pat in x
return _na_map(f, arr, na)
+
def str_startswith(arr, pat, na=np.nan):
@@ -816,11 +822,13 @@ def __iter__(self):
g = self.get(i)
def _wrap_result(self, result):
- assert result.ndim < 3
- if result.ndim == 1:
+ if not hasattr(result, 'ndim'):
+ return result
+ elif result.ndim == 1:
return Series(result, index=self.series.index,
name=self.series.name)
else:
+ assert result.ndim < 3
return DataFrame(result, index=self.series.index)
@copy(str_cat)
@@ -844,11 +852,11 @@ def join(self, sep):
return self._wrap_result(result)
@copy(str_contains)
- def contains(self, pat, case=True, flags=0, na=np.nan):
+ def contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
result = str_contains(self.series, pat, case=case, flags=flags,
- na=na)
+ na=na, regex=regex)
return self._wrap_result(result)
-
+
@copy(str_replace)
def replace(self, pat, repl, n=-1, case=True, flags=0):
result = str_replace(self.series, pat, repl, n=n, case=case,
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 15193e44bd5cf..b8033abf0a6dc 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -167,11 +167,15 @@ def test_count(self):
tm.assert_almost_equal(result, exp)
def test_contains(self):
- values = ['foo', NA, 'fooommm__foo', 'mmm_']
+ values = ['foo', NA, 'fooommm__foo', 'mmm_', 'foommm[_]+bar']
pat = 'mmm[_]+'
result = strings.str_contains(values, pat)
- expected = [False, np.nan, True, True]
+ expected = [False, NA, True, True, False]
+ tm.assert_almost_equal(result, expected)
+
+ result = strings.str_contains(values, pat, regex=False)
+ expected = [False, NA, False, False, True]
tm.assert_almost_equal(result, expected)
values = ['foo', 'xyz', 'fooommm__foo', 'mmm_']
diff --git a/vb_suite/strings.py b/vb_suite/strings.py
new file mode 100644
index 0000000000000..287fd6d5bf2e2
--- /dev/null
+++ b/vb_suite/strings.py
@@ -0,0 +1,53 @@
+from vbench.api import Benchmark
+
+common_setup = """from pandas_vb_common import *
+"""
+
+setup = common_setup + """
+import string
+import itertools as IT
+
+def make_series(letters, strlen, size):
+ return Series(
+ np.fromiter(IT.cycle(letters), count=size*strlen, dtype='|S1')
+ .view('|S{}'.format(strlen)))
+
+many = make_series('matchthis'+string.uppercase, strlen=19, size=10000) # 31% matches
+few = make_series('matchthis'+string.uppercase*42, strlen=19, size=10000) # 1% matches
+"""
+
+strings_cat = Benchmark("many.str.cat(sep=',')", setup)
+strings_title = Benchmark("many.str.title()", setup)
+strings_count = Benchmark("many.str.count('matchthis')", setup)
+strings_contains_many = Benchmark("many.str.contains('matchthis')", setup)
+strings_contains_few = Benchmark("few.str.contains('matchthis')", setup)
+strings_contains_many_noregex = Benchmark(
+ "many.str.contains('matchthis', regex=False)", setup)
+strings_contains_few_noregex = Benchmark(
+ "few.str.contains('matchthis', regex=False)", setup)
+strings_startswith = Benchmark("many.str.startswith('matchthis')", setup)
+strings_endswith = Benchmark("many.str.endswith('matchthis')", setup)
+strings_lower = Benchmark("many.str.lower()", setup)
+strings_upper = Benchmark("many.str.upper()", setup)
+strings_replace = Benchmark("many.str.replace(r'(matchthis)', r'\1\1')", setup)
+strings_repeat = Benchmark(
+ "many.str.repeat(list(IT.islice(IT.cycle(range(1,4)),len(many))))", setup)
+strings_match = Benchmark("many.str.match(r'mat..this')", setup)
+strings_extract = Benchmark("many.str.extract(r'(\w*)matchthis(\w*)')", setup)
+strings_join_split = Benchmark("many.str.join(r'--').str.split('--')", setup)
+strings_len = Benchmark("many.str.len()", setup)
+strings_findall = Benchmark("many.str.findall(r'[A-Z]+')", setup)
+strings_pad = Benchmark("many.str.pad(100, side='both')", setup)
+strings_center = Benchmark("many.str.center(100)", setup)
+strings_slice = Benchmark("many.str.slice(5,15,2)", setup)
+strings_strip = Benchmark("many.str.strip('matchthis')", setup)
+strings_lstrip = Benchmark("many.str.lstrip('matchthis')", setup)
+strings_rstrip = Benchmark("many.str.rstrip('matchthis')", setup)
+strings_get = Benchmark("many.str.get(0)", setup)
+
+setup = common_setup + """
+import pandas.util.testing as testing
+ser = pd.Series(testing.makeUnicodeIndex())
+"""
+
+strings_encode_decode = Benchmark("ser.str.encode('utf-8').str.decode('utf-8')", setup)
diff --git a/vb_suite/suite.py b/vb_suite/suite.py
index e5002ef78ab9b..26091d83f7c34 100644
--- a/vb_suite/suite.py
+++ b/vb_suite/suite.py
@@ -22,6 +22,7 @@
'reindex',
'replace',
'sparse',
+ 'strings',
'reshape',
'stat_ops',
'timeseries',
| Using regex=False can be faster when full regex searching is not needed.
See http://stackoverflow.com/q/20951840/190597
Example use case:
```
import string
import itertools as IT
import numpy as np
from pandas import Series
def make_series(letters, strlen, size):
return Series(
np.fromiter(IT.cycle(letters), count=size*strlen, dtype='|S1')
.view('|S{}'.format(strlen)))
many = make_series('matchthis'+string.uppercase, strlen=19, size=10000) # 31% matches
few = make_series('matchthis'+string.uppercase*42, strlen=19, size=10000) # 1% matches
```
```
In [115]: %timeit many.str.contains('matchthis')
100 loops, best of 3: 4.93 ms per loop
In [116]: %timeit many.str.contains('matchthis', regex=False)
100 loops, best of 3: 2.44 ms per loop
In [118]: %timeit few.str.contains('matchthis')
100 loops, best of 3: 4.81 ms per loop
In [119]: %timeit few.str.contains('matchthis', regex=False)
100 loops, best of 3: 2.37 ms per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5879 | 2014-01-08T15:17:03Z | 2014-01-15T00:26:34Z | 2014-01-15T00:26:34Z | 2014-06-15T00:35:15Z |
DOC: Add %in% operator into compare w r (GH3850) | diff --git a/doc/source/comparison_with_r.rst b/doc/source/comparison_with_r.rst
index 0738930b4ea25..a5b8fabac11ac 100644
--- a/doc/source/comparison_with_r.rst
+++ b/doc/source/comparison_with_r.rst
@@ -66,6 +66,44 @@ function.
For more details and examples see :ref:`the groupby documentation
<groupby.split>`.
+|match|_
+~~~~~~~~~~~~
+
+A common way to select data in R is using ``%in%`` which is defined using the
+function ``match``. The operator ``%in%`` is used to return a logical vector
+indicating if there is a match or not:
+
+.. code-block:: r
+
+ s <- 0:4
+ s %in% c(2,4)
+
+The :meth:`~pandas.DataFrame.isin` method is similar to R ``%in%`` operator:
+
+.. ipython:: python
+
+ s = pd.Series(np.arange(5),dtype=np.float32)
+ s.isin([2, 4])
+
+The ``match`` function returns a vector of the positions of matches
+of its first argument in its second:
+
+.. code-block:: r
+
+ s <- 0:4
+ match(s, c(2,4))
+
+The :meth:`~pandas.core.groupby.GroupBy.apply` method can be used to replicate
+this:
+
+.. ipython:: python
+
+ s = pd.Series(np.arange(5),dtype=np.float32)
+ Series(pd.match(s,[2,4],np.nan))
+
+For more details and examples see :ref:`the reshaping documentation
+<indexing.basics.indexing_isin>`.
+
|tapply|_
~~~~~~~~~
@@ -372,6 +410,9 @@ For more details and examples see :ref:`the reshaping documentation
.. |aggregate| replace:: ``aggregate``
.. _aggregate: http://finzi.psych.upenn.edu/R/library/stats/html/aggregate.html
+.. |match| replace:: ``match`` / ``%in%``
+.. _match: http://finzi.psych.upenn.edu/R/library/base/html/match.html
+
.. |tapply| replace:: ``tapply``
.. _tapply: http://finzi.psych.upenn.edu/R/library/base/html/tapply.html
| Doesn't close #3850 but at least the `%in%` operator is now in the comparison with R docs. I've lumped it with the `match` function since thats the page you see the `%in%` operator in the R docs http://finzi.psych.upenn.edu/R/library/base/html/match.html.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5875 | 2014-01-08T09:21:06Z | 2014-01-15T16:15:01Z | 2014-01-15T16:15:01Z | 2014-06-26T12:22:49Z |
BUG: Bug in groupby dtype conversion with datetimelike (GH5869) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4dbb450c8aed7..7ee3bdddce2ad 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -80,6 +80,7 @@ Bug Fixes
- Fix issue of boolean comparison on empty DataFrames (:issue:`5808`)
- Bug in isnull handling ``NaT`` in an object array (:issue:`5443`)
- Bug in ``to_datetime`` when passed a ``np.nan`` or integer datelike and a format string (:issue:`5863`)
+ - Bug in groupby dtype conversion with datetimelike (:issue:`5869`)
pandas 0.13.0
-------------
diff --git a/pandas/core/common.py b/pandas/core/common.py
index a9b56b6905b6b..4e964b2576845 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1102,6 +1102,14 @@ def _possibly_downcast_to_dtype(result, dtype):
# hit here
if (new_result == result).all():
return new_result
+
+ # a datetimelike
+ elif dtype.kind in ['M','m'] and result.dtype.kind in ['i']:
+ try:
+ result = result.astype(dtype)
+ except:
+ pass
+
except:
pass
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 34c8869f72a53..9ce7f30c2401e 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -2672,6 +2672,14 @@ def test_groupby_first_datetime64(self):
got_dt = result.dtype
self.assert_(issubclass(got_dt.type, np.datetime64))
+ def test_groupby_max_datetime64(self):
+ # GH 5869
+ # datetimelike dtype conversion from int
+ df = DataFrame(dict(A = Timestamp('20130101'), B = np.arange(5)))
+ expected = df.groupby('A')['A'].apply(lambda x: x.max())
+ result = df.groupby('A')['A'].max()
+ assert_series_equal(result,expected)
+
def test_groupby_categorical_unequal_len(self):
import pandas as pd
#GH3011
| closes #5869
| https://api.github.com/repos/pandas-dev/pandas/pulls/5870 | 2014-01-07T20:23:43Z | 2014-01-07T20:44:31Z | 2014-01-07T20:44:31Z | 2014-06-17T08:06:13Z |
BLD: fixup setup.py, initialize pipe variable to None | diff --git a/setup.py b/setup.py
index 497c6a5644def..97938dd0b1867 100755
--- a/setup.py
+++ b/setup.py
@@ -200,6 +200,7 @@ def build_extensions(self):
import subprocess
FULLVERSION += '.dev'
+ pipe = None
for cmd in ['git','git.cmd']:
try:
pipe = subprocess.Popen([cmd, "describe", "--always"],
@@ -210,7 +211,7 @@ def build_extensions(self):
except:
pass
- if pipe.returncode != 0:
+ if pipe is None or pipe.returncode != 0:
warnings.warn("WARNING: Couldn't get git revision, using generic version string")
else:
rev = so.strip()
@@ -218,7 +219,7 @@ def build_extensions(self):
if sys.version_info[0] >= 3:
rev = rev.decode('ascii')
- # use result og git describe as version string
+ # use result of git describe as version string
FULLVERSION = rev.lstrip('v')
else:
| recent changes (fe9c0ae0) broke setup.py for some users:
https://github.com/pydata/pandas/issues/5867#issuecomment-31759183
| https://api.github.com/repos/pandas-dev/pandas/pulls/5868 | 2014-01-07T18:57:13Z | 2014-01-07T19:25:21Z | 2014-01-07T19:25:21Z | 2014-07-16T08:45:37Z |
DOC: Flesh out the R comparison section of docs (GH3980) | diff --git a/doc/source/comparison_with_r.rst b/doc/source/comparison_with_r.rst
index 9aedb801250d7..ce34c3e99a6f5 100644
--- a/doc/source/comparison_with_r.rst
+++ b/doc/source/comparison_with_r.rst
@@ -30,6 +30,77 @@ R packages.
Base R
------
+|aggregate|_
+~~~~~~~~~~~~
+
+In R you may want to split data into subsets and compute the mean for each.
+Using a data.frame called ``df`` and splitting it into groups ``by1`` and
+``by2``:
+
+.. code-block:: r
+
+ df <- data.frame(
+ v1 = c(1,3,5,7,8,3,5,NA,4,5,7,9),
+ v2 = c(11,33,55,77,88,33,55,NA,44,55,77,99),
+ by1 = c("red", "blue", 1, 2, NA, "big", 1, 2, "red", 1, NA, 12),
+ by2 = c("wet", "dry", 99, 95, NA, "damp", 95, 99, "red", 99, NA, NA))
+ aggregate(x=df[, c("v1", "v2")], by=list(mydf2$by1, mydf2$by2), FUN = mean)
+
+The :meth:`~pandas.DataFrame.groupby` method is similar to base R ``aggregate``
+function.
+
+.. ipython:: python
+
+ from pandas import DataFrame
+ df = DataFrame({
+ 'v1': [1,3,5,7,8,3,5,np.nan,4,5,7,9],
+ 'v2': [11,33,55,77,88,33,55,np.nan,44,55,77,99],
+ 'by1': ["red", "blue", 1, 2, np.nan, "big", 1, 2, "red", 1, np.nan, 12],
+ 'by2': ["wet", "dry", 99, 95, np.nan, "damp", 95, 99, "red", 99, np.nan,
+ np.nan]
+ })
+
+ g = df.groupby(['by1','by2'])
+ g[['v1','v2']].mean()
+
+For more details and examples see :ref:`the groupby documentation
+<groupby.split>`.
+
+|tapply|_
+~~~~~~~~~
+
+``tapply`` is similar to ``aggregate``, but data can be in a ragged array,
+since the subclass sizes are possibly irregular. Using a data.frame called
+``baseball``, and retrieving information based on the array ``team``:
+
+.. code-block:: r
+
+ baseball <-
+ data.frame(team = gl(5, 5,
+ labels = paste("Team", LETTERS[1:5])),
+ player = sample(letters, 25),
+ batting.average = runif(25, .200, .400))
+
+ tapply(baseball$batting.average, baseball.example$team,
+ max)
+
+In ``pandas`` we may use :meth:`~pandas.pivot_table` method to handle this:
+
+.. ipython:: python
+
+ import random
+ import string
+
+ baseball = DataFrame({
+ 'team': ["team %d" % (x+1) for x in range(5)]*5,
+ 'player': random.sample(list(string.ascii_lowercase),25),
+ 'batting avg': np.random.uniform(.200, .400, 25)
+ })
+ baseball.pivot_table(values='batting avg', cols='team', aggfunc=np.max)
+
+For more details and examples see :ref:`the reshaping documentation
+<reshaping.pivot>`.
+
|subset|_
~~~~~~~~~~
@@ -51,9 +122,6 @@ index/slice as well as standard boolean indexing:
.. ipython:: python
- from pandas import DataFrame
- from numpy import random
-
df = DataFrame({'a': random.randn(10), 'b': random.randn(10)})
df.query('a <= b')
df[df.a <= df.b]
@@ -120,8 +188,6 @@ table below shows how these data structures could be mapped in Python.
An expression using a data.frame called ``df`` in R where you want to
summarize ``x`` by ``month``:
-
-
.. code-block:: r
require(plyr)
@@ -140,16 +206,14 @@ summarize ``x`` by ``month``:
In ``pandas`` the equivalent expression, using the
:meth:`~pandas.DataFrame.groupby` method, would be:
-
-
.. ipython:: python
df = DataFrame({
- 'x': random.uniform(1., 168., 120),
- 'y': random.uniform(7., 334., 120),
- 'z': random.uniform(1.7, 20.7, 120),
+ 'x': np.random.uniform(1., 168., 120),
+ 'y': np.random.uniform(7., 334., 120),
+ 'z': np.random.uniform(1.7, 20.7, 120),
'month': [5,6,7,8]*30,
- 'week': random.randint(1,4, 120)
+ 'week': np.random.randint(1,4, 120)
})
grouped = df.groupby(['month','week'])
@@ -235,8 +299,8 @@ For more details and examples see :ref:`the reshaping documentation
|cast|_
~~~~~~~
-An expression using a data.frame called ``df`` in R to cast into a higher
-dimensional array:
+In R ``acast`` is an expression using a data.frame called ``df`` in R to cast
+into a higher dimensional array:
.. code-block:: r
@@ -256,9 +320,9 @@ In Python the best way is to make use of :meth:`~pandas.pivot_table`:
.. ipython:: python
df = DataFrame({
- 'x': random.uniform(1., 168., 12),
- 'y': random.uniform(7., 334., 12),
- 'z': random.uniform(1.7, 20.7, 12),
+ 'x': np.random.uniform(1., 168., 12),
+ 'y': np.random.uniform(7., 334., 12),
+ 'z': np.random.uniform(1.7, 20.7, 12),
'month': [5,6,7]*4,
'week': [1,2]*6
})
@@ -266,8 +330,50 @@ In Python the best way is to make use of :meth:`~pandas.pivot_table`:
pd.pivot_table(mdf, values='value', rows=['variable','week'],
cols=['month'], aggfunc=np.mean)
+Similarly for ``dcast`` which uses a data.frame called ``df`` in R to
+aggregate information based on ``Animal`` and ``FeedType``:
+
+.. code-block:: r
+
+ df <- data.frame(
+ Animal = c('Animal1', 'Animal2', 'Animal3', 'Animal2', 'Animal1',
+ 'Animal2', 'Animal3'),
+ FeedType = c('A', 'B', 'A', 'A', 'B', 'B', 'A'),
+ Amount = c(10, 7, 4, 2, 5, 6, 2)
+ )
+
+ dcast(df, Animal ~ FeedType, sum, fill=NaN)
+ # Alternative method using base R
+ with(df, tapply(Amount, list(Animal, FeedType), sum))
+
+Python can approach this in two different ways. Firstly, similar to above
+using :meth:`~pandas.pivot_table`:
+
+.. ipython:: python
+
+ df = DataFrame({
+ 'Animal': ['Animal1', 'Animal2', 'Animal3', 'Animal2', 'Animal1',
+ 'Animal2', 'Animal3'],
+ 'FeedType': ['A', 'B', 'A', 'A', 'B', 'B', 'A'],
+ 'Amount': [10, 7, 4, 2, 5, 6, 2],
+ })
+
+ df.pivot_table(values='Amount', rows='Animal', cols='FeedType', aggfunc='sum')
+
+The second approach is to use the :meth:`~pandas.DataFrame.groupby` method:
+
+.. ipython:: python
+
+ df.groupby(['Animal','FeedType'])['Amount'].sum()
+
For more details and examples see :ref:`the reshaping documentation
-<reshaping.pivot>`.
+<reshaping.pivot>` or :ref:`the groupby documentation<groupby.split>`.
+
+.. |aggregate| replace:: ``aggregate``
+.. _aggregate: http://finzi.psych.upenn.edu/R/library/stats/html/aggregate.html
+
+.. |tapply| replace:: ``tapply``
+.. _tapply: http://finzi.psych.upenn.edu/R/library/base/html/tapply.html
.. |with| replace:: ``with``
.. _with: http://finzi.psych.upenn.edu/R/library/base/html/with.html
| @jreback added section for `aggregate`, `tapply` and `dcast`, with the `dcast` example coming from http://stackoverflow.com/questions/19237878/subsetting-a-python-dataframe.
#3980
| https://api.github.com/repos/pandas-dev/pandas/pulls/5866 | 2014-01-07T09:44:37Z | 2014-01-07T11:02:55Z | 2014-01-07T11:02:55Z | 2014-07-10T09:42:20Z |
BUG: bug in to_datetime when passed a np.nan or integer datelike and a format string (GH5863) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9a3e101fce5d5..4dbb450c8aed7 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -79,6 +79,7 @@ Bug Fixes
- Bug in selection with missing values via ``.ix`` from a duplicate indexed DataFrame failing (:issue:`5835`)
- Fix issue of boolean comparison on empty DataFrames (:issue:`5808`)
- Bug in isnull handling ``NaT`` in an object array (:issue:`5443`)
+ - Bug in ``to_datetime`` when passed a ``np.nan`` or integer datelike and a format string (:issue:`5863`)
pandas 0.13.0
-------------
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index f4dcdb7a44a3e..4fb8bc7deddb4 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -804,6 +804,31 @@ def test_to_datetime_default(self):
xp = datetime(2001, 1, 1)
self.assert_(rs, xp)
+
+ def test_to_datetime_mixed(self):
+
+ # 5863
+ # passing a string format with embedded np.nan
+
+ ts = Series([np.nan, '2013-04-08 00:00:00.000', '9999-12-31 00:00:00.000'])
+ expected = Series([NaT,Timestamp('20130408'),NaT])
+
+ result = to_datetime(ts, format='%Y-%m-%d %H:%M:%S.%f')
+ assert_series_equal(result, ts)
+
+ # raises if specified
+ self.assertRaises(pd.tslib.OutOfBoundsDatetime, to_datetime, ts, format='%Y-%m-%d %H:%M:%S.%f', errors='raise')
+
+ result = to_datetime(ts, format='%Y-%m-%d %H:%M:%S.%f',coerce=True)
+ expected = Series([NaT,Timestamp('20130408'),NaT])
+ assert_series_equal(result,expected)
+
+ # passing integers
+ ts = Series([np.nan, 20130408, '20130409'])
+ result = to_datetime(ts, format='%Y%m%d')
+ expected = Series([NaT,Timestamp('20130408'),Timestamp('20130409')])
+ assert_series_equal(result,expected)
+
def test_dayfirst(self):
# GH 3341
diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py
index af1a31bcec311..d3c686cbfa4d2 100644
--- a/pandas/tseries/tools.py
+++ b/pandas/tseries/tools.py
@@ -112,7 +112,12 @@ def _convert_listlike(arg, box):
# fallback
if result is None:
- result = tslib.array_strptime(arg, format, coerce=coerce)
+ try:
+ result = tslib.array_strptime(arg, format, coerce=coerce)
+ except (tslib.OutOfBoundsDatetime):
+ if errors == 'raise':
+ raise
+ result = arg
else:
result = tslib.array_to_datetime(arg, raise_=errors == 'raise',
utc=utc, dayfirst=dayfirst,
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 96391f703d1d7..bda6625f3c3ad 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1197,6 +1197,7 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False):
pandas_datetimestruct dts
ndarray[int64_t] iresult
int year, month, day, minute, hour, second, fraction, weekday, julian
+ object val
global _TimeRE_cache, _regex_cache
with _cache_lock:
@@ -1252,14 +1253,26 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False):
cdef int parse_code
for i in range(n):
- found = format_regex.match(values[i])
+ val = values[i]
+ if util.is_string_object(val):
+ if val in _nat_strings:
+ iresult[i] = iNaT
+ continue
+ else:
+ if util._checknull(val) or val is NaT:
+ iresult[i] = iNaT
+ continue
+ else:
+ val = str(val)
+
+ found = format_regex.match(val)
if not found:
if coerce:
iresult[i] = iNaT
continue
raise ValueError("time data %r does not match format %r" %
(values[i], fmt))
- if len(values[i]) != found.end():
+ if len(val) != found.end():
if coerce:
iresult[i] = iNaT
continue
@@ -1402,7 +1415,13 @@ def array_strptime(ndarray[object] values, object fmt, coerce=False):
dts.us = fraction
iresult[i] = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts)
- _check_dts_bounds(&dts)
+ try:
+ _check_dts_bounds(&dts)
+ except ValueError:
+ if coerce:
+ iresult[i] = iNaT
+ continue
+ raise
return result
| closes #5863
| https://api.github.com/repos/pandas-dev/pandas/pulls/5864 | 2014-01-06T23:47:36Z | 2014-01-07T00:41:00Z | 2014-01-07T00:41:00Z | 2014-06-27T05:14:01Z |
COMPAT: add different numexpr versions for testing / skip encoding tests on too low tables versions | diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt
index dc6e2d9f55977..186d13c6dec7c 100644
--- a/ci/requirements-2.7.txt
+++ b/ci/requirements-2.7.txt
@@ -4,7 +4,7 @@ xlwt==0.7.5
numpy==1.8.0
cython==0.19.1
bottleneck==0.6.0
-numexpr==2.1
+numexpr==2.0.1
tables==2.3.1
matplotlib==1.1.1
openpyxl==1.6.2
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 5fcafdc295c5c..e478f46a7345f 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -844,8 +844,10 @@ def check(format,index):
def test_encoding(self):
+ if LooseVersion(tables.__version__) < '3.0.0':
+ raise nose.SkipTest('tables version does not support proper encoding')
if sys.byteorder != 'little':
- raise nose.SkipTest('system byteorder is not little, skipping test_encoding!')
+ raise nose.SkipTest('system byteorder is not little')
with ensure_clean_store(self.path) as store:
df = DataFrame(dict(A='foo',B='bar'),index=range(5))
| https://api.github.com/repos/pandas-dev/pandas/pulls/5860 | 2014-01-05T20:07:58Z | 2014-01-05T20:08:05Z | 2014-01-05T20:08:05Z | 2014-07-16T08:45:29Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.