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 |
|---|---|---|---|---|---|---|---|
Backport PR #38247 on branch 1.2.x (BUG: Limited available colors) | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index af9219bc25931..bc7f5b8174573 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -308,6 +308,7 @@ Other enhancements
- Improved error reporting for subsetting columns of a :class:`.DataFrameGroupBy` with ``axis=1`` (:issue:`37725`)
- Implement method ``cross`` for :meth:`DataFrame.merge` and :meth:`DataFrame.join` (:issue:`5401`)
- When :func:`read_csv/sas/json` are called with ``chuncksize``/``iterator`` they can be used in a ``with`` statement as they return context-managers (:issue:`38225`)
+- Augmented the list of named colors available for styling Excel exports, enabling all of CSS4 colors (:issue:`38247`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/formats/_color_data.py b/pandas/io/formats/_color_data.py
new file mode 100644
index 0000000000000..e5b72b2befa4f
--- /dev/null
+++ b/pandas/io/formats/_color_data.py
@@ -0,0 +1,155 @@
+# GH37967: Enable the use of CSS named colors, as defined in
+# matplotlib.colors.CSS4_COLORS, when exporting to Excel.
+# This data has been copied here, instead of being imported from matplotlib,
+# not to have ``to_excel`` methods require matplotlib.
+# source: matplotlib._color_data (3.3.3)
+CSS4_COLORS = {
+ "aliceblue": "F0F8FF",
+ "antiquewhite": "FAEBD7",
+ "aqua": "00FFFF",
+ "aquamarine": "7FFFD4",
+ "azure": "F0FFFF",
+ "beige": "F5F5DC",
+ "bisque": "FFE4C4",
+ "black": "000000",
+ "blanchedalmond": "FFEBCD",
+ "blue": "0000FF",
+ "blueviolet": "8A2BE2",
+ "brown": "A52A2A",
+ "burlywood": "DEB887",
+ "cadetblue": "5F9EA0",
+ "chartreuse": "7FFF00",
+ "chocolate": "D2691E",
+ "coral": "FF7F50",
+ "cornflowerblue": "6495ED",
+ "cornsilk": "FFF8DC",
+ "crimson": "DC143C",
+ "cyan": "00FFFF",
+ "darkblue": "00008B",
+ "darkcyan": "008B8B",
+ "darkgoldenrod": "B8860B",
+ "darkgray": "A9A9A9",
+ "darkgreen": "006400",
+ "darkgrey": "A9A9A9",
+ "darkkhaki": "BDB76B",
+ "darkmagenta": "8B008B",
+ "darkolivegreen": "556B2F",
+ "darkorange": "FF8C00",
+ "darkorchid": "9932CC",
+ "darkred": "8B0000",
+ "darksalmon": "E9967A",
+ "darkseagreen": "8FBC8F",
+ "darkslateblue": "483D8B",
+ "darkslategray": "2F4F4F",
+ "darkslategrey": "2F4F4F",
+ "darkturquoise": "00CED1",
+ "darkviolet": "9400D3",
+ "deeppink": "FF1493",
+ "deepskyblue": "00BFFF",
+ "dimgray": "696969",
+ "dimgrey": "696969",
+ "dodgerblue": "1E90FF",
+ "firebrick": "B22222",
+ "floralwhite": "FFFAF0",
+ "forestgreen": "228B22",
+ "fuchsia": "FF00FF",
+ "gainsboro": "DCDCDC",
+ "ghostwhite": "F8F8FF",
+ "gold": "FFD700",
+ "goldenrod": "DAA520",
+ "gray": "808080",
+ "green": "008000",
+ "greenyellow": "ADFF2F",
+ "grey": "808080",
+ "honeydew": "F0FFF0",
+ "hotpink": "FF69B4",
+ "indianred": "CD5C5C",
+ "indigo": "4B0082",
+ "ivory": "FFFFF0",
+ "khaki": "F0E68C",
+ "lavender": "E6E6FA",
+ "lavenderblush": "FFF0F5",
+ "lawngreen": "7CFC00",
+ "lemonchiffon": "FFFACD",
+ "lightblue": "ADD8E6",
+ "lightcoral": "F08080",
+ "lightcyan": "E0FFFF",
+ "lightgoldenrodyellow": "FAFAD2",
+ "lightgray": "D3D3D3",
+ "lightgreen": "90EE90",
+ "lightgrey": "D3D3D3",
+ "lightpink": "FFB6C1",
+ "lightsalmon": "FFA07A",
+ "lightseagreen": "20B2AA",
+ "lightskyblue": "87CEFA",
+ "lightslategray": "778899",
+ "lightslategrey": "778899",
+ "lightsteelblue": "B0C4DE",
+ "lightyellow": "FFFFE0",
+ "lime": "00FF00",
+ "limegreen": "32CD32",
+ "linen": "FAF0E6",
+ "magenta": "FF00FF",
+ "maroon": "800000",
+ "mediumaquamarine": "66CDAA",
+ "mediumblue": "0000CD",
+ "mediumorchid": "BA55D3",
+ "mediumpurple": "9370DB",
+ "mediumseagreen": "3CB371",
+ "mediumslateblue": "7B68EE",
+ "mediumspringgreen": "00FA9A",
+ "mediumturquoise": "48D1CC",
+ "mediumvioletred": "C71585",
+ "midnightblue": "191970",
+ "mintcream": "F5FFFA",
+ "mistyrose": "FFE4E1",
+ "moccasin": "FFE4B5",
+ "navajowhite": "FFDEAD",
+ "navy": "000080",
+ "oldlace": "FDF5E6",
+ "olive": "808000",
+ "olivedrab": "6B8E23",
+ "orange": "FFA500",
+ "orangered": "FF4500",
+ "orchid": "DA70D6",
+ "palegoldenrod": "EEE8AA",
+ "palegreen": "98FB98",
+ "paleturquoise": "AFEEEE",
+ "palevioletred": "DB7093",
+ "papayawhip": "FFEFD5",
+ "peachpuff": "FFDAB9",
+ "peru": "CD853F",
+ "pink": "FFC0CB",
+ "plum": "DDA0DD",
+ "powderblue": "B0E0E6",
+ "purple": "800080",
+ "rebeccapurple": "663399",
+ "red": "FF0000",
+ "rosybrown": "BC8F8F",
+ "royalblue": "4169E1",
+ "saddlebrown": "8B4513",
+ "salmon": "FA8072",
+ "sandybrown": "F4A460",
+ "seagreen": "2E8B57",
+ "seashell": "FFF5EE",
+ "sienna": "A0522D",
+ "silver": "C0C0C0",
+ "skyblue": "87CEEB",
+ "slateblue": "6A5ACD",
+ "slategray": "708090",
+ "slategrey": "708090",
+ "snow": "FFFAFA",
+ "springgreen": "00FF7F",
+ "steelblue": "4682B4",
+ "tan": "D2B48C",
+ "teal": "008080",
+ "thistle": "D8BFD8",
+ "tomato": "FF6347",
+ "turquoise": "40E0D0",
+ "violet": "EE82EE",
+ "wheat": "F5DEB3",
+ "white": "FFFFFF",
+ "whitesmoke": "F5F5F5",
+ "yellow": "FFFF00",
+ "yellowgreen": "9ACD32",
+}
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index be8f2de1d53fb..0cad67169feff 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -21,6 +21,7 @@
from pandas.core import generic
import pandas.core.common as com
+from pandas.io.formats._color_data import CSS4_COLORS
from pandas.io.formats.css import CSSResolver, CSSWarning
from pandas.io.formats.format import get_level_lengths
from pandas.io.formats.printing import pprint_thing
@@ -65,28 +66,7 @@ class CSSToExcelConverter:
CSS processed by :meth:`__call__`.
"""
- NAMED_COLORS = {
- "maroon": "800000",
- "brown": "A52A2A",
- "red": "FF0000",
- "pink": "FFC0CB",
- "orange": "FFA500",
- "yellow": "FFFF00",
- "olive": "808000",
- "green": "008000",
- "purple": "800080",
- "fuchsia": "FF00FF",
- "lime": "00FF00",
- "teal": "008080",
- "aqua": "00FFFF",
- "blue": "0000FF",
- "navy": "000080",
- "black": "000000",
- "gray": "808080",
- "grey": "808080",
- "silver": "C0C0C0",
- "white": "FFFFFF",
- }
+ NAMED_COLORS = CSS4_COLORS
VERTICAL_MAP = {
"top": "top",
diff --git a/pandas/tests/io/formats/test_to_excel.py b/pandas/tests/io/formats/test_to_excel.py
index 4f1af132204bb..968ad63eaceef 100644
--- a/pandas/tests/io/formats/test_to_excel.py
+++ b/pandas/tests/io/formats/test_to_excel.py
@@ -2,9 +2,12 @@
ExcelFormatter is tested implicitly in pandas/tests/io/excel
"""
+import string
import pytest
+import pandas.util._test_decorators as td
+
import pandas._testing as tm
from pandas.io.formats.css import CSSWarning
@@ -313,3 +316,18 @@ def test_css_to_excel_bad_colors(input_color):
with tm.assert_produces_warning(CSSWarning):
convert = CSSToExcelConverter()
assert expected == convert(css)
+
+
+def tests_css_named_colors_valid():
+ upper_hexs = set(map(str.upper, string.hexdigits))
+ for color in CSSToExcelConverter.NAMED_COLORS.values():
+ assert len(color) == 6 and all(c in upper_hexs for c in color)
+
+
+@td.skip_if_no_mpl
+def test_css_named_colors_from_mpl_present():
+ from matplotlib.colors import CSS4_COLORS as mpl_colors
+
+ pd_colors = CSSToExcelConverter.NAMED_COLORS
+ for name, color in mpl_colors.items():
+ assert name in pd_colors and pd_colors[name] == color[1:]
| Backport PR #38247: BUG: Limited available colors | https://api.github.com/repos/pandas-dev/pandas/pulls/38435 | 2020-12-12T23:32:26Z | 2020-12-13T17:09:57Z | 2020-12-13T17:09:57Z | 2020-12-13T19:19:45Z |
BUG: read_csv raising TypeError for engine=c with names and parse_dates | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index ab9f303bec6aa..30f71201ed3dc 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -147,7 +147,7 @@ MultiIndex
I/O
^^^
--
+- Bug in :func:`read_csv` raising ``TypeError`` when ``names`` and ``parse_dates`` is specified for ``engine="c"`` (:issue:`33699`)
-
Period
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 5b623c360c3ef..7a56b03326762 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1431,7 +1431,7 @@ def _should_parse_dates(self, i):
name = self.index_names[i]
else:
name = None
- j = self.index_col[i]
+ j = i if self.index_col is None else self.index_col[i]
if is_scalar(self.parse_dates):
return (j == self.parse_dates) or (
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index 119b4090dd4c7..c0b29d5019675 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -1595,3 +1595,12 @@ def test_missing_parse_dates_column_raises(
parser.read_csv(
content, sep=",", names=names, usecols=usecols, parse_dates=parse_dates
)
+
+
+def test_date_parser_and_names(all_parsers):
+ # GH#33699
+ parser = all_parsers
+ data = StringIO("""x,y\n1,2""")
+ result = parser.read_csv(data, parse_dates=["B"], names=["B"])
+ expected = DataFrame({"B": ["y", "2"]}, index=["x", "1"])
+ tm.assert_frame_equal(result, expected)
| - [x] closes #33699
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/38431 | 2020-12-12T21:04:30Z | 2020-12-12T23:03:53Z | 2020-12-12T23:03:53Z | 2020-12-12T23:09:31Z |
CLN: Move print_versions into pandas proper. | diff --git a/ci/print_versions.py b/ci/print_versions.py
index 0df8bb7e28786..f2549fe73be24 100755
--- a/ci/print_versions.py
+++ b/ci/print_versions.py
@@ -1,132 +1,5 @@
#!/usr/bin/env python
-import sys
-print("\nINSTALLED VERSIONS")
-print("------------------")
-print("Python: %d.%d.%d.%s.%s" % sys.version_info[:])
-try:
- import os, sys
- (sysname, nodename, release, version, machine) = os.uname()
- print("OS: %s %s %s %s" % (sysname, release, version,machine))
- print("byteorder: %s" % sys.byteorder)
- print("LC_ALL: %s" % os.environ.get('LC_ALL',"None"))
- print("LANG: %s" % os.environ.get('LANG',"None"))
-except:
- pass
+from pandas.util.print_versions import show_versions
-print("")
-try:
- import Cython
- print("Cython: %s" % Cython.__version__)
-except:
- print("Cython: Not installed")
-
-try:
- import numpy
- print("Numpy: %s" % numpy.version.version)
-except:
- print("Numpy: Not installed")
-
-try:
- import scipy
- print("Scipy: %s" % scipy.version.version)
-except:
- print("Scipy: Not installed")
-
-try:
- import statsmodels
- print("statsmodels: %s" % statsmodels.__version__)
-except:
- print("statsmodels: Not installed")
-try:
- import patsy
- print(" patsy: %s" % patsy.__version__)
-except:
- print(" patsy: Not installed")
-
-try:
- import scikits.timeseries as ts
- print("scikits.timeseries: %s" % ts.__version__)
-except:
- print("scikits.timeseries: Not installed")
-
-try:
- import dateutil
- print("dateutil: %s" % dateutil.__version__)
-except:
- print("dateutil: Not installed")
-
-try:
- import pytz
- print("pytz: %s" % pytz.VERSION)
-except:
- print("pytz: Not installed")
-
-try:
- import bottleneck
- print("bottleneck: %s" % bottleneck.__version__)
-except:
- print("bottleneck: Not installed")
-
-try:
- import tables
- print("PyTables: %s" % tables.__version__)
-except:
- print("PyTables: Not Installed")
-
-try:
- import numexpr
- print(" numexpr: %s" % numexpr.__version__)
-except:
- print(" numexpr: Not Installed")
-
-try:
- import matplotlib
- print("matplotlib: %s" % matplotlib.__version__)
-except:
- print("matplotlib: Not installed")
-
-try:
- import openpyxl
- print("openpyxl: %s" % openpyxl.__version__)
-except:
- print("openpyxl: Not installed")
-
-try:
- import xlrd
- print("xlrd: %s" % xlrd.__VERSION__)
-except:
- print("xlrd: Not installed")
-
-try:
- import xlwt
- print("xlwt: %s" % xlwt.__VERSION__)
-except:
- print("xlwt: Not installed")
-
-try:
- import sqlalchemy
- print("sqlalchemy: %s" % sqlalchemy.__version__)
-except:
- print("sqlalchemy: Not installed")
-
-try:
- import lxml
- from lxml import etree
- print("lxml: %s" % etree.__version__)
-except:
- print("lxml: Not installed")
-
-try:
- import bs4
- print("bs4: %s" % bs4.__version__)
-except:
- print("bs4: Not installed")
-
-try:
- import html5lib
- print("html5lib: %s" % html5lib.__version__)
-except:
- print("html5lib: Not installed")
-
-print("\n")
+show_versions()
diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py
new file mode 100644
index 0000000000000..b7b4a936a1e90
--- /dev/null
+++ b/pandas/util/print_versions.py
@@ -0,0 +1,135 @@
+import os
+import sys
+
+def show_versions():
+ print("\nINSTALLED VERSIONS")
+ print("------------------")
+ print("Python: %d.%d.%d.%s.%s" % sys.version_info[:])
+ try:
+ (sysname, nodename, release, version, machine) = os.uname()
+ print("OS: %s %s %s %s" % (sysname, release, version,machine))
+ print("byteorder: %s" % sys.byteorder)
+ print("LC_ALL: %s" % os.environ.get('LC_ALL',"None"))
+ print("LANG: %s" % os.environ.get('LANG',"None"))
+ except:
+ pass
+
+ print("")
+ try:
+ import Cython
+ print("Cython: %s" % Cython.__version__)
+ except:
+ print("Cython: Not installed")
+
+ try:
+ import numpy
+ print("Numpy: %s" % numpy.version.version)
+ except:
+ print("Numpy: Not installed")
+
+ try:
+ import scipy
+ print("Scipy: %s" % scipy.version.version)
+ except:
+ print("Scipy: Not installed")
+
+ try:
+ import statsmodels
+ print("statsmodels: %s" % statsmodels.__version__)
+ except:
+ print("statsmodels: Not installed")
+ try:
+ import patsy
+ print(" patsy: %s" % patsy.__version__)
+ except:
+ print(" patsy: Not installed")
+
+ try:
+ import scikits.timeseries as ts
+ print("scikits.timeseries: %s" % ts.__version__)
+ except:
+ print("scikits.timeseries: Not installed")
+
+ try:
+ import dateutil
+ print("dateutil: %s" % dateutil.__version__)
+ except:
+ print("dateutil: Not installed")
+
+ try:
+ import pytz
+ print("pytz: %s" % pytz.VERSION)
+ except:
+ print("pytz: Not installed")
+
+ try:
+ import bottleneck
+ print("bottleneck: %s" % bottleneck.__version__)
+ except:
+ print("bottleneck: Not installed")
+
+ try:
+ import tables
+ print("PyTables: %s" % tables.__version__)
+ except:
+ print("PyTables: Not Installed")
+
+ try:
+ import numexpr
+ print(" numexpr: %s" % numexpr.__version__)
+ except:
+ print(" numexpr: Not Installed")
+
+ try:
+ import matplotlib
+ print("matplotlib: %s" % matplotlib.__version__)
+ except:
+ print("matplotlib: Not installed")
+
+ try:
+ import openpyxl
+ print("openpyxl: %s" % openpyxl.__version__)
+ except:
+ print("openpyxl: Not installed")
+
+ try:
+ import xlrd
+ print("xlrd: %s" % xlrd.__VERSION__)
+ except:
+ print("xlrd: Not installed")
+
+ try:
+ import xlwt
+ print("xlwt: %s" % xlwt.__VERSION__)
+ except:
+ print("xlwt: Not installed")
+
+ try:
+ import sqlalchemy
+ print("sqlalchemy: %s" % sqlalchemy.__version__)
+ except:
+ print("sqlalchemy: Not installed")
+
+ try:
+ import lxml
+ from lxml import etree
+ print("lxml: %s" % etree.__version__)
+ except:
+ print("lxml: Not installed")
+
+ try:
+ import bs4
+ print("bs4: %s" % bs4.__version__)
+ except:
+ print("bs4: Not installed")
+
+ try:
+ import html5lib
+ print("html5lib: %s" % html5lib.__version__)
+ except:
+ print("html5lib: Not installed")
+
+ print("\n")
+
+if __name__ == "__main__":
+ show_versions()
| Moves print_versions under util so that it can be called from buildbot
(and so we can tell people to run `from pandas.util.print_versions import show_versions; show_versions()`
when trying to debug)
cc @yarikoptic
| https://api.github.com/repos/pandas-dev/pandas/pulls/4760 | 2013-09-06T02:26:58Z | 2013-09-06T02:49:12Z | 2013-09-06T02:49:12Z | 2014-07-16T08:26:47Z |
BUG: Bug with reindexing on the index with a non-unique index will now raise a ValueError | diff --git a/doc/source/release.rst b/doc/source/release.rst
index d75e9d2cee52e..9a34cdbdfb5a8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -151,6 +151,7 @@ pandas 0.13
- ``Series.isin()`` and ``DataFrame.isin()`` now raise a ``TypeError`` when
passed a string (:issue:`4763`). Pass a ``list`` of one element (containing
the string) instead.
+ - Remove undocumented/unused ``kind`` keyword argument from ``read_excel``, and ``ExcelFile``. (:issue:`4713`, :issue:`4712`)
**Internal Refactoring**
@@ -172,7 +173,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- ``_indexed_same,reindex_like,align,where,mask``
- ``fillna,replace`` (``Series`` replace is now consistent with ``DataFrame``)
- ``filter`` (also added axis argument to selectively filter on a different axis)
- - ``reindex,reindex_axis`` (which was the biggest change to make generic)
+ - ``reindex,reindex_axis,take``
- ``truncate`` (moved to become part of ``NDFrame``)
- These are API changes which make ``Panel`` more consistent with ``DataFrame``
@@ -224,7 +225,6 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility
- Refactor of Series arithmetic with time-like objects (datetime/timedelta/time
etc.) into a separate, cleaned up wrapper class. (:issue:`4613`)
-- Remove undocumented/unused ``kind`` keyword argument from ``read_excel``, and ``ExcelFile``. (:issue:`4713`, :issue:`4712`)
**Experimental Features**
@@ -326,6 +326,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Bug with using ``QUOTE_NONE`` with ``to_csv`` causing ``Exception``. (:issue:`4328`)
- Bug with Series indexing not raising an error when the right-hand-side has an incorrect length (:issue:`2702`)
- Bug in multi-indexing with a partial string selection as one part of a MultIndex (:issue:`4758`)
+ - Bug with reindexing on the index with a non-unique index will now raise ``ValueError`` (:issue:`4746`)
pandas 0.12
===========
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index d1decc164484d..6b8b7e73f3ac4 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -297,7 +297,7 @@ and behaviors. Series formerly subclassed directly from ``ndarray``. (:issue:`40
- ``_indexed_same,reindex_like,align,where,mask``
- ``fillna,replace`` (``Series`` replace is now consistent with ``DataFrame``)
- ``filter`` (also added axis argument to selectively filter on a different axis)
- - ``reindex,reindex_axis`` (which was the biggest change to make generic)
+ - ``reindex,reindex_axis,take``
- ``truncate`` (moved to become part of ``NDFrame``)
- These are API changes which make ``Panel`` more consistent with ``DataFrame``
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8c6e7697f8ea1..a3eb3ea54c784 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2267,7 +2267,7 @@ def _reindex_index(self, new_index, method, copy, level, fill_value=NA,
limit=limit, copy_if_needed=True,
takeable=takeable)
return self._reindex_with_indexers({0: [new_index, indexer]},
- copy=copy, fill_value=fill_value)
+ copy=copy, fill_value=fill_value, allow_dups=takeable)
def _reindex_columns(self, new_columns, copy, level, fill_value=NA,
limit=None, takeable=False):
@@ -2275,7 +2275,7 @@ def _reindex_columns(self, new_columns, copy, level, fill_value=NA,
limit=limit, copy_if_needed=True,
takeable=takeable)
return self._reindex_with_indexers({1: [new_columns, indexer]},
- copy=copy, fill_value=fill_value)
+ copy=copy, fill_value=fill_value, allow_dups=takeable)
def _reindex_multi(self, axes, copy, fill_value):
""" we are guaranteed non-Nones in the axes! """
@@ -2513,49 +2513,6 @@ def _maybe_cast(values, labels=None):
delevel = deprecate('delevel', reset_index)
- def take(self, indices, axis=0, convert=True):
- """
- Analogous to ndarray.take, return DataFrame corresponding to requested
- indices along an axis
-
- Parameters
- ----------
- indices : list / array of ints
- axis : {0, 1}
- convert : convert indices for negative values, check bounds, default True
- mainly useful for an user routine calling
-
- Returns
- -------
- taken : DataFrame
- """
-
- # check/convert indicies here
- if convert:
- axis = self._get_axis_number(axis)
- indices = _maybe_convert_indices(
- indices, len(self._get_axis(axis)))
-
- if self._is_mixed_type:
- if axis == 0:
- new_data = self._data.take(indices, axis=1, verify=False)
- return DataFrame(new_data)
- else:
- new_columns = self.columns.take(indices)
- return self.reindex(columns=new_columns)
- else:
- new_values = com.take_nd(self.values,
- com._ensure_int64(indices),
- axis=axis)
- if axis == 0:
- new_columns = self.columns
- new_index = self.index.take(indices)
- else:
- new_columns = self.columns.take(indices)
- new_index = self.index
- return self._constructor(new_values, index=new_index,
- columns=new_columns)
-
#----------------------------------------------------------------------
# Reindex-based selection methods
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 796c3948a2681..7f5b9b7f75545 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -862,12 +862,13 @@ def take(self, indices, axis=0, convert=True):
indices = _maybe_convert_indices(
indices, len(self._get_axis(axis)))
- if axis == 0:
+ baxis = self._get_block_manager_axis(axis)
+ if baxis == 0:
labels = self._get_axis(axis)
new_items = labels.take(indices)
- new_data = self._data.reindex_axis(new_items, axis=0)
+ new_data = self._data.reindex_axis(new_items, indexer=indices, axis=0)
else:
- new_data = self._data.take(indices, axis=axis, verify=False)
+ new_data = self._data.take(indices, axis=baxis)
return self._constructor(new_data)
def select(self, crit, axis=0):
@@ -944,7 +945,7 @@ def drop(self, labels, axis=0, level=None):
new_axis = axis.drop(labels, level=level)
else:
new_axis = axis.drop(labels)
- dropped = self.reindex(**{axis_name: new_axis})
+ dropped = self.reindex(**{ axis_name: new_axis })
try:
dropped.axes[axis_].set_names(axis.names, inplace=True)
except AttributeError:
@@ -1161,7 +1162,8 @@ def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,
return self._reindex_with_indexers({axis: [new_index, indexer]}, method=method, fill_value=fill_value,
limit=limit, copy=copy)._propogate_attributes(self)
- def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, limit=None, copy=False):
+ def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, limit=None, copy=False, allow_dups=False):
+ """ allow_dups indicates an internal call here """
# reindex doing multiple operations on different axes if indiciated
new_data = self._data
@@ -1183,7 +1185,7 @@ def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, lim
# TODO: speed up on homogeneous DataFrame objects
indexer = com._ensure_int64(indexer)
new_data = new_data.reindex_indexer(index, indexer, axis=baxis,
- fill_value=fill_value)
+ fill_value=fill_value, allow_dups=allow_dups)
elif baxis == 0 and index is not None and index is not new_data.axes[baxis]:
new_data = new_data.reindex_items(index, copy=copy,
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 9ecdf1930604f..19eeecfeb2bde 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -668,7 +668,7 @@ def _reindex(keys, level=None):
if axis+1 > ndim:
raise AssertionError("invalid indexing error with non-unique index")
- result = result._reindex_with_indexers({ axis : [ new_labels, new_indexer ] }, copy=True)
+ result = result._reindex_with_indexers({ axis : [ new_labels, new_indexer ] }, copy=True, allow_dups=True)
return result
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index e0ee99455d238..91fdc712fb9b8 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -198,6 +198,7 @@ def reindex_axis(self, indexer, method=None, axis=1, fill_value=None, limit=None
raise AssertionError('axis must be at least 1, got %d' % axis)
if fill_value is None:
fill_value = self.fill_value
+
new_values = com.take_nd(self.values, indexer, axis,
fill_value=fill_value, mask_info=mask_info)
return make_block(
@@ -1515,7 +1516,20 @@ def reindex_items_from(self, new_ref_items, indexer=None, method=None, fill_valu
if indexer is None:
indexer = np.arange(len(self.items))
- new_values = com.take_1d(self.values.values, indexer)
+ # single block
+ if self.ndim == 1:
+
+ new_items = new_ref_items
+ new_values = com.take_1d(self.values.values, indexer)
+
+ else:
+
+ # if we don't overlap at all, then don't include this block
+ new_items = self.items & new_ref_items
+ if not len(new_items):
+ return None
+
+ new_values = self.values.values
# fill if needed
if method is not None or limit is not None:
@@ -1523,7 +1537,7 @@ def reindex_items_from(self, new_ref_items, indexer=None, method=None, fill_valu
fill_value = self.fill_value
new_values = com.interpolate_2d(new_values, method=method, limit=limit, fill_value=fill_value)
- return self.make_block(new_values, items=new_ref_items, ref_items=new_ref_items, copy=copy)
+ return self.make_block(new_values, items=new_items, ref_items=new_ref_items, copy=copy)
def sparse_reindex(self, new_index):
""" sparse reindex and return a new block
@@ -2718,10 +2732,14 @@ def reindex_axis0_with_method(self, new_axis, indexer=None, method=None, fill_va
raise AssertionError('method argument not supported for '
'axis == 0')
- def reindex_indexer(self, new_axis, indexer, axis=1, fill_value=None):
+ def reindex_indexer(self, new_axis, indexer, axis=1, fill_value=None, allow_dups=False):
"""
pandas-indexer with -1's only.
"""
+ # trying to reindex on an axis with duplicates
+ if not allow_dups and not self.axes[axis].is_unique:
+ raise ValueError("cannot reindex from a duplicate axis")
+
if axis == 0:
return self._reindex_indexer_items(new_axis, indexer, fill_value)
@@ -2789,15 +2807,34 @@ def reindex_items(self, new_items, indexer=None, copy=True, fill_value=None):
if indexer is None:
for blk in self.blocks:
if copy:
- new_blocks.append(blk.reindex_items_from(new_items))
+ blk = blk.reindex_items_from(new_items)
else:
blk.ref_items = new_items
+ if blk is not None:
new_blocks.append(blk)
else:
- for block in self.blocks:
- newb = block.reindex_items_from(new_items, copy=copy)
- if len(newb.items) > 0:
- new_blocks.append(newb)
+
+ # unique
+ if self.axes[0].is_unique:
+ for block in self.blocks:
+
+ newb = block.reindex_items_from(new_items, copy=copy)
+ if newb is not None and len(newb.items) > 0:
+ new_blocks.append(newb)
+
+ # non-unique
+ else:
+ rl = self._set_ref_locs()
+ for i, idx in enumerate(indexer):
+ blk, lidx = rl[idx]
+ item = new_items.take([i])
+ blk = make_block(_block_shape(blk.iget(lidx)),
+ item,
+ new_items,
+ ndim=self.ndim,
+ fastpath=True,
+ placement = [i])
+ new_blocks.append(blk)
# add a na block if we are missing items
mask = indexer == -1
diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py
index 91f2fe319957b..e0a9d2b937225 100644
--- a/pandas/sparse/tests/test_sparse.py
+++ b/pandas/sparse/tests/test_sparse.py
@@ -384,7 +384,9 @@ def test_getitem_slice(self):
idx = self.bseries.index
res = self.bseries[::2]
tm.assert_isinstance(res, SparseSeries)
- assert_sp_series_equal(res, self.bseries.reindex(idx[::2]))
+
+ expected = self.bseries.reindex(idx[::2])
+ assert_sp_series_equal(res, expected)
res = self.bseries[:5]
tm.assert_isinstance(res, SparseSeries)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index b4ec36ac5f29e..bb76547da0c28 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -2879,7 +2879,7 @@ def test_constructor_column_duplicates(self):
columns=['b', 'a', 'a'])
- def test_column_duplicates_operations(self):
+ def test_column_dups_operations(self):
def check(result, expected=None):
if expected is not None:
@@ -2973,22 +2973,6 @@ def check(result, expected=None):
expected = DataFrame([[1,5,7.],[1,5,7.],[1,5,7.]],columns=['bar','hello','foo2'])
check(df,expected)
- # reindex
- df = DataFrame([[1,5,7.],[1,5,7.],[1,5,7.]],columns=['bar','a','a'])
- expected = DataFrame([[1],[1],[1]],columns=['bar'])
- result = df.reindex(columns=['bar'])
- check(result,expected)
-
- result1 = DataFrame([[1],[1],[1]],columns=['bar']).reindex(columns=['bar','foo'])
- result2 = df.reindex(columns=['bar','foo'])
- check(result2,result1)
-
- # drop
- df = DataFrame([[1,5,7.],[1,5,7.],[1,5,7.]],columns=['bar','a','a'])
- df = df.drop(['a'],axis=1)
- expected = DataFrame([[1],[1],[1]],columns=['bar'])
- check(df,expected)
-
# values
df = DataFrame([[1,2.5],[3,4.5]], index=[1,2], columns=['x','x'])
result = df.values
@@ -3016,6 +3000,17 @@ def check(result, expected=None):
columns=['RT','TClose','TExg','RPT_Date','STK_ID','STK_Name','QT_Close']).set_index(['STK_ID','RPT_Date'],drop=False)
assert_frame_equal(result,expected)
+ # reindex is invalid!
+ df = DataFrame([[1,5,7.],[1,5,7.],[1,5,7.]],columns=['bar','a','a'])
+ self.assertRaises(ValueError, df.reindex, columns=['bar'])
+ self.assertRaises(ValueError, df.reindex, columns=['bar','foo'])
+
+ # drop
+ df = DataFrame([[1,5,7.],[1,5,7.],[1,5,7.]],columns=['bar','a','a'])
+ df = df.drop(['a'],axis=1)
+ expected = DataFrame([[1],[1],[1]],columns=['bar'])
+ check(df,expected)
+
def test_insert_benchmark(self):
# from the vb_suite/frame_methods/frame_insert_columns
N = 10
@@ -7573,6 +7568,21 @@ def test_reindex_fill_value(self):
expected = df.reindex(lrange(15)).fillna(0)
assert_frame_equal(result, expected)
+ def test_reindex_dups(self):
+
+ # GH4746, reindex on duplicate index error messages
+ arr = np.random.randn(10)
+ df = DataFrame(arr,index=[1,2,3,4,5,1,2,3,4,5])
+
+ # set index is ok
+ result = df.copy()
+ result.index = list(range(len(df)))
+ expected = DataFrame(arr,index=list(range(len(df))))
+ assert_frame_equal(result,expected)
+
+ # reindex fails
+ self.assertRaises(ValueError, df.reindex, index=list(range(len(df))))
+
def test_align(self):
af, bf = self.frame.align(self.frame)
| closes #4746
| https://api.github.com/repos/pandas-dev/pandas/pulls/4757 | 2013-09-05T19:23:07Z | 2013-09-06T23:09:09Z | 2013-09-06T23:09:08Z | 2014-06-16T12:19:34Z |
BUG/ER: (GH2702) Bug with Series indexing not raising an error when the right-hand-side has an incorrect length | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 557c4b293a84e..8f782f31fd72c 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -319,6 +319,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
etc. (:issue:`4718`, :issue:`4628`)
- Bug in using ``iloc/loc`` with a cross-sectional and duplicate indicies (:issue:`4726`)
- Bug with using ``QUOTE_NONE`` with ``to_csv`` causing ``Exception``. (:issue:`4328`)
+ - Bug with Series indexing not raising an error when the right-hand-side has an incorrect length (:issue:`2702`)
pandas 0.12
===========
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index d025c7a7fcf6d..0d0f0135c1855 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -547,10 +547,41 @@ def setitem(self, indexer, value):
dtype, _ = com._maybe_promote(arr_value.dtype)
values = values.astype(dtype)
+ transf = (lambda x: x.T) if self.ndim == 2 else (lambda x: x)
+ values = transf(values)
+ l = len(values)
+
+ # length checking
+ # boolean with truth values == len of the value is ok too
+ if isinstance(indexer, (np.ndarray, list)):
+ if is_list_like(value) and len(indexer) != len(value):
+ if not (isinstance(indexer, np.ndarray) and indexer.dtype == np.bool_ and len(indexer[indexer]) == len(value)):
+ raise ValueError("cannot set using a list-like indexer with a different length than the value")
+
+ # slice
+ elif isinstance(indexer, slice):
+
+ if is_list_like(value) and l:
+ start = indexer.start
+ stop = indexer.stop
+ step = indexer.step
+ if start is None:
+ start = 0
+ elif start < 0:
+ start += l
+ if stop is None or stop > l:
+ stop = len(values)
+ elif stop < 0:
+ stop += l
+ if step is None:
+ step = 1
+ elif step < 0:
+ step = abs(step)
+ if (stop-start) / step != len(value):
+ raise ValueError("cannot set using a slice indexer with a different length than the value")
+
try:
# set and return a block
- transf = (lambda x: x.T) if self.ndim == 2 else (lambda x: x)
- values = transf(values)
values[indexer] = value
# coerce and try to infer the dtypes of the result
@@ -561,7 +592,9 @@ def setitem(self, indexer, value):
values = self._try_coerce_result(values)
values = self._try_cast_result(values, dtype)
return [make_block(transf(values), self.items, self.ref_items, ndim=self.ndim, fastpath=True)]
- except:
+ except (ValueError, TypeError) as detail:
+ raise
+ except (Exception) as detail:
pass
return [ self ]
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 8396de9c5997b..3b36d7c38e16d 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1096,10 +1096,9 @@ def _set_labels(self, key, value):
self._set_values(indexer, value)
def _set_values(self, key, value):
- values = self.values
if isinstance(key, Series):
key = key.values
- values[key] = _index.convert_scalar(values, value)
+ self._data = self._data.setitem(key,value)
# help out SparseSeries
_get_val_at = ndarray.__getitem__
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 282dad5c0d6be..514245e82ac28 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1284,6 +1284,59 @@ def f():
expected = Series(np.nan,index=[9])
assert_series_equal(result, expected)
+ def test_where_setitem_invalid(self):
+
+ # GH 2702
+ # make sure correct exceptions are raised on invalid list assignment
+
+ # slice
+ s = Series(list('abc'))
+ def f():
+ s[0:3] = list(range(27))
+ self.assertRaises(ValueError, f)
+
+ s[0:3] = list(range(3))
+ expected = Series([0,1,2])
+ assert_series_equal(s, expected)
+
+ # slice with step
+ s = Series(list('abcdef'))
+ def f():
+ s[0:4:2] = list(range(27))
+ self.assertRaises(ValueError, f)
+
+ s = Series(list('abcdef'))
+ s[0:4:2] = list(range(2))
+ expected = Series([0,'b',1,'d','e','f'])
+ assert_series_equal(s, expected)
+
+ # neg slices
+ s = Series(list('abcdef'))
+ def f():
+ s[:-1] = list(range(27))
+ self.assertRaises(ValueError, f)
+
+ s[-3:-1] = list(range(2))
+ expected = Series(['a','b','c',0,1,'f'])
+ assert_series_equal(s, expected)
+
+ # list
+ s = Series(list('abc'))
+ def f():
+ s[[0,1,2]] = list(range(27))
+ self.assertRaises(ValueError, f)
+
+ s = Series(list('abc'))
+ def f():
+ s[[0,1,2]] = list(range(2))
+ self.assertRaises(ValueError, f)
+
+ # scalar
+ s = Series(list('abc'))
+ s[0] = list(range(10))
+ expected = Series([list(range(10)),'b','c'])
+ assert_series_equal(s, expected)
+
def test_where_broadcast(self):
# Test a variety of differently sized series
for size in range(2, 6):
@@ -2550,22 +2603,23 @@ def test_between(self):
expected = s[5:16].dropna()
assert_series_equal(result, expected)
- def test_setitem_na_exception(self):
- def testme1():
- s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
- s[::2] = np.nan
-
- def testme2():
- s = Series([True, True, False, False])
- s[::2] = np.nan
+ def test_setitem_na(self):
+ # these induce dtype changes
+ expected = Series([np.nan, 3, np.nan, 5, np.nan, 7, np.nan, 9, np.nan])
+ s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
+ s[::2] = np.nan
+ assert_series_equal(s, expected)
- def testme3():
- s = Series(np.arange(10))
- s[:5] = np.nan
+ # get's coerced to float, right?
+ expected = Series([np.nan, 1, np.nan, 0])
+ s = Series([True, True, False, False])
+ s[::2] = np.nan
+ assert_series_equal(s, expected)
- self.assertRaises(Exception, testme1)
- self.assertRaises(Exception, testme2)
- self.assertRaises(Exception, testme3)
+ expected = Series([np.nan, np.nan, np.nan, np.nan, np.nan, 5, 6, 7, 8, 9])
+ s = Series(np.arange(10))
+ s[:5] = np.nan
+ assert_series_equal(s, expected)
def test_scalar_na_cmp_corners(self):
s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])
| closes #2702
Base use cases (note that a completely changed series will morph to the new dtype if necessary)
```
In [1]: s = Series(list('abc'))
In [2]: s[0:3] = list(range(3))
In [3]: s
Out[3]:
0 0
1 1
2 2
dtype: int64
In [4]: s = Series(list('abc'))
In [5]: s[0:2] = list(range(2))
In [6]: s
Out[6]:
0 0
1 1
2 c
dtype: object
```
This is a bit odd, but allowed
```
In [4]: s[0] = list(range(10))
In [5]: s
Out[5]:
0 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 b
2 c
dtype: object
```
These all will raise error messages now
```
In [1]: s = Series(list('abc'))
In [2]: s[0:3] = list(range(27))
ValueError: cannot set using a slice indexer with a different length than the value
In [3]: s[[0,1,2]] = list(range(27))
ValueError: cannot set using a list-like indexer with a different length than the value
In [4]: s[[0,1,2]] = list(range(2))
ValueError: cannot set using a list-like indexer with a different length than the value
```
With a step and a slice indexer (not sure was tested before)
When the length of the slicer matches exactly it works
```
In [5]: s = Series(list('abcdef'))
In [6]: s[0:4:2] = list(range(2))
In [7]: s
Out[7]:
0 0
1 b
2 1
3 d
4 e
5 f
dtype: object
```
Raises when it doesn't
```
In [8]: s[0:4:2] = list(range(27))
ValueError: cannot set using a slice indexer with a different length than the value
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4756 | 2013-09-05T18:13:02Z | 2013-09-06T03:11:15Z | 2013-09-06T03:11:15Z | 2014-06-16T16:32:22Z |
BUG: TimeSeries compat from < 0.13 | diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index 58bbf70c0bea9..bf52fc30a9ea3 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -1,12 +1,13 @@
""" support pre 0.12 series pickle compatibility """
import sys
-import pickle
import numpy as np
import pandas
+import pickle as pkl
from pandas import compat
-from pandas.core.series import Series
-from pandas.sparse.series import SparseSeries
+from pandas.compat import u, string_types
+from pandas.core.series import Series, TimeSeries
+from pandas.sparse.series import SparseSeries, SparseTimeSeries
def load_reduce(self):
stack = self.stack
@@ -14,49 +15,89 @@ def load_reduce(self):
func = stack[-1]
if type(args[0]) is type:
n = args[0].__name__
- if n == 'DeprecatedSeries':
+ if n == u('DeprecatedSeries') or n == u('DeprecatedTimeSeries'):
stack[-1] = object.__new__(Series)
return
- elif n == 'DeprecatedSparseSeries':
+ elif n == u('DeprecatedSparseSeries') or n == u('DeprecatedSparseTimeSeries'):
stack[-1] = object.__new__(SparseSeries)
return
try:
value = func(*args)
except:
- print(sys.exc_info())
- print(func, args)
+
+ # try to reencode the arguments
+ if self.encoding is not None:
+ args = tuple([ arg.encode(self.encoding) if isinstance(arg, string_types) else arg for arg in args ])
+ try:
+ stack[-1] = func(*args)
+ return
+ except:
+ pass
+
+ if self.is_verbose:
+ print(sys.exc_info())
+ print(func, args)
raise
stack[-1] = value
if compat.PY3:
- class Unpickler(pickle._Unpickler):
+ class Unpickler(pkl._Unpickler):
pass
else:
- class Unpickler(pickle.Unpickler):
+ class Unpickler(pkl.Unpickler):
pass
-Unpickler.dispatch[pickle.REDUCE[0]] = load_reduce
+Unpickler.dispatch[pkl.REDUCE[0]] = load_reduce
+
+def load(fh, encoding=None, compat=False, is_verbose=False):
+ """
+ load a pickle, with a provided encoding
-def load(file):
- # try to load a compatibility pickle
- # fake the old class hierarchy
- # if it works, then return the new type objects
+ if compat is True:
+ fake the old class hierarchy
+ if it works, then return the new type objects
+
+ Parameters
+ ----------
+ fh: a filelike object
+ encoding: an optional encoding
+ compat: provide Series compatibility mode, boolean, default False
+ is_verbose: show exception output
+ """
try:
- pandas.core.series.Series = DeprecatedSeries
- pandas.sparse.series.SparseSeries = DeprecatedSparseSeries
- with open(file,'rb') as fh:
- return Unpickler(fh).load()
+ if compat:
+ pandas.core.series.Series = DeprecatedSeries
+ pandas.core.series.TimeSeries = DeprecatedTimeSeries
+ pandas.sparse.series.SparseSeries = DeprecatedSparseSeries
+ pandas.sparse.series.SparseTimeSeries = DeprecatedSparseTimeSeries
+ fh.seek(0)
+ if encoding is not None:
+ up = Unpickler(fh, encoding=encoding)
+ else:
+ up = Unpickler(fh)
+ up.is_verbose = is_verbose
+
+ return up.load()
except:
raise
finally:
- pandas.core.series.Series = Series
- pandas.sparse.series.SparseSeries = SparseSeries
+ if compat:
+ pandas.core.series.Series = Series
+ pandas.core.series.Series = TimeSeries
+ pandas.sparse.series.SparseSeries = SparseSeries
+ pandas.sparse.series.SparseTimeSeries = SparseTimeSeries
-class DeprecatedSeries(Series, np.ndarray):
+class DeprecatedSeries(np.ndarray, Series):
+ pass
+
+class DeprecatedTimeSeries(DeprecatedSeries):
pass
class DeprecatedSparseSeries(DeprecatedSeries):
pass
+
+class DeprecatedSparseTimeSeries(DeprecatedSparseSeries):
+ pass
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 80d5112fa3054..e0ee99455d238 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1845,6 +1845,11 @@ def __setstate__(self, state):
blocks = []
for values, items in zip(bvalues, bitems):
+
+ # numpy < 1.7 pickle compat
+ if values.dtype == 'M8[us]':
+ values = values.astype('M8[ns]')
+
blk = make_block(values, items, self.axes[0])
blocks.append(blk)
self.blocks = blocks
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index efa8bdb0b123b..af1b333312309 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -1,4 +1,4 @@
-from pandas.compat import cPickle as pkl, PY3
+from pandas.compat import cPickle as pkl, pickle_compat as pc, PY3
def to_pickle(obj, path):
"""
@@ -31,11 +31,23 @@ def read_pickle(path):
-------
unpickled : type of object stored in file
"""
+
+ def try_read(path, encoding=None):
+ # try with current pickle, if we have a Type Error then
+ # try with the compat pickle to handle subclass changes
+ # pass encoding only if its not None as py2 doesn't handle
+ # the param
+ try:
+ with open(path,'rb') as fh:
+ with open(path,'rb') as fh:
+ return pc.load(fh, encoding=encoding, compat=False)
+ except:
+ with open(path,'rb') as fh:
+ return pc.load(fh, encoding=encoding, compat=True)
+
try:
- with open(path, 'rb') as fh:
- return pkl.load(fh)
+ return try_read(path)
except:
if PY3:
- with open(path, 'rb') as fh:
- return pkl.load(fh, encoding='latin1')
+ return try_read(path, encoding='latin1')
raise
diff --git a/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle b/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle
new file mode 100644
index 0000000000000..6b471d55b1642
Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.11.0/0.11.0_x86_64_linux_3.3.0.pickle differ
diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_i686_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_i686_linux_2.7.3.pickle
new file mode 100644
index 0000000000000..17061f6b7dc0f
Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_i686_linux_2.7.3.pickle differ
diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle
new file mode 100644
index 0000000000000..470d3e89c433d
Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.12.0/0.12.0_x86_64_linux_2.7.3.pickle differ
diff --git a/pandas/io/tests/data/legacy_pickle/0.12.0/x86_64_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.12.0/x86_64_linux_2.7.3.pickle
new file mode 100644
index 0000000000000..e8c1e52078f7c
Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.12.0/x86_64_linux_2.7.3.pickle differ
diff --git a/pandas/io/tests/data/legacy_pickle/0.13.0/0.12.0-300-g6ffed43_x86_64_linux_2.7.3.pickle b/pandas/io/tests/data/legacy_pickle/0.13.0/0.12.0-300-g6ffed43_x86_64_linux_2.7.3.pickle
new file mode 100644
index 0000000000000..93e1f3e6c9607
Binary files /dev/null and b/pandas/io/tests/data/legacy_pickle/0.13.0/0.12.0-300-g6ffed43_x86_64_linux_2.7.3.pickle differ
diff --git a/pandas/io/tests/generate_legacy_pickles.py b/pandas/io/tests/generate_legacy_pickles.py
index f5d949e2cfc45..f54a67b7f76cf 100644
--- a/pandas/io/tests/generate_legacy_pickles.py
+++ b/pandas/io/tests/generate_legacy_pickles.py
@@ -1,26 +1,47 @@
""" self-contained to write legacy pickle files """
from __future__ import print_function
-from pandas.compat import zip, cPickle as pickle
+# make sure we are < 0.13 compat (in py3)
+try:
+ from pandas.compat import zip, cPickle as pickle
+except:
+ import pickle
def _create_sp_series():
import numpy as np
- from pandas import bdate_range, SparseSeries
+ from pandas import SparseSeries
nan = np.nan
# nan-based
- arr = np.arange(15, dtype=float)
+ arr = np.arange(15, dtype=np.float64)
index = np.arange(15)
arr[7:12] = nan
arr[-1:] = nan
- date_index = bdate_range('1/1/2011', periods=len(index))
- bseries = SparseSeries(arr, index=index, kind='block')
+ bseries = SparseSeries(arr, kind='block')
bseries.name = 'bseries'
return bseries
+def _create_sp_tsseries():
+
+ import numpy as np
+ from pandas import bdate_range, SparseTimeSeries
+
+ nan = np.nan
+
+ # nan-based
+ arr = np.arange(15, dtype=np.float64)
+ index = np.arange(15)
+ arr[7:12] = nan
+ arr[-1:] = nan
+
+ date_index = bdate_range('1/1/2011', periods=len(index))
+ bseries = SparseTimeSeries(arr, index=date_index, kind='block')
+ bseries.name = 'btsseries'
+ return bseries
+
def _create_sp_frame():
import numpy as np
from pandas import bdate_range, SparseDataFrame
@@ -29,7 +50,7 @@ def _create_sp_frame():
data = {'A': [nan, nan, nan, 0, 1, 2, 3, 4, 5, 6],
'B': [0, 1, 2, nan, nan, nan, 3, 4, 5, 6],
- 'C': np.arange(10),
+ 'C': np.arange(10).astype(np.int64),
'D': [0, 1, 2, 3, 4, 5, nan, nan, nan, nan]}
dates = bdate_range('1/1/2011', periods=10)
@@ -40,8 +61,8 @@ def create_data():
import numpy as np
import pandas
- from pandas import (Series,DataFrame,Panel,
- SparseSeries,SparseDataFrame,SparsePanel,
+ from pandas import (Series,TimeSeries,DataFrame,Panel,
+ SparseSeries,SparseTimeSeries,SparseDataFrame,SparsePanel,
Index,MultiIndex,PeriodIndex,
date_range,bdate_range,Timestamp)
nan = np.nan
@@ -61,10 +82,11 @@ def create_data():
names=['first', 'second']))
series = dict(float = Series(data['A']),
int = Series(data['B']),
- mixed = Series(data['E']))
+ mixed = Series(data['E']),
+ ts = TimeSeries(np.arange(10).astype(np.int64),index=date_range('20130101',periods=10)))
frame = dict(float = DataFrame(dict(A = series['float'], B = series['float'] + 1)),
- int = DataFrame(dict(A = series['int'] , B = series['int'] + 1)),
- mixed = DataFrame(dict([ (k,data[k]) for k in ['A','B','C','D']])))
+ int = DataFrame(dict(A = series['int'] , B = series['int'] + 1)),
+ mixed = DataFrame(dict([ (k,data[k]) for k in ['A','B','C','D']])))
panel = dict(float = Panel(dict(ItemA = frame['float'], ItemB = frame['float']+1)))
@@ -74,7 +96,8 @@ def create_data():
panel = panel,
index = index,
mi = mi,
- sp_series = dict(float = _create_sp_series()),
+ sp_series = dict(float = _create_sp_series(),
+ ts = _create_sp_tsseries()),
sp_frame = dict(float = _create_sp_frame())
)
@@ -92,24 +115,11 @@ def write_legacy_pickles():
print("This script generates a pickle file for the current arch, system, and python version")
- base_dir, _ = os.path.split(os.path.abspath(__file__))
- base_dir = os.path.join(base_dir,'data/legacy_pickle')
-
- # could make this a parameter?
- version = None
-
-
- if version is None:
- version = pandas.__version__
- pth = os.path.join(base_dir, str(version))
- try:
- os.mkdir(pth)
- except:
- pass
+ version = pandas.__version__
# construct a reasonable platform name
- f = '_'.join([ str(pl.machine()), str(pl.system().lower()), str(pl.python_version()) ])
- pth = os.path.abspath(os.path.join(pth,'%s.pickle' % f))
+ f = '_'.join([ str(version), str(pl.machine()), str(pl.system().lower()), str(pl.python_version()) ])
+ pth = '{0}.pickle'.format(f)
fh = open(pth,'wb')
pickle.dump(create_data(),fh,pickle.HIGHEST_PROTOCOL)
diff --git a/pandas/io/tests/test_pickle.py b/pandas/io/tests/test_pickle.py
index f2ddce7fa7b7e..92231d2ef094f 100644
--- a/pandas/io/tests/test_pickle.py
+++ b/pandas/io/tests/test_pickle.py
@@ -4,7 +4,7 @@
from datetime import datetime, timedelta
import operator
-import pickle
+import pickle as pkl
import unittest
import nose
import os
@@ -29,25 +29,11 @@ def compare(self, vf):
# py3 compat when reading py2 pickle
try:
- with open(vf,'rb') as fh:
- data = pickle.load(fh)
- except ValueError as detail:
-
- # we are trying to read a py3 pickle in py2.....
+ data = pandas.read_pickle(vf)
+ except (ValueError) as detail:
+ # trying to read a py3 pickle in py2
return
- # we have a deprecated klass
- except TypeError as detail:
-
- from pandas.compat.pickle_compat import load
- data = load(vf)
-
- except:
- if not compat.PY3:
- raise
- with open(vf,'rb') as fh:
- data = pickle.load(fh, encoding='latin1')
-
for typ, dv in data.items():
for dt, result in dv.items():
@@ -64,23 +50,26 @@ def compare(self, vf):
comparator = getattr(tm,"assert_%s_equal" % typ)
comparator(result,expected)
- def test_read_pickles_0_10_1(self):
+ def read_pickles(self, version):
if not is_little_endian():
- raise nose.SkipTest("known failure of test_read_pickles_0_10_1 on non-little endian")
+ raise nose.SkipTest("known failure on non-little endian")
- pth = tm.get_data_path('legacy_pickle/0.10.1')
+ pth = tm.get_data_path('legacy_pickle/{0}'.format(str(version)))
for f in os.listdir(pth):
vf = os.path.join(pth,f)
self.compare(vf)
+ def test_read_pickles_0_10_1(self):
+ self.read_pickles('0.10.1')
+
def test_read_pickles_0_11_0(self):
- if not is_little_endian():
- raise nose.SkipTest("known failure of test_read_pickles_0_11_0 on non-little endian")
+ self.read_pickles('0.11.0')
- pth = tm.get_data_path('legacy_pickle/0.11.0')
- for f in os.listdir(pth):
- vf = os.path.join(pth,f)
- self.compare(vf)
+ def test_read_pickles_0_12_0(self):
+ self.read_pickles('0.12.0')
+
+ def test_read_pickles_0_13_0(self):
+ self.read_pickles('0.13.0')
if __name__ == '__main__':
import nose
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index ce538b72904da..e91cad62e7dce 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -533,6 +533,12 @@ def __setstate__(self, state):
self.offset = own_state[1]
self.tz = own_state[2]
np.ndarray.__setstate__(self, nd_state)
+
+ # provide numpy < 1.7 compat
+ if nd_state[2] == 'M8[us]':
+ new_state = np.ndarray.__reduce__(self.values.astype('M8[ns]'))
+ np.ndarray.__setstate__(self, new_state[2])
+
else: # pragma: no cover
np.ndarray.__setstate__(self, state)
diff --git a/setup.py b/setup.py
index 956b9b13db2ce..f04b39f864ecf 100755
--- a/setup.py
+++ b/setup.py
@@ -526,6 +526,8 @@ def pxd(name):
package_data={'pandas.io': ['tests/data/legacy_hdf/*.h5',
'tests/data/legacy_pickle/0.10.1/*.pickle',
'tests/data/legacy_pickle/0.11.0/*.pickle',
+ 'tests/data/legacy_pickle/0.12.0/*.pickle',
+ 'tests/data/legacy_pickle/0.13.0/*.pickle',
'tests/data/*.csv',
'tests/data/*.dta',
'tests/data/*.txt',
| fixes a pickle compat issue for < 0.13 when presented with a TimeSeries (was an oversight on the initial PR).
additional tests as well
| https://api.github.com/repos/pandas-dev/pandas/pulls/4755 | 2013-09-05T14:44:45Z | 2013-09-06T23:06:27Z | 2013-09-06T23:06:27Z | 2014-06-27T17:57:48Z |
CLN: Remove redundant call to get_splitter | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 723ff2fd5ab56..14e8fba359e6a 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -589,9 +589,6 @@ def get_iterator(self, data, axis=0, keep_internal=True):
Generator yielding sequence of (name, subsetted object)
for each group
"""
- comp_ids, _, ngroups = self.group_info
- splitter = get_splitter(data, comp_ids, ngroups, axis=axis,
- keep_internal=keep_internal)
splitter = self._get_splitter(data, axis=axis,
keep_internal=keep_internal)
keys = self._get_group_keys()
| `get_splitter` was called directly, then again through an internal method. Results from the first call are not used for anything and immediately replaced.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4753 | 2013-09-05T13:39:28Z | 2013-09-06T22:01:31Z | 2013-09-06T22:01:31Z | 2014-07-16T08:26:35Z |
BUG: Fix crash using to_csv with QUOTE_NONE | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 74ac180a7d121..69647939ab0d0 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -315,6 +315,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix some inconsistencies with ``Index.rename`` and ``MultiIndex.rename``,
etc. (:issue:`4718`, :issue:`4628`)
- Bug in using ``iloc/loc`` with a cross-sectional and duplicate indicies (:issue:`4726`)
+ - Bug with using ``QUOTE_NONE`` with ``to_csv`` causing ``Exception``. (:issue:`4328`)
pandas 0.12
===========
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 8077254de47ff..978b82aed22d9 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -787,7 +787,7 @@ def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None,
cols=None, header=True, index=True, index_label=None,
mode='w', nanRep=None, encoding=None, quoting=None,
line_terminator='\n', chunksize=None, engine=None,
- tupleize_cols=True):
+ tupleize_cols=True, quotechar='"'):
self.engine = engine # remove for 0.13
self.obj = obj
@@ -807,6 +807,11 @@ def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None,
quoting = csv.QUOTE_MINIMAL
self.quoting = quoting
+ if quoting == csv.QUOTE_NONE:
+ # prevents crash in _csv
+ quotechar = None
+ self.quotechar = quotechar
+
self.line_terminator = line_terminator
#GH3457
@@ -950,13 +955,14 @@ def save(self):
close = True
try:
+ writer_kwargs = dict(lineterminator=self.line_terminator,
+ delimiter=self.sep, quoting=self.quoting,
+ quotechar=self.quotechar)
if self.encoding is not None:
- self.writer = com.UnicodeWriter(f, lineterminator=self.line_terminator,
- delimiter=self.sep, encoding=self.encoding,
- quoting=self.quoting)
+ writer_kwargs['encoding'] = self.encoding
+ self.writer = com.UnicodeWriter(f, **writer_kwargs)
else:
- self.writer = csv.writer(f, lineterminator=self.line_terminator,
- delimiter=self.sep, quoting=self.quoting)
+ self.writer = csv.writer(f, **writer_kwargs)
if self.engine == 'python':
# to be removed in 0.13
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index b992b2d60a08d..d72c379919e93 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -6,6 +6,7 @@
from datetime import datetime, timedelta, time
import operator
import re
+import csv
import unittest
import nose
@@ -5465,8 +5466,6 @@ def test_to_csv_float_format(self):
assert_frame_equal(rs, xp)
def test_to_csv_quoting(self):
- import csv
-
df = DataFrame({'A': [1, 2, 3], 'B': ['foo', 'bar', 'baz']})
buf = StringIO()
@@ -5489,8 +5488,6 @@ def test_to_csv_quoting(self):
self.assertEqual(buf.getvalue(), text)
def test_to_csv_unicodewriter_quoting(self):
- import csv
-
df = DataFrame({'A': [1, 2, 3], 'B': ['foo', 'bar', 'baz']})
buf = StringIO()
@@ -5505,6 +5502,17 @@ def test_to_csv_unicodewriter_quoting(self):
self.assertEqual(result, expected)
+ def test_to_csv_quote_none(self):
+ # GH4328
+ df = DataFrame({'A': ['hello', '{"hello"}']})
+ for encoding in (None, 'utf-8'):
+ buf = StringIO()
+ df.to_csv(buf, quoting=csv.QUOTE_NONE,
+ encoding=encoding, index=False)
+ result = buf.getvalue()
+ expected = 'A\nhello\n{"hello"}\n'
+ self.assertEqual(result, expected)
+
def test_to_csv_index_no_leading_comma(self):
df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
index=['one', 'two', 'three'])
| Fixes #4328.
Now passes `quotechar` to csv's writer. Default is same as csv (`'"'`), but sets to `None` with `quoting=csv.QUOTE_NONE`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4752 | 2013-09-05T01:48:14Z | 2013-09-05T02:37:09Z | 2013-09-05T02:37:08Z | 2015-08-10T12:29:04Z |
BUG: Fix wrong str.format() calls in Index.summary | diff --git a/doc/source/release.rst b/doc/source/release.rst
index bbadba61c0135..74ac180a7d121 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -1039,6 +1039,8 @@ pandas 0.10.1
- Fix Period resampling bug when all values fall into a single bin (:issue:`2070`)
- Fix buggy interaction with usecols argument in read_csv when there is an
implicit first index column (:issue:`2654`)
+ - Fix bug in ``Index.summary()`` where string format methods were being called incorrectly.
+ (:issue:`3869`)
pandas 0.10.0
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 91e4d51c6c0ad..57a913acf6355 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -310,10 +310,12 @@ def _has_complex_internals(self):
def summary(self, name=None):
if len(self) > 0:
head = self[0]
- if hasattr(head,'format'):
+ if hasattr(head,'format') and\
+ not isinstance(head, compat.string_types):
head = head.format()
tail = self[-1]
- if hasattr(tail,'format'):
+ if hasattr(tail,'format') and\
+ not isinstance(tail, compat.string_types):
tail = tail.format()
index_summary = ', %s to %s' % (com.pprint_thing(head),
com.pprint_thing(tail))
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 410d310e002b2..5b91f011c98f8 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -418,6 +418,12 @@ def test_is_all_dates(self):
def test_summary(self):
self._check_method_works(Index.summary)
+ # GH3869
+ ind = Index(['{other}%s',"~:{range}:0"], name='A')
+ result = ind.summary()
+ # shouldn't be formatted accidentally.
+ self.assert_('~:{range}:0' in result)
+ self.assert_('{other}%s' in result)
def test_format(self):
self._check_method_works(Index.format)
| Fixes #3869.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4751 | 2013-09-05T01:20:12Z | 2013-09-05T02:18:00Z | 2013-09-05T02:18:00Z | 2014-06-22T12:04:51Z |
CLN: Make ExcelWriter more pluggable | diff --git a/doc/source/io.rst b/doc/source/io.rst
index da611c0375789..9fd2c167fa605 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1681,6 +1681,24 @@ one can use the ExcelWriter class, as in the following example:
df2.to_excel(writer, sheet_name='sheet2')
writer.save()
+.. _io.excel.writers:
+
+Excel writer engines
+~~~~~~~~~~~~~~~~~~~~
+
+.. versionadded:: 0.13
+
+``pandas`` chooses an Excel writer via two methods:
+
+1. the ``engine`` keyword argument
+2. the filename extension (via the default specified in config options)
+
+``pandas`` only supports ``openpyxl`` for ``.xlsx`` and ``.xlsm`` files and
+``xlwt`` for ``.xls`` files. If you have multiple engines installed, you can choose the
+engine to use by default via the options ``io.excel.xlsx.writer`` and
+``io.excel.xls.writer``.
+
+
.. _io.hdf5:
HDF5 (PyTables)
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 101ec290a58cf..c80ddd01cdf07 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -106,6 +106,13 @@ Improvements to existing features
- Add ``axis`` and ``level`` keywords to ``where``, so that the ``other`` argument
can now be an alignable pandas object.
- ``to_datetime`` with a format of '%Y%m%d' now parses much faster
+ - It's now easier to hook new Excel writers into pandas (just subclass
+ ``ExcelWriter`` and register your engine). You can specify an ``engine`` in
+ ``to_excel`` or in ``ExcelWriter``. You can also specify which writers you
+ want to use by default with config options ``io.excel.xlsx.writer`` and
+ ``io.excel.xls.writer``. (:issue:`4745`, :issue:`4750`)
+ - ``Panel.to_excel()`` now accepts keyword arguments that will be passed to
+ its ``DataFrame``'s ``to_excel()`` methods. (:issue:`4750`)
API Changes
~~~~~~~~~~~
@@ -194,6 +201,7 @@ API Changes
- default for ``tupleize_cols`` is now ``False`` for both ``to_csv`` and ``read_csv``. Fair warning in 0.12 (:issue:`3604`)
- moved timedeltas support to pandas.tseries.timedeltas.py; add timedeltas string parsing,
add top-level ``to_timedelta`` function
+ - ``NDFrame`` now is compatible with Python's toplevel ``abs()`` function (:issue:`4821`).
Internal Refactoring
~~~~~~~~~~~~~~~~~~~~
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index 494cc5fe9ad29..1b5939eb98417 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -17,6 +17,8 @@
* binary_type: str in Python 2, bythes in Python 3
* string_types: basestring in Python 2, str in Python 3
* bind_method: binds functions to classes
+* add_metaclass(metaclass) - class decorator that recreates class with with the
+ given metaclass instead (and avoids intermediary class creation)
Python 2.6 compatibility:
* OrderedDict
@@ -34,7 +36,6 @@
import types
PY3 = (sys.version_info[0] >= 3)
-# import iterator versions of these functions
try:
import __builtin__ as builtins
@@ -96,6 +97,7 @@ def str_to_bytes(s, encoding='ascii'):
def bytes_to_str(b, encoding='ascii'):
return b
+ # import iterator versions of these functions
range = xrange
zip = itertools.izip
filter = itertools.ifilter
@@ -196,6 +198,19 @@ def u(s):
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
+
+def add_metaclass(metaclass):
+ """Class decorator for creating a class with a metaclass."""
+ def wrapper(cls):
+ orig_vars = cls.__dict__.copy()
+ orig_vars.pop('__dict__', None)
+ orig_vars.pop('__weakref__', None)
+ for slots_var in orig_vars.get('__slots__', ()):
+ orig_vars.pop(slots_var)
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
+ return wrapper
+
+
# ----------------------------------------------------------------------------
# Python 2.6 compatibility shims
#
diff --git a/pandas/core/config.py b/pandas/core/config.py
index a14e8afa21322..f81958a0e58fc 100644
--- a/pandas/core/config.py
+++ b/pandas/core/config.py
@@ -73,7 +73,7 @@ def _get_single_key(pat, silent):
if len(keys) == 0:
if not silent:
_warn_if_deprecated(pat)
- raise KeyError('No such keys(s)')
+ raise KeyError('No such keys(s): %r' % pat)
if len(keys) > 1:
raise KeyError('Pattern matched multiple keys')
key = keys[0]
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index 6119de5af19e0..797e979963ae2 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -279,3 +279,24 @@ def use_inf_as_null_cb(key):
with cf.config_prefix('mode'):
cf.register_option('use_inf_as_null', False, use_inf_as_null_doc,
cb=use_inf_as_null_cb)
+
+
+# Set up the io.excel specific configuration.
+writer_engine_doc = """
+: string
+ The default Excel writer engine for '{ext}' files. Available options: '{default}' (the default){others}.
+"""
+
+with cf.config_prefix('io.excel'):
+ # going forward, will be additional writers
+ for ext, options in [('xls', ['xlwt']),
+ ('xlsm', ['openpyxl']),
+ ('xlsx', ['openpyxl'])]:
+ default = options.pop(0)
+ if options:
+ options = " " + ", ".join(options)
+ else:
+ options = ""
+ doc = writer_engine_doc.format(ext=ext, default=default,
+ others=options)
+ cf.register_option(ext + '.writer', default, doc, validator=str)
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 92fcfaa5f2f9c..28ff12a6e51c4 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -1146,15 +1146,8 @@ class ExcelFormatter(object):
sequence should be given if the DataFrame uses MultiIndex.
"""
- def __init__(self,
- df,
- na_rep='',
- float_format=None,
- cols=None,
- header=True,
- index=True,
- index_label=None
- ):
+ def __init__(self, df, na_rep='', float_format=None, cols=None,
+ header=True, index=True, index_label=None):
self.df = df
self.rowcounter = 0
self.na_rep = na_rep
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2b0e18c0c5524..bd601c5c8408e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1354,7 +1354,7 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,
def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='',
float_format=None, cols=None, header=True, index=True,
- index_label=None, startrow=0, startcol=0):
+ index_label=None, startrow=0, startcol=0, engine=None):
"""
Write DataFrame to a excel sheet
@@ -1381,6 +1381,10 @@ def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='',
sequence should be given if the DataFrame uses MultiIndex.
startow : upper left cell row to dump data frame
startcol : upper left cell column to dump data frame
+ engine : string, default None
+ write engine to use - you can also set this via the options
+ ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
+ ``io.excel.xlsm.writer``.
Notes
@@ -1396,7 +1400,7 @@ def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='',
from pandas.io.excel import ExcelWriter
need_save = False
if isinstance(excel_writer, compat.string_types):
- excel_writer = ExcelWriter(excel_writer)
+ excel_writer = ExcelWriter(excel_writer, engine=engine)
need_save = True
formatter = fmt.ExcelFormatter(self,
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index bca6f985ac689..6f02b49326e4d 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -458,22 +458,53 @@ def to_sparse(self, fill_value=None, kind='block'):
default_kind=kind,
default_fill_value=fill_value)
- def to_excel(self, path, na_rep=''):
+ def to_excel(self, path, na_rep='', engine=None, **kwargs):
"""
Write each DataFrame in Panel to a separate excel sheet
Parameters
----------
- excel_writer : string or ExcelWriter object
+ path : string or ExcelWriter object
File path or existing ExcelWriter
na_rep : string, default ''
Missing data representation
+ engine : string, default None
+ write engine to use - you can also set this via the options
+ ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
+ ``io.excel.xlsm.writer``.
+
+ Keyword Arguments
+ -----------------
+ float_format : string, default None
+ Format string for floating point numbers
+ cols : sequence, optional
+ Columns to write
+ header : boolean or list of string, default True
+ Write out column names. If a list of string is given it is
+ assumed to be aliases for the column names
+ index : boolean, default True
+ Write row names (index)
+ index_label : string or sequence, default None
+ Column label for index column(s) if desired. If None is given, and
+ `header` and `index` are True, then the index names are used. A
+ sequence should be given if the DataFrame uses MultiIndex.
+ startow : upper left cell row to dump data frame
+ startcol : upper left cell column to dump data frame
+
+ Keyword arguments (and na_rep) are passed to the ``to_excel`` method
+ for each DataFrame written.
"""
from pandas.io.excel import ExcelWriter
- writer = ExcelWriter(path)
+
+ if isinstance(path, compat.string_types):
+ writer = ExcelWriter(path, engine=engine)
+ else:
+ writer = path
+ kwargs['na_rep'] = na_rep
+
for item, df in compat.iteritems(self):
name = str(item)
- df.to_excel(writer, name, na_rep=na_rep)
+ df.to_excel(writer, name, **kwargs)
writer.save()
def as_matrix(self):
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 5ff42c5cd12a6..f34c4f99a856d 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -4,17 +4,46 @@
#----------------------------------------------------------------------
# ExcelFile class
-
+import os
import datetime
+import abc
import numpy as np
from pandas.io.parsers import TextParser
from pandas.tseries.period import Period
from pandas import json
-from pandas.compat import map, zip, reduce, range, lrange
+from pandas.compat import map, zip, reduce, range, lrange, u, add_metaclass
+from pandas.core import config
+from pandas.core.common import pprint_thing, PandasError
import pandas.compat as compat
from warnings import warn
+__all__ = ["read_excel", "ExcelWriter", "ExcelFile"]
+
+_writer_extensions = ["xlsx", "xls", "xlsm"]
+_writers = {}
+
+def register_writer(klass):
+ """Adds engine to the excel writer registry. You must use this method to
+ integrate with ``to_excel``. Also adds config options for any new
+ ``supported_extensions`` defined on the writer."""
+ if not compat.callable(klass):
+ raise ValueError("Can only register callables as engines")
+ engine_name = klass.engine
+ _writers[engine_name] = klass
+ for ext in klass.supported_extensions:
+ if ext.startswith('.'):
+ ext = ext[1:]
+ if ext not in _writer_extensions:
+ config.register_option("io.excel.%s.writer" % ext,
+ engine_name, validator=str)
+ _writer_extensions.append(ext)
+
+def get_writer(engine_name):
+ try:
+ return _writers[engine_name]
+ except KeyError:
+ raise ValueError("No Excel writer '%s'" % engine_name)
def read_excel(path_or_buf, sheetname, **kwds):
"""Read an Excel table into a pandas DataFrame
@@ -240,85 +269,6 @@ def _trim_excel_header(row):
return row
-class CellStyleConverter(object):
- """
- Utility Class which converts a style dict to xlrd or openpyxl style
- """
-
- @staticmethod
- def to_xls(style_dict, num_format_str=None):
- """
- converts a style_dict to an xlwt style object
- Parameters
- ----------
- style_dict: style dictionary to convert
- """
- import xlwt
-
- def style_to_xlwt(item, firstlevel=True, field_sep=',', line_sep=';'):
- """helper wich recursively generate an xlwt easy style string
- for example:
-
- hstyle = {"font": {"bold": True},
- "border": {"top": "thin",
- "right": "thin",
- "bottom": "thin",
- "left": "thin"},
- "align": {"horiz": "center"}}
- will be converted to
- font: bold on; \
- border: top thin, right thin, bottom thin, left thin; \
- align: horiz center;
- """
- if hasattr(item, 'items'):
- if firstlevel:
- it = ["%s: %s" % (key, style_to_xlwt(value, False))
- for key, value in item.items()]
- out = "%s " % (line_sep).join(it)
- return out
- else:
- it = ["%s %s" % (key, style_to_xlwt(value, False))
- for key, value in item.items()]
- out = "%s " % (field_sep).join(it)
- return out
- else:
- item = "%s" % item
- item = item.replace("True", "on")
- item = item.replace("False", "off")
- return item
-
- if style_dict:
- xlwt_stylestr = style_to_xlwt(style_dict)
- style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
- else:
- style = xlwt.XFStyle()
- if num_format_str is not None:
- style.num_format_str = num_format_str
-
- return style
-
- @staticmethod
- def to_xlsx(style_dict):
- """
- converts a style_dict to an openpyxl style object
- Parameters
- ----------
- style_dict: style dictionary to convert
- """
-
- from openpyxl.style import Style
- xls_style = Style()
- for key, value in style_dict.items():
- for nk, nv in value.items():
- if key == "borders":
- (xls_style.borders.__getattribute__(nk)
- .__setattr__('border_style', nv))
- else:
- xls_style.__getattribute__(key).__setattr__(nk, nv)
-
- return xls_style
-
-
def _conv_value(val):
# convert value for excel dump
if isinstance(val, np.int64):
@@ -331,41 +281,78 @@ def _conv_value(val):
return val
+class ExcelWriterMeta(abc.ABCMeta):
+ """
+ Metaclass that dynamically chooses the ExcelWriter to use.
+
+ If you directly instantiate a subclass, it skips the engine lookup.
+
+ Defining an ExcelWriter implementation (see abstract methods on ExcelWriter for more...).
+
+ - Mandatory (but not checked at run time):
+ - ``write_cells(self, cells, sheet_name=None, startrow=0, startcol=0)``
+ --> called to write additional DataFrames to disk
+ - ``supported_extensions`` (tuple of supported extensions), used to check
+ that engine supports the given extension.
+ - ``engine`` - string that gives the engine name. Necessary to
+ instantiate class directly and bypass ``ExcelWriterMeta`` engine lookup.
+ - ``save(self)`` --> called to save file to disk
+ - Optional:
+ - ``__init__(self, path, **kwargs)`` --> always called with path as first
+ argument.
+
+ You also need to register the class with ``register_writer()``.
+ """
+
+ def __call__(cls, path, **kwargs):
+ engine = kwargs.pop('engine', None)
+ # if it's not an ExcelWriter baseclass, dont' do anything (you've
+ # probably made an explicit choice here)
+ if not isinstance(getattr(cls, 'engine', None), compat.string_types):
+ if engine is None:
+ ext = os.path.splitext(path)[-1][1:]
+ try:
+ engine = config.get_option('io.excel.%s.writer' % ext)
+ except KeyError:
+ error = ValueError("No engine for filetype: '%s'" % ext)
+ raise error
+ cls = get_writer(engine)
+ writer = cls.__new__(cls, path, **kwargs)
+ writer.__init__(path, **kwargs)
+ return writer
+
+
+@add_metaclass(ExcelWriterMeta)
class ExcelWriter(object):
"""
- Class for writing DataFrame objects into excel sheets, uses xlwt for xls,
- openpyxl for xlsx. See DataFrame.to_excel for typical usage.
+ Class for writing DataFrame objects into excel sheets, default is to use
+ xlwt for xls, openpyxl for xlsx. See DataFrame.to_excel for typical usage.
Parameters
----------
path : string
- Path to xls file
+ Path to xls or xlsx file.
+ engine : string (optional)
+ Engine to use for writing. If None, defaults to ``io.excel.<extension>.writer``.
+ NOTE: can only be passed as a keyword argument.
"""
- def __init__(self, path):
- self.use_xlsx = True
- if path.endswith('.xls'):
- self.use_xlsx = False
- import xlwt
- self.book = xlwt.Workbook()
- self.fm_datetime = xlwt.easyxf(
- num_format_str='YYYY-MM-DD HH:MM:SS')
- self.fm_date = xlwt.easyxf(num_format_str='YYYY-MM-DD')
- else:
- from openpyxl.workbook import Workbook
- self.book = Workbook() # optimized_write=True)
- # open pyxl 1.6.1 adds a dummy sheet remove it
- if self.book.worksheets:
- self.book.remove_sheet(self.book.worksheets[0])
- self.path = path
- self.sheets = {}
- self.cur_sheet = None
+ # declare external properties you can count on
+ book = None
+ curr_sheet = None
+ path = None
- def save(self):
- """
- Save workbook to disk
- """
- self.book.save(self.path)
+ @abc.abstractproperty
+ def supported_extensions(self):
+ "extensions that writer engine supports"
+ pass
+
+ @abc.abstractproperty
+ def engine(self):
+ "name of engine"
+ pass
+
+ @abc.abstractmethod
def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
"""
Write given formated cells into Excel an excel sheet
@@ -379,20 +366,77 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
startrow: upper left cell row to dump data frame
startcol: upper left cell column to dump data frame
"""
+ pass
+
+ @abc.abstractmethod
+ def save(self):
+ """
+ Save workbook to disk.
+ """
+ pass
+
+ def __init__(self, path, engine=None, **engine_kwargs):
+ # note that subclasses will *never* get anything for engine
+ # included here so that it's visible as part of the public signature.
+
+ # validate that this engine can handle the extnesion
+ ext = os.path.splitext(path)[-1]
+ self.check_extension(ext)
+
+ self.path = path
+ self.sheets = {}
+ self.cur_sheet = None
+
+ def _get_sheet_name(self, sheet_name):
if sheet_name is None:
sheet_name = self.cur_sheet
if sheet_name is None: # pragma: no cover
raise ValueError('Must pass explicit sheet_name or set '
'cur_sheet property')
- if self.use_xlsx:
- self._writecells_xlsx(cells, sheet_name, startrow, startcol)
+ return sheet_name
+
+ @classmethod
+ def check_extension(cls, ext):
+ """checks that path's extension against the Writer's supported
+ extensions. If it isn't supported, raises UnsupportedFiletypeError."""
+ if ext.startswith('.'):
+ ext = ext[1:]
+ if not any(ext in extension for extension in cls.supported_extensions):
+ msg = (u("Invalid extension for engine '%s': '%s'") %
+ (pprint_thing(cls.engine), pprint_thing(ext)))
+ raise ValueError(msg)
else:
- self._writecells_xls(cells, sheet_name, startrow, startcol)
+ return True
+
+
+class _OpenpyxlWriter(ExcelWriter):
+ engine = 'openpyxl'
+ supported_extensions = ('.xlsx', '.xlsm')
- def _writecells_xlsx(self, cells, sheet_name, startrow, startcol):
+ def __init__(self, path, **engine_kwargs):
+ # Use the openpyxl module as the Excel writer.
+ from openpyxl.workbook import Workbook
+ super(_OpenpyxlWriter, self).__init__(path, **engine_kwargs)
+
+ # Create workbook object with default optimized_write=True.
+ self.book = Workbook()
+ # Openpyxl 1.6.1 adds a dummy sheet. We remove it.
+ if self.book.worksheets:
+ self.book.remove_sheet(self.book.worksheets[0])
+
+ def save(self):
+ """
+ Save workbook to disk.
+ """
+ return self.book.save(self.path)
+
+ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
+ # Write the frame cells using openpyxl.
from openpyxl.cell import get_column_letter
+ sheet_name = self._get_sheet_name(sheet_name)
+
if sheet_name in self.sheets:
wks = self.sheets[sheet_name]
else:
@@ -405,7 +449,7 @@ def _writecells_xlsx(self, cells, sheet_name, startrow, startcol):
xcell = wks.cell("%s%s" % (colletter, startrow + cell.row + 1))
xcell.value = _conv_value(cell.val)
if cell.style:
- style = CellStyleConverter.to_xlsx(cell.style)
+ style = self._convert_to_style(cell.style)
for field in style.__fields__:
xcell.style.__setattr__(field,
style.__getattribute__(field))
@@ -425,8 +469,55 @@ def _writecells_xlsx(self, cells, sheet_name, startrow, startcol):
startrow + cell.row + 1,
cletterend,
startrow + cell.mergestart + 1))
+ @classmethod
+ def _convert_to_style(cls, style_dict):
+ """
+ converts a style_dict to an openpyxl style object
+ Parameters
+ ----------
+ style_dict: style dictionary to convert
+ """
+
+ from openpyxl.style import Style
+ xls_style = Style()
+ for key, value in style_dict.items():
+ for nk, nv in value.items():
+ if key == "borders":
+ (xls_style.borders.__getattribute__(nk)
+ .__setattr__('border_style', nv))
+ else:
+ xls_style.__getattribute__(key).__setattr__(nk, nv)
+
+ return xls_style
+
+register_writer(_OpenpyxlWriter)
+
+
+class _XlwtWriter(ExcelWriter):
+ engine = 'xlwt'
+ supported_extensions = ('.xls',)
+
+ def __init__(self, path, **engine_kwargs):
+ # Use the xlwt module as the Excel writer.
+ import xlwt
+
+ super(_XlwtWriter, self).__init__(path, **engine_kwargs)
+
+ self.book = xlwt.Workbook()
+ self.fm_datetime = xlwt.easyxf(num_format_str='YYYY-MM-DD HH:MM:SS')
+ self.fm_date = xlwt.easyxf(num_format_str='YYYY-MM-DD')
+
+ def save(self):
+ """
+ Save workbook to disk.
+ """
+ return self.book.save(self.path)
+
+ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
+ # Write the frame cells using xlwt.
+
+ sheet_name = self._get_sheet_name(sheet_name)
- def _writecells_xls(self, cells, sheet_name, startrow, startcol):
if sheet_name in self.sheets:
wks = self.sheets[sheet_name]
else:
@@ -451,7 +542,7 @@ def _writecells_xls(self, cells, sheet_name, startrow, startcol):
if stylekey in style_dict:
style = style_dict[stylekey]
else:
- style = CellStyleConverter.to_xls(cell.style, num_format_str)
+ style = self._convert_to_style(cell.style, num_format_str)
style_dict[stylekey] = style
if cell.mergestart is not None and cell.mergeend is not None:
@@ -464,3 +555,59 @@ def _writecells_xls(self, cells, sheet_name, startrow, startcol):
wks.write(startrow + cell.row,
startcol + cell.col,
val, style)
+
+ @classmethod
+ def _style_to_xlwt(cls, item, firstlevel=True, field_sep=',', line_sep=';'):
+ """helper which recursively generate an xlwt easy style string
+ for example:
+
+ hstyle = {"font": {"bold": True},
+ "border": {"top": "thin",
+ "right": "thin",
+ "bottom": "thin",
+ "left": "thin"},
+ "align": {"horiz": "center"}}
+ will be converted to
+ font: bold on; \
+ border: top thin, right thin, bottom thin, left thin; \
+ align: horiz center;
+ """
+ if hasattr(item, 'items'):
+ if firstlevel:
+ it = ["%s: %s" % (key, cls._style_to_xlwt(value, False))
+ for key, value in item.items()]
+ out = "%s " % (line_sep).join(it)
+ return out
+ else:
+ it = ["%s %s" % (key, cls._style_to_xlwt(value, False))
+ for key, value in item.items()]
+ out = "%s " % (field_sep).join(it)
+ return out
+ else:
+ item = "%s" % item
+ item = item.replace("True", "on")
+ item = item.replace("False", "off")
+ return item
+
+ @classmethod
+ def _convert_to_style(cls, style_dict, num_format_str=None):
+ """
+ converts a style_dict to an xlwt style object
+ Parameters
+ ----------
+ style_dict: style dictionary to convert
+ """
+ import xlwt
+
+ if style_dict:
+ xlwt_stylestr = cls._style_to_xlwt(style_dict)
+ style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
+ else:
+ style = xlwt.XFStyle()
+ if num_format_str is not None:
+ style.num_format_str = num_format_str
+
+ return style
+
+register_writer(_XlwtWriter)
+
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 3f41be6ae64c6..a9822ea0b46c9 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -18,7 +18,10 @@
import pandas.io.parsers as parsers
from pandas.io.parsers import (read_csv, read_table, read_fwf,
TextParser, TextFileReader)
-from pandas.io.excel import ExcelFile, ExcelWriter, read_excel
+from pandas.io.excel import (
+ ExcelFile, ExcelWriter, read_excel, _XlwtWriter, _OpenpyxlWriter,
+ register_writer
+)
from pandas.util.testing import (assert_almost_equal,
assert_series_equal,
network,
@@ -602,6 +605,59 @@ def test_excel_roundtrip_datetime(self):
recons = reader.parse('test1')
tm.assert_frame_equal(self.tsframe, recons)
+ def test_ExcelWriter_dispatch(self):
+ with tm.assertRaisesRegexp(ValueError, 'No engine'):
+ writer = ExcelWriter('nothing')
+
+ _skip_if_no_openpyxl()
+ writer = ExcelWriter('apple.xlsx')
+ tm.assert_isinstance(writer, _OpenpyxlWriter)
+
+ _skip_if_no_xlwt()
+ writer = ExcelWriter('apple.xls')
+ tm.assert_isinstance(writer, _XlwtWriter)
+
+
+ def test_register_writer(self):
+ # some awkward mocking to test out dispatch and such actually works
+ called_save = []
+ called_write_cells = []
+ class DummyClass(ExcelWriter):
+ called_save = False
+ called_write_cells = False
+ supported_extensions = ['test', 'xlsx', 'xls']
+ engine = 'dummy'
+
+ def save(self):
+ called_save.append(True)
+
+ def write_cells(self, *args, **kwargs):
+ called_write_cells.append(True)
+
+ def check_called(func):
+ func()
+ self.assert_(len(called_save) >= 1)
+ self.assert_(len(called_write_cells) >= 1)
+ del called_save[:]
+ del called_write_cells[:]
+
+ register_writer(DummyClass)
+ writer = ExcelWriter('something.test')
+ tm.assert_isinstance(writer, DummyClass)
+ df = tm.makeCustomDataframe(1, 1)
+ panel = tm.makePanel()
+ func = lambda: df.to_excel('something.test')
+ check_called(func)
+ check_called(lambda: panel.to_excel('something.test'))
+ from pandas import set_option, get_option
+ val = get_option('io.excel.xlsx.writer')
+ set_option('io.excel.xlsx.writer', 'dummy')
+ check_called(lambda: df.to_excel('something.xlsx'))
+ check_called(lambda: df.to_excel('something.xls', engine='dummy'))
+ set_option('io.excel.xlsx.writer', val)
+
+
+
def test_to_excel_periodindex(self):
_skip_if_no_excelsuite()
@@ -731,13 +787,11 @@ def test_to_excel_unicode_filename(self):
tm.assert_frame_equal(rs, xp)
def test_to_excel_styleconverter(self):
- from pandas.io.excel import CellStyleConverter
+ _skip_if_no_xlwt()
+ _skip_if_no_openpyxl()
- try:
- import xlwt
- import openpyxl
- except ImportError:
- raise nose.SkipTest
+ import xlwt
+ import openpyxl
hstyle = {"font": {"bold": True},
"borders": {"top": "thin",
@@ -745,7 +799,7 @@ def test_to_excel_styleconverter(self):
"bottom": "thin",
"left": "thin"},
"alignment": {"horizontal": "center"}}
- xls_style = CellStyleConverter.to_xls(hstyle)
+ xls_style = _XlwtWriter._convert_to_style(hstyle)
self.assertTrue(xls_style.font.bold)
self.assertEquals(xlwt.Borders.THIN, xls_style.borders.top)
self.assertEquals(xlwt.Borders.THIN, xls_style.borders.right)
@@ -753,7 +807,7 @@ def test_to_excel_styleconverter(self):
self.assertEquals(xlwt.Borders.THIN, xls_style.borders.left)
self.assertEquals(xlwt.Alignment.HORZ_CENTER, xls_style.alignment.horz)
- xlsx_style = CellStyleConverter.to_xlsx(hstyle)
+ xlsx_style = _OpenpyxlWriter._convert_to_style(hstyle)
self.assertTrue(xlsx_style.font.bold)
self.assertEquals(openpyxl.style.Border.BORDER_THIN,
xlsx_style.borders.top.border_style)
| FIxes #4745 and makes it easier to swap in other `ExcelWriter`s.
Basically, you can subclass `ExcelWriter` (or not), register the engine with `register_engine`, and then either pass it as an `engine` keyword to `read_excel` or set it as the default writer using the config options (i.e., `io.excel.xlsx.writer` or `io.excel.xls.writer`). Engine names are validated by checking that they are already defined and that they are able to read files of that type (that said, if you can set up external config files to be parsed by pandas, this validation should be removed, because it won't work if pandas is loaded before an external dependency [e.g., a plugin that registers a writer class]). When you call `ExcelWriter`, the metaclass swaps in the appropriate engine class automatically [thereby being backwards compatible].
The great thing is that it should be _really_ simple to add additional writers and relatively trivial to add additional readers by following the same format. (if, for example, we wanted to resurrect `openpyxl` for brave souls or something).
Here's the 'interface':
- Mandatory (but not checked at run time):
- `write_cells(self, cells, sheet_name=None, startrow=0, startcol=0)`
--> called to write additional DataFrames to disk
- `supported_extensions` (tuple of supported extensions), used to check
that engine supports the given extension.
- `engine` - string that gives the engine name. Necessary to
instantiate class directly and bypass `ExcelWriterMeta` engine lookup.
- `save(self)` --> called to save file to disk
- Optional:
- `__init__(self, path, **kwargs)` --> always called with path as first
argument.
- `check_extension(cls, ext)` --> called to check that the engine supports a
given extension (and used to validate user selection of engine as option).
This supercedes `supported_exceptions`.
You also need to register the class with `register_engine()`. If you don't subclass `ExcelWriter`,
you will have to implement `check_extensions(ext)` yourself.
There's a tiny bit of metaclass magic to make this backwards-compatible, but it's nothing particularly complicated.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4750 | 2013-09-05T00:25:02Z | 2013-09-13T11:08:18Z | 2013-09-13T11:08:18Z | 2014-06-17T06:40:42Z |
BUG: series replace should allow a single list | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9a34cdbdfb5a8..08a9b15dc9f58 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -152,6 +152,8 @@ pandas 0.13
passed a string (:issue:`4763`). Pass a ``list`` of one element (containing
the string) instead.
- Remove undocumented/unused ``kind`` keyword argument from ``read_excel``, and ``ExcelFile``. (:issue:`4713`, :issue:`4712`)
+ - The ``method`` argument of ``NDFrame.replace()`` is valid again, so that a
+ a list can be passed to ``to_replace`` (:issue:`4743`).
**Internal Refactoring**
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 6fc006eae74fe..8b9ba4d5eea16 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1047,6 +1047,7 @@ def wrapper(arr, mask, limit=None):
np.int64)
+
def pad_1d(values, limit=None, mask=None):
dtype = values.dtype.name
@@ -1188,6 +1189,14 @@ def _consensus_name_attr(objs):
return None
return name
+
+_fill_methods = {'pad': pad_1d, 'backfill': backfill_1d}
+
+def _get_fill_func(method):
+ method = _clean_fill_method(method)
+ return _fill_methods[method]
+
+
#----------------------------------------------------------------------
# Lots of little utilities
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 7f5b9b7f75545..3bdfd98127bb7 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5,6 +5,7 @@
import numpy as np
import pandas.lib as lib
+import pandas as pd
from pandas.core.base import PandasObject
from pandas.core.index import Index, MultiIndex, _ensure_index
import pandas.core.indexing as indexing
@@ -19,6 +20,33 @@
_infer_dtype_from_scalar, _maybe_promote,
ABCSeries)
+
+
+def is_dictlike(x):
+ return isinstance(x, (dict, com.ABCSeries))
+
+
+def _single_replace(self, to_replace, method, inplace, limit):
+ orig_dtype = self.dtype
+ result = self if inplace else self.copy()
+ fill_f = com._get_fill_func(method)
+
+ mask = com.mask_missing(result.values, to_replace)
+ values = fill_f(result.values, limit=limit, mask=mask)
+
+ if values.dtype == orig_dtype and inplace:
+ return
+
+ result = pd.Series(values, index=self.index, name=self.name,
+ dtype=self.dtype)
+
+ if inplace:
+ self._data = result._data
+ return
+
+ return result
+
+
class NDFrame(PandasObject):
"""
@@ -1581,7 +1609,7 @@ def bfill(self, axis=0, inplace=False, limit=None, downcast=None):
limit=limit, downcast=downcast)
def replace(self, to_replace=None, value=None, inplace=False, limit=None,
- regex=False, method=None, axis=None):
+ regex=False, method='pad', axis=None):
"""
Replace values given in 'to_replace' with 'value'.
@@ -1643,14 +1671,19 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
string. Otherwise, `to_replace` must be ``None`` because this
parameter will be interpreted as a regular expression or a list,
dict, or array of regular expressions.
+ method : string, optional, {'pad', 'ffill', 'bfill'}
+ The method to use when for replacement, when ``to_replace`` is a
+ ``list``.
See also
--------
- reindex, asfreq, fillna
+ NDFrame.reindex
+ NDFrame.asfreq
+ NDFrame.fillna
Returns
-------
- filled : DataFrame
+ filled : NDFrame
Raises
------
@@ -1681,11 +1714,6 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
if not com.is_bool(regex) and to_replace is not None:
raise AssertionError("'to_replace' must be 'None' if 'regex' is "
"not a bool")
- if method is not None:
- from warnings import warn
- warn('the "method" argument is deprecated and will be removed in'
- 'v0.13; this argument has no effect')
-
if axis is not None:
from warnings import warn
warn('the "axis" argument is deprecated and will be removed in'
@@ -1693,14 +1721,16 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
self._consolidate_inplace()
- def is_dictlike(x):
- return isinstance(x, (dict, com.ABCSeries))
-
if value is None:
+ if isinstance(to_replace, list):
+ return _single_replace(self, to_replace, method, inplace,
+ limit)
+
if not is_dictlike(to_replace):
if not is_dictlike(regex):
raise TypeError('If "to_replace" and "value" are both None'
- ' then regex must be a mapping')
+ ' and "to_replace" is not a list, then '
+ 'regex must be a mapping')
to_replace = regex
regex = True
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 556973acdcb95..4d86e8ae4a25b 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -4608,6 +4608,63 @@ def test_replace(self):
result = ser.replace([0, 1, 2, 3, 4], [4, 3, 2, 1, 0])
assert_series_equal(result, Series([4, 3, 2, 1, 0]))
+ def test_replace_with_single_list(self):
+ ser = Series([0, 1, 2, 3, 4])
+ result = ser.replace([1,2,3])
+ assert_series_equal(result, Series([0,0,0,0,4]))
+
+ s = ser.copy()
+ s.replace([1,2,3],inplace=True)
+ assert_series_equal(s, Series([0,0,0,0,4]))
+
+ # make sure things don't get corrupted when fillna call fails
+ s = ser.copy()
+ with tm.assertRaises(ValueError):
+ s.replace([1,2,3],inplace=True,method='crash_cymbal')
+ assert_series_equal(s, ser)
+
+ def test_replace_mixed_types(self):
+ s = Series(np.arange(5))
+
+ def check_replace(to_rep, val, expected):
+ sc = s.copy()
+ r = s.replace(to_rep, val)
+ sc.replace(to_rep, val, inplace=True)
+ assert_series_equal(expected, r)
+ assert_series_equal(expected, sc)
+
+ # should NOT upcast to float
+ e = Series([0,1,2,3,4])
+ tr, v = [3], [3.0]
+ check_replace(tr, v, e)
+
+ # MUST upcast to float
+ e = Series([0,1,2,3.5,4])
+ tr, v = [3], [3.5]
+ check_replace(tr, v, e)
+
+ # casts to object
+ e = Series([0,1,2,3.5,'a'])
+ tr, v = [3,4], [3.5,'a']
+ check_replace(tr, v, e)
+
+ # again casts to object
+ e = Series([0,1,2,3.5,Timestamp('20130101')])
+ tr, v = [3,4],[3.5,Timestamp('20130101')]
+ check_replace(tr, v, e)
+
+ # casts to float
+ e = Series([0,1,2,3.5,1])
+ tr, v = [3,4],[3.5,True]
+ check_replace(tr, v, e)
+
+ # test an object with dates + floats + integers + strings
+ dr = date_range('1/1/2001', '1/10/2001',
+ freq='D').to_series().reset_index(drop=True)
+ r = dr.astype(object).replace([dr[0],dr[1],dr[2]], [1.0,2,'a'])
+ assert_series_equal(r, Series([1.0,2,'a'] +
+ dr[3:].tolist(),dtype=object))
+
def test_asfreq(self):
ts = Series([0., 1., 2.], index=[datetime(2009, 10, 30),
datetime(2009, 11, 30),
| Also reverts the `method` parameter of `NDFrame.replace()` deprecation
closes #4743
| https://api.github.com/repos/pandas-dev/pandas/pulls/4748 | 2013-09-04T19:23:07Z | 2013-09-06T23:40:44Z | 2013-09-06T23:40:44Z | 2014-06-21T17:17:09Z |
ENH ohlc resample for DataFrame | diff --git a/doc/source/release.rst b/doc/source/release.rst
index bbadba61c0135..70aeb454e9ef2 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -56,6 +56,7 @@ pandas 0.13
- Significant table writing performance improvements in ``HDFStore``
- JSON date serialisation now performed in low-level C code.
- Add ``drop_level`` argument to xs (:issue:`4180`)
+ - Can now resample a DataFrame with ohlc (:issue:`2320`)
- ``Index.copy()`` and ``MultiIndex.copy()`` now accept keyword arguments to
change attributes (i.e., ``names``, ``levels``, ``labels``)
(:issue:`4039`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 723ff2fd5ab56..0a39b83d35e66 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1619,7 +1619,6 @@ def _iterate_slices(self):
for val in slice_axis:
if val in self.exclusions:
continue
-
yield val, slicer(val)
def _cython_agg_general(self, how, numeric_only=True):
@@ -2233,6 +2232,26 @@ def _wrap_agged_blocks(self, blocks):
return result.convert_objects()
+ def _iterate_column_groupbys(self):
+ for i, colname in enumerate(self.obj.columns):
+ yield colname, SeriesGroupBy(self.obj.iloc[:, i], selection=colname,
+ grouper=self.grouper,
+ exclusions=self.exclusions)
+
+ def _apply_to_column_groupbys(self, func):
+ from pandas.tools.merge import concat
+ return concat((func(col_groupby)
+ for _, col_groupby in self._iterate_column_groupbys()),
+ keys=self.obj.columns,
+ axis=1)
+
+ def ohlc(self):
+ """
+ Compute sum of values, excluding missing values
+
+ For multiple groupings, the result index will be a MultiIndex
+ """
+ return self._apply_to_column_groupbys(lambda x: x._cython_agg_general('ohlc'))
from pandas.tools.plotting import boxplot_frame_groupby
DataFrameGroupBy.boxplot = boxplot_frame_groupby
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py
index 3fdeacad5ffcd..1c6c4eae8d279 100644
--- a/pandas/tseries/tests/test_resample.py
+++ b/pandas/tseries/tests/test_resample.py
@@ -259,6 +259,31 @@ def test_resample_ohlc(self):
self.assertEquals(xs['low'], s[:5].min())
self.assertEquals(xs['close'], s[4])
+ def test_resample_ohlc_dataframe(self):
+ df = (pd.DataFrame({'PRICE': {Timestamp('2011-01-06 10:59:05', tz=None): 24990,
+ Timestamp('2011-01-06 12:43:33', tz=None): 25499,
+ Timestamp('2011-01-06 12:54:09', tz=None): 25499},
+ 'VOLUME': {Timestamp('2011-01-06 10:59:05', tz=None): 1500000000,
+ Timestamp('2011-01-06 12:43:33', tz=None): 5000000000,
+ Timestamp('2011-01-06 12:54:09', tz=None): 100000000}})
+ ).reindex_axis(['VOLUME', 'PRICE'], axis=1)
+ res = df.resample('H', how='ohlc')
+ exp = pd.concat([df['VOLUME'].resample('H', how='ohlc'),
+ df['PRICE'].resample('H', how='ohlc')],
+ axis=1,
+ keys=['VOLUME', 'PRICE'])
+ assert_frame_equal(exp, res)
+
+ df.columns = [['a', 'b'], ['c', 'd']]
+ res = df.resample('H', how='ohlc')
+ exp.columns = pd.MultiIndex.from_tuples([('a', 'c', 'open'), ('a', 'c', 'high'),
+ ('a', 'c', 'low'), ('a', 'c', 'close'), ('b', 'd', 'open'),
+ ('b', 'd', 'high'), ('b', 'd', 'low'), ('b', 'd', 'close')])
+ assert_frame_equal(exp, res)
+
+ # dupe columns fail atm
+ # df.columns = ['PRICE', 'PRICE']
+
def test_resample_reresample(self):
dti = DatetimeIndex(
start=datetime(2005, 1, 1), end=datetime(2005, 1, 10),
| closes #2320
Can use ohlc from DataFrame.
cc @jreback
Example:
```
In [24]: df = pd.DataFrame({'PRICE': {Timestamp('2011-01-06 10:59:05', tz=None): 24990,
Timestamp('2011-01-06 12:43:33', tz=None): 25499,
Timestamp('2011-01-06 12:54:09', tz=None): 25499},
'VOLUME': {Timestamp('2011-01-06 10:59:05', tz=None): 1500000000,
Timestamp('2011-01-06 12:43:33', tz=None): 5000000000,
Timestamp('2011-01-06 12:54:09', tz=None): 100000000}})
In [25]: df.resample('H', how='ohlc')
Out[25]:
PRICE VOLUME \
open high low close open high
2011-01-06 10:00:00 24990 24990 24990 24990 1500000000 1500000000
2011-01-06 11:00:00 NaN NaN NaN NaN NaN NaN
2011-01-06 12:00:00 25499 25499 25499 25499 5000000000 5000000000
low close
2011-01-06 10:00:00 1500000000 1500000000
2011-01-06 11:00:00 NaN NaN
2011-01-06 12:00:00 100000000 100000000
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4740 | 2013-09-03T23:35:28Z | 2013-09-10T06:40:38Z | 2013-09-10T06:40:38Z | 2014-06-22T17:56:54Z |
API: allow single element boolean Series to improve on numpy behavior( related GH4657) | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index b167b00b58ef1..9782967fd0a59 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -219,7 +219,7 @@ Boolean Reductions
.. _basics.reductions:
-Furthermore, you can apply the reduction functions: ``any()`` and ``all()`` to provide a
+Furthermore, you can apply the reductions: ``empty``, ``any()``, ``all()``, and ``bool()`` to provide a
way to summarize these results.
.. ipython:: python
@@ -233,7 +233,7 @@ You can reduce to a final boolean value.
(df>0).any().any()
-Finally you can test if a pandas object is empty, via the ``empty`` property.
+You can test if a pandas object is empty, via the ``empty`` property.
.. ipython:: python
@@ -262,6 +262,15 @@ Finally you can test if a pandas object is empty, via the ``empty`` property.
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
+To evaluate single-element pandas objects in a boolean context, use the method ``.bool()``:
+
+ .. ipython:: python
+
+ Series([True]).bool()
+ Series([False]).bool()
+ DataFrame([[True]]).bool()
+ DataFrame([[False]]).bool()
+
See :ref:`gotchas<gotchas.truth>` for a more detailed discussion.
diff --git a/doc/source/gotchas.rst b/doc/source/gotchas.rst
index 58eb6dccfc967..6cef1d52a6cec 100644
--- a/doc/source/gotchas.rst
+++ b/doc/source/gotchas.rst
@@ -59,6 +59,15 @@ or return if ``any`` value is ``True``.
print("I am any")
>>> I am any
+To evaluate single-element pandas objects in a boolean context, use the method ``.bool()``:
+
+ .. ipython:: python
+
+ Series([True]).bool()
+ Series([False]).bool()
+ DataFrame([[True]]).bool()
+ DataFrame([[False]]).bool()
+
See :ref:`boolean reductions<basics.reductions>` for more examples.
Bitwise boolean
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 801158a00b9ab..de81df9c15a42 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -241,7 +241,7 @@ API Changes
- Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
- ``__nonzero__`` for all NDFrame objects, will now raise a ``ValueError``, this reverts back to (:issue:`1073`, :issue:`4633`)
- behavior.
+ behavior. Add ``.bool()`` method to ``NDFrame`` objects to facilitate evaluating of single-element boolean Series
- ``DataFrame.update()`` no longer raises a ``DataConflictError``, it now
will raise a ``ValueError`` instead (if necessary) (:issue:`4732`)
- ``Series.isin()`` and ``DataFrame.isin()`` now raise a ``TypeError`` when
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 9a4d644b12104..5ff7038d02e45 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -55,10 +55,14 @@ API changes
index.set_names(["bob", "cranberry"], inplace=True)
- Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
+ - Remove deprecated ``Factor`` (:issue:`3650`)
+ - Remove deprecated ``set_printoptions/reset_printoptions`` (:issue:``3046``)
+ - Remove deprecated ``_verbose_info`` (:issue:`3215`)
- ``__nonzero__`` for all NDFrame objects, will now raise a ``ValueError``, this reverts back to (:issue:`1073`, :issue:`4633`)
- behavior. See :ref:`gotchas<gotchas.truth>` for a more detailed discussion.
+ behavior. Added the ``.bool()`` method to ``NDFrame`` objects to facilitate evaluating of single-element boolean Series
+ See :ref:`gotchas<gotchas.truth>` for a more detailed discussion.
- This prevent behaviors like (which will now all raise ``ValueError``)
+ This prevents behaviors like (which will now all raise ``ValueError``)
.. code-block:: python
@@ -68,6 +72,16 @@ API changes
df1 and df2
s1 and s2
+
+ To evaluate single-element pandas objects in a boolean context, use the method ``.bool()``:
+
+ .. ipython:: python
+
+ Series([True]).bool()
+ Series([False]).bool()
+ DataFrame([[True]]).bool()
+ DataFrame([[False]]).bool()
+
- All non-Index NDFrames (``Series``, ``DataFrame``, ``Panel``, ``Panel4D``,
``SparsePanel``, etc.), now support the entire set of arithmetic operators
and arithmetic flex methods (add, sub, mul, etc.). ``SparsePanel`` does not
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 18a03eb313dd2..7712d91ff4c71 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -596,10 +596,25 @@ def empty(self):
return not all(len(self._get_axis(a)) > 0 for a in self._AXIS_ORDERS)
def __nonzero__(self):
- raise ValueError("The truth value of an array is ambiguous. Use a.empty, a.item(), a.any() or a.all().")
+ raise ValueError("The truth value of a {0} is ambiguous. "
+ "Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(self.__class__.__name__))
__bool__ = __nonzero__
+ def bool(self):
+ """ Return the bool of a single element PandasObject
+ This must be a boolean scalar value, either True or False
+
+ Raise a ValueError if the PandasObject does not have exactly
+ 1 element, or that element is not boolean """
+ v = self.squeeze()
+ if isinstance(v, (bool,np.bool_)):
+ return bool(v)
+ elif np.isscalar(v):
+ raise ValueError("bool cannot act on a non-boolean single element {0}".format(self.__class__.__name__))
+
+ self.__nonzero__()
+
def __abs__(self):
return self.abs()
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 884e737f357a7..3161fd0496f6c 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -7,6 +7,7 @@
import operator
import types
+import warnings
from numpy import nan, ndarray
import numpy as np
@@ -913,7 +914,6 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None,
"""
if nanRep is not None: # pragma: no cover
- import warnings
warnings.warn("nanRep is deprecated, use na_rep", FutureWarning)
na_rep = nanRep
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 35ecef2acf818..835198400cd5a 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -2662,18 +2662,18 @@ def test_select_dtypes(self):
df = DataFrame(np.random.randn(5,2), columns =['A','B'])
df['object'] = 'foo'
df.ix[4:5,'object'] = 'bar'
- df['bool'] = df['A'] > 0
+ df['boolv'] = df['A'] > 0
_maybe_remove(store, 'df')
store.append('df', df, data_columns = True)
- expected = df[df.bool == True].reindex(columns=['A','bool'])
+ expected = df[df.boolv == True].reindex(columns=['A','boolv'])
for v in [True,'true',1]:
- result = store.select('df', Term('bool == %s' % str(v)), columns = ['A','bool'])
+ result = store.select('df', Term('boolv == %s' % str(v)), columns = ['A','boolv'])
tm.assert_frame_equal(expected, result)
- expected = df[df.bool == False ].reindex(columns=['A','bool'])
+ expected = df[df.boolv == False ].reindex(columns=['A','boolv'])
for v in [False,'false',0]:
- result = store.select('df', Term('bool == %s' % str(v)), columns = ['A','bool'])
+ result = store.select('df', Term('boolv == %s' % str(v)), columns = ['A','boolv'])
tm.assert_frame_equal(expected, result)
# integer index
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 7f50cb2453a21..b8c143e10111d 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -205,11 +205,31 @@ def test_get_numeric_data_preserve_dtype(self):
def test_nonzero_single_element(self):
+ # allow single item via bool method
s = Series([True])
- self.assertRaises(ValueError, lambda : bool(s))
+ self.assert_(s.bool() is True)
s = Series([False])
- self.assertRaises(ValueError, lambda : bool(s))
+ self.assert_(s.bool() is False)
+
+ # single item nan to raise
+ for s in [ Series([np.nan]), Series([pd.NaT]), Series([True]), Series([False]) ]:
+ self.assertRaises(ValueError, lambda : bool(s))
+
+ for s in [ Series([np.nan]), Series([pd.NaT])]:
+ self.assertRaises(ValueError, lambda : s.bool())
+
+ # multiple bool are still an error
+ for s in [Series([True,True]), Series([False, False])]:
+ self.assertRaises(ValueError, lambda : bool(s))
+ self.assertRaises(ValueError, lambda : s.bool())
+
+ # single non-bool are an error
+ for s in [Series([1]), Series([0]),
+ Series(['a']), Series([0.0])]:
+ self.assertRaises(ValueError, lambda : bool(s))
+ self.assertRaises(ValueError, lambda : s.bool())
+
class TestDataFrame(unittest.TestCase, Generic):
_typ = DataFrame
@@ -220,6 +240,19 @@ def test_rename_mi(self):
index=MultiIndex.from_tuples([("A",x) for x in ["a","B","c"]]))
result = df.rename(str.lower)
+ def test_nonzero_single_element(self):
+
+ # allow single item via bool method
+ df = DataFrame([[True]])
+ self.assert_(df.bool() is True)
+
+ df = DataFrame([[False]])
+ self.assert_(df.bool() is False)
+
+ df = DataFrame([[False, False]])
+ self.assertRaises(ValueError, lambda : df.bool())
+ self.assertRaises(ValueError, lambda : bool(df))
+
def test_get_numeric_data_preserve_dtype(self):
# get the numeric data
| related #4657
| https://api.github.com/repos/pandas-dev/pandas/pulls/4738 | 2013-09-03T22:01:37Z | 2013-10-01T00:03:52Z | 2013-10-01T00:03:52Z | 2014-06-17T15:59:26Z |
CLN: Improve Exceptions in core/frame and testing in test_frame and test_multilievel | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 557c4b293a84e..544e414132acd 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -71,8 +71,9 @@ pandas 0.13
when the key is a column
- Support for using a ``DatetimeIndex/PeriodsIndex`` directly in a datelike calculation
e.g. s-s.index (:issue:`4629`)
- - Better/cleaned up exceptions in core/common, io/excel and core/format.
- (:issue:`4721`, :issue:`3954`)
+ - Better/cleaned up exceptions in core/common, io/excel and core/format
+ (:issue:`4721`, :issue:`3954`), as well as cleaned up test cases in
+ tests/test_frame, tests/test_multilevel (:issue:`4732`).
**API Changes**
@@ -143,9 +144,10 @@ pandas 0.13
now returns a ``MultiIndex`` rather than an ``Index``. (:issue:`4039`)
- Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
- - Factored out excel_value_to_python_value from ExcelFile::_parse_excel (:issue:`4589`)
- ``__nonzero__`` for all NDFrame objects, will now raise a ``ValueError``, this reverts back to (:issue:`1073`, :issue:`4633`)
behavior.
+ - ``DataFrame.update()`` no longer raises a ``DataConflictError``, it now
+ will raise a ``ValueError`` instead (if necessary) (:issue:`4732`)
**Internal Refactoring**
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index 7a444ab01e10a..494cc5fe9ad29 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -665,6 +665,25 @@ def __and__(self, other):
else:
from collections import OrderedDict, Counter
+if PY3:
+ def raise_with_traceback(exc, traceback=Ellipsis):
+ if traceback == Ellipsis:
+ _, _, traceback = sys.exc_info()
+ raise exc.with_traceback(traceback)
+else:
+ # this version of raise is a syntax error in Python 3
+ exec("""
+def raise_with_traceback(exc, traceback=Ellipsis):
+ if traceback == Ellipsis:
+ _, _, traceback = sys.exc_info()
+ raise exc, None, traceback
+""")
+
+raise_with_traceback.__doc__ = (
+"""Raise exception with existing traceback.
+If traceback is not passed, uses sys.exc_info() to get traceback."""
+)
+
# http://stackoverflow.com/questions/4126348
# Thanks to @martineau at SO
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 978b82aed22d9..6b4dc979d5279 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -825,9 +825,8 @@ def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None,
# validate mi options
if self.has_mi_columns:
- # guarded against in to_csv itself
- if cols is not None: # pragma: no cover
- raise AssertionError("cannot specify cols with a multi_index on the columns")
+ if cols is not None:
+ raise TypeError("cannot specify cols with a MultiIndex on the columns")
if cols is not None:
if isinstance(cols,Index):
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index d184120185955..0cd9f7f3f5330 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -12,8 +12,6 @@
# pylint: disable=E1101,E1103
# pylint: disable=W0212,W0231,W0703,W0622
-from pandas.compat import range, zip, lrange, lmap, lzip, StringIO, u, OrderedDict
-from pandas import compat
import operator
import sys
import collections
@@ -38,6 +36,8 @@
import pandas.core.expressions as expressions
from pandas.sparse.array import SparseArray
from pandas.compat.scipy import scoreatpercentile as _quantile
+from pandas.compat import(range, zip, lrange, lmap, lzip, StringIO, u,
+ OrderedDict, raise_with_traceback)
from pandas import compat
from pandas.util.terminal import get_terminal_size
from pandas.util.decorators import deprecate, Appender, Substitution
@@ -180,12 +180,6 @@
merged : DataFrame
"""
-# Custom error class for update
-
-
-class DataConflictError(Exception):
- pass
-
#----------------------------------------------------------------------
# Factory helper methods
@@ -237,8 +231,8 @@ def f(self, other, axis=default_axis, level=None, fill_value=None):
casted = DataFrame(other, index=self.index,
columns=self.columns)
return self._combine_frame(casted, na_op, fill_value, level)
- else: # pragma: no cover
- raise ValueError("Bad argument shape")
+ else:
+ raise ValueError("Incompatible argument shape %s" % (other.shape,))
else:
return self._combine_const(other, na_op)
@@ -303,8 +297,9 @@ def f(self, other, axis=default_axis, level=None):
return self._flex_compare_frame(casted, na_op, str_rep, level)
- else: # pragma: no cover
- raise ValueError("Bad argument shape")
+ else:
+ raise ValueError("Incompatible argument shape: %s" %
+ (other.shape,))
else:
return self._combine_const(other, na_op)
@@ -351,7 +346,7 @@ class DataFrame(NDFrame):
Index to use for resulting frame. Will default to np.arange(n) if
no indexing information part of input data and no index provided
columns : Index or array-like
- Column labels to use for resulting frame. Will default to
+ Column labels to use for resulting frame. Will default to
np.arange(n) if no column labels are provided
dtype : dtype, default None
Data type to force, otherwise infer
@@ -407,7 +402,8 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
copy=copy)
elif isinstance(data, (np.ndarray, Series)):
if data.dtype.names:
- data_columns, data = _rec_to_dict(data)
+ data_columns = list(data.dtype.names)
+ data = dict((k, data[k]) for k in data_columns)
if columns is None:
columns = data_columns
mgr = self._init_dict(data, index, columns, dtype=dtype)
@@ -438,9 +434,10 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
else:
try:
arr = np.array(data, dtype=dtype, copy=copy)
- except (ValueError, TypeError):
- raise PandasError('DataFrame constructor called with '
- 'incompatible data and dtype')
+ except (ValueError, TypeError) as e:
+ exc = TypeError('DataFrame constructor called with '
+ 'incompatible data and dtype: %s' % e)
+ raise_with_traceback(exc)
if arr.ndim == 0 and index is not None and columns is not None:
if isinstance(data, compat.string_types) and dtype is None:
@@ -527,8 +524,10 @@ def _init_ndarray(self, values, index, columns, dtype=None,
if values.dtype != dtype:
try:
values = values.astype(dtype)
- except Exception:
- raise ValueError('failed to cast to %s' % dtype)
+ except Exception as orig:
+ e = ValueError("failed to cast to '%s' (Exception was: %s)"
+ % (dtype, orig))
+ raise_with_traceback(e)
N, K = values.shape
@@ -650,11 +649,7 @@ def __unicode__(self):
self.shape[0] <= max_info_rows)
self.info(buf=buf, verbose=verbose)
- value = buf.getvalue()
- if not isinstance(value, compat.text_type):
- raise AssertionError()
-
- return value
+ return buf.getvalue()
def _repr_html_(self):
"""
@@ -853,8 +848,8 @@ def dot(self, other):
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[1] != rvals.shape[0]:
- raise Exception('Dot product shape mismatch, %s vs %s' %
- (lvals.shape, rvals.shape))
+ raise ValueError('Dot product shape mismatch, %s vs %s' %
+ (lvals.shape, rvals.shape))
if isinstance(other, DataFrame):
return self._constructor(np.dot(lvals, rvals),
@@ -1162,7 +1157,7 @@ def from_items(cls, items, columns=None, orient='columns'):
return cls._from_arrays(arrays, columns, None)
elif orient == 'index':
if columns is None:
- raise ValueError("Must pass columns with orient='index'")
+ raise TypeError("Must pass columns with orient='index'")
keys = _ensure_index(keys)
@@ -1248,12 +1243,12 @@ def to_panel(self):
from pandas.core.reshape import block2d_to_blocknd
# only support this kind for now
- if (not isinstance(self.index, MultiIndex) or
+ if (not isinstance(self.index, MultiIndex) or # pragma: no cover
len(self.index.levels) != 2):
- raise AssertionError('Must have 2-level MultiIndex')
+ raise NotImplementedError('Only 2-level MultiIndex are supported.')
if not self.index.is_unique:
- raise Exception("Can't convert non-uniquely indexed "
+ raise ValueError("Can't convert non-uniquely indexed "
"DataFrame to Panel")
self._consolidate_inplace()
@@ -1626,8 +1621,9 @@ def info(self, verbose=True, buf=None, max_cols=None):
len(self.columns))
space = max([len(com.pprint_thing(k)) for k in self.columns]) + 4
counts = self.count()
- if len(cols) != len(counts):
- raise AssertionError('Columns must equal counts')
+ if len(cols) != len(counts): # pragma: no cover
+ raise AssertionError('Columns must equal counts (%d != %d)' %
+ (len(cols), len(counts)))
for col, count in compat.iteritems(counts):
col = com.pprint_thing(col)
lines.append(_put_str(col, space) +
@@ -1852,7 +1848,7 @@ def _getitem_array(self, key):
warnings.warn("Boolean Series key will be reindexed to match "
"DataFrame index.", UserWarning)
elif len(key) != len(self.index):
- raise ValueError('Item wrong length %d instead of %d!' %
+ raise ValueError('Item wrong length %d instead of %d.' %
(len(key), len(self.index)))
# _check_bool_indexer will throw exception if Series key cannot
# be reindexed to match DataFrame rows
@@ -1938,7 +1934,7 @@ def _setitem_array(self, key, value):
else:
if isinstance(value, DataFrame):
if len(value.columns) != len(key):
- raise AssertionError('Columns must be same length as key')
+ raise ValueError('Columns must be same length as key')
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
@@ -1949,11 +1945,11 @@ def _setitem_frame(self, key, value):
# support boolean setting with DataFrame input, e.g.
# df[df > df2] = 0
if key.values.dtype != np.bool_:
- raise ValueError('Must pass DataFrame with boolean values only')
+ raise TypeError('Must pass DataFrame with boolean values only')
if self._is_mixed_type:
if not self._is_numeric_mixed_type:
- raise ValueError(
+ raise TypeError(
'Cannot do boolean setting on mixed-type frame')
self.where(-key, value, inplace=True)
@@ -2009,8 +2005,8 @@ def _sanitize_column(self, key, value):
value = value.T
else:
if len(value) != len(self.index):
- raise AssertionError('Length of values does not match '
- 'length of index')
+ raise ValueError('Length of values does not match '
+ 'length of index')
if not isinstance(value, np.ndarray):
if isinstance(value, list) and len(value) > 0:
@@ -2223,7 +2219,7 @@ def lookup(self, row_labels, col_labels):
"""
n = len(row_labels)
if n != len(col_labels):
- raise AssertionError('Row labels must have same size as '
+ raise ValueError('Row labels must have same size as '
'column labels')
thresh = 1000
@@ -2232,9 +2228,9 @@ def lookup(self, row_labels, col_labels):
ridx = self.index.get_indexer(row_labels)
cidx = self.columns.get_indexer(col_labels)
if (ridx == -1).any():
- raise ValueError('One or more row labels was not found')
+ raise KeyError('One or more row labels was not found')
if (cidx == -1).any():
- raise ValueError('One or more column labels was not found')
+ raise KeyError('One or more column labels was not found')
flat_index = ridx * len(self.columns) + cidx
result = values.flat[flat_index]
else:
@@ -2392,7 +2388,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
if verify_integrity and not index.is_unique:
duplicates = index.get_duplicates()
- raise Exception('Index has duplicate keys: %s' % duplicates)
+ raise ValueError('Index has duplicate keys: %s' % duplicates)
for c in to_remove:
del frame[c]
@@ -2593,12 +2589,9 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None):
return result
axis = self._get_axis_number(axis)
- if axis == 0:
- agg_axis = 1
- elif axis == 1:
- agg_axis = 0
- else: # pragma: no cover
- raise ValueError('axis must be 0 or 1')
+ if axis not in (0, 1): # pragma: no cover
+ raise AssertionError('axis must be 0 or 1')
+ agg_axis = 1 - axis
agg_obj = self
if subset is not None:
@@ -2615,9 +2608,9 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None):
mask = count > 0
else:
if how is not None:
- raise ValueError('do not recognize %s' % how)
+ raise ValueError('invalid how option: %s' % how)
else:
- raise ValueError('must specify how or thresh')
+ raise TypeError('must specify how or thresh')
return self.take(mask.nonzero()[0], axis=axis, convert=False)
@@ -2757,14 +2750,14 @@ def sort_index(self, axis=0, by=None, ascending=True, inplace=False,
from pandas.core.groupby import _lexsort_indexer
axis = self._get_axis_number(axis)
- if axis not in [0, 1]:
- raise ValueError('Axis must be 0 or 1, got %s' % str(axis))
+ if axis not in [0, 1]: # pragma: no cover
+ raise AssertionError('Axis must be 0 or 1, got %s' % str(axis))
labels = self._get_axis(axis)
if by is not None:
if axis != 0:
- raise AssertionError('Axis must be 0')
+ raise ValueError('When sorting by column, axis must be 0 (rows)')
if not isinstance(by, (tuple, list)):
by = [by]
@@ -2835,7 +2828,7 @@ def sortlevel(self, level=0, axis=0, ascending=True, inplace=False):
axis = self._get_axis_number(axis)
the_axis = self._get_axis(axis)
if not isinstance(the_axis, MultiIndex):
- raise Exception('can only sort by level with a hierarchical index')
+ raise TypeError('can only sort by level with a hierarchical index')
new_axis, indexer = the_axis.sortlevel(level, ascending=ascending)
@@ -2900,7 +2893,7 @@ def reorder_levels(self, order, axis=0):
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis),
MultiIndex): # pragma: no cover
- raise Exception('Can only reorder levels on a hierarchical axis.')
+ raise TypeError('Can only reorder levels on a hierarchical axis.')
result = self.copy()
@@ -2976,7 +2969,8 @@ def _combine_series_infer(self, other, func, fill_value=None):
def _combine_match_index(self, other, func, fill_value=None):
left, right = self.align(other, join='outer', axis=0, copy=False)
if fill_value is not None:
- raise NotImplementedError
+ raise NotImplementedError("fill_value %r not supported." %
+ fill_value)
return self._constructor(func(left.values.T, right.values).T,
index=left.index,
columns=self.columns, copy=False)
@@ -2984,7 +2978,8 @@ def _combine_match_index(self, other, func, fill_value=None):
def _combine_match_columns(self, other, func, fill_value=None):
left, right = self.align(other, join='outer', axis=1, copy=False)
if fill_value is not None:
- raise NotImplementedError
+ raise NotImplementedError("fill_value %r not supported" %
+ fill_value)
new_data = left._data.eval(
func, right, axes=[left.columns, self.index])
@@ -2999,7 +2994,7 @@ def _combine_const(self, other, func, raise_on_error=True):
def _compare_frame(self, other, func, str_rep):
if not self._indexed_same(other):
- raise Exception('Can only compare identically-labeled '
+ raise ValueError('Can only compare identically-labeled '
'DataFrame objects')
def _compare(a, b):
@@ -3164,8 +3159,9 @@ def update(self, other, join='left', overwrite=True, filter_func=None,
If True, will raise an error if the DataFrame and other both
contain data in the same place.
"""
- if join != 'left':
- raise NotImplementedError
+ # TODO: Support other joins
+ if join != 'left': # pragma: no cover
+ raise NotImplementedError("Only left join is supported")
if not isinstance(other, DataFrame):
other = DataFrame(other)
@@ -3182,7 +3178,7 @@ def update(self, other, join='left', overwrite=True, filter_func=None,
mask_this = notnull(that)
mask_that = notnull(this)
if any(mask_this & mask_that):
- raise DataConflictError("Data overlaps.")
+ raise ValueError("Data overlaps.")
if overwrite:
mask = isnull(that)
@@ -3556,8 +3552,8 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
series_gen = (Series.from_array(arr, index=res_columns, name=name)
for i, (arr, name) in
enumerate(zip(values, res_index)))
- else:
- raise ValueError('Axis must be 0 or 1, got %s' % str(axis))
+ else: # pragma : no cover
+ raise AssertionError('Axis must be 0 or 1, got %s' % str(axis))
keys = []
results = {}
@@ -3615,7 +3611,7 @@ def _apply_broadcast(self, func, axis):
elif axis == 1:
target = self.T
else: # pragma: no cover
- raise ValueError('Axis must be 0 or 1, got %s' % axis)
+ raise AssertionError('Axis must be 0 or 1, got %s' % axis)
result_values = np.empty_like(target.values)
columns = target.columns
@@ -3669,7 +3665,7 @@ def append(self, other, ignore_index=False, verify_integrity=False):
If True do not use the index labels. Useful for gluing together
record arrays
verify_integrity : boolean, default False
- If True, raise Exception on creating index with duplicates
+ If True, raise ValueError on creating index with duplicates
Notes
-----
@@ -3685,7 +3681,7 @@ def append(self, other, ignore_index=False, verify_integrity=False):
if isinstance(other, dict):
other = Series(other)
if other.name is None and not ignore_index:
- raise Exception('Can only append a Series if '
+ raise TypeError('Can only append a Series if '
'ignore_index=True')
index = None if other.name is None else [other.name]
@@ -3757,7 +3753,7 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
if isinstance(other, Series):
if other.name is None:
- raise AssertionError('Other Series must have a name')
+ raise ValueError('Other Series must have a name')
other = DataFrame({other.name: other})
if isinstance(other, DataFrame):
@@ -4042,6 +4038,10 @@ def _count_level(self, level, axis=0, numeric_only=False):
if axis == 1:
frame = frame.T
+ if not isinstance(frame.index, MultiIndex):
+ raise TypeError("Can only count levels on hierarchical %s." %
+ self._get_axis_name(axis))
+
# python 2.5
mask = notnull(frame.values).view(np.uint8)
@@ -4282,13 +4282,16 @@ def _reduce(self, op, axis=0, skipna=True, numeric_only=None,
try:
values = self.values
result = f(values)
- except Exception:
+ except Exception as e:
if filter_type is None or filter_type == 'numeric':
data = self._get_numeric_data()
elif filter_type == 'bool':
data = self._get_bool_data()
- else:
- raise NotImplementedError
+ else: # pragma: no cover
+ e = NotImplementedError("Handling exception with filter_"
+ "type %s not implemented."
+ % filter_type)
+ raise_with_traceback(e)
result = f(data.values)
labels = data._get_agg_axis(axis)
else:
@@ -4297,8 +4300,10 @@ def _reduce(self, op, axis=0, skipna=True, numeric_only=None,
data = self._get_numeric_data()
elif filter_type == 'bool':
data = self._get_bool_data()
- else:
- raise NotImplementedError
+ else: # pragma: no cover
+ msg = ("Generating numeric_only data with filter_type %s"
+ "not supported." % filter_type)
+ raise NotImplementedError(msg)
values = data.values
labels = data._get_agg_axis(axis)
else:
@@ -4386,7 +4391,7 @@ def _get_agg_axis(self, axis_num):
elif axis_num == 1:
return self.index
else:
- raise Exception('Must have 0<= axis <= 1')
+ raise ValueError('Axis must be 0 or 1 (got %r)' % axis_num)
def quantile(self, q=0.5, axis=0, numeric_only=True):
"""
@@ -4534,8 +4539,8 @@ def to_timestamp(self, freq=None, how='start', axis=0, copy=True):
new_data.set_axis(1, self.index.to_timestamp(freq=freq, how=how))
elif axis == 1:
new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how))
- else:
- raise ValueError('Axis must be 0 or 1. Got %s' % str(axis))
+ else: # pragma: no cover
+ raise AssertionError('Axis must be 0 or 1. Got %s' % str(axis))
return self._constructor(new_data)
@@ -4569,8 +4574,8 @@ def to_period(self, freq=None, axis=0, copy=True):
if freq is None:
freq = self.columns.freqstr or self.columns.inferred_freq
new_data.set_axis(0, self.columns.to_period(freq=freq))
- else:
- raise ValueError('Axis must be 0 or 1. Got %s' % str(axis))
+ else: # pragma: no cover
+ raise AssertionError('Axis must be 0 or 1. Got %s' % str(axis))
return self._constructor(new_data)
@@ -4823,22 +4828,6 @@ def convert(v):
return values
-def _rec_to_dict(arr):
- if isinstance(arr, (np.ndarray, Series)):
- columns = list(arr.dtype.names)
- sdict = dict((k, arr[k]) for k in columns)
- elif isinstance(arr, DataFrame):
- columns = list(arr.columns)
- sdict = dict((k, v.values) for k, v in compat.iteritems(arr))
- elif isinstance(arr, dict):
- columns = sorted(arr)
- sdict = arr.copy()
- else: # pragma: no cover
- raise TypeError('%s' % type(arr))
-
- return columns, sdict
-
-
def _to_arrays(data, columns, coerce_float=False, dtype=None):
"""
Return list of arrays, columns
@@ -4933,8 +4922,7 @@ def _list_of_dict_to_arrays(data, columns, coerce_float=False, dtype=None):
# assure that they are of the base dict class and not of derived
# classes
- data = [(type(d) is dict) and d or dict(d)
- for d in data]
+ data = [(type(d) is dict) and d or dict(d) for d in data]
content = list(lib.dicts_to_array(data, list(columns)).T)
return _convert_object_array(content, columns, dtype=dtype,
@@ -4945,7 +4933,8 @@ def _convert_object_array(content, columns, coerce_float=False, dtype=None):
if columns is None:
columns = _default_index(len(content))
else:
- if len(columns) != len(content):
+ if len(columns) != len(content): # pragma: no cover
+ # caller's responsibility to check for this...
raise AssertionError('%d columns passed, passed data had %s '
'columns' % (len(columns), len(content)))
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index b0ab62b7158c9..796c3948a2681 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -417,7 +417,7 @@ def rename(self, *args, **kwargs):
inplace = kwargs.get('inplace', False)
if (com._count_not_none(*axes.values()) == 0):
- raise Exception('must pass an index to rename')
+ raise TypeError('must pass an index to rename')
# renamer function if passed a dict
def _get_rename_function(mapper):
@@ -1242,7 +1242,7 @@ def filter(self, items=None, like=None, regex=None, axis=None):
matcher = re.compile(regex)
return self.select(lambda x: matcher.search(x) is not None, axis=axis_name)
else:
- raise ValueError('items was None!')
+ raise TypeError('Must pass either `items`, `like`, or `regex`')
#----------------------------------------------------------------------
# Attribute access
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 856e97ad163f2..636a5e88817ee 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -84,7 +84,7 @@ def __setitem__(self, key, value):
if isinstance(key, tuple):
if len(key) > self.ndim:
- raise IndexingError('only tuples of length <= %d supported',
+ raise IndexingError('only tuples of length <= %d supported' %
self.ndim)
indexer = self._convert_tuple(key, is_setter=True)
else:
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index d025c7a7fcf6d..294b90bd4092f 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1625,7 +1625,7 @@ def set_axis(self, axis, value, maybe_rename=True, check_axis=True):
value = _ensure_index(value)
if check_axis and len(value) != len(cur_axis):
- raise Exception('Length mismatch (%d vs %d)'
+ raise ValueError('Length mismatch (%d vs %d)'
% (len(value), len(cur_axis)))
self.axes[axis] = value
@@ -2297,7 +2297,7 @@ def fast_2d_xs(self, loc, copy=False):
return result
if not copy:
- raise Exception('cannot get view of mixed-type or '
+ raise TypeError('cannot get view of mixed-type or '
'non-consolidated DataFrame')
items = self.items
@@ -2483,7 +2483,8 @@ def _set_item(item, arr):
def insert(self, loc, item, value, allow_duplicates=False):
if not allow_duplicates and item in self.items:
- raise Exception('cannot insert %s, already exists' % item)
+ # Should this be a different kind of error??
+ raise ValueError('cannot insert %s, already exists' % item)
try:
new_items = self.items.insert(loc, item)
@@ -2826,7 +2827,8 @@ def _maybe_rename_join(self, other, lsuffix, rsuffix, copydata=True):
to_rename = self.items.intersection(other.items)
if len(to_rename) > 0:
if not lsuffix and not rsuffix:
- raise Exception('columns overlap: %s' % to_rename)
+ raise ValueError('columns overlap but no suffix specified: %s'
+ % to_rename)
def lrenamer(x):
if x in to_rename:
diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py
index a8a36ef8ca0be..312667930b54d 100644
--- a/pandas/core/reshape.py
+++ b/pandas/core/reshape.py
@@ -21,10 +21,6 @@
from pandas.core.index import Index, MultiIndex
-class ReshapeError(Exception):
- pass
-
-
class _Unstacker(object):
"""
Helper class to unstack data / pivot with multi-level index
@@ -129,8 +125,8 @@ def _make_selectors(self):
mask.put(selector, True)
if mask.sum() < len(self.index):
- raise ReshapeError('Index contains duplicate entries, '
- 'cannot reshape')
+ raise ValueError('Index contains duplicate entries, '
+ 'cannot reshape')
self.group_index = comp_index
self.mask = mask
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 8396de9c5997b..43bf4db7b29db 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2377,7 +2377,7 @@ def sort(self, axis=0, kind='quicksort', order=None, ascending=True):
if (true_base is not None and
(true_base.ndim != 1 or true_base.shape != self.shape)):
- raise Exception('This Series is a view of some other array, to '
+ raise TypeError('This Series is a view of some other array, to '
'sort in-place you must create a copy')
self[:] = sortedSeries
@@ -2542,7 +2542,7 @@ def sortlevel(self, level=0, ascending=True):
sorted : Series
"""
if not isinstance(self.index, MultiIndex):
- raise Exception('can only sort by level with a hierarchical index')
+ raise TypeError('can only sort by level with a hierarchical index')
new_index, indexer = self.index.sortlevel(level, ascending=ascending)
new_values = self.values.take(indexer)
diff --git a/pandas/sparse/frame.py b/pandas/sparse/frame.py
index dd7bd52076e06..d8f6d531a6983 100644
--- a/pandas/sparse/frame.py
+++ b/pandas/sparse/frame.py
@@ -600,7 +600,8 @@ def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, lim
def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
sort=False):
if isinstance(other, Series):
- assert(other.name is not None)
+ if other.name is None:
+ raise ValueError('Other Series must have a name')
other = SparseDataFrame({other.name: other},
default_fill_value=self._default_fill_value)
if on is not None:
@@ -627,19 +628,19 @@ def _join_index(self, other, how, lsuffix, rsuffix):
return concat([this, other], axis=1, verify_integrity=True)
def _maybe_rename_join(self, other, lsuffix, rsuffix):
- intersection = self.columns.intersection(other.columns)
-
- if len(intersection) > 0:
+ to_rename = self.columns.intersection(other.columns)
+ if len(to_rename) > 0:
if not lsuffix and not rsuffix:
- raise Exception('columns overlap: %s' % intersection)
+ raise ValueError('columns overlap but no suffix specified: %s'
+ % to_rename)
def lrenamer(x):
- if x in intersection:
+ if x in to_rename:
return '%s%s' % (x, lsuffix)
return x
def rrenamer(x):
- if x in intersection:
+ if x in to_rename:
return '%s%s' % (x, rsuffix)
return x
@@ -687,7 +688,7 @@ def apply(self, func, axis=0, broadcast=False, reduce=False):
----------
func : function
Function to apply to each column
- axis : {0, 1}
+ axis : {0, 1, 'index', 'columns'}
broadcast : bool, default False
For aggregation functions, return object of same size with values
propagated
@@ -698,6 +699,7 @@ def apply(self, func, axis=0, broadcast=False, reduce=False):
"""
if not len(self.columns):
return self
+ axis = self._get_axis_number(axis)
if isinstance(func, np.ufunc):
new_series = {}
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 118672a85d3fb..c39634281ebb7 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -40,6 +40,8 @@
assertRaisesRegexp,
makeCustomDataframe as mkdf,
ensure_clean)
+from pandas.core.indexing import IndexingError
+from pandas.core.common import PandasError
import pandas.util.testing as tm
import pandas.lib as lib
@@ -115,7 +117,8 @@ def test_getitem(self):
self.assert_(self.frame[key] is not None)
self.assert_('random' not in self.frame)
- self.assertRaises(Exception, self.frame.__getitem__, 'random')
+ with assertRaisesRegexp(KeyError, 'no item named random'):
+ self.frame['random']
def test_getitem_dupe_cols(self):
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=['a', 'a', 'b'])
@@ -154,10 +157,10 @@ def test_getitem_list(self):
self.assertEqual(result.columns.name, 'foo')
- self.assertRaises(Exception, self.frame.__getitem__,
- ['B', 'A', 'foo'])
- self.assertRaises(Exception, self.frame.__getitem__,
- Index(['B', 'A', 'foo']))
+ with assertRaisesRegexp(KeyError, 'not in index'):
+ self.frame[['B', 'A', 'food']]
+ with assertRaisesRegexp(KeyError, 'not in index'):
+ self.frame[Index(['B', 'A', 'foo'])]
# tuples
df = DataFrame(randn(8, 3),
@@ -178,6 +181,12 @@ def test_setitem_list(self):
assert_series_equal(self.frame['B'], data['A'])
assert_series_equal(self.frame['A'], data['B'])
+ with assertRaisesRegexp(ValueError, 'Columns must be same length as key'):
+ data[['A']] = self.frame[['A', 'B']]
+ with assertRaisesRegexp(ValueError, 'Length of values does not match '
+ 'length of index'):
+ data['A'] = range(len(data.index) - 1)
+
df = DataFrame(0, lrange(3), ['tt1', 'tt2'], dtype=np.int_)
df.ix[1, ['tt1', 'tt2']] = [1, 2]
@@ -214,12 +223,14 @@ def test_getitem_boolean(self):
subframe = self.tsframe[indexer]
self.assert_(np.array_equal(subindex, subframe.index))
- self.assertRaises(Exception, self.tsframe.__getitem__, indexer[:-1])
+ with assertRaisesRegexp(ValueError, 'Item wrong length'):
+ self.tsframe[indexer[:-1]]
subframe_obj = self.tsframe[indexer_obj]
assert_frame_equal(subframe_obj, subframe)
- self.assertRaises(ValueError, self.tsframe.__getitem__, self.tsframe)
+ with tm.assertRaisesRegexp(ValueError, 'boolean values only'):
+ self.tsframe[self.tsframe]
# test that Series work
indexer_obj = Series(indexer_obj, self.tsframe.index)
@@ -381,8 +392,8 @@ def test_setitem(self):
tm.assert_dict_equal(series, self.frame['col6'],
compare_keys=False)
- self.assertRaises(Exception, self.frame.__setitem__,
- randn(len(self.frame) + 1))
+ with tm.assertRaises(KeyError):
+ self.frame[randn(len(self.frame) + 1)] = 1
# set ndarray
arr = randn(len(self.frame))
@@ -462,7 +473,9 @@ def test_setitem_boolean(self):
values[values == 2] = 3
assert_almost_equal(df.values, values)
- self.assertRaises(Exception, df.__setitem__, df * 0, 2)
+ with assertRaisesRegexp(TypeError, 'Must pass DataFrame with boolean '
+ 'values only'):
+ df[df * 0] = 2
# index with DataFrame
mask = df > np.abs(df)
@@ -1176,14 +1189,11 @@ def test_getitem_fancy_ints(self):
def test_getitem_setitem_fancy_exceptions(self):
ix = self.frame.ix
- self.assertRaises(Exception, ix.__getitem__,
- (slice(None, None, None),
- slice(None, None, None),
- slice(None, None, None)))
- self.assertRaises(Exception, ix.__setitem__,
- (slice(None, None, None),
- slice(None, None, None),
- slice(None, None, None)), 1)
+ with assertRaisesRegexp(IndexingError, 'Too many indexers'):
+ ix[:, :, :]
+ with assertRaisesRegexp(IndexingError, 'only tuples of length <= 2 '
+ 'supported'):
+ ix[:, :, :] = 1
def test_getitem_setitem_boolean_misaligned(self):
# boolean index misaligned labels
@@ -1230,8 +1240,10 @@ def test_getitem_setitem_float_labels(self):
self.assertEqual(len(result), 2)
# this should raise an exception
- self.assertRaises(Exception, df.ix.__getitem__, slice(1, 2))
- self.assertRaises(Exception, df.ix.__setitem__, slice(1, 2), 0)
+ with tm.assertRaises(KeyError):
+ df.ix[1:2]
+ with tm.assertRaises(KeyError):
+ df.ix[1:2] = 0
# #2727
index = Index([1.0, 2.5, 3.5, 4.5, 5.0])
@@ -1470,11 +1482,14 @@ def testit(df):
assert_almost_equal(df['mask'], exp_mask)
self.assert_(df['mask'].dtype == np.bool_)
- self.assertRaises(ValueError, self.frame.lookup,
- ['xyz'], ['A'])
+ with tm.assertRaises(KeyError):
+ self.frame.lookup(['xyz'], ['A'])
+
+ with tm.assertRaises(KeyError):
+ self.frame.lookup([self.frame.index[0]], ['xyz'])
- self.assertRaises(ValueError, self.frame.lookup,
- [self.frame.index[0]], ['xyz'])
+ with tm.assertRaisesRegexp(ValueError, 'same size'):
+ self.frame.lookup(['a', 'b', 'c'], ['a'])
def test_set_value(self):
for idx in self.frame.index:
@@ -1721,10 +1736,6 @@ def test_join_index(self):
self.assert_(joined.index.equals(f2.index))
self.assertEqual(len(joined.columns), 4)
- # corner case
- self.assertRaises(Exception, self.frame.join, self.frame,
- how='left')
-
# inner
f = self.frame.reindex(columns=['A', 'B'])[:10]
@@ -1734,10 +1745,6 @@ def test_join_index(self):
self.assert_(joined.index.equals(f.index.intersection(f2.index)))
self.assertEqual(len(joined.columns), 4)
- # corner case
- self.assertRaises(Exception, self.frame.join, self.frame,
- how='inner')
-
# outer
f = self.frame.reindex(columns=['A', 'B'])[:10]
@@ -1747,11 +1754,12 @@ def test_join_index(self):
self.assert_(tm.equalContents(self.frame.index, joined.index))
self.assertEqual(len(joined.columns), 4)
- # corner case
- self.assertRaises(Exception, self.frame.join, self.frame,
- how='outer')
+ assertRaisesRegexp(ValueError, 'join method', f.join, f2, how='foo')
- self.assertRaises(Exception, f.join, f2, how='foo')
+ # corner case - overlapping columns
+ for how in ('outer', 'left', 'inner'):
+ with assertRaisesRegexp(ValueError, 'columns overlap but no suffix'):
+ self.frame.join(self.frame, how=how)
def test_join_index_more(self):
af = self.frame.ix[:, ['A', 'B']]
@@ -1778,7 +1786,7 @@ def test_join_index_series(self):
assert_frame_equal(joined, self.frame, check_names=False) # TODO should this check_names ?
s.name = None
- self.assertRaises(Exception, df.join, s)
+ assertRaisesRegexp(ValueError, 'must have a name', df.join, s)
def test_join_overlap(self):
df1 = self.frame.ix[:, ['A', 'B', 'C']]
@@ -1858,22 +1866,23 @@ def setUp(self):
def test_get_axis(self):
f = self.frame
- self.assert_(f._get_axis_name(0) == 'index')
- self.assert_(f._get_axis_name(1) == 'columns')
- self.assert_(f._get_axis_name('index') == 'index')
- self.assert_(f._get_axis_name('columns') == 'columns')
- self.assertRaises(Exception, f._get_axis_name, 'foo')
- self.assertRaises(Exception, f._get_axis_name, None)
-
- self.assert_(f._get_axis_number(0) == 0)
- self.assert_(f._get_axis_number(1) == 1)
- self.assert_(f._get_axis_number('index') == 0)
- self.assert_(f._get_axis_number('columns') == 1)
- self.assertRaises(Exception, f._get_axis_number, 2)
- self.assertRaises(Exception, f._get_axis_number, None)
-
- self.assert_(self.frame._get_axis(0) is self.frame.index)
- self.assert_(self.frame._get_axis(1) is self.frame.columns)
+ self.assertEquals(f._get_axis_number(0), 0)
+ self.assertEquals(f._get_axis_number(1), 1)
+ self.assertEquals(f._get_axis_number('index'), 0)
+ self.assertEquals(f._get_axis_number('columns'), 1)
+
+ self.assertEquals(f._get_axis_name(0), 'index')
+ self.assertEquals(f._get_axis_name(1), 'columns')
+ self.assertEquals(f._get_axis_name('index'), 'index')
+ self.assertEquals(f._get_axis_name('columns'), 'columns')
+
+ self.assert_(f._get_axis(0) is f.index)
+ self.assert_(f._get_axis(1) is f.columns)
+
+ assertRaisesRegexp(ValueError, 'No axis named', f._get_axis_number, 2)
+ assertRaisesRegexp(ValueError, 'No axis.*foo', f._get_axis_name, 'foo')
+ assertRaisesRegexp(ValueError, 'No axis.*None', f._get_axis_name, None)
+ assertRaisesRegexp(ValueError, 'No axis named', f._get_axis_number, None)
def test_set_index(self):
idx = Index(np.arange(len(self.mixed_frame)))
@@ -1882,8 +1891,8 @@ def test_set_index(self):
_ = self.mixed_frame['foo']
self.mixed_frame.index = idx
self.assert_(self.mixed_frame['foo'].index is idx)
- self.assertRaises(Exception, setattr, self.mixed_frame, 'index',
- idx[::2])
+ with assertRaisesRegexp(ValueError, 'Length mismatch'):
+ self.mixed_frame.index = idx[::2]
def test_set_index_cast(self):
@@ -1957,7 +1966,8 @@ def test_set_index2(self):
assert_frame_equal(df3, expected_nodrop)
# corner case
- self.assertRaises(Exception, df.set_index, 'A', verify_integrity=True)
+ with assertRaisesRegexp(ValueError, 'Index has duplicate keys'):
+ df.set_index('A', verify_integrity=True)
# append
result = df.set_index(['A', 'B'], append=True)
@@ -1981,8 +1991,8 @@ def test_set_index_nonuniq(self):
'C': ['a', 'b', 'c', 'd', 'e'],
'D': np.random.randn(5),
'E': np.random.randn(5)})
- self.assertRaises(Exception, df.set_index, 'A', verify_integrity=True,
- inplace=True)
+ with assertRaisesRegexp(ValueError, 'Index has duplicate keys'):
+ df.set_index('A', verify_integrity=True, inplace=True)
self.assert_('A' in df)
def test_set_index_bug(self):
@@ -2040,8 +2050,8 @@ def test_set_index_empty_column(self):
def test_set_columns(self):
cols = Index(np.arange(len(self.mixed_frame.columns)))
self.mixed_frame.columns = cols
- self.assertRaises(Exception, setattr, self.mixed_frame, 'columns',
- cols[::2])
+ with assertRaisesRegexp(ValueError, 'Length mismatch'):
+ self.mixed_frame.columns = cols[::2]
def test_keys(self):
getkeys = self.frame.keys
@@ -2220,12 +2230,11 @@ def test_constructor_dict(self):
# Corner cases
self.assertEqual(len(DataFrame({})), 0)
- self.assertRaises(Exception, lambda x: DataFrame([self.ts1, self.ts2]))
- # mix dict and array, wrong size
- self.assertRaises(Exception, DataFrame,
- {'A': {'a': 'a', 'b': 'b'},
- 'B': ['a', 'b', 'c']})
+ # mix dict and array, wrong size - no spec for which error should raise
+ # first
+ with tm.assertRaises(ValueError):
+ DataFrame({'A': {'a': 'a', 'b': 'b'}, 'B': ['a', 'b', 'c']})
# Length-one dict micro-optimization
frame = DataFrame({'A': {'1': 1, '2': 2}})
@@ -2248,36 +2257,33 @@ def test_constructor_dict(self):
self.assert_(frame.index.equals(Index([])))
def test_constructor_error_msgs(self):
-
+ msg = "Mixing dicts with non-Series may lead to ambiguous ordering."
# mix dict and array, wrong size
- def testit():
+ with assertRaisesRegexp(ValueError, msg):
DataFrame({'A': {'a': 'a', 'b': 'b'},
'B': ['a', 'b', 'c']})
- assertRaisesRegexp(ValueError, "Mixing dicts with non-Series may lead to ambiguous ordering.", testit)
# wrong size ndarray, GH 3105
- def testit():
- DataFrame(np.arange(12).reshape((4, 3)), columns=['foo', 'bar', 'baz'],
+ msg = "Shape of passed values is \(3, 4\), indices imply \(3, 3\)"
+ with assertRaisesRegexp(ValueError, msg):
+ DataFrame(np.arange(12).reshape((4, 3)),
+ columns=['foo', 'bar', 'baz'],
index=date_range('2000-01-01', periods=3))
- assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 4\), indices imply \(3, 3\)", testit)
+
# higher dim raise exception
- def testit():
+ with assertRaisesRegexp(ValueError, 'Must pass 2-d input'):
DataFrame(np.zeros((3, 3, 3)), columns=['A', 'B', 'C'], index=[1])
- assertRaisesRegexp(ValueError, "Must pass 2-d input", testit)
# wrong size axis labels
- def testit():
+ with assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 2\), indices imply \(3, 1\)"):
DataFrame(np.random.rand(2,3), columns=['A', 'B', 'C'], index=[1])
- assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 2\), indices imply \(3, 1\)", testit)
- def testit():
+ with assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 2\), indices imply \(2, 2\)"):
DataFrame(np.random.rand(2,3), columns=['A', 'B'], index=[1, 2])
- assertRaisesRegexp(ValueError, "Shape of passed values is \(3, 2\), indices imply \(2, 2\)", testit)
- def testit():
+ with assertRaisesRegexp(ValueError, 'If using all scalar values, you must must pass an index'):
DataFrame({'a': False, 'b': True})
- assertRaisesRegexp(ValueError, 'If using all scalar values, you must must pass an index', testit)
def test_insert_error_msmgs(self):
@@ -2285,10 +2291,10 @@ def test_insert_error_msmgs(self):
df = DataFrame(np.random.randint(0,2,(4,4)),
columns=['a', 'b', 'c', 'd'])
- def testit():
+ msg = 'incompatible index of inserted column with frame index'
+ with assertRaisesRegexp(TypeError, msg):
df['gr'] = df.groupby(['b', 'c']).count()
- assertRaisesRegexp(TypeError, 'incompatible index of inserted column with frame index', testit)
def test_constructor_subclass_dict(self):
# Test for passing dict subclass to constructor
@@ -2362,38 +2368,38 @@ def test_constructor_dict_of_tuples(self):
expected = DataFrame(dict((k, list(v)) for k, v in compat.iteritems(data)))
assert_frame_equal(result, expected, check_dtype=False)
- def test_constructor_ndarray(self):
- mat = np.zeros((2, 3), dtype=float)
-
+ def _check_basic_constructor(self, empty):
+ "mat: 2d matrix with shpae (3, 2) to input. empty - makes sized objects"
+ mat = empty((2, 3), dtype=float)
# 2-D input
frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2])
self.assertEqual(len(frame.index), 2)
self.assertEqual(len(frame.columns), 3)
- # cast type
- frame = DataFrame(mat, columns=['A', 'B', 'C'],
- index=[1, 2], dtype=np.int64)
- self.assert_(frame.values.dtype == np.int64)
-
# 1-D input
- frame = DataFrame(np.zeros(3), columns=['A'], index=[1, 2, 3])
+ frame = DataFrame(empty((3,)), columns=['A'], index=[1, 2, 3])
self.assertEqual(len(frame.index), 3)
self.assertEqual(len(frame.columns), 1)
- frame = DataFrame(['foo', 'bar'], index=[0, 1], columns=['A'])
- self.assertEqual(len(frame), 2)
- # higher dim raise exception
- self.assertRaises(Exception, DataFrame, np.zeros((3, 3, 3)),
- columns=['A', 'B', 'C'], index=[1])
+ # cast type
+ frame = DataFrame(mat, columns=['A', 'B', 'C'],
+ index=[1, 2], dtype=np.int64)
+ self.assert_(frame.values.dtype == np.int64)
# wrong size axis labels
- self.assertRaises(Exception, DataFrame, mat,
- columns=['A', 'B', 'C'], index=[1])
+ msg = r'Shape of passed values is \(3, 2\), indices imply \(3, 1\)'
+ with assertRaisesRegexp(ValueError, msg):
+ DataFrame(mat, columns=['A', 'B', 'C'], index=[1])
+ msg = r'Shape of passed values is \(3, 2\), indices imply \(2, 2\)'
+ with assertRaisesRegexp(ValueError, msg):
+ DataFrame(mat, columns=['A', 'B'], index=[1, 2])
- self.assertRaises(Exception, DataFrame, mat,
- columns=['A', 'B'], index=[1, 2])
+ # higher dim raise exception
+ with assertRaisesRegexp(ValueError, 'Must pass 2-d input'):
+ DataFrame(empty((3, 3, 3)), columns=['A', 'B', 'C'],
+ index=[1])
# automatic labeling
frame = DataFrame(mat)
@@ -2407,70 +2413,36 @@ def test_constructor_ndarray(self):
self.assert_(np.array_equal(frame.index, lrange(2)))
# 0-length axis
- frame = DataFrame(np.empty((0, 3)))
+ frame = DataFrame(empty((0, 3)))
self.assert_(len(frame.index) == 0)
- frame = DataFrame(np.empty((3, 0)))
+ frame = DataFrame(empty((3, 0)))
self.assert_(len(frame.columns) == 0)
- def test_constructor_maskedarray(self):
- mat = ma.masked_all((2, 3), dtype=float)
+ def test_constructor_ndarray(self):
+ mat = np.zeros((2, 3), dtype=float)
+ self._check_basic_constructor(np.ones)
- # 2-D input
- frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2])
+ frame = DataFrame(['foo', 'bar'], index=[0, 1], columns=['A'])
+ self.assertEqual(len(frame), 2)
- self.assertEqual(len(frame.index), 2)
- self.assertEqual(len(frame.columns), 3)
- self.assertTrue(np.all(~np.asarray(frame == frame)))
- # cast type
- frame = DataFrame(mat, columns=['A', 'B', 'C'],
- index=[1, 2], dtype=np.int64)
- self.assert_(frame.values.dtype == np.int64)
+ def test_constructor_maskedarray(self):
+ self._check_basic_constructor(ma.masked_all)
# Check non-masked values
- mat2 = ma.copy(mat)
- mat2[0, 0] = 1.0
- mat2[1, 2] = 2.0
- frame = DataFrame(mat2, columns=['A', 'B', 'C'], index=[1, 2])
+ mat = ma.masked_all((2, 3), dtype=float)
+ mat[0, 0] = 1.0
+ mat[1, 2] = 2.0
+ frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2])
self.assertEqual(1.0, frame['A'][1])
self.assertEqual(2.0, frame['C'][2])
- # 1-D input
- frame = DataFrame(ma.masked_all((3,)), columns=['A'], index=[1, 2, 3])
- self.assertEqual(len(frame.index), 3)
- self.assertEqual(len(frame.columns), 1)
+ # what is this even checking??
+ mat = ma.masked_all((2, 3), dtype=float)
+ frame = DataFrame(mat, columns=['A', 'B', 'C'], index=[1, 2])
self.assertTrue(np.all(~np.asarray(frame == frame)))
- # higher dim raise exception
- self.assertRaises(Exception, DataFrame, ma.masked_all((3, 3, 3)),
- columns=['A', 'B', 'C'], index=[1])
-
- # wrong size axis labels
- self.assertRaises(Exception, DataFrame, mat,
- columns=['A', 'B', 'C'], index=[1])
-
- self.assertRaises(Exception, DataFrame, mat,
- columns=['A', 'B'], index=[1, 2])
-
- # automatic labeling
- frame = DataFrame(mat)
- self.assert_(np.array_equal(frame.index, lrange(2)))
- self.assert_(np.array_equal(frame.columns, lrange(3)))
-
- frame = DataFrame(mat, index=[1, 2])
- self.assert_(np.array_equal(frame.columns, lrange(3)))
-
- frame = DataFrame(mat, columns=['A', 'B', 'C'])
- self.assert_(np.array_equal(frame.index, lrange(2)))
-
- # 0-length axis
- frame = DataFrame(ma.masked_all((0, 3)))
- self.assert_(len(frame.index) == 0)
-
- frame = DataFrame(ma.masked_all((3, 0)))
- self.assert_(len(frame.columns) == 0)
-
def test_constructor_maskedarray_nonfloat(self):
# masked int promoted to float
mat = ma.masked_all((2, 3), dtype=int)
@@ -2570,8 +2542,8 @@ def test_constructor_arrays_and_scalars(self):
exp = DataFrame({'a': df['a'].values, 'b': [True] * 10})
assert_frame_equal(df, exp)
-
- self.assertRaises(ValueError, DataFrame, {'a': False, 'b': True})
+ with tm.assertRaisesRegexp(ValueError, 'must pass an index'):
+ DataFrame({'a': False, 'b': True})
def test_constructor_DataFrame(self):
df = DataFrame(self.frame)
@@ -2602,12 +2574,14 @@ def test_constructor_more(self):
self.assertEqual(dm.values.shape, (10, 0))
# corner, silly
- self.assertRaises(Exception, DataFrame, (1, 2, 3))
+ # TODO: Fix this Exception to be better...
+ with assertRaisesRegexp(PandasError, 'constructor not properly called'):
+ DataFrame((1, 2, 3))
# can't cast
mat = np.array(['foo', 'bar'], dtype=object).reshape(2, 1)
- self.assertRaises(ValueError, DataFrame, mat, index=[0, 1],
- columns=[0], dtype=float)
+ with assertRaisesRegexp(ValueError, 'cast'):
+ DataFrame(mat, index=[0, 1], columns=[0], dtype=float)
dm = DataFrame(DataFrame(self.frame._series))
tm.assert_frame_equal(dm, self.frame)
@@ -2718,7 +2692,8 @@ class CustomDict(dict):
def test_constructor_ragged(self):
data = {'A': randn(10),
'B': randn(8)}
- self.assertRaises(Exception, DataFrame, data)
+ assertRaisesRegexp(ValueError, 'arrays must all be same length',
+ DataFrame, data)
def test_constructor_scalar(self):
idx = Index(lrange(3))
@@ -2739,8 +2714,8 @@ def test_constructor_mixed_dict_and_Series(self):
self.assert_(result.index.is_monotonic)
# ordering ambiguous, raise exception
- self.assertRaises(Exception, DataFrame,
- {'A': ['a', 'b'], 'B': {'a': 'a', 'b': 'b'}})
+ with assertRaisesRegexp(ValueError, 'ambiguous ordering'):
+ DataFrame({'A': ['a', 'b'], 'B': {'a': 'a', 'b': 'b'}})
# this is OK though
result = DataFrame({'A': ['a', 'b'],
@@ -2850,10 +2825,11 @@ def test_constructor_from_items(self):
columns=self.mixed_frame.columns,
orient='index')
assert_frame_equal(recons, self.mixed_frame)
- self.assert_(recons['A'].dtype == np.float64)
+ self.assertEqual(recons['A'].dtype, np.float64)
- self.assertRaises(ValueError, DataFrame.from_items, row_items,
- orient='index')
+ with tm.assertRaisesRegexp(TypeError,
+ "Must pass columns with orient='index'"):
+ DataFrame.from_items(row_items, orient='index')
# orient='index', but thar be tuples
arr = lib.list_to_object_array(
@@ -2878,9 +2854,8 @@ def test_constructor_mix_series_nonseries(self):
'B': list(self.frame['B'])}, columns=['A', 'B'])
assert_frame_equal(df, self.frame.ix[:, ['A', 'B']])
- self.assertRaises(ValueError, DataFrame,
- {'A': self.frame['A'],
- 'B': list(self.frame['B'])[:-2]})
+ with tm.assertRaisesRegexp(ValueError, 'does not match index length'):
+ DataFrame({'A': self.frame['A'], 'B': list(self.frame['B'])[:-2]})
def test_constructor_miscast_na_int_dtype(self):
df = DataFrame([[np.nan, 1], [1, 0]], dtype=np.int64)
@@ -2932,6 +2907,8 @@ def check(result, expected=None):
df['string'] = 'bah'
expected = DataFrame([[1,1,1,5,'bah'],[1,1,2,5,'bah'],[2,1,3,5,'bah']],columns=['foo','bar','foo','hello','string'])
check(df,expected)
+ with assertRaisesRegexp(ValueError, 'Length of value'):
+ df.insert(0, 'AnotherColumn', range(len(df.index) - 1))
# insert same dtype
df['foo2'] = 3
@@ -2965,7 +2942,7 @@ def check(result, expected=None):
check(df,expected)
# insert a dup
- self.assertRaises(Exception, df.insert, 2, 'new_col', 4.)
+ assertRaisesRegexp(ValueError, 'cannot insert', df.insert, 2, 'new_col', 4.)
df.insert(2,'new_col',4.,allow_duplicates=True)
expected = DataFrame([[1,1,4.,5.,'bah',3],[1,2,4.,5.,'bah',3],[2,3,4.,5.,'bah',3]],columns=['foo','foo','new_col','new_col','string','foo2'])
check(df,expected)
@@ -3071,8 +3048,8 @@ def test_constructor_single_value(self):
self.assertRaises(com.PandasError, DataFrame, 'a', [1, 2])
self.assertRaises(com.PandasError, DataFrame, 'a', columns=['a', 'c'])
- self.assertRaises(
- com.PandasError, DataFrame, 'a', [1, 2], ['a', 'c'], float)
+ with tm.assertRaisesRegexp(TypeError, 'incompatible data and dtype'):
+ DataFrame('a', [1, 2], ['a', 'c'], float)
def test_constructor_with_datetimes(self):
@@ -3497,8 +3474,9 @@ def test_from_records_to_records(self):
tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))
# wrong length
- self.assertRaises(Exception, DataFrame.from_records, arr,
- index=index[:-1])
+ msg = r'Shape of passed values is \(3,\), indices imply \(3, 1\)'
+ with assertRaisesRegexp(ValueError, msg):
+ DataFrame.from_records(arr, index=index[:-1])
indexed_frame = DataFrame.from_records(arr, index='f1')
@@ -3816,7 +3794,7 @@ def test_get_agg_axis(self):
idx = self.frame._get_agg_axis(1)
self.assert_(idx is self.frame.index)
- self.assertRaises(Exception, self.frame._get_agg_axis, 2)
+ self.assertRaises(ValueError, self.frame._get_agg_axis, 2)
def test_nonzero(self):
self.assertTrue(self.empty.empty)
@@ -3991,19 +3969,20 @@ def test_insert(self):
# new item
df['x'] = df['a'].astype('float32')
result = Series(dict(float64 = 5, float32 = 1))
- self.assert_((df.get_dtype_counts() == result).all() == True)
+ self.assert_((df.get_dtype_counts() == result).all())
# replacing current (in different block)
df['a'] = df['a'].astype('float32')
result = Series(dict(float64 = 4, float32 = 2))
- self.assert_((df.get_dtype_counts() == result).all() == True)
+ self.assert_((df.get_dtype_counts() == result).all())
df['y'] = df['a'].astype('int32')
result = Series(dict(float64 = 4, float32 = 2, int32 = 1))
- self.assert_((df.get_dtype_counts() == result).all() == True)
+ self.assert_((df.get_dtype_counts() == result).all())
- self.assertRaises(Exception, df.insert, 1, 'a', df['b'])
- self.assertRaises(Exception, df.insert, 1, 'c', df['b'])
+ with assertRaisesRegexp(ValueError, 'already exists'):
+ df.insert(1, 'a', df['b'])
+ self.assertRaises(ValueError, df.insert, 1, 'c', df['b'])
df.columns.name = 'some_name'
# preserve columns name field
@@ -4310,6 +4289,15 @@ def test_arith_flex_frame(self):
assert_frame_equal(result, exp)
_check_mixed_int(result, dtype = dtype)
+ # ndim >= 3
+ ndim_5 = np.ones(self.frame.shape + (3, 4, 5))
+ with assertRaisesRegexp(ValueError, 'shape'):
+ f(self.frame, ndim_5)
+
+ with assertRaisesRegexp(ValueError, 'shape'):
+ getattr(self.frame, op)(ndim_5)
+
+
# res_add = self.frame.add(self.frame)
# res_sub = self.frame.sub(self.frame)
# res_mul = self.frame.mul(self.frame)
@@ -4329,6 +4317,10 @@ def test_arith_flex_frame(self):
result = self.frame[:0].add(self.frame)
assert_frame_equal(result, self.frame * np.nan)
+ with assertRaisesRegexp(NotImplementedError, 'fill_value'):
+ self.frame.add(self.frame.irow(0), fill_value=3)
+ with assertRaisesRegexp(NotImplementedError, 'fill_value'):
+ self.frame.add(self.frame.irow(0), axis='index', fill_value=3)
def test_arith_mixed(self):
@@ -4377,34 +4369,32 @@ def test_bool_flex_frame(self):
other_data = np.random.randn(5, 3)
df = DataFrame(data)
other = DataFrame(other_data)
-
- # No NAs
-
- # DataFrame
- self.assert_(df.eq(df).values.all())
- self.assert_(not df.ne(df).values.any())
-
- assert_frame_equal((df == other), df.eq(other))
- assert_frame_equal((df != other), df.ne(other))
- assert_frame_equal((df > other), df.gt(other))
- assert_frame_equal((df < other), df.lt(other))
- assert_frame_equal((df >= other), df.ge(other))
- assert_frame_equal((df <= other), df.le(other))
+ ndim_5 = np.ones(df.shape + (1, 3))
# Unaligned
- def _check_unaligned_frame(meth, op, df, other, default=False):
+ def _check_unaligned_frame(meth, op, df, other):
part_o = other.ix[3:, 1:].copy()
- rs = meth(df, part_o)
+ rs = meth(part_o)
xp = op(df, part_o.reindex(index=df.index, columns=df.columns))
assert_frame_equal(rs, xp)
- _check_unaligned_frame(DataFrame.eq, operator.eq, df, other)
- _check_unaligned_frame(DataFrame.ne, operator.ne, df, other,
- default=True)
- _check_unaligned_frame(DataFrame.gt, operator.gt, df, other)
- _check_unaligned_frame(DataFrame.lt, operator.lt, df, other)
- _check_unaligned_frame(DataFrame.ge, operator.ge, df, other)
- _check_unaligned_frame(DataFrame.le, operator.le, df, other)
+ # DataFrame
+ self.assert_(df.eq(df).values.all())
+ self.assert_(not df.ne(df).values.any())
+ for op in ['eq', 'ne', 'gt', 'lt', 'ge', 'le']:
+ f = getattr(df, op)
+ o = getattr(operator, op)
+ # No NAs
+ assert_frame_equal(f(other), o(df, other))
+ _check_unaligned_frame(f, o, df, other)
+ # ndarray
+ assert_frame_equal(f(other.values), o(df, other.values))
+ # scalar
+ assert_frame_equal(f(0), o(df, 0))
+ # NAs
+ assert_frame_equal(f(np.nan), o(df, np.nan))
+ with assertRaisesRegexp(ValueError, 'shape'):
+ f(ndim_5)
# Series
def _test_seq(df, idx_ser, col_ser):
@@ -4443,14 +4433,6 @@ def _test_seq(df, idx_ser, col_ser):
col_ser = Series(np.random.randn(3))
_test_seq(df, idx_ser, col_ser)
- # ndarray
-
- assert_frame_equal((df == other.values), df.eq(other.values))
- assert_frame_equal((df != other.values), df.ne(other.values))
- assert_frame_equal((df > other.values), df.gt(other.values))
- assert_frame_equal((df < other.values), df.lt(other.values))
- assert_frame_equal((df >= other.values), df.ge(other.values))
- assert_frame_equal((df <= other.values), df.le(other.values))
# list/tuple
_test_seq(df, idx_ser.values, col_ser.values)
@@ -4470,20 +4452,7 @@ def _test_seq(df, idx_ser, col_ser):
rs = df.le(df)
self.assert_(not rs.ix[0, 0])
- # scalar
- assert_frame_equal(df.eq(0), df == 0)
- assert_frame_equal(df.ne(0), df != 0)
- assert_frame_equal(df.gt(0), df > 0)
- assert_frame_equal(df.lt(0), df < 0)
- assert_frame_equal(df.ge(0), df >= 0)
- assert_frame_equal(df.le(0), df <= 0)
-
- assert_frame_equal(df.eq(np.nan), df == np.nan)
- assert_frame_equal(df.ne(np.nan), df != np.nan)
- assert_frame_equal(df.gt(np.nan), df > np.nan)
- assert_frame_equal(df.lt(np.nan), df < np.nan)
- assert_frame_equal(df.ge(np.nan), df >= np.nan)
- assert_frame_equal(df.le(np.nan), df <= np.nan)
+
# complex
arr = np.array([np.nan, 1, 6, np.nan])
@@ -4512,19 +4481,20 @@ def test_arith_flex_series(self):
row = df.xs('a')
col = df['two']
+ # after arithmetic refactor, add truediv here
+ ops = ['add', 'sub', 'mul', 'mod']
+ for op in ops:
+ f = getattr(df, op)
+ op = getattr(operator, op)
+ assert_frame_equal(f(row), op(df, row))
+ assert_frame_equal(f(col, axis=0), op(df.T, col).T)
- assert_frame_equal(df.add(row), df + row)
+ # special case for some reason
assert_frame_equal(df.add(row, axis=None), df + row)
- assert_frame_equal(df.sub(row), df - row)
- assert_frame_equal(df.div(row), df / row)
- assert_frame_equal(df.mul(row), df * row)
- assert_frame_equal(df.mod(row), df % row)
- assert_frame_equal(df.add(col, axis=0), (df.T + col).T)
- assert_frame_equal(df.sub(col, axis=0), (df.T - col).T)
+ # cases which will be refactored after big arithmetic refactor
+ assert_frame_equal(df.div(row), df / row)
assert_frame_equal(df.div(col, axis=0), (df.T / col).T)
- assert_frame_equal(df.mul(col, axis=0), (df.T * col).T)
- assert_frame_equal(df.mod(col, axis=0), (df.T % col).T)
def test_arith_non_pandas_object(self):
df = self.simple
@@ -4697,11 +4667,14 @@ def test_comparisons(self):
df2 = tm.makeTimeDataFrame()
row = self.simple.xs('a')
+ ndim_5 = np.ones(df1.shape + (1, 1, 1))
def test_comp(func):
result = func(df1, df2)
self.assert_(np.array_equal(result.values,
func(df1.values, df2.values)))
+ with assertRaisesRegexp(ValueError, 'Wrong number of dimensions'):
+ func(df1, ndim_5)
result2 = func(self.simple, row)
self.assert_(np.array_equal(result2.values,
@@ -4711,7 +4684,10 @@ def test_comp(func):
self.assert_(np.array_equal(result3.values,
func(self.frame.values, 0)))
- self.assertRaises(Exception, func, self.simple, self.simple[:2])
+
+ with assertRaisesRegexp(ValueError, 'Can only compare '
+ 'identically-labeled DataFrame'):
+ func(self.simple, self.simple[:2])
test_comp(operator.eq)
test_comp(operator.ne)
@@ -5289,20 +5265,19 @@ def _make_frame(names=None):
df.to_csv(path,tupleize_cols=False)
# catch invalid headers
- def testit():
+ with assertRaisesRegexp(CParserError, 'Passed header=\[0,1,2\] are too many rows for this multi_index of columns'):
read_csv(path,tupleize_cols=False,header=lrange(3),index_col=0)
- assertRaisesRegexp(CParserError, 'Passed header=\[0,1,2\] are too many rows for this multi_index of columns', testit)
- def testit():
+ with assertRaisesRegexp(CParserError, 'Passed header=\[0,1,2,3,4,5,6\], len of 7, but only 6 lines in file'):
read_csv(path,tupleize_cols=False,header=lrange(7),index_col=0)
- assertRaisesRegexp(CParserError, 'Passed header=\[0,1,2,3,4,5,6\], len of 7, but only 6 lines in file', testit)
- for i in [3,4,5,6,7]:
- self.assertRaises(Exception, read_csv, path, tupleize_cols=False, header=lrange(i), index_col=0)
- self.assertRaises(Exception, read_csv, path, tupleize_cols=False, header=[0,2], index_col=0)
+ for i in [4,5,6]:
+ with tm.assertRaises(CParserError):
+ read_csv(path, tupleize_cols=False, header=lrange(i), index_col=0)
# write with cols
- self.assertRaises(Exception, df.to_csv, path,tupleize_cols=False,cols=['foo','bar'])
+ with assertRaisesRegexp(TypeError, 'cannot specify cols with a MultiIndex'):
+ df.to_csv(path, tupleize_cols=False, cols=['foo', 'bar'])
with ensure_clean(pname) as path:
# empty
@@ -5650,7 +5625,8 @@ def test_convert_objects(self):
# via astype, but errors
converted = self.mixed_frame.copy()
- self.assertRaises(Exception, converted['H'].astype, 'int32')
+ with assertRaisesRegexp(ValueError, 'invalid literal'):
+ converted['H'].astype('int32')
# mixed in a single column
df = DataFrame(dict(s = Series([1, 'na', 3 ,4])))
@@ -5669,9 +5645,12 @@ def test_append_series_dict(self):
columns=['foo', 'bar', 'baz', 'qux'])
series = df.ix[4]
- self.assertRaises(ValueError, df.append, series, verify_integrity=True)
+ with assertRaisesRegexp(ValueError, 'Indexes have overlapping values'):
+ df.append(series, verify_integrity=True)
series.name = None
- self.assertRaises(Exception, df.append, series, verify_integrity=True)
+ with assertRaisesRegexp(TypeError, 'Can only append a Series if '
+ 'ignore_index=True'):
+ df.append(series, verify_integrity=True)
result = df.append(series[::-1], ignore_index=True)
expected = df.append(DataFrame({0: series[::-1]}, index=df.columns).T,
@@ -6138,10 +6117,13 @@ def test_dropna(self):
expected = df.ix[:, [0, 1, 3]]
assert_frame_equal(dropped, expected)
+ # bad input
+ self.assertRaises(ValueError, df.dropna, axis=3)
+
def test_dropna_corner(self):
# bad input
self.assertRaises(ValueError, self.frame.dropna, how='foo')
- self.assertRaises(ValueError, self.frame.dropna, how=None)
+ self.assertRaises(TypeError, self.frame.dropna, how=None)
def test_dropna_multiple_axes(self):
df = DataFrame([[1, np.nan, 2, 3],
@@ -6440,7 +6422,8 @@ def test_fillna_dict_series(self):
assert_frame_equal(result, expected)
# disable this for now
- self.assertRaises(Exception, df.fillna, df.max(1), axis=1)
+ with assertRaisesRegexp(NotImplementedError, 'column by column'):
+ df.fillna(df.max(1), axis=1)
def test_fillna_columns(self):
df = DataFrame(np.random.randn(10, 10))
@@ -6456,10 +6439,8 @@ def test_fillna_columns(self):
assert_frame_equal(result, expected)
def test_fillna_invalid_method(self):
- try:
+ with assertRaisesRegexp(ValueError, 'ffil'):
self.frame.fillna(method='ffil')
- except ValueError as inst:
- self.assert_('ffil' in str(inst))
def test_fillna_invalid_value(self):
# list
@@ -7322,8 +7303,8 @@ def test_xs(self):
self.assertEqual(xs['A'], 1)
self.assertEqual(xs['B'], '1')
- self.assertRaises(Exception, self.tsframe.xs,
- self.tsframe.index[0] - datetools.bday)
+ with tm.assertRaises(KeyError):
+ self.tsframe.xs(self.tsframe.index[0] - datetools.bday)
# xs get column
series = self.frame.xs('A', axis=1)
@@ -7414,7 +7395,8 @@ def test_pivot_duplicates(self):
data = DataFrame({'a': ['bar', 'bar', 'foo', 'foo', 'foo'],
'b': ['one', 'two', 'one', 'one', 'two'],
'c': [1., 2., 3., 3., 4.]})
- self.assertRaises(Exception, data.pivot, 'a', 'b', 'c')
+ with assertRaisesRegexp(ValueError, 'duplicate entries'):
+ data.pivot('a', 'b', 'c')
def test_pivot_empty(self):
df = DataFrame({}, columns=['a', 'b', 'c'])
@@ -7994,7 +7976,7 @@ def test_rename(self):
self.assert_(np.array_equal(renamed.index, ['BAR', 'FOO']))
# have to pass something
- self.assertRaises(Exception, self.frame.rename)
+ self.assertRaises(TypeError, self.frame.rename)
# partial columns
renamed = self.frame.rename(columns={'C': 'foo', 'D': 'bar'})
@@ -8157,7 +8139,8 @@ def test_shift(self):
assert_frame_equal(shifted2, shifted3)
assert_frame_equal(ps, shifted2.shift(-1, 'B'))
- self.assertRaises(ValueError, ps.shift, freq='D')
+ assertRaisesRegexp(ValueError, 'does not match PeriodIndex freq',
+ ps.shift, freq='D')
def test_shift_bool(self):
df = DataFrame({'high': [True, False],
@@ -8182,7 +8165,7 @@ def test_tshift(self):
shifted3 = ps.tshift(freq=datetools.bday)
assert_frame_equal(shifted, shifted3)
- self.assertRaises(ValueError, ps.tshift, freq='M')
+ assertRaisesRegexp(ValueError, 'does not match', ps.tshift, freq='M')
# DatetimeIndex
shifted = self.tsframe.tshift(1)
@@ -8294,7 +8277,6 @@ def test_apply_ignore_failures(self):
expected = self.mixed_frame._get_numeric_data().apply(np.mean)
assert_series_equal(result, expected)
- # test with hierarchical index
def test_apply_mixed_dtype_corner(self):
df = DataFrame({'A': ['foo'],
@@ -8411,9 +8393,10 @@ def transform2(row):
try:
transformed = data.apply(transform, axis=1)
- except Exception as e:
+ except AttributeError as e:
self.assertEqual(len(e.args), 2)
self.assertEqual(e.args[1], 'occurred at index 4')
+ self.assertEqual(e.args[0], "'float' object has no attribute 'startswith'")
def test_swapaxes(self):
df = DataFrame(np.random.randn(10, 5))
@@ -8530,7 +8513,8 @@ def test_filter(self):
self.assertEqual(len(filtered.columns), 2)
# pass in None
- self.assertRaises(Exception, self.frame.filter, items=None)
+ with assertRaisesRegexp(TypeError, 'Must pass'):
+ self.frame.filter(items=None)
# objects
filtered = self.mixed_frame.filter(like='foo')
@@ -8630,6 +8614,9 @@ def test_sort_index(self):
assert_frame_equal(sorted_df, expected)
self.assertRaises(ValueError, frame.sort_index, axis=2, inplace=True)
+ msg = 'When sorting by column, axis must be 0'
+ with assertRaisesRegexp(ValueError, msg):
+ frame.sort_index(by='A', axis=1)
def test_sort_index_multicolumn(self):
import random
@@ -8735,17 +8722,16 @@ def test_sort_inplace(self):
assert_frame_equal(sorted_df, expected)
def test_sort_index_duplicates(self):
- df = DataFrame([[1, 2], [3, 4]], columns=['a', 'a'])
+ df = DataFrame([lrange(5,9), lrange(4)],
+ columns=['a', 'a', 'b', 'b'])
- try:
+ with assertRaisesRegexp(ValueError, 'duplicate'):
df.sort_index(by='a')
- except Exception as e:
- self.assertTrue('duplicate' in str(e))
-
- try:
+ with assertRaisesRegexp(ValueError, 'duplicate'):
df.sort_index(by=['a'])
- except Exception as e:
- self.assertTrue('duplicate' in str(e))
+ with assertRaisesRegexp(ValueError, 'duplicate'):
+ # multi-column 'by' is separate codepath
+ df.sort_index(by=['a', 'b'])
def test_sort_datetimes(self):
@@ -8771,7 +8757,8 @@ def test_sort_datetimes(self):
def test_frame_column_inplace_sort_exception(self):
s = self.frame['A']
- self.assertRaises(Exception, s.sort)
+ with assertRaisesRegexp(TypeError, "This Series is a view"):
+ s.sort()
cp = s.copy()
cp.sort() # it works!
@@ -8982,9 +8969,8 @@ def test_update_raise(self):
other = DataFrame([[2., nan],
[nan, 7]], index=[1, 3], columns=[1, 2])
-
- np.testing.assert_raises(Exception, df.update, *(other,),
- **{'raise_conflict': True})
+ with assertRaisesRegexp(ValueError, "Data overlaps"):
+ df.update(other, raise_conflict=True)
def test_update_from_non_df(self):
d = {'a': Series([1, 2, 3, 4]), 'b': Series([5, 6, 7, 8])}
@@ -9416,8 +9402,8 @@ def wrapper(x):
# comp = frame.apply(alternative, axis=1).reindex(result.index)
# assert_series_equal(result, comp)
- self.assertRaises(Exception, f, axis=2)
-
+ # bad axis
+ assertRaisesRegexp(ValueError, 'No axis named 2', f, axis=2)
# make sure works on mixed-type frame
getattr(self.mixed_frame, name)(axis=0)
getattr(self.mixed_frame, name)(axis=1)
@@ -9731,18 +9717,6 @@ def test_describe_empty_int_columns(self):
Series([0, 0], dtype=float, name='count'))
self.assert_(isnull(desc.ix[1:]).all().all())
- def test_get_axis_etc(self):
- f = self.frame
-
- self.assertEquals(f._get_axis_number(0), 0)
- self.assertEquals(f._get_axis_number(1), 1)
- self.assertEquals(f._get_axis_name(0), 'index')
- self.assertEquals(f._get_axis_name(1), 'columns')
-
- self.assert_(f._get_axis(0) is f.index)
- self.assert_(f._get_axis(1) is f.columns)
- self.assertRaises(Exception, f._get_axis_number, 2)
-
def test_axis_aliases(self):
f = self.frame
@@ -10391,8 +10365,8 @@ def test_xs_view(self):
self.assert_((dm.xs(2) == 5).all())
# TODO (?): deal with mixed-type fiasco?
- self.assertRaises(Exception, self.mixed_frame.xs,
- self.mixed_frame.index[2], copy=False)
+ with assertRaisesRegexp(TypeError, 'cannot get view of mixed-type'):
+ self.mixed_frame.xs(self.mixed_frame.index[2], copy=False)
# unconsolidated
dm['foo'] = 6.
@@ -10417,6 +10391,8 @@ def test_boolean_indexing(self):
df1[df1 > 2.0 * df2] = -1
assert_frame_equal(df1, expected)
+ with assertRaisesRegexp(ValueError, 'Item wrong length'):
+ df1[df1.index[:-1] > 2] = -1
def test_boolean_indexing_mixed(self):
df = DataFrame(
@@ -10443,7 +10419,8 @@ def test_boolean_indexing_mixed(self):
# add object, should this raise?
df['foo'] = 'test'
- self.assertRaises(ValueError, df.__setitem__, df>0.3, 1)
+ with tm.assertRaisesRegexp(TypeError, 'boolean setting on mixed-type'):
+ df[df > 0.3] = 1
def test_sum_bools(self):
df = DataFrame(index=lrange(1), columns=lrange(10))
@@ -10574,7 +10551,8 @@ def test_dot(self):
exp = a.dot(a.ix[0])
assert_series_equal(result, exp)
- self.assertRaises(Exception, a.dot, row[:-1])
+ with assertRaisesRegexp(ValueError, 'Dot product shape mismatch'):
+ a.dot(row[:-1])
a = np.random.rand(1, 5)
b = np.random.rand(5, 1)
@@ -10588,7 +10566,7 @@ def test_dot(self):
df = DataFrame(randn(3, 4), index=[1, 2, 3], columns=lrange(4))
df2 = DataFrame(randn(5, 3), index=lrange(5), columns=[1, 2, 3])
- self.assertRaises(ValueError, df.dot, df2)
+ assertRaisesRegexp(ValueError, 'aligned', df.dot, df2)
def test_idxmin(self):
frame = self.frame
@@ -10602,7 +10580,7 @@ def test_idxmin(self):
Series.idxmin, axis=axis, skipna=skipna)
assert_series_equal(result, expected)
- self.assertRaises(Exception, frame.idxmin, axis=2)
+ self.assertRaises(ValueError, frame.idxmin, axis=2)
def test_idxmax(self):
frame = self.frame
@@ -10616,7 +10594,7 @@ def test_idxmax(self):
Series.idxmax, axis=axis, skipna=skipna)
assert_series_equal(result, expected)
- self.assertRaises(Exception, frame.idxmax, axis=2)
+ self.assertRaises(ValueError, frame.idxmax, axis=2)
def test_stale_cached_series_bug_473(self):
Y = DataFrame(np.random.random((4, 4)), index=('a', 'b', 'c', 'd'),
@@ -10765,7 +10743,8 @@ def wrapper(x):
# comp = frame.apply(alternative, axis=1).reindex(result.index)
# assert_series_equal(result, comp)
- self.assertRaises(Exception, f, axis=2)
+ # bad axis
+ self.assertRaises(ValueError, f, axis=2)
# make sure works on mixed-type frame
mixed = self.mixed_frame
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index 50d94ada7b9df..21462780e2ffd 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -10,7 +10,8 @@
from pandas.util.testing import (assert_almost_equal,
assert_series_equal,
- assert_frame_equal)
+ assert_frame_equal,
+ assertRaisesRegexp)
import pandas.core.common as com
import pandas.util.testing as tm
from pandas.compat import (range, lrange, StringIO, lzip, u, cPickle,
@@ -270,7 +271,8 @@ def test_frame_getitem_setitem_boolean(self):
np.putmask(values[:-1], values[:-1] < 0, 2)
assert_almost_equal(df.values, values)
- self.assertRaises(Exception, df.__setitem__, df * 0, 2)
+ with assertRaisesRegexp(TypeError, 'boolean values only'):
+ df[df * 0] = 2
def test_frame_getitem_setitem_slice(self):
# getitem
@@ -427,6 +429,9 @@ def test_xs_level(self):
expected = df[1:2]
expected.index = expected.index.droplevel(2)
assert_frame_equal(result, expected)
+ # can't produce a view of a multiindex with a level without copying
+ with assertRaisesRegexp(ValueError, 'Cannot retrieve view'):
+ self.frame.xs('two', level='second', copy=False)
def test_xs_level_multiple(self):
from pandas import read_table
@@ -441,6 +446,8 @@ def test_xs_level_multiple(self):
result = df.xs(('a', 4), level=['one', 'four'])
expected = df.xs('a').xs(4, level='four')
assert_frame_equal(result, expected)
+ with assertRaisesRegexp(ValueError, 'Cannot retrieve view'):
+ df.xs(('a', 4), level=['one', 'four'], copy=False)
# GH2107
dates = lrange(20111201, 20111205)
@@ -620,14 +627,14 @@ def test_getitem_partial_column_select(self):
def test_sortlevel(self):
df = self.frame.copy()
df.index = np.arange(len(df))
- self.assertRaises(Exception, df.sortlevel, 0)
+ assertRaisesRegexp(TypeError, 'hierarchical index', df.sortlevel, 0)
# axis=1
# series
a_sorted = self.frame['A'].sortlevel(0)
- self.assertRaises(Exception,
- self.frame.reset_index()['A'].sortlevel)
+ with assertRaisesRegexp(TypeError, 'hierarchical index'):
+ self.frame.reset_index()['A'].sortlevel()
# preserve names
self.assertEquals(a_sorted.index.names, self.frame.index.names)
@@ -722,7 +729,7 @@ def _check_counts(frame, axis=0):
# can't call with level on regular DataFrame
df = tm.makeTimeDataFrame()
- self.assertRaises(Exception, df.count, level=0)
+ assertRaisesRegexp(TypeError, 'hierarchical', df.count, level=0)
self.frame['D'] = 'foo'
result = self.frame.count(level=0, numeric_only=True)
@@ -1085,8 +1092,11 @@ def test_reorder_levels(self):
expected = self.ymd.T.swaplevel(0, 1, axis=1).swaplevel(1, 2, axis=1)
assert_frame_equal(result, expected)
- self.assertRaises(Exception, self.ymd.index.reorder_levels,
- [1, 2, 3])
+ with assertRaisesRegexp(TypeError, 'hierarchical axis'):
+ self.ymd.reorder_levels([1, 2], axis=1)
+
+ with assertRaisesRegexp(IndexError, 'Too many levels'):
+ self.ymd.index.reorder_levels([1, 2, 3])
def test_insert_index(self):
df = self.ymd[:5].T
@@ -1202,8 +1212,8 @@ def test_count(self):
expect = self.series.count(level=0)
assert_series_equal(result, expect)
- self.assertRaises(Exception, series.count, 'x')
- self.assertRaises(Exception, frame.count, level='x')
+ self.assertRaises(KeyError, series.count, 'x')
+ self.assertRaises(KeyError, frame.count, level='x')
AGG_FUNCTIONS = ['sum', 'prod', 'min', 'max', 'median', 'mean', 'skew',
'mad', 'std', 'var']
@@ -1420,6 +1430,7 @@ def test_partial_ix_missing(self):
# self.ymd.ix[2000, 0] = 0
# self.assert_((self.ymd.ix[2000]['A'] == 0).all())
+ # Pretty sure the second (and maybe even the first) is already wrong.
self.assertRaises(Exception, self.ymd.ix.__getitem__, (2000, 6))
self.assertRaises(Exception, self.ymd.ix.__getitem__, (2000, 6), 0)
@@ -1774,14 +1785,6 @@ def test_indexing_over_hashtable_size_cutoff(self):
_index._SIZE_CUTOFF = old_cutoff
- def test_xs_mixed_no_copy(self):
- index = MultiIndex.from_arrays([['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
- names=['first', 'second'])
- data = DataFrame(np.random.rand(len(index)), index=index,
- columns=['A'])
-
- self.assertRaises(Exception, data.xs, 2, level=1, copy=False)
-
def test_multiindex_na_repr(self):
# only an issue with long columns
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 8ad88374f40f6..938025c450258 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1276,7 +1276,7 @@ def test_to_panel_duplicates(self):
# #2441
df = DataFrame({'a': [0, 0, 1], 'b': [1, 1, 1], 'c': [1, 2, 3]})
idf = df.set_index(['a', 'b'])
- self.assertRaises(Exception, idf.to_panel)
+ assertRaisesRegexp(ValueError, 'non-uniquely indexed', idf.to_panel)
def test_filter(self):
pass
diff --git a/pandas/tests/test_tests.py b/pandas/tests/test_tests.py
index b52ab61f7be6b..1890c2607fc89 100644
--- a/pandas/tests/test_tests.py
+++ b/pandas/tests/test_tests.py
@@ -4,23 +4,32 @@
import unittest
import warnings
import nose
+import sys
-from pandas.util.testing import assert_almost_equal
+from pandas.util.testing import (
+ assert_almost_equal, assertRaisesRegexp, raise_with_traceback
+)
# let's get meta.
class TestUtilTesting(unittest.TestCase):
_multiprocess_can_split_ = True
- def __init__(self, *args):
- super(TestUtilTesting, self).__init__(*args)
-
- def setUp(self):
- pass
-
- def tearDown(self):
- pass
-
def test_assert_almost_equal(self):
# don't die because values are not ndarrays
assert_almost_equal(1.1,1.1,check_less_precise=True)
+
+ def test_raise_with_traceback(self):
+ with assertRaisesRegexp(LookupError, "error_text"):
+ try:
+ raise ValueError("THIS IS AN ERROR")
+ except ValueError as e:
+ e = LookupError("error_text")
+ raise_with_traceback(e)
+ with assertRaisesRegexp(LookupError, "error_text"):
+ try:
+ raise ValueError("This is another error")
+ except ValueError:
+ e = LookupError("error_text")
+ _, _, traceback = sys.exc_info()
+ raise_with_traceback(e, traceback)
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index b28da7c9d7e0b..45894eb419489 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -121,6 +121,7 @@ def __init__(self, value=None, freq=None, ordinal=None,
base, mult = _gfc(freq)
if mult != 1:
+ # TODO: Better error message - this is slightly confusing
raise ValueError('Only mult == 1 supported')
if self.ordinal is None:
diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py
index b7916bd98d70f..b95ea2cacda55 100644
--- a/pandas/tseries/tests/test_period.py
+++ b/pandas/tseries/tests/test_period.py
@@ -26,7 +26,8 @@
randn = np.random.randn
from pandas import Series, TimeSeries, DataFrame
-from pandas.util.testing import assert_series_equal, assert_almost_equal
+from pandas.util.testing import(assert_series_equal, assert_almost_equal,
+ assertRaisesRegexp)
import pandas.util.testing as tm
from pandas import compat
from numpy.testing import assert_array_equal
@@ -272,7 +273,7 @@ def _ex(p):
result = p.to_timestamp('S', how='start')
self.assertEquals(result, expected)
- self.assertRaises(ValueError, p.to_timestamp, '5t')
+ assertRaisesRegexp(ValueError, 'Only mult == 1', p.to_timestamp, '5t')
def test_start_time(self):
freq_lst = ['A', 'Q', 'M', 'D', 'H', 'T', 'S']
@@ -1427,7 +1428,8 @@ def _get_with_delta(delta, freq='A-DEC'):
self.assert_(result.columns.equals(exp_index))
# invalid axis
- self.assertRaises(ValueError, df.to_timestamp, axis=2)
+ assertRaisesRegexp(ValueError, 'axis', df.to_timestamp, axis=2)
+ assertRaisesRegexp(ValueError, 'Only mult == 1', df.to_timestamp, '5t', axis=1)
def test_index_duplicate_periods(self):
# monotonic
@@ -1886,9 +1888,8 @@ def test_align_series(self):
# it works!
for kind in ['inner', 'outer', 'left', 'right']:
ts.align(ts[::2], join=kind)
-
- self.assertRaises(Exception, ts.__add__,
- ts.asfreq('D', how='end'))
+ with assertRaisesRegexp(ValueError, 'Only like-indexed'):
+ ts + ts.asfreq('D', how="end")
def test_align_frame(self):
rng = period_range('1/1/2000', '1/1/2010', freq='A')
@@ -1915,7 +1916,7 @@ def test_union(self):
# raise if different frequencies
index = period_range('1/1/2000', '1/20/2000', freq='D')
index2 = period_range('1/1/2000', '1/20/2000', freq='W-WED')
- self.assertRaises(Exception, index.union, index2)
+ self.assertRaises(ValueError, index.union, index2)
self.assertRaises(ValueError, index.join, index.to_timestamp())
@@ -1934,7 +1935,7 @@ def test_intersection(self):
# raise if different frequencies
index = period_range('1/1/2000', '1/20/2000', freq='D')
index2 = period_range('1/1/2000', '1/20/2000', freq='W-WED')
- self.assertRaises(Exception, index.intersection, index2)
+ self.assertRaises(ValueError, index.intersection, index2)
def test_fields(self):
# year, month, day, hour, minute
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 8af88895a8b73..c652c2da3214c 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -26,7 +26,8 @@
import pandas.core.panel4d as panel4d
import pandas.compat as compat
from pandas.compat import(
- map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter
+ map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter,
+ raise_with_traceback
)
from pandas import bdate_range
@@ -1031,7 +1032,7 @@ def assertRaises(_exception, _callable=None, *args, **kwargs):
>>> assertRaises(TypeError, ",".join, [1, 3, 5]);
"""
manager = _AssertRaisesContextmanager(exception=_exception)
- # don't return anything if usedin function form
+ # don't return anything if used in function form
if _callable is not None:
with manager:
_callable(*args, **kwargs)
@@ -1111,8 +1112,9 @@ def handle_success(self, exc_type, exc_value, traceback):
if self.regexp is not None:
val = str(exc_value)
if not self.regexp.search(val):
- raise AssertionError('"%s" does not match "%s"' %
- (self.regexp.pattern, str(val)))
+ e = AssertionError('"%s" does not match "%s"' %
+ (self.regexp.pattern, str(val)))
+ raise_with_traceback(e, traceback)
return True
| More specific Exceptions (and better testing for them) through a number of parts of pandas. In particular, in `core/frame` / tests/test_frame and tests/test_multilevel Associated changes in some other parts of pandas to support it (mostly making sparse have the same exceptions as core/frame).
- nearly everything that was a `TypeError` now checks message (to avoid `TypeError` confusion from changes in signature).
- refactored some test methods and changed some places to use `assertRaises` and `assertRaisesRegexp` as context managers.
- core/reshape no longer uses a specific `ReshapeError` (which wasn't really being used anywhere)
- marked guard test cases with `# pragma: no cover` to hopefully make it easier to use coverage.
- new `raise_with_traceback` method in `compat` which allows for 2/3 compatible preservation of traceback.
Obviously some squashing to come.
Related to #3954.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4732 | 2013-09-02T01:17:54Z | 2013-09-06T02:01:08Z | 2013-09-06T02:01:08Z | 2014-06-16T19:56:48Z |
BUG: (GH4726) bug in getting a cross-sectional using iloc/loc with a duplicate items index | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 592d6804a04ee..b3500b4f98b37 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -307,8 +307,10 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs (:issue:`4576`)
- Fix error/dtype conversion with setitem of ``None`` on ``Series/DataFrame`` (:issue:`4667`)
- Fix decoding based on a passed in non-default encoding in ``pd.read_stata`` (:issue:`4626`)
- - Fix some inconsistencies with ``Index.rename`` and ``MultiIndex.rename`` (:issue:`4718`, :issue:`4628`)
- Fix ``DataFrame.from_records`` with a plain-vanilla ``ndarray``. (:issue:`4727`)
+ - Fix some inconsistencies with ``Index.rename`` and ``MultiIndex.rename``,
+ etc. (:issue:`4718`, :issue:`4628`)
+ - Bug in using ``iloc/loc`` with a cross-sectional and duplicate indicies (:issue:`4726`)
pandas 0.12
===========
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 4344b2542ffd6..c6af7e27070a9 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -72,9 +72,6 @@ def __init__(self, values, items, ref_items, ndim=None, fastpath=False, placemen
self.items = _ensure_index(items)
self.ref_items = _ensure_index(ref_items)
- def _gi(self, arg):
- return self.values[arg]
-
@property
def _consolidate_key(self):
return (self._can_consolidate, self.dtype.name)
@@ -1165,9 +1162,6 @@ def __init__(self, values, items, ref_items, fastpath=False, placement=None, **k
super(DatetimeBlock, self).__init__(values, items, ref_items,
fastpath=True, placement=placement, **kwargs)
- def _gi(self, arg):
- return lib.Timestamp(self.values[arg])
-
def _can_hold_element(self, element):
if is_list_like(element):
element = np.array(element)
@@ -1200,7 +1194,7 @@ def _try_coerce_result(self, result):
if result.dtype == 'i8':
result = tslib.array_to_datetime(
result.astype(object).ravel()).reshape(result.shape)
- elif isinstance(result, np.integer):
+ elif isinstance(result, (np.integer, np.datetime64)):
result = lib.Timestamp(result)
return result
@@ -1267,10 +1261,9 @@ def set(self, item, value):
self.values[loc] = value
def get_values(self, dtype=None):
+ # return object dtype as Timestamps
if dtype == object:
- flat_i8 = self.values.ravel().view(np.int64)
- res = tslib.ints_to_pydatetime(flat_i8)
- return res.reshape(self.values.shape)
+ return lib.map_infer(self.values.ravel(), lib.Timestamp).reshape(self.values.shape)
return self.values
@@ -2272,7 +2265,8 @@ def xs(self, key, axis=1, copy=True):
def fast_2d_xs(self, loc, copy=False):
"""
-
+ get a cross sectional for a given location in the
+ items ; handle dups
"""
if len(self.blocks) == 1:
result = self.blocks[0].values[:, loc]
@@ -2284,15 +2278,20 @@ def fast_2d_xs(self, loc, copy=False):
raise Exception('cannot get view of mixed-type or '
'non-consolidated DataFrame')
- dtype = _interleaved_dtype(self.blocks)
-
items = self.items
+
+ # non-unique (GH4726)
+ if not items.is_unique:
+ return self._interleave(items).ravel()
+
+ # unique
+ dtype = _interleaved_dtype(self.blocks)
n = len(items)
result = np.empty(n, dtype=dtype)
for blk in self.blocks:
for j, item in enumerate(blk.items):
i = items.get_loc(item)
- result[i] = blk._gi((j, loc))
+ result[i] = blk._try_coerce_result(blk.iget((j, loc)))
return result
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 76003de65180f..da4e1e98e6b7a 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1215,6 +1215,20 @@ def test_astype_assignment_with_iloc(self):
result = df.get_dtype_counts().sort_index()
expected = Series({ 'int64' : 4, 'float64' : 1, 'object' : 2 }).sort_index()
+ def test_dups_loc(self):
+
+ # GH4726
+ # dup indexing with iloc/loc
+ df = DataFrame([[1,2,'foo','bar',Timestamp('20130101')]],
+ columns=['a','a','a','a','a'],index=[1])
+ expected = Series([1,2,'foo','bar',Timestamp('20130101')],index=['a','a','a','a','a'])
+
+ result = df.iloc[0]
+ assert_series_equal(result,expected)
+
+ result = df.loc[1]
+ assert_series_equal(result,expected)
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| closes #4726
| https://api.github.com/repos/pandas-dev/pandas/pulls/4729 | 2013-09-01T21:38:12Z | 2013-09-02T13:07:12Z | 2013-09-02T13:07:12Z | 2014-07-15T01:06:57Z |
BUG: Fix DataFrame.from_records w/ normal ndarray. | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 6530b7e5e9238..abbee59941c8c 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -306,8 +306,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs (:issue:`4576`)
- Fix error/dtype conversion with setitem of ``None`` on ``Series/DataFrame`` (:issue:`4667`)
- Fix decoding based on a passed in non-default encoding in ``pd.read_stata`` (:issue:`4626`)
- - Fix some inconsistencies with ``Index.rename`` and ``MultiIndex.rename``,
- etc. (:issue:`4718`, :issue:`4628`)
+ - Fix some inconsistencies with ``Index.rename`` and ``MultiIndex.rename`` (:issue:`4718`, :issue:`4628`)
+ - Fix ``DataFrame.from_records`` with a plain-vanilla ``ndarray``. (:issue:`4727`)
pandas 0.12
===========
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5d8cc0b9d8de0..4e9f28122b43d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4876,7 +4876,9 @@ def _to_arrays(data, columns, coerce_float=False, dtype=None):
return _list_of_series_to_arrays(data, columns,
coerce_float=coerce_float,
dtype=dtype)
- elif isinstance(data, (np.ndarray, Series)):
+ elif (isinstance(data, (np.ndarray, Series))
+ and data.dtype.names is not None):
+
columns = list(data.dtype.names)
arrays = [data[k] for k in columns]
return arrays, columns
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 41b705d22b85d..b992b2d60a08d 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3468,12 +3468,15 @@ def test_from_records_to_records(self):
indexed_frame = DataFrame.from_records(arr, index=index)
self.assert_(np.array_equal(indexed_frame.index, index))
+ # without names, it should go to last ditch
+ arr2 = np.zeros((2,3))
+ tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))
+
# wrong length
self.assertRaises(Exception, DataFrame.from_records, arr,
index=index[:-1])
indexed_frame = DataFrame.from_records(arr, index='f1')
- self.assertRaises(Exception, DataFrame.from_records, np.zeros((2, 3)))
# what to do?
records = indexed_frame.to_records()
| I haven't looked at the `from_records` code before, which is why I'm spending all this time laying out a relatively minor change. Previously, was causing a TypeError about None not being iterable when arr.dtype.names was None. Now goes to 'last ditch' parsing instead.
This was the original test case (that dates back, in one form or another, to at least 2010), looked like this:
``` python
self.assertRaises(Exception, DataFrame.from_records, np.zeros((2, 3)))
```
Problem is that the actual Exception was a `TypeError: None is not iterable`-style exception, not something internal to the code. I changed this so now an `ndarray` that isn't structured (i.e., has `arr.dtype.names is None`) is treated separately from the structured ndarrays (so it goes into the general case 'last ditch' verison).
Now it basically produces the same thing as passing the array to the DataFrame constructor:
``` python
arr2 = np.zeros((2,3))
tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4727 | 2013-09-01T19:29:21Z | 2013-09-01T21:05:27Z | 2013-09-01T21:05:27Z | 2014-06-22T21:30:43Z |
DOC: small clarification in DataFrame docstring | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c7ff4c052638d..5d8cc0b9d8de0 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -351,7 +351,8 @@ class DataFrame(NDFrame):
Index to use for resulting frame. Will default to np.arange(n) if
no indexing information part of input data and no index provided
columns : Index or array-like
- Will default to np.arange(n) if not column labels provided
+ Column labels to use for resulting frame. Will default to
+ np.arange(n) if no column labels are provided
dtype : dtype, default None
Data type to force, otherwise infer
copy : boolean, default False
| Two small things:
- add that it is actually for the column labels
- fixes small typo (not -> no)
| https://api.github.com/repos/pandas-dev/pandas/pulls/4723 | 2013-09-01T09:00:17Z | 2013-09-01T12:54:23Z | 2013-09-01T12:54:23Z | 2014-07-16T08:25:56Z |
PERF: faster plotting of timeseries with PeriodIndex | diff --git a/doc/source/release.rst b/doc/source/release.rst
index e12e6c91d46d0..3df6bc167386c 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -47,7 +47,7 @@ pandas 0.13
- ``get_dummies`` works with NaN (:issue:`4446`)
- Added a test for ``read_clipboard()`` and ``to_clipboard()`` (:issue:`4282`)
- Added bins argument to ``value_counts`` (:issue:`3945`), also sort and
- ascending, now available in Series method as well as top-level function.
+ ascending, now available in Series method as well as top-level function.
- Text parser now treats anything that reads like inf ("inf", "Inf", "-Inf",
"iNf", etc.) to infinity. (:issue:`4220`, :issue:`4219`), affecting
``read_table``, ``read_csv``, etc.
@@ -74,6 +74,8 @@ pandas 0.13
- Better/cleaned up exceptions in core/common, io/excel and core/format
(:issue:`4721`, :issue:`3954`), as well as cleaned up test cases in
tests/test_frame, tests/test_multilevel (:issue:`4732`).
+ - Performance improvement of timesesies plotting with PeriodIndex and added
+ test to vbench (:issue:`4705` and :issue:`4722`)
**API Changes**
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 9d570d8bcbadf..1583a3c0b52d9 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -60,6 +60,7 @@ def test_plot(self):
_check_plot_works(self.ts.plot, style='.', logx=True)
_check_plot_works(self.ts.plot, style='.', loglog=True)
_check_plot_works(self.ts[:10].plot, kind='bar')
+ _check_plot_works(self.iseries.plot)
_check_plot_works(self.series[:5].plot, kind='bar')
_check_plot_works(self.series[:5].plot, kind='line')
_check_plot_works(self.series[:5].plot, kind='barh')
diff --git a/pandas/tseries/converter.py b/pandas/tseries/converter.py
index 54c2a4a2a3056..7c34562e64f6e 100644
--- a/pandas/tseries/converter.py
+++ b/pandas/tseries/converter.py
@@ -111,6 +111,8 @@ def convert(values, units, axis):
if (isinstance(values, valid_types) or com.is_integer(values) or
com.is_float(values)):
return get_datevalue(values, axis.freq)
+ if isinstance(values, PeriodIndex):
+ return values.asfreq(axis.freq).values
if isinstance(values, Index):
return values.map(lambda x: get_datevalue(x, axis.freq))
if isinstance(values, (list, tuple, np.ndarray)):
diff --git a/vb_suite/plotting.py b/vb_suite/plotting.py
new file mode 100644
index 0000000000000..735ed78c1441e
--- /dev/null
+++ b/vb_suite/plotting.py
@@ -0,0 +1,25 @@
+from vbench.benchmark import Benchmark
+from datetime import datetime
+
+common_setup = """from pandas_vb_common import *
+
+try:
+ from pandas import date_range
+except ImportError:
+ def date_range(start=None, end=None, periods=None, freq=None):
+ return DateRange(start, end, periods=periods, offset=freq)
+
+"""
+
+#-----------------------------------------------------------------------------
+# Timeseries plotting
+
+setup = common_setup + """
+N = 2000
+M = 5
+df = DataFrame(np.random.randn(N,M), index=date_range('1/1/1975', periods=N))
+"""
+
+plot_timeseries_period = Benchmark("df.plot()", setup=setup,
+ name='plot_timeseries_period')
+
diff --git a/vb_suite/suite.py b/vb_suite/suite.py
index 905c4371837cc..ca83855c2a109 100644
--- a/vb_suite/suite.py
+++ b/vb_suite/suite.py
@@ -17,6 +17,7 @@
'miscellaneous',
'panel_ctor',
'parser',
+ 'plotting',
'reindex',
'replace',
'sparse',
| See discussion in #4705.
This improves the speed of plotting timeseries with PeriodIndex (or with DatetimeIndex that is converted to a PeriodIndex during plotting) drastically: from 30 s in 0.12 (but 7 s in 0.11) to 0.2 s with this commit for the plotting of following data:
``` python
N = 10000
M = 25
df = pd.DataFrame(np.random.randn(N,M), index=pd.date_range('1/1/1975', periods=N))
df.plot()
```
Some questions I still have:
- I added a check for `PeriodIndex`, but I left the original `if isinstance(values, Index)` in place. Is this needed? Is it possible that another index than PeriodIndex ends up in PeriodConverter?
- @jreback You asked in the issue to do some tests (to at least ensure that their is a valid plot). Do you just mean by plotting it and looking if it seems OK? This seems OK. Or can you do some tests for plotting in the testing infrastructure?
- Would it be interesting to add a performance test for this case? Because it was a big decrease in speed with 0.12 which was not detected.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4722 | 2013-09-01T08:47:05Z | 2013-09-07T21:27:23Z | 2013-09-07T21:27:23Z | 2014-06-20T14:26:19Z |
CLN: Improve Exceptions in core/common, io/excel and core/format | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 592d6804a04ee..57fbbf631fec4 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -71,6 +71,8 @@ pandas 0.13
when the key is a column
- Support for using a ``DatetimeIndex/PeriodsIndex`` directly in a datelike calculation
e.g. s-s.index (:issue:`4629`)
+ - Better/cleaned up exceptions in core/common, io/excel and core/format.
+ (:issue:`4721`, :issue:`3954`)
**API Changes**
diff --git a/pandas/core/common.py b/pandas/core/common.py
index a995881d5c1e9..6fc006eae74fe 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -541,7 +541,7 @@ def take_nd(arr, indexer, axis=0, out=None, fill_value=np.nan,
mask_info = mask, needs_masking
if needs_masking:
if out is not None and out.dtype != dtype:
- raise Exception('Incompatible type for fill_value')
+ raise TypeError('Incompatible type for fill_value')
else:
# if not, then depromote, set fill_value to dummy
# (it won't be used but we don't want the cython code
@@ -612,7 +612,7 @@ def take_2d_multi(arr, indexer, out=None, fill_value=np.nan,
mask_info = (row_mask, col_mask), (row_needs, col_needs)
if row_needs or col_needs:
if out is not None and out.dtype != dtype:
- raise Exception('Incompatible type for fill_value')
+ raise TypeError('Incompatible type for fill_value')
else:
# if not, then depromote, set fill_value to dummy
# (it won't be used but we don't want the cython code
@@ -857,8 +857,8 @@ def changeit():
# if we are trying to do something unsafe
# like put a bigger dtype in a smaller one, use the smaller one
- if change.dtype.itemsize < r.dtype.itemsize:
- raise Exception(
+ if change.dtype.itemsize < r.dtype.itemsize: # pragma: no cover
+ raise AssertionError(
"cannot change dtype of input to smaller size")
change.dtype = r.dtype
change[:] = r
@@ -1159,8 +1159,8 @@ def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None):
# reshape a 1 dim if needed
ndim = values.ndim
if values.ndim == 1:
- if axis != 0:
- raise Exception("cannot interpolate on a ndim == 1 with axis != 0")
+ if axis != 0: # pragma: no cover
+ raise AssertionError("cannot interpolate on a ndim == 1 with axis != 0")
values = values.reshape(tuple((1,) + values.shape))
if fill_value is None:
@@ -1434,13 +1434,17 @@ def ensure_float(arr):
return arr
-def _mut_exclusive(arg1, arg2):
- if arg1 is not None and arg2 is not None:
- raise Exception('mutually exclusive arguments')
- elif arg1 is not None:
- return arg1
+def _mut_exclusive(**kwargs):
+ item1, item2 = kwargs.items()
+ label1, val1 = item1
+ label2, val2 = item2
+ if val1 is not None and val2 is not None:
+ raise TypeError('mutually exclusive arguments: %r and %r' %
+ (label1, label2))
+ elif val1 is not None:
+ return val1
else:
- return arg2
+ return val2
def _any_none(*args):
diff --git a/pandas/core/format.py b/pandas/core/format.py
index e84916009bbe1..8077254de47ff 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -1,13 +1,13 @@
from __future__ import print_function
# pylint: disable=W0141
-from pandas import compat
import sys
-from pandas.compat import StringIO, lzip, range, map, zip, reduce, u, OrderedDict
from pandas.core.common import adjoin, isnull, notnull
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas import compat
+from pandas.compat import(StringIO, lzip, range, map, zip, reduce, u,
+ OrderedDict)
from pandas.util.terminal import get_terminal_size
from pandas.core.config import get_option, set_option, reset_option
import pandas.core.common as com
@@ -356,7 +356,7 @@ def get_col_type(dtype):
column_format = 'l%s' % ''.join(map(get_col_type, dtypes))
else:
column_format = '%s' % ''.join(map(get_col_type, dtypes))
- elif not isinstance(column_format, compat.string_types):
+ elif not isinstance(column_format, compat.string_types): # pragma: no cover
raise AssertionError(('column_format must be str or unicode, not %s'
% type(column_format)))
@@ -820,8 +820,9 @@ def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None,
# validate mi options
if self.has_mi_columns:
- if cols is not None:
- raise Exception("cannot specify cols with a multi_index on the columns")
+ # guarded against in to_csv itself
+ if cols is not None: # pragma: no cover
+ raise AssertionError("cannot specify cols with a multi_index on the columns")
if cols is not None:
if isinstance(cols,Index):
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 4f998b49260e6..5ff42c5cd12a6 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -73,7 +73,7 @@ def __init__(self, path_or_buf, **kwds):
import xlrd # throw an ImportError if we need to
ver = tuple(map(int, xlrd.__VERSION__.split(".")[:2]))
- if ver < (0, 9):
+ if ver < (0, 9): # pragma: no cover
raise ImportError("pandas requires xlrd >= 0.9.0 for excel "
"support, current version " + xlrd.__VERSION__)
@@ -382,8 +382,8 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
if sheet_name is None:
sheet_name = self.cur_sheet
if sheet_name is None: # pragma: no cover
- raise Exception('Must pass explicit sheet_name or set '
- 'cur_sheet property')
+ raise ValueError('Must pass explicit sheet_name or set '
+ 'cur_sheet property')
if self.use_xlsx:
self._writecells_xlsx(cells, sheet_name, startrow, startcol)
else:
diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py
index ab946090c8ea8..261443a95b111 100644
--- a/pandas/sparse/panel.py
+++ b/pandas/sparse/panel.py
@@ -319,8 +319,8 @@ def reindex(self, major=None, items=None, minor=None, major_axis=None,
-------
reindexed : SparsePanel
"""
- major = com._mut_exclusive(major, major_axis)
- minor = com._mut_exclusive(minor, minor_axis)
+ major = com._mut_exclusive(major=major, major_axis=major_axis)
+ minor = com._mut_exclusive(minor=minor, minor_axis=minor_axis)
if com._all_none(items, major, minor):
raise ValueError('Must specify at least one axis')
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 799cdd31c0a65..e2051eba7f42a 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -20,6 +20,14 @@
_multiprocess_can_split_ = True
+def test_mut_exclusive():
+ msg = "mutually exclusive arguments: '[ab]' and '[ab]'"
+ with tm.assertRaisesRegexp(TypeError, msg):
+ com._mut_exclusive(a=1, b=2)
+ assert com._mut_exclusive(a=1, b=None) == 1
+ assert com._mut_exclusive(major=None, major_axis=None) is None
+
+
def test_is_sequence():
is_seq = com._is_sequence
assert(is_seq((1, 2)))
@@ -360,6 +368,8 @@ def test_is_recompilable():
class TestTake(unittest.TestCase):
+ # standard incompatible fill error
+ fill_error = re.compile("Incompatible type for fill_value")
_multiprocess_can_split_ = True
@@ -381,8 +391,8 @@ def _test_dtype(dtype, can_hold_na):
expected[3] = np.nan
tm.assert_almost_equal(out, expected)
else:
- self.assertRaises(Exception, com.take_1d, data,
- indexer, out=out)
+ with tm.assertRaisesRegexp(TypeError, self.fill_error):
+ com.take_1d(data, indexer, out=out)
# no exception o/w
data.take(indexer, out=out)
@@ -466,13 +476,11 @@ def _test_dtype(dtype, can_hold_na):
tm.assert_almost_equal(out0, expected0)
tm.assert_almost_equal(out1, expected1)
else:
- self.assertRaises(Exception, com.take_nd, data,
- indexer, out=out0, axis=0)
- self.assertRaises(Exception, com.take_nd, data,
- indexer, out=out1, axis=1)
- # no exception o/w
- data.take(indexer, out=out0, axis=0)
- data.take(indexer, out=out1, axis=1)
+ for i, out in enumerate([out0, out1]):
+ with tm.assertRaisesRegexp(TypeError, self.fill_error):
+ com.take_nd(data, indexer, out=out, axis=i)
+ # no exception o/w
+ data.take(indexer, out=out, axis=i)
_test_dtype(np.float64, True)
_test_dtype(np.float32, True)
@@ -572,16 +580,11 @@ def _test_dtype(dtype, can_hold_na):
tm.assert_almost_equal(out1, expected1)
tm.assert_almost_equal(out2, expected2)
else:
- self.assertRaises(Exception, com.take_nd, data,
- indexer, out=out0, axis=0)
- self.assertRaises(Exception, com.take_nd, data,
- indexer, out=out1, axis=1)
- self.assertRaises(Exception, com.take_nd, data,
- indexer, out=out2, axis=2)
- # no exception o/w
- data.take(indexer, out=out0, axis=0)
- data.take(indexer, out=out1, axis=1)
- data.take(indexer, out=out2, axis=2)
+ for i, out in enumerate([out0, out1, out2]):
+ with tm.assertRaisesRegexp(TypeError, self.fill_error):
+ com.take_nd(data, indexer, out=out, axis=i)
+ # no exception o/w
+ data.take(indexer, out=out, axis=i)
_test_dtype(np.float64, True)
_test_dtype(np.float32, True)
| Related to #3954.
Cleanups to Exceptions in core/common, io/excel, core/format. A few places I added `# pragma: no cover`, because it looked like the code was generally unreachable. A few cleanups in tests/test_common and better error message in `_mut_exclusive` (which needs to be used in Panel.reindex later on).
Specific places to look at (you can also grep for `# pragma: no cover` in the diff):
- core/common - lines 860 and 1162
- core/format - lines 359 and 823
- io/excel - lines 73, 382
| https://api.github.com/repos/pandas-dev/pandas/pulls/4721 | 2013-09-01T02:13:11Z | 2013-09-02T02:11:31Z | 2013-09-02T02:11:31Z | 2014-06-25T23:05:47Z |
DOC: Updates to CONTRIBUTING.md | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 32b0c27fc8691..ac972b47e7b60 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -32,8 +32,8 @@ your contribution or address the issue you're having.
- **Make sure the test suite passes**., and that means on python3 as well.
You can use "test_fast.sh", or tox locally and/or enable Travis-CI on your fork.
See the "Getting Travis-CI going" below.
- - We suggest you enable Travis-CI on your fork, to make it easier for the team
- to see that the PR does indeed pass all the tests.
+ - If you are changing any code, you need to enable Travis-CI on your fork,
+ to make it easier for the team to see that the PR does indeed pass all the tests.
- Back-compatibility **really** matters. Pandas already has a large user-base and
a lot of existing user code. Don't break old code if you can avoid it
Explain the need if there is one in the PR.
@@ -69,7 +69,8 @@ your contribution or address the issue you're having.
with self.assertRaises(ValueError):
foo
- which fails on python 2.6, use `self.assertRaises(TheException,func,args)` instead.
+ which fails on python 2.6. You need to use `assertRaises` from
+ `pandas.util.testing` instead (or use `self.assertRaises(TheException,func,args)`).
- doc/source/release.rst and doc/source/vx.y.z.txt contain an on-going
changelog for each release as it is worked on. Add entries to these files
| Some updates that are probably necessary - figured I'd put this in a PR first then merge in a bit.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4719 | 2013-08-31T23:28:43Z | 2013-09-01T18:45:34Z | 2013-09-01T18:45:34Z | 2014-07-16T08:25:51Z |
ENH: Better rename/set_names handling for Index | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 570300b7c79de..6530b7e5e9238 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -306,6 +306,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs (:issue:`4576`)
- Fix error/dtype conversion with setitem of ``None`` on ``Series/DataFrame`` (:issue:`4667`)
- Fix decoding based on a passed in non-default encoding in ``pd.read_stata`` (:issue:`4626`)
+ - Fix some inconsistencies with ``Index.rename`` and ``MultiIndex.rename``,
+ etc. (:issue:`4718`, :issue:`4628`)
pandas 0.12
===========
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 04f48f85fa023..a57af06f24cc9 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -114,7 +114,7 @@ def __hash__(self):
def _disabled(self, *args, **kwargs):
"""This method will not function because object is immutable."""
raise TypeError("'%s' does not support mutable operations." %
- self.__class__)
+ self.__class__.__name__)
def __unicode__(self):
from pandas.core.common import pprint_thing
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 0d3bd1a0c6de2..a995881d5c1e9 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1783,7 +1783,7 @@ def is_re_compilable(obj):
def is_list_like(arg):
- return hasattr(arg, '__iter__') and not isinstance(arg, compat.string_types)
+ return hasattr(arg, '__iter__') and not isinstance(arg, compat.string_and_binary_types)
def _is_sequence(x):
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 05eb53a444294..91e4d51c6c0ad 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -273,16 +273,33 @@ def set_names(self, names, inplace=False):
Returns
-------
- new index (of same type and class...etc)
+ new index (of same type and class...etc) [if inplace, returns None]
"""
+ if not com.is_list_like(names):
+ raise TypeError("Must pass list-like as `names`.")
if inplace:
idx = self
else:
idx = self._shallow_copy()
idx._set_names(names)
- return idx
+ if not inplace:
+ return idx
def rename(self, name, inplace=False):
+ """
+ Set new names on index. Defaults to returning new index.
+
+ Parameters
+ ----------
+ name : str or list
+ name to set
+ inplace : bool
+ if True, mutates in place
+
+ Returns
+ -------
+ new index (of same type and class...etc) [if inplace, returns None]
+ """
return self.set_names([name], inplace=inplace)
@property
@@ -1556,6 +1573,7 @@ class MultiIndex(Index):
_levels = FrozenList()
_labels = FrozenList()
_comparables = ['names']
+ rename = Index.set_names
def __new__(cls, levels=None, labels=None, sortorder=None, names=None,
copy=False):
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 16f3026896d4f..410d310e002b2 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -4,6 +4,7 @@
from pandas.compat import range, lrange, lzip, u, zip
import operator
import pickle
+import re
import unittest
import nose
import os
@@ -44,10 +45,35 @@ def test_wrong_number_names(self):
def testit(ind):
ind.names = ["apple", "banana", "carrot"]
- indices = (self.dateIndex, self.unicodeIndex, self.strIndex, self.intIndex, self.floatIndex, self.empty, self.tuples)
+ indices = (self.dateIndex, self.unicodeIndex, self.strIndex,
+ self.intIndex, self.floatIndex, self.empty, self.tuples)
for ind in indices:
assertRaisesRegexp(ValueError, "^Length", testit, ind)
+ def test_set_name_methods(self):
+ new_name = "This is the new name for this index"
+ indices = (self.dateIndex, self.intIndex, self.unicodeIndex,
+ self.empty)
+ for ind in indices:
+ original_name = ind.name
+ new_ind = ind.set_names([new_name])
+ self.assertEqual(new_ind.name, new_name)
+ self.assertEqual(ind.name, original_name)
+ res = ind.rename(new_name, inplace=True)
+ # should return None
+ self.assert_(res is None)
+ self.assertEqual(ind.name, new_name)
+ self.assertEqual(ind.names, [new_name])
+ with assertRaisesRegexp(TypeError, "list-like"):
+ # should still fail even if it would be the right length
+ ind.set_names("a")
+ # rename in place just leaves tuples and other containers alone
+ name = ('A', 'B')
+ ind = self.intIndex
+ ind.rename(name, inplace=True)
+ self.assertEqual(ind.name, name)
+ self.assertEqual(ind.names, [name])
+
def test_hash_error(self):
self.assertRaises(TypeError, hash, self.strIndex)
@@ -1018,6 +1044,48 @@ def setUp(self):
labels=[major_labels, minor_labels],
names=self.index_names)
+ def test_set_names_and_rename(self):
+ # so long as these are synonyms, we don't need to test set_names
+ self.assert_(self.index.rename == self.index.set_names)
+ new_names = [name + "SUFFIX" for name in self.index_names]
+ ind = self.index.set_names(new_names)
+ self.assertEqual(self.index.names, self.index_names)
+ self.assertEqual(ind.names, new_names)
+ with assertRaisesRegexp(ValueError, "^Length"):
+ ind.set_names(new_names + new_names)
+ new_names2 = [name + "SUFFIX2" for name in new_names]
+ res = ind.set_names(new_names2, inplace=True)
+ self.assert_(res is None)
+ self.assertEqual(ind.names, new_names2)
+
+ def test_set_levels_and_set_labels(self):
+ # side note - you probably wouldn't want to use levels and labels
+ # directly like this - but it is possible.
+ levels, labels = self.index.levels, self.index.labels
+ new_levels = [[lev + 'a' for lev in level] for level in levels]
+ major_labels, minor_labels = labels
+ major_labels = [(x + 1) % 3 for x in major_labels]
+ minor_labels = [(x + 1) % 1 for x in minor_labels]
+ new_labels = [major_labels, minor_labels]
+
+ def test_metadata_immutable(self):
+ levels, labels = self.index.levels, self.index.labels
+ # shouldn't be able to set at either the top level or base level
+ mutable_regex = re.compile('does not support mutable operations')
+ with assertRaisesRegexp(TypeError, mutable_regex):
+ levels[0] = levels[0]
+ with assertRaisesRegexp(TypeError, mutable_regex):
+ levels[0][0] = levels[0][0]
+ # ditto for labels
+ with assertRaisesRegexp(TypeError, mutable_regex):
+ labels[0] = labels[0]
+ with assertRaisesRegexp(TypeError, mutable_regex):
+ labels[0][0] = labels[0][0]
+ # and for names
+ names = self.index.names
+ with assertRaisesRegexp(TypeError, mutable_regex):
+ names[0] = names[0]
+
def test_copy_in_constructor(self):
levels = np.array(["a", "b", "c"])
labels = np.array([1, 1, 2, 0, 0, 1, 1])
| Fixes #4628
- MultiIndex now responds correctly to `rename` (synonym for
`set_names`)
- `set_names` checks that input is list like.
- Cleaner error message for immutable ops.
- Added in previously missing tests for MultiIndex immutable metadata.
- Altered `is_list_like` to check for binary_types as well.
For now, this is the behavior for Index.rename. It's simple and clear and lets existing code just work instead of dealing with typechecks:
``` python
In [2]: ind = Index(range(10))
In [3]: ind = ind.rename((u'A', u'B'))
In [4]: ind.name
Out[4]: (u'A', u'B')
In [5]: ind.names
Out[5]: FrozenList([(u'A', u'B')])
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4718 | 2013-08-31T23:24:53Z | 2013-09-01T01:21:37Z | 2013-09-01T01:21:37Z | 2014-06-12T13:18:24Z |
API/BUG: a column multi-index will be recreated properly (GH4710) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 15c2895f19cc3..570300b7c79de 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -113,6 +113,8 @@ pandas 0.13
via the option ``io.hdf.dropna_table`` (:issue:`4625`)
- the ``format`` keyword now replaces the ``table`` keyword; allowed values are ``fixed(f)|table(t)``
the ``Storer`` format has been renamed to ``Fixed``
+ - a column multi-index will be recreated properly (:issue:`4710`); raise on trying to use a multi-index
+ with data_columns on the same axis
- ``JSON``
- added ``date_unit`` parameter to specify resolution of timestamps. Options
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index aa1c20d582b5b..600f886c57c65 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -15,6 +15,7 @@
import warnings
import numpy as np
+import pandas
from pandas import (Series, TimeSeries, DataFrame, Panel, Panel4D, Index,
MultiIndex, Int64Index, Timestamp)
from pandas.sparse.api import SparseSeries, SparseDataFrame, SparsePanel
@@ -1379,11 +1380,7 @@ def update_info(self, info):
for key in self._info_fields:
value = getattr(self, key, None)
-
- try:
- idx = info[self.name]
- except:
- idx = info[self.name] = dict()
+ idx = _get_info(info, self.name)
existing_value = idx.get(key)
if key in idx and value is not None and existing_value != value:
@@ -2783,7 +2780,10 @@ def validate_data_columns(self, data_columns, min_itemsize):
if not len(self.non_index_axes):
return []
- axis_labels = self.non_index_axes[0][1]
+ axis, axis_labels = self.non_index_axes[0]
+ info = self.info.get(axis,dict())
+ if info.get('type') == 'MultiIndex' and data_columns is not None:
+ raise ValueError("cannot use a multi-index on axis [{0}] with data_columns".format(axis))
# evaluate the passed data_columns, True == use all columns
# take only valide axis labels
@@ -2879,6 +2879,11 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
if sorted(append_axis) == sorted(exist_axis):
append_axis = exist_axis
+ # the non_index_axes info
+ info = _get_info(self.info,i)
+ info['names'] = list(a.names)
+ info['type'] = a.__class__.__name__
+
self.non_index_axes.append((i, append_axis))
# set axis positions (based on the axes)
@@ -3459,10 +3464,20 @@ def read(self, where=None, columns=None, **kwargs):
if not self.read_axes(where=where, **kwargs):
return None
+ info = self.info.get(self.non_index_axes[0][0],dict()) if len(self.non_index_axes) else dict()
index = self.index_axes[0].values
frames = []
for a in self.values_axes:
- cols = Index(a.values)
+
+ # we could have a multi-index constructor here
+ # _ensure_index doesn't recognized our list-of-tuples here
+ if info.get('type') == 'MultiIndex':
+ cols = MultiIndex.from_tuples(a.values)
+ else:
+ cols = Index(a.values)
+ names = info.get('names')
+ if names is not None:
+ cols.set_names(names,inplace=True)
if self.is_transposed:
values = a.cvalues
@@ -3657,6 +3672,14 @@ class AppendableNDimTable(AppendablePanelTable):
obj_type = Panel4D
+def _get_info(info, name):
+ """ get/create the info for this name """
+ try:
+ idx = info[name]
+ except:
+ idx = info[name] = dict()
+ return idx
+
def _convert_index(index, encoding=None):
index_name = getattr(index, 'name', None)
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index e2abae83a099a..66f3d3766ee3e 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -1448,6 +1448,32 @@ def test_append_hierarchical(self):
expected = df.reindex(columns=['A','B'])
tm.assert_frame_equal(result,expected)
+ def test_column_multiindex(self):
+ # GH 4710
+ # recreate multi-indexes properly
+
+ index = MultiIndex.from_tuples([('A','a'), ('A','b'), ('B','a'), ('B','b')], names=['first','second'])
+ df = DataFrame(np.arange(12).reshape(3,4), columns=index)
+
+ with ensure_clean(self.path) as store:
+
+ store.put('df',df)
+ tm.assert_frame_equal(store['df'],df,check_index_type=True,check_column_type=True)
+
+ store.put('df1',df,format='table')
+ tm.assert_frame_equal(store['df1'],df,check_index_type=True,check_column_type=True)
+
+ self.assertRaises(ValueError, store.put, 'df2',df,format='table',data_columns=['A'])
+ self.assertRaises(ValueError, store.put, 'df3',df,format='table',data_columns=True)
+
+ # non_index_axes name
+ df = DataFrame(np.arange(12).reshape(3,4), columns=Index(list('ABCD'),name='foo'))
+
+ with ensure_clean(self.path) as store:
+
+ store.put('df1',df,format='table')
+ tm.assert_frame_equal(store['df1'],df,check_index_type=True,check_column_type=True)
+
def test_pass_spec_to_storer(self):
df = tm.makeDataFrame()
| closes #4710
API: raise on trying to use a multi-index with data_columns on the same axis
| https://api.github.com/repos/pandas-dev/pandas/pulls/4716 | 2013-08-31T19:51:41Z | 2013-08-31T20:00:14Z | 2013-08-31T20:00:14Z | 2014-06-16T09:10:52Z |
API: change nomeclature in HDFStore to use format=fixed(f) | table(t) | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 73a7c2d1e1121..92042b6fe58c5 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1794,27 +1794,31 @@ similar to how ``read_csv`` and ``to_csv`` work. (new in 0.11.0)
os.remove('store_tl.h5')
-.. _io.hdf5-storer:
+.. _io.hdf5-fixed:
-Storer Format
-~~~~~~~~~~~~~
+Fixed Format
+~~~~~~~~~~~~
+
+.. note::
+
+ This was prior to 0.13.0 the ``Storer`` format.
The examples above show storing using ``put``, which write the HDF5 to ``PyTables`` in a fixed array format, called
-the ``storer`` format. These types of stores are are **not** appendable once written (though you can simply
+the ``fixed`` format. These types of stores are are **not** appendable once written (though you can simply
remove them and rewrite). Nor are they **queryable**; they must be
retrieved in their entirety. These offer very fast writing and slightly faster reading than ``table`` stores.
-This format is specified by default when using ``put`` or by ``fmt='s'``
+This format is specified by default when using ``put`` or ``to_hdf`` or by ``format='fixed'`` or ``format='f'``
.. warning::
- A ``storer`` format will raise a ``TypeError`` if you try to retrieve using a ``where`` .
+ A ``fixed`` format will raise a ``TypeError`` if you try to retrieve using a ``where`` .
.. code-block:: python
- DataFrame(randn(10,2)).to_hdf('test_storer.h5','df')
+ DataFrame(randn(10,2)).to_hdf('test_fixed.h5','df')
- pd.read_hdf('test_storer.h5','df',where='index>5')
- TypeError: cannot pass a where specification when reading a non-table
+ pd.read_hdf('test_fixed.h5','df',where='index>5')
+ TypeError: cannot pass a where specification when reading a fixed format.
this store must be selected in its entirety
@@ -1827,7 +1831,11 @@ Table Format
format. Conceptually a ``table`` is shaped very much like a DataFrame,
with rows and columns. A ``table`` may be appended to in the same or
other sessions. In addition, delete & query type operations are
-supported. This format is specified by ``fmt='t'`` to ``append`` or ``put``.
+supported. This format is specified by ``format='table'`` or ``format='t'``
+to ``append`` or ``put`` or ``to_hdf``
+
+This format can be set as an option as well ``pd.set_option('io.hdf.default_format','table')`` to
+enable ``put/append/to_hdf`` to by default store in the ``table`` format.
.. ipython:: python
:suppress:
@@ -1854,7 +1862,7 @@ supported. This format is specified by ``fmt='t'`` to ``append`` or ``put``.
.. note::
- You can also create a ``table`` by passing ``fmt='t'`` to a ``put`` operation.
+ You can also create a ``table`` by passing ``format='table'`` or ``format='t'`` to a ``put`` operation.
.. _io.hdf5-keys:
@@ -2363,7 +2371,7 @@ Starting in 0.11, passing a ``min_itemsize`` dict will cause all passed columns
External Compatibility
~~~~~~~~~~~~~~~~~~~~~~
-``HDFStore`` write storer objects in specific formats suitable for
+``HDFStore`` write ``table`` format objects in specific formats suitable for
producing loss-less roundtrips to pandas objects. For external
compatibility, ``HDFStore`` can read native ``PyTables`` format
tables. It is possible to write an ``HDFStore`` object that can easily
diff --git a/doc/source/release.rst b/doc/source/release.rst
index f492570c9bb0b..9247b9bd44382 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -108,10 +108,11 @@ pandas 0.13
- removed the ``warn`` argument from ``open``. Instead a ``PossibleDataLossError`` exception will
be raised if you try to use ``mode='w'`` with an OPEN file handle (:issue:`4367`)
- allow a passed locations array or mask as a ``where`` condition (:issue:`4467`)
- - the ``fmt`` keyword now replaces the ``table`` keyword; allowed values are ``s|t``
- add the keyword ``dropna=True`` to ``append`` to change whether ALL nan rows are not written
to the store (default is ``True``, ALL nan rows are NOT written), also settable
via the option ``io.hdf.dropna_table`` (:issue:`4625`)
+ - the ``format`` keyword now replaces the ``table`` keyword; allowed values are ``fixed(f)|table(t)``
+ the ``Storer`` format has been renamed to ``Fixed``
- ``JSON``
- added ``date_unit`` parameter to specify resolution of timestamps. Options
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index f8a565157a04c..5791a50684144 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -79,17 +79,17 @@ API changes
- allow a passed locations array or mask as a ``where`` condition (:issue:`4467`).
See :ref:`here<io.hdf5-where_mask>` for an example.
- - the ``fmt`` keyword now replaces the ``table`` keyword; allowed values are ``s|t``
- the same defaults as prior < 0.13.0 remain, e.g. ``put`` implies 's' (Storer) format
- and ``append`` imples 't' (Table) format
+ - the ``format`` keyword now replaces the ``table`` keyword; allowed values are ``fixed(f)`` or ``table(t)``
+ the same defaults as prior < 0.13.0 remain, e.g. ``put`` implies 'fixed` or 'f' (Fixed) format
+ and ``append`` imples 'table' or 't' (Table) format
.. ipython:: python
path = 'test.h5'
df = DataFrame(randn(10,2))
- df.to_hdf(path,'df_table',fmt='t')
+ df.to_hdf(path,'df_table',format='table')
df.to_hdf(path,'df_table2',append=True)
- df.to_hdf(path,'df_storer')
+ df.to_hdf(path,'df_fixed')
with get_store(path) as store:
print store
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index d15ce05e84d40..47fed4ea911e5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -678,6 +678,15 @@ def to_hdf(self, path_or_buf, key, **kwargs):
and if the file does not exist it is created.
``'r+'``
It is similar to ``'a'``, but the file must already exist.
+ format : 'fixed(f)|table(t)', default is 'fixed'
+ fixed(f) : Fixed format
+ Fast writing/reading. Not-appendable, nor searchable
+ table(t) : Table format
+ Write as a PyTables Table structure which may perform worse but
+ allow more flexible operations like searching / selecting subsets
+ of the data
+ append : boolean, default False
+ For Table formats, append the input data to the existing
complevel : int, 1-9, default 0
If a complib is specified compression will be applied
where possible
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 33921b7e534e5..aa1c20d582b5b 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -103,19 +103,19 @@ class DuplicateWarning(Warning):
# formats
_FORMAT_MAP = {
- u('s') : 's',
- u('storer') : 's',
- u('t') : 't',
- u('table') : 't',
+ u('f') : 'fixed',
+ u('fixed') : 'fixed',
+ u('t') : 'table',
+ u('table') : 'table',
}
-fmt_deprecate_doc = """
+format_deprecate_doc = """
the table keyword has been deprecated
-use the fmt='s|t' keyword instead
- s : specifies the Storer format
- and is the default for put operations
- t : specifies the Table format
- and is the default for append operations
+use the format='fixed(f)|table(t)' keyword instead
+ fixed(f) : specifies the Fixed format
+ and is the default for put operations
+ table(t) : specifies the Table format
+ and is the default for append operations
"""
# map object types
@@ -133,16 +133,16 @@ class DuplicateWarning(Warning):
# storer class map
_STORER_MAP = {
- u('TimeSeries'): 'LegacySeriesStorer',
- u('Series'): 'LegacySeriesStorer',
- u('DataFrame'): 'LegacyFrameStorer',
- u('DataMatrix'): 'LegacyFrameStorer',
- u('series'): 'SeriesStorer',
- u('sparse_series'): 'SparseSeriesStorer',
- u('frame'): 'FrameStorer',
- u('sparse_frame'): 'SparseFrameStorer',
- u('wide'): 'PanelStorer',
- u('sparse_panel'): 'SparsePanelStorer',
+ u('TimeSeries'): 'LegacySeriesFixed',
+ u('Series'): 'LegacySeriesFixed',
+ u('DataFrame'): 'LegacyFrameFixed',
+ u('DataMatrix'): 'LegacyFrameFixed',
+ u('series'): 'SeriesFixed',
+ u('sparse_series'): 'SparseSeriesFixed',
+ u('frame'): 'FrameFixed',
+ u('sparse_frame'): 'SparseFrameFixed',
+ u('wide'): 'PanelFixed',
+ u('sparse_panel'): 'SparsePanelFixed',
}
# table class map
@@ -172,10 +172,17 @@ class DuplicateWarning(Warning):
: boolean
drop ALL nan rows when appending to a table
"""
+format_doc = """
+: format
+ default format writing format, if None, then
+ put will default to 'fixed' and append will default to 'table'
+"""
with config.config_prefix('io.hdf'):
config.register_option('dropna_table', True, dropna_doc,
validator=config.is_bool)
+ config.register_option('default_format', None, format_doc,
+ validator=config.is_one_of_factory(['fixed','table',None]))
# oh the troubles to reduce import time
_table_mod = None
@@ -294,11 +301,7 @@ class HDFStore(StringMixin):
"""
dict-like IO interface for storing pandas objects in PyTables
- format.
-
- DataFrame and Panel can be stored in Table format, which is slower to
- read and write but can be searched and manipulated more like an SQL
- table. See HDFStore.put for more information
+ either Fixed or Table format.
Parameters
----------
@@ -670,7 +673,7 @@ def func(_start, _stop):
return TableIterator(self, func, nrows=nrows, start=start, stop=stop, auto_close=auto_close).get_values()
- def put(self, key, value, fmt=None, append=False, **kwargs):
+ def put(self, key, value, format=None, append=False, **kwargs):
"""
Store object in HDFStore
@@ -678,19 +681,20 @@ def put(self, key, value, fmt=None, append=False, **kwargs):
----------
key : object
value : {Series, DataFrame, Panel}
- fmt : 's|t', default is 's' for storer format
- s : storer format
- Fast writing/reading. Not-appendable, nor searchable
- t : table format
- Write as a PyTables Table structure which may perform worse but
- allow more flexible operations like searching / selecting subsets
- of the data
+ format : 'fixed(f)|table(t)', default is 'fixed'
+ fixed(f) : Fixed format
+ Fast writing/reading. Not-appendable, nor searchable
+ table(t) : Table format
+ Write as a PyTables Table structure which may perform worse but
+ allow more flexible operations like searching / selecting subsets
+ of the data
append : boolean, default False
- For table data structures, append the input data to the existing
- table
+ For Table format, append the input data to the existing
encoding : default None, provide an encoding for strings
"""
- kwargs = self._validate_format(fmt or 's', kwargs)
+ if format is None:
+ format = get_option("io.hdf.default_format") or 'fixed'
+ kwargs = self._validate_format(format, kwargs)
self._write_to_group(key, value, append=append, **kwargs)
def remove(self, key, where=None, start=None, stop=None):
@@ -742,7 +746,7 @@ def remove(self, key, where=None, start=None, stop=None):
'can only remove with where on objects written as tables')
return s.delete(where=where, start=start, stop=stop)
- def append(self, key, value, fmt=None, append=True, columns=None, dropna=None, **kwargs):
+ def append(self, key, value, format=None, append=True, columns=None, dropna=None, **kwargs):
"""
Append to Table in file. Node must already exist and be Table
format.
@@ -751,11 +755,11 @@ def append(self, key, value, fmt=None, append=True, columns=None, dropna=None, *
----------
key : object
value : {Series, DataFrame, Panel, Panel4D}
- fmt : 't', default is 't' for table format
- t : table format
- Write as a PyTables Table structure which may perform worse but
- allow more flexible operations like searching / selecting subsets
- of the data
+ format: 'table' is the default
+ table(t) : table format
+ Write as a PyTables Table structure which may perform worse but
+ allow more flexible operations like searching / selecting subsets
+ of the data
append : boolean, default True, append the input data to the existing
data_columns : list of columns to create as data columns, or True to use all columns
min_itemsize : dict of columns that specify minimum string sizes
@@ -776,7 +780,9 @@ def append(self, key, value, fmt=None, append=True, columns=None, dropna=None, *
if dropna is None:
dropna = get_option("io.hdf.dropna_table")
- kwargs = self._validate_format(fmt or 't', kwargs)
+ if format is None:
+ format = get_option("io.hdf.default_format") or 'table'
+ kwargs = self._validate_format(format, kwargs)
self._write_to_group(key, value, append=append, dropna=dropna, **kwargs)
def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, **kwargs):
@@ -864,7 +870,7 @@ def create_table_index(self, key, **kwargs):
return
if not s.is_table:
- raise TypeError("cannot create table index on a non-table")
+ raise TypeError("cannot create table index on a Fixed format store")
s.create_index(**kwargs)
def groups(self):
@@ -942,39 +948,36 @@ def _check_if_open(self):
if not self.is_open:
raise ClosedFileError("{0} file is not open!".format(self._path))
- def _validate_format(self, fmt, kwargs):
+ def _validate_format(self, format, kwargs):
""" validate / deprecate formats; return the new kwargs """
kwargs = kwargs.copy()
- if 'format' in kwargs:
- raise TypeError("pls specify an object format with the 'fmt' keyword")
-
# table arg
table = kwargs.pop('table',None)
if table is not None:
- warnings.warn(fmt_deprecate_doc,FutureWarning)
+ warnings.warn(format_deprecate_doc,FutureWarning)
if table:
- fmt = 't'
+ format = 'table'
else:
- fmt = 's'
+ format = 'fixed'
# validate
try:
- kwargs['fmt'] = _FORMAT_MAP[fmt.lower()]
+ kwargs['format'] = _FORMAT_MAP[format.lower()]
except:
- raise TypeError("invalid HDFStore format specified [{0}]".format(fmt))
+ raise TypeError("invalid HDFStore format specified [{0}]".format(format))
return kwargs
- def _create_storer(self, group, fmt=None, value=None, append=False, **kwargs):
- """ return a suitable Storer class to operate """
+ def _create_storer(self, group, format=None, value=None, append=False, **kwargs):
+ """ return a suitable class to operate """
def error(t):
raise TypeError(
- "cannot properly create the storer for: [%s] [group->%s,value->%s,fmt->%s,append->%s,kwargs->%s]" %
- (t, group, type(value), fmt, append, kwargs))
+ "cannot properly create the storer for: [%s] [group->%s,value->%s,format->%s,append->%s,kwargs->%s]" %
+ (t, group, type(value), format, append, kwargs))
pt = _ensure_decoded(getattr(group._v_attrs, 'pandas_type', None))
tt = _ensure_decoded(getattr(group._v_attrs, 'table_type', None))
@@ -998,7 +1001,7 @@ def error(t):
error('_TYPE_MAP')
# we are actually a table
- if fmt == 't':
+ if format == 'table':
pt += u('_table')
# a storer node
@@ -1050,7 +1053,7 @@ def error(t):
error('_TABLE_MAP')
def _write_to_group(
- self, key, value, fmt, index=True, append=False,
+ self, key, value, format, index=True, append=False,
complib=None, encoding=None, **kwargs):
group = self.get_node(key)
@@ -1061,7 +1064,7 @@ def _write_to_group(
# we don't want to store a table node at all if are object is 0-len
# as there are not dtypes
- if getattr(value,'empty',None) and (fmt == 't' or append):
+ if getattr(value,'empty',None) and (format == 'table' or append):
return
if group is None:
@@ -1081,12 +1084,12 @@ def _write_to_group(
group = self._handle.createGroup(path, p)
path = new_path
- s = self._create_storer(group, fmt, value, append=append,
+ s = self._create_storer(group, format, value, append=append,
encoding=encoding, **kwargs)
if append:
- # raise if we are trying to append to a non-table,
+ # raise if we are trying to append to a Fixed format,
# or a table that exists (and we are putting)
- if not s.is_table or (s.is_table and fmt == 's' and s.is_exists):
+ if not s.is_table or (s.is_table and format == 'fixed' and s.is_exists):
raise ValueError('Can only append to Tables')
if not s.is_exists:
s.set_object_info()
@@ -1094,7 +1097,7 @@ def _write_to_group(
s.set_object_info()
if not s.is_table and complib:
- raise ValueError('Compression not supported on non-table')
+ raise ValueError('Compression not supported on Fixed format stores')
# write the object
s.write(obj=value, append=append, complib=complib, **kwargs)
@@ -1765,11 +1768,11 @@ def get_attr(self):
pass
-class Storer(StringMixin):
+class Fixed(StringMixin):
""" represent an object in my store
- facilitate read/write of various types of objects
- this is an abstract base class
+ facilitate read/write of various types of objects
+ this is an abstract base class
Parameters
----------
@@ -1921,9 +1924,9 @@ def delete(self, where=None, **kwargs):
raise TypeError("cannot delete on an abstract storer")
-class GenericStorer(Storer):
+class GenericFixed(Fixed):
- """ a generified storer version """
+ """ a generified fixed version """
_index_type_map = {DatetimeIndex: 'datetime',
PeriodIndex: 'period'}
_reverse_index_map = dict([(v, k)
@@ -1950,10 +1953,10 @@ def f(values, freq=None, tz=None):
def validate_read(self, kwargs):
if kwargs.get('columns') is not None:
- raise TypeError("cannot pass a column specification when reading a non-table "
+ raise TypeError("cannot pass a column specification when reading a Fixed format store."
"this store must be selected in its entirety")
if kwargs.get('where') is not None:
- raise TypeError("cannot pass a where specification when reading from a non-table "
+ raise TypeError("cannot pass a where specification when reading from a Fixed format store."
"this store must be selected in its entirety")
@property
@@ -2212,7 +2215,7 @@ def write_array(self, key, value, items=None):
getattr(self.group, key)._v_attrs.transposed = transposed
-class LegacyStorer(GenericStorer):
+class LegacyFixed(GenericFixed):
def read_index_legacy(self, key):
node = getattr(self.group, key)
@@ -2221,7 +2224,7 @@ def read_index_legacy(self, key):
return _unconvert_index_legacy(data, kind, encoding=self.encoding)
-class LegacySeriesStorer(LegacyStorer):
+class LegacySeriesFixed(LegacyFixed):
def read(self, **kwargs):
self.validate_read(kwargs)
@@ -2230,7 +2233,7 @@ def read(self, **kwargs):
return Series(values, index=index)
-class LegacyFrameStorer(LegacyStorer):
+class LegacyFrameFixed(LegacyFixed):
def read(self, **kwargs):
self.validate_read(kwargs)
@@ -2240,7 +2243,7 @@ def read(self, **kwargs):
return DataFrame(values, index=index, columns=columns)
-class SeriesStorer(GenericStorer):
+class SeriesFixed(GenericFixed):
pandas_kind = u('series')
attributes = ['name']
@@ -2262,13 +2265,13 @@ def read(self, **kwargs):
return Series(values, index=index, name=self.name)
def write(self, obj, **kwargs):
- super(SeriesStorer, self).write(obj, **kwargs)
+ super(SeriesFixed, self).write(obj, **kwargs)
self.write_index('index', obj.index)
self.write_array('values', obj.values)
self.attrs.name = obj.name
-class SparseSeriesStorer(GenericStorer):
+class SparseSeriesFixed(GenericFixed):
pandas_kind = u('sparse_series')
attributes = ['name', 'fill_value', 'kind']
@@ -2282,7 +2285,7 @@ def read(self, **kwargs):
name=self.name)
def write(self, obj, **kwargs):
- super(SparseSeriesStorer, self).write(obj, **kwargs)
+ super(SparseSeriesFixed, self).write(obj, **kwargs)
self.write_index('index', obj.index)
self.write_index('sp_index', obj.sp_index)
self.write_array('sp_values', obj.sp_values)
@@ -2291,7 +2294,7 @@ def write(self, obj, **kwargs):
self.attrs.kind = obj.kind
-class SparseFrameStorer(GenericStorer):
+class SparseFrameFixed(GenericFixed):
pandas_kind = u('sparse_frame')
attributes = ['default_kind', 'default_fill_value']
@@ -2301,7 +2304,7 @@ def read(self, **kwargs):
sdict = {}
for c in columns:
key = 'sparse_series_%s' % c
- s = SparseSeriesStorer(self.parent, getattr(self.group, key))
+ s = SparseSeriesFixed(self.parent, getattr(self.group, key))
s.infer_axes()
sdict[c] = s.read()
return SparseDataFrame(sdict, columns=columns,
@@ -2310,21 +2313,21 @@ def read(self, **kwargs):
def write(self, obj, **kwargs):
""" write it as a collection of individual sparse series """
- super(SparseFrameStorer, self).write(obj, **kwargs)
+ super(SparseFrameFixed, self).write(obj, **kwargs)
for name, ss in compat.iteritems(obj):
key = 'sparse_series_%s' % name
if key not in self.group._v_children:
node = self._handle.createGroup(self.group, key)
else:
node = getattr(self.group, key)
- s = SparseSeriesStorer(self.parent, node)
+ s = SparseSeriesFixed(self.parent, node)
s.write(ss)
self.attrs.default_fill_value = obj.default_fill_value
self.attrs.default_kind = obj.default_kind
self.write_index('columns', obj.columns)
-class SparsePanelStorer(GenericStorer):
+class SparsePanelFixed(GenericFixed):
pandas_kind = u('sparse_panel')
attributes = ['default_kind', 'default_fill_value']
@@ -2336,14 +2339,14 @@ def read(self, **kwargs):
for name in items:
key = 'sparse_frame_%s' % name
node = getattr(self.group, key)
- s = SparseFrameStorer(self.parent, getattr(self.group, key))
+ s = SparseFrameFixed(self.parent, getattr(self.group, key))
s.infer_axes()
sdict[name] = s.read()
return SparsePanel(sdict, items=items, default_kind=self.default_kind,
default_fill_value=self.default_fill_value)
def write(self, obj, **kwargs):
- super(SparsePanelStorer, self).write(obj, **kwargs)
+ super(SparsePanelFixed, self).write(obj, **kwargs)
self.attrs.default_fill_value = obj.default_fill_value
self.attrs.default_kind = obj.default_kind
self.write_index('items', obj.items)
@@ -2354,11 +2357,11 @@ def write(self, obj, **kwargs):
node = self._handle.createGroup(self.group, key)
else:
node = getattr(self.group, key)
- s = SparseFrameStorer(self.parent, node)
+ s = SparseFrameFixed(self.parent, node)
s.write(sdf)
-class BlockManagerStorer(GenericStorer):
+class BlockManagerFixed(GenericFixed):
attributes = ['ndim', 'nblocks']
is_shape_reversed = False
@@ -2412,7 +2415,7 @@ def read(self, **kwargs):
return self.obj_type(BlockManager(blocks, axes))
def write(self, obj, **kwargs):
- super(BlockManagerStorer, self).write(obj, **kwargs)
+ super(BlockManagerFixed, self).write(obj, **kwargs)
data = obj._data
if not data.is_consolidated():
data = data.consolidate()
@@ -2430,22 +2433,22 @@ def write(self, obj, **kwargs):
self.write_index('block%d_items' % i, blk.items)
-class FrameStorer(BlockManagerStorer):
+class FrameFixed(BlockManagerFixed):
pandas_kind = u('frame')
obj_type = DataFrame
-class PanelStorer(BlockManagerStorer):
+class PanelFixed(BlockManagerFixed):
pandas_kind = u('wide')
obj_type = Panel
is_shape_reversed = True
def write(self, obj, **kwargs):
obj._consolidate_inplace()
- return super(PanelStorer, self).write(obj, **kwargs)
+ return super(PanelFixed, self).write(obj, **kwargs)
-class Table(Storer):
+class Table(Fixed):
""" represent a table:
facilitate read/write of various types of tables
@@ -3992,7 +3995,7 @@ def eval(self):
else:
raise TypeError(
- "passing a filterable condition to a non-table indexer [%s]" % str(self))
+ "passing a filterable condition to a Fixed format indexer [%s]" % str(self))
def convert_value(self, v):
""" convert the expression that is in the term to something that is accepted by pytables """
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index ab7e5cf813b24..0ab7a32938646 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -150,38 +150,38 @@ def roundtrip(key, obj,**kwargs):
def test_api(self):
# GH4584
- # API issue when to_hdf doesn't acdept append AND table args
+ # API issue when to_hdf doesn't acdept append AND format args
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
- df.iloc[:10].to_hdf(path,'df',append=True,table=True)
- df.iloc[10:].to_hdf(path,'df',append=True,table=True)
+ df.iloc[:10].to_hdf(path,'df',append=True,format='table')
+ df.iloc[10:].to_hdf(path,'df',append=True,format='table')
assert_frame_equal(read_hdf(path,'df'),df)
# append to False
- df.iloc[:10].to_hdf(path,'df',append=False,table=True)
- df.iloc[10:].to_hdf(path,'df',append=True,table=True)
+ df.iloc[:10].to_hdf(path,'df',append=False,format='table')
+ df.iloc[10:].to_hdf(path,'df',append=True,format='table')
assert_frame_equal(read_hdf(path,'df'),df)
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
df.iloc[:10].to_hdf(path,'df',append=True)
- df.iloc[10:].to_hdf(path,'df',append=True,table='t')
+ df.iloc[10:].to_hdf(path,'df',append=True,format='table')
assert_frame_equal(read_hdf(path,'df'),df)
# append to False
- df.iloc[:10].to_hdf(path,'df',append=False,table='t')
+ df.iloc[:10].to_hdf(path,'df',append=False,format='table')
df.iloc[10:].to_hdf(path,'df',append=True)
assert_frame_equal(read_hdf(path,'df'),df)
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
- df.to_hdf(path,'df',append=False,table=False)
+ df.to_hdf(path,'df',append=False,format='fixed')
assert_frame_equal(read_hdf(path,'df'),df)
- df.to_hdf(path,'df',append=False,fmt='s')
+ df.to_hdf(path,'df',append=False,format='f')
assert_frame_equal(read_hdf(path,'df'),df)
df.to_hdf(path,'df',append=False)
@@ -193,34 +193,77 @@ def test_api(self):
with ensure_clean(self.path) as store:
df = tm.makeDataFrame()
- store.append('df',df.iloc[:10],append=True,table=True)
- store.append('df',df.iloc[10:],append=True,table=True)
+ 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)
# append to False
- store.append('df',df.iloc[:10],append=False,table=True)
- store.append('df',df.iloc[10:],append=True,table=True)
+ 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)
# formats
- store.append('df',df.iloc[:10],append=False,fmt='t')
- store.append('df',df.iloc[10:],append=True,fmt='t')
+ 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)
_maybe_remove(store,'df')
- store.append('df',df.iloc[:10],append=False,fmt='t')
- store.append('df',df.iloc[10:],append=True,fmt=None)
+ 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)
with tm.ensure_clean(self.path) as path:
# invalid
df = tm.makeDataFrame()
- self.assertRaises(ValueError, df.to_hdf, path,'df',append=True,fmt='s')
+ self.assertRaises(ValueError, df.to_hdf, path,'df',append=True,format='f')
+ self.assertRaises(ValueError, df.to_hdf, path,'df',append=True,format='fixed')
- self.assertRaises(TypeError, df.to_hdf, path,'df',append=True,fmt='foo')
- self.assertRaises(TypeError, df.to_hdf, path,'df',append=False,fmt='bar')
- self.assertRaises(TypeError, df.to_hdf, path,'df',format='s')
+ self.assertRaises(TypeError, df.to_hdf, path,'df',append=True,format='foo')
+ self.assertRaises(TypeError, df.to_hdf, path,'df',append=False,format='bar')
+
+
+ def test_api_default_format(self):
+
+ # default_format option
+ with ensure_clean(self.path) as store:
+ df = tm.makeDataFrame()
+
+ pandas.set_option('io.hdf.default_format','fixed')
+ _maybe_remove(store,'df')
+ store.put('df',df)
+ self.assert_(not store.get_storer('df').is_table)
+ self.assertRaises(ValueError, store.append, 'df2',df)
+
+ pandas.set_option('io.hdf.default_format','table')
+ _maybe_remove(store,'df')
+ store.put('df',df)
+ self.assert_(store.get_storer('df').is_table)
+ _maybe_remove(store,'df2')
+ store.append('df2',df)
+ self.assert_(store.get_storer('df').is_table)
+
+ pandas.set_option('io.hdf.default_format',None)
+
+ with tm.ensure_clean(self.path) as path:
+
+ df = tm.makeDataFrame()
+
+ pandas.set_option('io.hdf.default_format','fixed')
+ df.to_hdf(path,'df')
+ with get_store(path) as store:
+ self.assert_(not store.get_storer('df').is_table)
+ self.assertRaises(ValueError, df.to_hdf, path,'df2', append=True)
+
+ pandas.set_option('io.hdf.default_format','table')
+ df.to_hdf(path,'df3')
+ with get_store(path) as store:
+ self.assert_(store.get_storer('df3').is_table)
+ df.to_hdf(path,'df4',append=True)
+ with get_store(path) as store:
+ self.assert_(store.get_storer('df4').is_table)
+
+ pandas.set_option('io.hdf.default_format',None)
def test_keys(self):
@@ -466,7 +509,7 @@ def test_put(self):
store['foo/bar/bah'] = df[:10]
store['foo'] = df[:10]
store['/foo'] = df[:10]
- store.put('c', df[:10], table=True)
+ store.put('c', df[:10], format='table')
# not OK, not a table
self.assertRaises(
@@ -481,7 +524,7 @@ def test_put(self):
self.assertRaises(ValueError, store.put, 'c', df[10:], append=True)
# overwrite table
- store.put('c', df[:10], table=True, append=False)
+ store.put('c', df[:10], format='table', append=False)
tm.assert_frame_equal(df[:10], store['c'])
def test_put_string_index(self):
@@ -514,12 +557,12 @@ def test_put_compression(self):
with ensure_clean(self.path) as store:
df = tm.makeTimeDataFrame()
- store.put('c', df, table=True, complib='zlib')
+ store.put('c', df, format='table', complib='zlib')
tm.assert_frame_equal(store['c'], df)
- # can't compress if table=False
+ # can't compress if format='fixed'
self.assertRaises(ValueError, store.put, 'b', df,
- table=False, complib='zlib')
+ format='fixed', complib='zlib')
def test_put_compression_blosc(self):
tm.skip_if_no_package('tables', '2.2', app='blosc support')
@@ -527,11 +570,11 @@ def test_put_compression_blosc(self):
with ensure_clean(self.path) as store:
- # can't compress if table=False
+ # can't compress if format='fixed'
self.assertRaises(ValueError, store.put, 'b', df,
- table=False, complib='blosc')
+ format='fixed', complib='blosc')
- store.put('c', df, table=True, complib='blosc')
+ store.put('c', df, format='table', complib='blosc')
tm.assert_frame_equal(store['c'], df)
def test_put_integer(self):
@@ -577,7 +620,7 @@ def test_append(self):
tm.assert_frame_equal(store['df1'], df)
_maybe_remove(store, 'df2')
- store.put('df2', df[:10], table=True)
+ store.put('df2', df[:10], format='table')
store.append('df2', df[10:])
tm.assert_frame_equal(store['df2'], df)
@@ -1376,7 +1419,7 @@ def test_append_diff_item_order(self):
wp2 = wp.ix[['ItemC', 'ItemB', 'ItemA'], 10:, :]
with ensure_clean(self.path) as store:
- store.put('panel', wp1, table=True)
+ store.put('panel', wp1, format='table')
self.assertRaises(ValueError, store.put, 'panel', wp2,
append=True)
@@ -1400,7 +1443,7 @@ def test_append_hierarchical(self):
tm.assert_frame_equal(result,expected)
with tm.ensure_clean('test.hdf') as path:
- df.to_hdf(path,'df',table=True)
+ df.to_hdf(path,'df',format='table')
result = read_hdf(path,'df',columns=['A','B'])
expected = df.reindex(columns=['A','B'])
tm.assert_frame_equal(result,expected)
@@ -1541,9 +1584,9 @@ def test_table_index_incompatible_dtypes(self):
index=date_range('1/1/2000', periods=3))
with ensure_clean(self.path) as store:
- store.put('frame', df1, table=True)
+ store.put('frame', df1, format='table')
self.assertRaises(TypeError, store.put, 'frame', df2,
- table=True, append=True)
+ format='table', append=True)
def test_table_values_dtypes_roundtrip(self):
@@ -1777,7 +1820,7 @@ def test_remove_where(self):
# try to remove non-table (with crit)
# non-table ok (where = None)
wp = tm.makePanel()
- store.put('wp', wp, fmt='t')
+ store.put('wp', wp, format='t')
store.remove('wp', [('minor_axis', ['A', 'D'])])
rs = store.select('wp')
expected = wp.reindex(minor_axis=['B', 'C'])
@@ -1785,7 +1828,7 @@ def test_remove_where(self):
# empty where
_maybe_remove(store, 'wp')
- store.put('wp', wp, fmt='t')
+ store.put('wp', wp, format='table')
# deleted number (entire table)
n = store.remove('wp', [])
@@ -1793,12 +1836,12 @@ def test_remove_where(self):
# non - empty where
_maybe_remove(store, 'wp')
- store.put('wp', wp, fmt='t')
+ store.put('wp', wp, format='table')
self.assertRaises(ValueError, store.remove,
'wp', ['foo'])
# selectin non-table with a where
- # store.put('wp2', wp, fmt='s')
+ # store.put('wp2', wp, format='f')
# self.assertRaises(ValueError, store.remove,
# 'wp2', [('column', ['A', 'D'])])
@@ -1811,7 +1854,7 @@ def test_remove_crit(self):
# group row removal
date4 = wp.major_axis.take([0, 1, 2, 4, 5, 6, 8, 9, 10])
crit4 = Term('major_axis', date4)
- store.put('wp3', wp, fmt='t')
+ store.put('wp3', wp, format='table')
n = store.remove('wp3', where=[crit4])
assert(n == 36)
result = store.select('wp3')
@@ -1819,7 +1862,7 @@ def test_remove_crit(self):
assert_panel_equal(result, expected)
# upper half
- store.put('wp', wp, fmt='t')
+ store.put('wp', wp, format='table')
date = wp.major_axis[len(wp.major_axis) // 2]
crit1 = Term('major_axis', '>', date)
@@ -1836,7 +1879,7 @@ def test_remove_crit(self):
assert_panel_equal(result, expected)
# individual row elements
- store.put('wp2', wp, fmt='t')
+ store.put('wp2', wp, format='table')
date1 = wp.major_axis[1:3]
crit1 = Term('major_axis', date1)
@@ -1862,7 +1905,7 @@ def test_remove_crit(self):
assert_panel_equal(result, expected)
# corners
- store.put('wp4', wp, fmt='t')
+ store.put('wp4', wp, format='table')
n = store.remove(
'wp4', where=[Term('major_axis', '>', wp.major_axis[-1])])
result = store.select('wp4')
@@ -1874,8 +1917,8 @@ def test_terms(self):
wp = tm.makePanel()
p4d = tm.makePanel4D()
- store.put('wp', wp, fmt='t')
- store.put('p4d', p4d, fmt='t')
+ store.put('wp', wp, format='table')
+ store.put('p4d', p4d, format='table')
# some invalid terms
terms = [
@@ -2230,8 +2273,8 @@ def test_wide_table(self):
def test_wide_table_dups(self):
wp = tm.makePanel()
with ensure_clean(self.path) as store:
- store.put('panel', wp, fmt='t')
- store.put('panel', wp, fmt='t', append=True)
+ store.put('panel', wp, format='table')
+ store.put('panel', wp, format='table', append=True)
with tm.assert_produces_warning(expected_warning=DuplicateWarning):
recons = store['panel']
@@ -2297,7 +2340,7 @@ def test_select(self):
# put/select ok
_maybe_remove(store, 'wp')
- store.put('wp', wp, fmt='t')
+ store.put('wp', wp, format='table')
store.select('wp')
# non-table ok (where = None)
@@ -2483,7 +2526,7 @@ def test_select_iterator(self):
with tm.ensure_clean(self.path) as path:
df = tm.makeTimeDataFrame(500)
- df.to_hdf(path,'df',fmt='t')
+ df.to_hdf(path,'df',format='table')
results = []
for x in read_hdf(path,'df',chunksize=100):
@@ -2534,7 +2577,7 @@ def test_retain_index_attributes(self):
with ensure_clean(self.path) as store:
_maybe_remove(store,'data')
- store.put('data', df, fmt='t')
+ store.put('data', df, format='table')
result = store.get('data')
tm.assert_frame_equal(df,result)
@@ -2592,7 +2635,7 @@ def test_panel_select(self):
wp = tm.makePanel()
with ensure_clean(self.path) as store:
- store.put('wp', wp, fmt='t')
+ store.put('wp', wp, format='table')
date = wp.major_axis[len(wp.major_axis) // 2]
crit1 = ('major_axis', '>=', date)
@@ -2612,7 +2655,7 @@ def test_frame_select(self):
df = tm.makeTimeDataFrame()
with ensure_clean(self.path) as store:
- store.put('frame', df,fmt='t')
+ store.put('frame', df,format='table')
date = df.index[len(df) // 2]
crit1 = ('index', '>=', date)
@@ -2920,7 +2963,7 @@ def test_select_filter_corner(self):
df.columns = ['%.3d' % c for c in df.columns]
with ensure_clean(self.path) as store:
- store.put('frame', df, fmt='t')
+ store.put('frame', df, format='table')
crit = Term('columns', df.columns[:75])
result = store.select('frame', [crit])
@@ -2958,7 +3001,7 @@ def _check_roundtrip_table(self, obj, comparator, compression=False):
options['complib'] = _default_compressor
with ensure_clean(self.path, 'w', **options) as store:
- store.put('obj', obj, fmt='t')
+ store.put('obj', obj, format='table')
retrieved = store['obj']
# sorted_obj = _test_sort(obj)
comparator(retrieved, obj)
@@ -2969,7 +3012,7 @@ def test_multiple_open_close(self):
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
- df.to_hdf(path,'df',mode='w',fmt='t')
+ df.to_hdf(path,'df',mode='w',format='table')
# single
store = HDFStore(path)
@@ -3031,7 +3074,7 @@ def test_multiple_open_close(self):
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
- df.to_hdf(path,'df',mode='w',fmt='t')
+ df.to_hdf(path,'df',mode='w',format='table')
store = HDFStore(path)
store.close()
@@ -3274,7 +3317,7 @@ def test_store_datetime_mixed(self):
# index=[np.arange(5).repeat(2),
# np.tile(np.arange(2), 5)])
- # self.assertRaises(Exception, store.put, 'foo', df, fmt='t')
+ # self.assertRaises(Exception, store.put, 'foo', df, format='table')
def _test_sort(obj):
| see #4645
Storer has been renamed to Fixed (and all docs changed)
added option: `io.hdf.default_format` to allow the overriding of the default format
format is now specified as: `format=` with a value of (`fixed(f)` or `table(t)`)
should be a bit more intuitve
| https://api.github.com/repos/pandas-dev/pandas/pulls/4715 | 2013-08-31T14:46:30Z | 2013-08-31T14:57:45Z | 2013-08-31T14:57:45Z | 2014-07-16T08:25:40Z |
API: for HDFStore, add the keyword dropna=True to append to change whether to write ALL nan rows to the store (GH4625) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4e6ac7240512c..f492570c9bb0b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -109,6 +109,9 @@ pandas 0.13
be raised if you try to use ``mode='w'`` with an OPEN file handle (:issue:`4367`)
- allow a passed locations array or mask as a ``where`` condition (:issue:`4467`)
- the ``fmt`` keyword now replaces the ``table`` keyword; allowed values are ``s|t``
+ - add the keyword ``dropna=True`` to ``append`` to change whether ALL nan rows are not written
+ to the store (default is ``True``, ALL nan rows are NOT written), also settable
+ via the option ``io.hdf.dropna_table`` (:issue:`4625`)
- ``JSON``
- added ``date_unit`` parameter to specify resolution of timestamps. Options
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 022799cd88014..f8a565157a04c 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -98,6 +98,9 @@ API changes
import os
os.remove(path)
+ - add the keyword ``dropna=True`` to ``append`` to change whether ALL nan rows are not written
+ to the store (default is ``True``, ALL nan rows are NOT written), also settable
+ via the option ``io.hdf.dropna_table`` (:issue:`4625`)
- Changes to how ``Index`` and ``MultiIndex`` handle metadata (``levels``,
``labels``, and ``names``) (:issue:`4039`):
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 1eb8b0f266f68..33921b7e534e5 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -32,6 +32,7 @@
from pandas.tools.merge import concat
from pandas import compat
from pandas.io.common import PerformanceWarning
+from pandas.core.config import get_option
import pandas.lib as lib
import pandas.algos as algos
@@ -165,6 +166,17 @@ class DuplicateWarning(Warning):
Panel4D: [1, 2, 3],
}
+# register our configuration options
+from pandas.core import config
+dropna_doc = """
+: boolean
+ drop ALL nan rows when appending to a table
+"""
+
+with config.config_prefix('io.hdf'):
+ config.register_option('dropna_table', True, dropna_doc,
+ validator=config.is_bool)
+
# oh the troubles to reduce import time
_table_mod = None
_table_supports_index = False
@@ -730,7 +742,7 @@ def remove(self, key, where=None, start=None, stop=None):
'can only remove with where on objects written as tables')
return s.delete(where=where, start=start, stop=stop)
- def append(self, key, value, fmt=None, append=True, columns=None, **kwargs):
+ def append(self, key, value, fmt=None, append=True, columns=None, dropna=None, **kwargs):
"""
Append to Table in file. Node must already exist and be Table
format.
@@ -751,7 +763,8 @@ def append(self, key, value, fmt=None, append=True, columns=None, **kwargs):
chunksize : size to chunk the writing
expectedrows : expected TOTAL row size of this table
encoding : default None, provide an encoding for strings
-
+ dropna : boolean, default True, do not write an ALL nan row to the store
+ settable by the option 'io.hdf.dropna_table'
Notes
-----
Does *not* check if data being appended overlaps with existing
@@ -761,8 +774,10 @@ def append(self, key, value, fmt=None, append=True, columns=None, **kwargs):
raise Exception(
"columns is not a supported keyword in append, try data_columns")
+ if dropna is None:
+ dropna = get_option("io.hdf.dropna_table")
kwargs = self._validate_format(fmt or 't', kwargs)
- self._write_to_group(key, value, append=append, **kwargs)
+ self._write_to_group(key, value, append=append, dropna=dropna, **kwargs)
def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, **kwargs):
"""
@@ -3219,7 +3234,7 @@ class AppendableTable(LegacyTable):
def write(self, obj, axes=None, append=False, complib=None,
complevel=None, fletcher32=None, min_itemsize=None, chunksize=None,
- expectedrows=None, **kwargs):
+ expectedrows=None, dropna=True, **kwargs):
if not append and self.is_exists:
self._handle.removeNode(self.group, 'table')
@@ -3254,29 +3269,36 @@ def write(self, obj, axes=None, append=False, complib=None,
a.validate_and_set(table, append)
# add the rows
- self.write_data(chunksize)
+ self.write_data(chunksize, dropna=dropna)
- def write_data(self, chunksize):
+ def write_data(self, chunksize, dropna=True):
""" we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk """
names = self.dtype.names
nrows = self.nrows_expected
- # create the masks & values
- masks = []
- for a in self.values_axes:
+ # if dropna==True, then drop ALL nan rows
+ if dropna:
+
+ masks = []
+ for a in self.values_axes:
+
+ # figure the mask: only do if we can successfully process this
+ # column, otherwise ignore the mask
+ mask = com.isnull(a.data).all(axis=0)
+ masks.append(mask.astype('u1'))
- # figure the mask: only do if we can successfully process this
- # column, otherwise ignore the mask
- mask = com.isnull(a.data).all(axis=0)
- masks.append(mask.astype('u1'))
+ # consolidate masks
+ mask = masks[0]
+ for m in masks[1:]:
+ mask = mask & m
+ mask = mask.ravel()
+
+ else:
- # consolidate masks
- mask = masks[0]
- for m in masks[1:]:
- mask = mask & m
- mask = mask.ravel()
+ mask = np.empty(nrows, dtype='u1')
+ mask.fill(False)
# broadcast the indexes if needed
indexes = [a.cvalues for a in self.index_axes]
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index e2d9235510f83..ab7e5cf813b24 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -757,19 +757,40 @@ def test_append_some_nans(self):
store.append('df3', df3[10:])
tm.assert_frame_equal(store['df3'], df3)
- ##### THIS IS A BUG, should not drop these all-nan rows
- ##### BUT need to store the index which we don't want to do....
- # nan some entire rows
+ def test_append_all_nans(self):
+
+ with ensure_clean(self.path) as store:
+
df = DataFrame({'A1' : np.random.randn(20),
'A2' : np.random.randn(20)},
index=np.arange(20))
+ df.ix[0:15,:] = np.nan
+
+
+ # nan some entire rows (dropna=True)
+ _maybe_remove(store, 'df')
+ store.append('df', df[:10], dropna=True)
+ store.append('df', df[10:], dropna=True)
+ tm.assert_frame_equal(store['df'], df[-4:])
+
+ # nan some entire rows (dropna=False)
+ _maybe_remove(store, 'df2')
+ store.append('df2', df[:10], dropna=False)
+ store.append('df2', df[10:], dropna=False)
+ tm.assert_frame_equal(store['df2'], df)
+
+ # tests the option io.hdf.dropna_table
+ pandas.set_option('io.hdf.dropna_table',False)
+ _maybe_remove(store, 'df3')
+ store.append('df3', df[:10])
+ store.append('df3', df[10:])
+ tm.assert_frame_equal(store['df3'], df)
+ pandas.set_option('io.hdf.dropna_table',True)
_maybe_remove(store, 'df4')
- df.ix[0:15,:] = np.nan
store.append('df4', df[:10])
store.append('df4', df[10:])
tm.assert_frame_equal(store['df4'], df[-4:])
- self.assert_(store.get_storer('df4').nrows == 4)
# nan some entire rows (string are still written!)
df = DataFrame({'A1' : np.random.randn(20),
@@ -777,12 +798,17 @@ def test_append_some_nans(self):
'B' : 'foo', 'C' : 'bar'},
index=np.arange(20))
- _maybe_remove(store, 'df5')
df.ix[0:15,:] = np.nan
- store.append('df5', df[:10])
- store.append('df5', df[10:])
- tm.assert_frame_equal(store['df5'], df)
- self.assert_(store.get_storer('df5').nrows == 20)
+
+ _maybe_remove(store, 'df')
+ store.append('df', df[:10], dropna=True)
+ store.append('df', df[10:], dropna=True)
+ tm.assert_frame_equal(store['df'], df)
+
+ _maybe_remove(store, 'df2')
+ store.append('df2', df[:10], dropna=False)
+ store.append('df2', df[10:], dropna=False)
+ tm.assert_frame_equal(store['df2'], df)
# nan some entire rows (but since we have dates they are still written!)
df = DataFrame({'A1' : np.random.randn(20),
@@ -790,12 +816,17 @@ def test_append_some_nans(self):
'B' : 'foo', 'C' : 'bar', 'D' : Timestamp("20010101"), 'E' : datetime.datetime(2001,1,2,0,0) },
index=np.arange(20))
- _maybe_remove(store, 'df6')
df.ix[0:15,:] = np.nan
- store.append('df6', df[:10])
- store.append('df6', df[10:])
- tm.assert_frame_equal(store['df6'], df)
- self.assert_(store.get_storer('df6').nrows == 20)
+
+ _maybe_remove(store, 'df')
+ store.append('df', df[:10], dropna=True)
+ store.append('df', df[10:], dropna=True)
+ tm.assert_frame_equal(store['df'], df)
+
+ _maybe_remove(store, 'df2')
+ store.append('df2', df[:10], dropna=False)
+ store.append('df2', df[10:], dropna=False)
+ tm.assert_frame_equal(store['df2'], df)
def test_append_frame_column_oriented(self):
| closes #4625
also settable via the option io.hdf.dropna_table
retains backward compat
| https://api.github.com/repos/pandas-dev/pandas/pulls/4714 | 2013-08-31T14:09:16Z | 2013-08-31T14:09:35Z | 2013-08-31T14:09:35Z | 2014-07-16T08:25:38Z |
CLN: Remove unused and undocumented kind keyword from read_excel | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4e6ac7240512c..c879d2a030d74 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -203,6 +203,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility
- Refactor of Series arithmetic with time-like objects (datetime/timedelta/time
etc.) into a separate, cleaned up wrapper class. (:issue:`4613`)
+- Remove undocumented/unused ``kind`` keyword argument from ``read_excel``, and ``ExcelFile``. (:issue:`4713`, :issue:`4712`)
**Experimental Features**
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 534a88e303dbf..4f998b49260e6 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -13,9 +13,10 @@
from pandas import json
from pandas.compat import map, zip, reduce, range, lrange
import pandas.compat as compat
+from warnings import warn
-def read_excel(path_or_buf, sheetname, kind=None, **kwds):
+def read_excel(path_or_buf, sheetname, **kwds):
"""Read an Excel table into a pandas DataFrame
Parameters
@@ -50,8 +51,11 @@ def read_excel(path_or_buf, sheetname, kind=None, **kwds):
parsed : DataFrame
DataFrame from the passed in Excel file
"""
- return ExcelFile(path_or_buf, kind=kind).parse(sheetname=sheetname,
- kind=kind, **kwds)
+ if 'kind' in kwds:
+ kwds.pop('kind')
+ warn("kind keyword is no longer supported in read_excel and may be "
+ "removed in a future version", FutureWarning)
+ return ExcelFile(path_or_buf).parse(sheetname=sheetname, **kwds)
class ExcelFile(object):
@@ -64,8 +68,7 @@ class ExcelFile(object):
path : string or file-like object
Path to xls or xlsx file
"""
- def __init__(self, path_or_buf, kind=None, **kwds):
- self.kind = kind
+ def __init__(self, path_or_buf, **kwds):
import xlrd # throw an ImportError if we need to
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 3b132be800cb1..8cf7eaa1b19e3 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1979,6 +1979,6 @@ def __init__(self, path):
super(ExcelWriter, self).__init__(path)
class ExcelFile(excel.ExcelFile):
- def __init__(self, path_or_buf, kind=None, **kwds):
+ def __init__(self, path_or_buf, **kwds):
warn("ExcelFile can now be imported from: pandas.io.excel", FutureWarning)
- super(ExcelFile, self).__init__(path_or_buf, kind=kind, **kwds)
+ super(ExcelFile, self).__init__(path_or_buf, **kwds)
| Pops kwarg and warns if you pass it (rather than passing on).
Fixes #4712
| https://api.github.com/repos/pandas-dev/pandas/pulls/4713 | 2013-08-30T22:19:44Z | 2013-09-01T21:03:40Z | 2013-09-01T21:03:40Z | 2014-06-13T16:05:16Z |
BUG: (GH4708) A zero length series written to HDF cannot be read back. | diff --git a/doc/source/release.rst b/doc/source/release.rst
index ccd5f2ae53294..3b34a5321d899 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -209,6 +209,7 @@ API Changes
- ``HDFStore``
+ - A zero length series written to HDF cannot be read back. (:issue:`4708`)
- ``append_to_multiple`` automatically synchronizes writing rows to multiple
tables and adds a ``dropna`` kwarg (:issue:`4698`)
- handle a passed ``Series`` in table format (:issue:`4330`)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 0fff14013efe4..5b7297c7be2f4 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2213,6 +2213,11 @@ def read_multi_index(self, key):
def read_index_node(self, node):
data = node[:]
+ # If the index was an empty array write_array_empty() will
+ # have written a sentinel. Here we relace it with the original.
+ if 'shape' in node._v_attrs \
+ and self._is_empty_array(getattr(node._v_attrs, 'shape')):
+ data = np.empty(getattr(node._v_attrs, 'shape'), dtype=getattr(node._v_attrs, 'value_type'))
kind = _ensure_decoded(node._v_attrs.kind)
name = None
@@ -2251,12 +2256,16 @@ def write_array_empty(self, key, value):
getattr(self.group, key)._v_attrs.value_type = str(value.dtype)
getattr(self.group, key)._v_attrs.shape = value.shape
+ def _is_empty_array(self, shape):
+ """Returns true if any axis is zero length."""
+ return any(x == 0 for x in shape)
+
def write_array(self, key, value, items=None):
if key in self.group:
self._handle.removeNode(self.group, key)
# Transform needed to interface with pytables row/col notation
- empty_array = any(x == 0 for x in value.shape)
+ empty_array = self._is_empty_array(value.shape)
transposed = False
if not empty_array:
@@ -2305,17 +2314,18 @@ def write_array(self, key, value, items=None):
vlarr = self._handle.createVLArray(self.group, key,
_tables().ObjectAtom())
vlarr.append(value)
- elif value.dtype.type == np.datetime64:
- self._handle.createArray(self.group, key, value.view('i8'))
- getattr(self.group, key)._v_attrs.value_type = 'datetime64'
- elif value.dtype.type == np.timedelta64:
- self._handle.createArray(self.group, key, value.view('i8'))
- getattr(self.group, key)._v_attrs.value_type = 'timedelta64'
else:
if empty_array:
self.write_array_empty(key, value)
else:
- self._handle.createArray(self.group, key, value)
+ if value.dtype.type == np.datetime64:
+ self._handle.createArray(self.group, key, value.view('i8'))
+ getattr(self.group, key)._v_attrs.value_type = 'datetime64'
+ elif value.dtype.type == np.timedelta64:
+ self._handle.createArray(self.group, key, value.view('i8'))
+ getattr(self.group, key)._v_attrs.value_type = 'timedelta64'
+ else:
+ self._handle.createArray(self.group, key, value)
getattr(self.group, key)._v_attrs.transposed = transposed
@@ -2362,11 +2372,7 @@ def shape(self):
def read(self, **kwargs):
self.validate_read(kwargs)
index = self.read_index('index')
- if len(index) > 0:
- values = self.read_array('values')
- else:
- values = []
-
+ values = self.read_array('values')
return Series(values, index=index, name=self.name)
def write(self, obj, **kwargs):
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 4f03f29d77ea3..730a9d907f496 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -2358,6 +2358,11 @@ def test_empty_series_frame(self):
self._check_roundtrip(df1, tm.assert_frame_equal)
self._check_roundtrip(df2, tm.assert_frame_equal)
+ def test_empty_series(self):
+ for dtype in [np.int64, np.float64, np.object, 'm8[ns]', 'M8[ns]']:
+ s = Series(dtype=dtype)
+ self._check_roundtrip(s, tm.assert_series_equal)
+
def test_can_serialize_dates(self):
rng = [x.date() for x in bdate_range('1/1/2000', '1/30/2000')]
| closes #4708 by spotting when the sentinel single value has been written. This was not being done for the index which resulted in a values/index length miss-match.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4709 | 2013-08-30T15:12:15Z | 2013-10-15T12:42:36Z | 2013-10-15T12:42:35Z | 2014-06-23T14:43:41Z |
ENH: Ability to tz localize when index is implicility in tz | diff --git a/doc/source/api.rst b/doc/source/api.rst
index f74f5f0d28a58..5ad36b3c8b45c 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -868,3 +868,149 @@ Serialization / IO / Conversion
Panel.to_frame
Panel.to_clipboard
+.. currentmodule:: pandas.core.index
+
+.. _api.index
+
+Index
+-----
+
+**Many of these methods or variants thereof are available on the objects that contain an index (Series/Dataframe)
+and those should most likely be used before calling these methods directly.**
+
+ * **values**
+Modifying and Computations
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.copy
+ Index.delete
+ Index.diff
+ Index.drop
+ Index.equals
+ Index.identical
+ Index.insert
+ Index.order
+ Index.reindex
+ Index.repeat
+ Index.set_names
+ Index.unique
+
+Conversion
+~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.astype
+ Index.tolist
+ Index.to_datetime
+ Index.to_series
+
+Sorting
+~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.argsort
+ Index.order
+ Index.sort
+
+Time-specific operations
+~~~~~~~~~~~~~~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.shift
+
+Combining / joining / merging
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.append
+ Index.intersection
+ Index.join
+ Index.union
+
+Selecting
+~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.get_indexer
+ Index.get_indexer_non_unique
+ Index.get_level_values
+ Index.get_loc
+ Index.get_value
+ Index.isin
+ Index.slice_indexer
+ Index.slice_locs
+
+Properties
+~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ Index.is_monotonic
+ Index.is_numeric
+
+.. currentmodule:: pandas.tseries.index
+
+.. _api.datetimeindex:
+
+DatetimeIndex
+-------------
+
+Time/Date Components
+~~~~~~~~~~~~~~~~~~~~
+ * **year**
+ * **month**
+ * **day**
+ * **hour**
+ * **minute**
+ * **second**
+ * **microsecond**
+ * **nanosecond**
+
+ * **weekofyear**
+ * **week**: Same as weekofyear
+ * **dayofweek**: (0=Monday, 6=Sunday)
+ * **weekday**: (0=Monday, 6=Sunday)
+ * **dayofyear**
+ * **quarter**
+
+ * **date**: Returns date component of Timestamps
+ * **time**: Returns time component of Timestamps
+
+
+Selecting
+~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ DatetimeIndex.indexer_at_time
+ DatetimeIndex.indexer_between_time
+
+
+Time-specific operations
+~~~~~~~~~~~~~~~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ DatetimeIndex.normalize
+ DatetimeIndex.snap
+ DatetimeIndex.tz_convert
+ DatetimeIndex.tz_localize
+
+
+Conversion
+~~~~~~~~~~
+.. autosummary::
+ :toctree: generated/
+
+ DatetimeIndex.to_datetime
+ DatetimeIndex.to_period
+ DatetimeIndex.to_pydatetime
+
+
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 058ea165120a6..fe21aa4326a07 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -160,6 +160,9 @@ Improvements to existing features
:issue:`4998`)
- ``to_dict`` now takes ``records`` as a possible outtype. Returns an array
of column-keyed dictionaries. (:issue:`4936`)
+ - ``tz_localize`` can infer a fall daylight savings transition based on the
+ structure of unlocalized data (:issue:`4230`)
+ - DatetimeIndex is now in the API documentation
API Changes
~~~~~~~~~~~
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst
index 85ac48c379aad..33b16c1448ed8 100644
--- a/doc/source/timeseries.rst
+++ b/doc/source/timeseries.rst
@@ -1108,6 +1108,20 @@ TimeSeries, aligning the data on the UTC timestamps:
.. _timeseries.timedeltas:
+In some cases, localize cannot determine the DST and non-DST hours when there are
+duplicates. This often happens when reading files that simply duplicate the hours.
+The infer_dst argument in tz_localize will attempt
+to determine the right offset.
+
+.. ipython:: python
+
+ rng_hourly = DatetimeIndex(['11/06/2011 00:00', '11/06/2011 01:00',
+ '11/06/2011 01:00', '11/06/2011 02:00',
+ '11/06/2011 03:00'])
+ rng_hourly.tz_localize('US/Eastern')
+ rng_hourly_eastern = rng_hourly.tz_localize('US/Eastern', infer_dst=True)
+ rng_hourly_eastern.values
+
Time Deltas
-----------
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 90d2989de65c2..9cf944895d64f 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -8,7 +8,7 @@ enhancements along with a large number of bug fixes.
.. warning::
- In 0.13.0 ``Series`` has internaly been refactored to no longer sub-class ``ndarray``
+ In 0.13.0 ``Series`` has internally been refactored to no longer sub-class ``ndarray``
but instead subclass ``NDFrame``, similarly to the rest of the pandas containers. This should be
a transparent change with only very limited API implications. See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
@@ -481,6 +481,10 @@ Enhancements
:ref:`See the docs<indexing.basics.indexing_isin>` for more.
+ - ``tz_localize`` can infer a fall daylight savings transition based on the structure
+ of the unlocalized data (:issue:`4230`), see :ref:`here<timeseries.timezone>`
+ - DatetimeIndex is now in the API documentation, see :ref:`here<api.datetimeindex>`
+
.. _whatsnew_0130.experimental:
Experimental
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3142f74f2f5c5..5ac9d12de8a9a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2752,7 +2752,7 @@ def tz_convert(self, tz, axis=0, copy=True):
return new_obj
- def tz_localize(self, tz, axis=0, copy=True):
+ def tz_localize(self, tz, axis=0, copy=True, infer_dst=False):
"""
Localize tz-naive TimeSeries to target time zone
@@ -2761,6 +2761,8 @@ def tz_localize(self, tz, axis=0, copy=True):
tz : string or pytz.timezone object
copy : boolean, default True
Also make a copy of the underlying data
+ infer_dst : boolean, default False
+ Attempt to infer fall dst-transition times based on order
Returns
-------
@@ -2778,7 +2780,7 @@ def tz_localize(self, tz, axis=0, copy=True):
new_data = new_data.copy()
new_obj = self._constructor(new_data)
- new_ax = ax.tz_localize(tz)
+ new_ax = ax.tz_localize(tz, infer_dst=infer_dst)
if axis == 0:
new_obj._set_axis(1, new_ax)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 79faad93ff1c1..ddbb67cc0c323 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2331,7 +2331,7 @@ def tz_convert(self, tz, copy=True):
return self._constructor(new_values, index=new_index, name=self.name)
- def tz_localize(self, tz, copy=True):
+ def tz_localize(self, tz, copy=True, infer_dst=False):
"""
Localize tz-naive TimeSeries to target time zone
Entries will retain their "naive" value but will be annotated as
@@ -2345,6 +2345,8 @@ def tz_localize(self, tz, copy=True):
tz : string or pytz.timezone object
copy : boolean, default True
Also make a copy of the underlying data
+ infer_dst : boolean, default False
+ Attempt to infer fall dst-transition hours based on order
Returns
-------
@@ -2358,7 +2360,7 @@ def tz_localize(self, tz, copy=True):
new_index = DatetimeIndex([], tz=tz)
else:
- new_index = self.index.tz_localize(tz)
+ new_index = self.index.tz_localize(tz, infer_dst=infer_dst)
new_values = self.values
if copy:
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 24e94f4c2d482..281ac0cc8a35a 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -147,6 +147,7 @@ def __new__(cls, data=None,
dayfirst = kwds.pop('dayfirst', None)
yearfirst = kwds.pop('yearfirst', None)
+ infer_dst = kwds.pop('infer_dst', False)
warn = False
if 'offset' in kwds and kwds['offset']:
freq = kwds['offset']
@@ -183,7 +184,8 @@ def __new__(cls, data=None,
if data is None:
return cls._generate(start, end, periods, name, offset,
- tz=tz, normalize=normalize)
+ tz=tz, normalize=normalize,
+ infer_dst=infer_dst)
if not isinstance(data, np.ndarray):
if np.isscalar(data):
@@ -209,7 +211,7 @@ def __new__(cls, data=None,
data.name = name
if tz is not None:
- return data.tz_localize(tz)
+ return data.tz_localize(tz, infer_dst=infer_dst)
return data
@@ -261,7 +263,8 @@ def __new__(cls, data=None,
getattr(data, 'tz', None) is None):
# Convert tz-naive to UTC
ints = subarr.view('i8')
- subarr = tslib.tz_localize_to_utc(ints, tz)
+ subarr = tslib.tz_localize_to_utc(ints, tz,
+ infer_dst=infer_dst)
subarr = subarr.view(_NS_DTYPE)
@@ -286,7 +289,7 @@ def __new__(cls, data=None,
@classmethod
def _generate(cls, start, end, periods, name, offset,
- tz=None, normalize=False):
+ tz=None, normalize=False, infer_dst=False):
if com._count_not_none(start, end, periods) != 2:
raise ValueError('Must specify two of start, end, or periods')
@@ -375,7 +378,8 @@ def _generate(cls, start, end, periods, name, offset,
index = _generate_regular_range(start, end, periods, offset)
if tz is not None and getattr(index, 'tz', None) is None:
- index = tslib.tz_localize_to_utc(com._ensure_int64(index), tz)
+ index = tslib.tz_localize_to_utc(com._ensure_int64(index), tz,
+ infer_dst=infer_dst)
index = index.view(_NS_DTYPE)
index = index.view(cls)
@@ -1537,9 +1541,17 @@ def tz_convert(self, tz):
# No conversion since timestamps are all UTC to begin with
return self._simple_new(self.values, self.name, self.offset, tz)
- def tz_localize(self, tz):
+ def tz_localize(self, tz, infer_dst=False):
"""
Localize tz-naive DatetimeIndex to given time zone (using pytz)
+
+ Parameters
+ ----------
+ tz : string or pytz.timezone
+ Time zone for time. Corresponding timestamps would be converted to
+ time zone of the TimeSeries
+ infer_dst : boolean, default False
+ Attempt to infer fall dst-transition hours based on order
Returns
-------
@@ -1550,7 +1562,7 @@ def tz_localize(self, tz):
tz = tools._maybe_get_tz(tz)
# Convert to UTC
- new_dates = tslib.tz_localize_to_utc(self.asi8, tz)
+ new_dates = tslib.tz_localize_to_utc(self.asi8, tz, infer_dst=infer_dst)
new_dates = new_dates.view(_NS_DTYPE)
return self._simple_new(new_dates, self.name, self.offset, tz)
diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py
index 80d85241ae0ff..083de95895d18 100644
--- a/pandas/tseries/tests/test_timezones.py
+++ b/pandas/tseries/tests/test_timezones.py
@@ -360,6 +360,32 @@ def test_with_tz_ambiguous_times(self):
dr = date_range(datetime(2011, 3, 13), periods=48,
freq=datetools.Minute(30), tz=pytz.utc)
+ def test_infer_dst(self):
+ # November 6, 2011, fall back, repeat 2 AM hour
+ # With no repeated hours, we cannot infer the transition
+ tz = pytz.timezone('US/Eastern')
+ dr = date_range(datetime(2011, 11, 6, 0), periods=5,
+ freq=datetools.Hour())
+ self.assertRaises(pytz.AmbiguousTimeError, dr.tz_localize,
+ tz, infer_dst=True)
+
+ # With repeated hours, we can infer the transition
+ dr = date_range(datetime(2011, 11, 6, 0), periods=5,
+ freq=datetools.Hour(), tz=tz)
+ di = DatetimeIndex(['11/06/2011 00:00', '11/06/2011 01:00',
+ '11/06/2011 01:00', '11/06/2011 02:00',
+ '11/06/2011 03:00'])
+ localized = di.tz_localize(tz, infer_dst=True)
+ self.assert_(np.array_equal(dr, localized))
+
+ # When there is no dst transition, nothing special happens
+ dr = date_range(datetime(2011, 6, 1, 0), periods=10,
+ freq=datetools.Hour())
+ localized = dr.tz_localize(tz)
+ localized_infer = dr.tz_localize(tz, infer_dst=True)
+ self.assert_(np.array_equal(localized, localized_infer))
+
+
# test utility methods
def test_infer_tz(self):
eastern = pytz.timezone('US/Eastern')
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index a8c27806c2c1e..5f81389f318f8 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1630,7 +1630,7 @@ cpdef ndarray _unbox_utcoffsets(object transinfo):
@cython.boundscheck(False)
@cython.wraparound(False)
-def tz_localize_to_utc(ndarray[int64_t] vals, object tz):
+def tz_localize_to_utc(ndarray[int64_t] vals, object tz, bint infer_dst=False):
"""
Localize tzinfo-naive DateRange to given time zone (using pytz). If
there are ambiguities in the values, raise AmbiguousTimeError.
@@ -1644,7 +1644,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz):
Py_ssize_t i, idx, pos, ntrans, n = len(vals)
int64_t *tdata
int64_t v, left, right
- ndarray[int64_t] result, result_a, result_b
+ ndarray[int64_t] result, result_a, result_b, dst_hours
pandas_datetimestruct dts
# Vectorized version of DstTzInfo.localize
@@ -1701,6 +1701,48 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz):
# timestamp falls to the right side of the DST transition
if v + deltas[pos] == vals[i]:
result_b[i] = v
+
+
+ if infer_dst:
+ dst_hours = np.empty(n, dtype=np.int64)
+ dst_hours.fill(NPY_NAT)
+
+ # Get the ambiguous hours (given the above, these are the hours
+ # where result_a != result_b and neither of them are NAT)
+ both_nat = np.logical_and(result_a != NPY_NAT, result_b != NPY_NAT)
+ both_eq = result_a == result_b
+ trans_idx = np.squeeze(np.nonzero(np.logical_and(both_nat, ~both_eq)))
+ if trans_idx.size == 1:
+ stamp = Timestamp(vals[trans_idx])
+ raise pytz.AmbiguousTimeError("Cannot infer dst time from %s as"
+ "there are no repeated times" % stamp)
+ # Split the array into contiguous chunks (where the difference between
+ # indices is 1). These are effectively dst transitions in different years
+ # which is useful for checking that there is not an ambiguous transition
+ # in an individual year.
+ if trans_idx.size > 0:
+ one_diff = np.where(np.diff(trans_idx)!=1)[0]+1
+ trans_grp = np.array_split(trans_idx, one_diff)
+
+ # Iterate through each day, if there are no hours where the delta is negative
+ # (indicates a repeat of hour) the switch cannot be inferred
+ for grp in trans_grp:
+
+ delta = np.diff(result_a[grp])
+ if grp.size == 1 or np.all(delta>0):
+ stamp = Timestamp(vals[grp[0]])
+ raise pytz.AmbiguousTimeError(stamp)
+
+ # Find the index for the switch and pull from a for dst and b for standard
+ switch_idx = (delta<=0).nonzero()[0]
+ if switch_idx.size > 1:
+ raise pytz.AmbiguousTimeError("There are %i dst switches "
+ "when there should only be 1."
+ % switch_idx.size)
+ switch_idx = switch_idx[0]+1 # Pull the only index and adjust
+ a_idx = grp[:switch_idx]
+ b_idx = grp[switch_idx:]
+ dst_hours[grp] = np.hstack((result_a[a_idx], result_b[b_idx]))
for i in range(n):
left = result_a[i]
@@ -1709,8 +1751,13 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz):
if left == right:
result[i] = left
else:
- stamp = Timestamp(vals[i])
- raise pytz.AmbiguousTimeError(stamp)
+ if infer_dst and dst_hours[i] != NPY_NAT:
+ result[i] = dst_hours[i]
+ else:
+ stamp = Timestamp(vals[i])
+ raise pytz.AmbiguousTimeError("Cannot infer dst time from %r, "\
+ "try using the 'infer_dst' argument"
+ % stamp)
elif left != NPY_NAT:
result[i] = left
elif right != NPY_NAT:
diff --git a/vb_suite/timeseries.py b/vb_suite/timeseries.py
index 353d7afc63cb3..a990a9873cea0 100644
--- a/vb_suite/timeseries.py
+++ b/vb_suite/timeseries.py
@@ -225,3 +225,21 @@ def date_range(start=None, end=None, periods=None, freq=None):
datetimeindex_unique = Benchmark('index.unique()', setup,
start_date=datetime(2012, 7, 1))
+
+# tz_localize with infer argument. This is an attempt to emulate the results
+# of read_csv with duplicated data. Not passing infer_dst will fail
+setup = common_setup + """
+dst_rng = date_range('10/29/2000 1:00:00',
+ '10/29/2000 1:59:59', freq='S')
+index = date_range('10/29/2000', '10/29/2000 00:59:59', freq='S')
+index = index.append(dst_rng)
+index = index.append(dst_rng)
+index = index.append(date_range('10/29/2000 2:00:00',
+ '10/29/2000 3:00:00', freq='S'))
+"""
+
+datetimeindex_infer_dst = \
+Benchmark('index.tz_localize("US/Eastern", infer_dst=True)',
+ setup, start_date=datetime(2013, 9, 30))
+
+
| Fix to issue #4230 which allows to localize an index which is
implicitly in a tz (e.g., reading from a file) by passing imply_dst to
tz_localize.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4706 | 2013-08-29T12:40:13Z | 2013-10-02T20:59:51Z | 2013-10-02T20:59:51Z | 2014-06-20T11:17:26Z |
HDFStore.append_to_multiple doesn't write rows that are all np.nan | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 92042b6fe58c5..67cbe35144461 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -2170,29 +2170,38 @@ multiple tables at once. The idea is to have one table (call it the
selector table) that you index most/all of the columns, and perform your
queries. The other table(s) are data tables with an index matching the
selector table's index. You can then perform a very fast query
-on the selector table, yet get lots of data back. This method works similar to
-having a very wide table, but is more efficient in terms of queries.
+on the selector table, yet get lots of data back. This method is similar to
+having a very wide table, but enables more efficient queries.
-Note, **THE USER IS RESPONSIBLE FOR SYNCHRONIZING THE TABLES**. This
-means, append to the tables in the same order; ``append_to_multiple``
-splits a single object to multiple tables, given a specification (as a
-dictionary). This dictionary is a mapping of the table names to the
-'columns' you want included in that table. Pass a `None` for a single
-table (optional) to let it have the remaining columns. The argument
-``selector`` defines which table is the selector table.
+The ``append_to_multiple`` method splits a given single DataFrame
+into multiple tables according to ``d``, a dictionary that maps the
+table names to a list of 'columns' you want in that table. If `None`
+is used in place of a list, that table will have the remaining
+unspecified columns of the given DataFrame. The argument ``selector``
+defines which table is the selector table (which you can make queries from).
+The argument ``dropna`` will drop rows from the input DataFrame to ensure
+tables are synchronized. This means that if a row for one of the tables
+being written to is entirely ``np.NaN``, that row will be dropped from all tables.
+
+If ``dropna`` is False, **THE USER IS RESPONSIBLE FOR SYNCHRONIZING THE TABLES**.
+Remember that entirely ``np.Nan`` rows are not written to the HDFStore, so if
+you choose to call ``dropna=False``, some tables may have more rows than others,
+and therefore ``select_as_multiple`` may not work or it may return unexpected
+results.
.. ipython:: python
df_mt = DataFrame(randn(8, 6), index=date_range('1/1/2000', periods=8),
columns=['A', 'B', 'C', 'D', 'E', 'F'])
df_mt['foo'] = 'bar'
+ df_mt.ix[1, ('A', 'B')] = np.nan
# you can also create the tables individually
store.append_to_multiple({'df1_mt': ['A', 'B'], 'df2_mt': None },
df_mt, selector='df1_mt')
store
- # indiviual tables were created
+ # individual tables were created
store.select('df1_mt')
store.select('df2_mt')
@@ -2200,7 +2209,6 @@ table (optional) to let it have the remaining columns. The argument
store.select_as_multiple(['df1_mt', 'df2_mt'], where=['A>0', 'B>0'],
selector = 'df1_mt')
-.. _io.hdf5-delete:
Delete from a Table
~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/release.rst b/doc/source/release.rst
index a03b647b310b6..bbadba61c0135 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -95,6 +95,8 @@ pandas 0.13
- ``HDFStore``
+ - ``append_to_multiple`` automatically synchronizes writing rows to multiple
+ tables and adds a ``dropna`` kwarg (:issue:`4698`)
- handle a passed ``Series`` in table format (:issue:`4330`)
- added an ``is_open`` property to indicate if the underlying file handle is_open;
a closed store will now report 'CLOSED' when viewing the store (rather than raising an error)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 600f886c57c65..5ab63d016c3b8 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -786,7 +786,7 @@ def append(self, key, value, format=None, append=True, columns=None, dropna=None
kwargs = self._validate_format(format, kwargs)
self._write_to_group(key, value, append=append, dropna=dropna, **kwargs)
- def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, **kwargs):
+ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, dropna=True, **kwargs):
"""
Append to multiple tables
@@ -798,6 +798,9 @@ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, *
selector : a string that designates the indexable table; all of its columns will
be designed as data_columns, unless data_columns is passed, in which
case these are used
+ data_columns : list of columns to create as data columns, or True to use all columns
+ dropna : if evaluates to True, drop rows from all tables if any single
+ row in each table has all NaN
Notes
-----
@@ -840,6 +843,14 @@ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, *
if data_columns is None:
data_columns = d[selector]
+ # ensure rows are synchronized across the tables
+ if dropna:
+ idxs = (value[cols].dropna(how='all').index for cols in d.values())
+ valid_index = next(idxs)
+ for index in idxs:
+ valid_index = valid_index.intersection(index)
+ value = value.ix[valid_index]
+
# append
for k, v in d.items():
dc = data_columns if k == selector else None
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 66f3d3766ee3e..6941452075f4b 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -2902,6 +2902,32 @@ def test_append_to_multiple(self):
expected = df[(df.A > 0) & (df.B > 0)]
tm.assert_frame_equal(result, expected)
+ def test_append_to_multiple_dropna(self):
+ df1 = tm.makeTimeDataFrame()
+ df2 = tm.makeTimeDataFrame().rename(columns=lambda x: "%s_2" % x)
+ df1.ix[1, ['A', 'B']] = np.nan
+ df = concat([df1, df2], axis=1)
+
+ with ensure_clean(self.path) as store:
+ # dropna=True should guarantee rows are synchronized
+ store.append_to_multiple(
+ {'df1': ['A', 'B'], 'df2': None}, df, selector='df1',
+ dropna=True)
+ result = store.select_as_multiple(['df1', 'df2'])
+ expected = df.dropna()
+ tm.assert_frame_equal(result, expected)
+ tm.assert_index_equal(store.select('df1').index,
+ store.select('df2').index)
+
+ # dropna=False shouldn't synchronize row indexes
+ store.append_to_multiple(
+ {'df1': ['A', 'B'], 'df2': None}, df, selector='df1',
+ dropna=False)
+ self.assertRaises(
+ ValueError, store.select_as_multiple, ['df1', 'df2'])
+ assert not store.select('df1').index.equals(
+ store.select('df2').index)
+
def test_select_as_multiple(self):
df1 = tm.makeTimeDataFrame()
| Hi,
Using HDFStore.append_to_multiple, if an entire row written to any one table consists entirely of np.nan, the row is not written to the table, but is written to the other tables. The following code reproduces and fixes the issue.
I would prefer that append_to_multiple maintain synchronized rows across tables, and to my knowledge, the best way to do that is drop that row from the other tables. We would probably need a fix that looks something like this PR.
I'm not sure if this is the best way to do this, and would love some feedback!
Thanks,
Alex
The Fix:
```
# setup
d = {'table1': ['col1', 'col2'], 'table2': ['col3', 'col4']}
value = pandas.DataFrame([[1,2,3,4], [5,6,None, None]], columns=['col1', 'col2', 'col3', 'col4'])
# fix (as in PR)
dfs = (value[cols] for cols in d.values())
valid_index = reduce(
lambda index1, index2: index2.intersection(index1),
[df.dropna(how='all').index for df in dfs])
value = value.ix[valid_index]
```
To reproduce the error:
```
In [1]: from pandas import DataFrame, HDFStore
In [2]: store = HDFStore('tmp1.h5')
In [3]: df = DataFrame([[1,2], [3,None]], columns=['a', 'b'])
In [4]: store.append_to_multiple({'table1': ['a'], 'table2': ['b']}, df, 'table1')
In [5]: store
Out[5]:
<class 'pandas.io.pytables.HDFStore'>
File path: tmp1.h5
/table1 frame_table (typ->appendable,nrows->2,ncols->1,indexers->[index],dc->[a])
/table2 frame_table (typ->appendable,nrows->1,ncols->1,indexers->[index])
store.select_as_multiple(['table1', 'table2'])
In [6]: store.select_as_multiple(['table1', 'table2'])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-1a2861fcaa34> in <module>()
----> 1 store.select_as_multiple(['table1', 'table2'])
/Users/alexgaudio/.virtualenvs/ds/lib/python2.7/site-packages/pandas/io/pytables.pyc in select_as_multiple(self, keys, where, selector, columns, start, stop, iterator, chunksize, auto_close, **kwargs)
540 nrows = t.nrows
541 elif t.nrows != nrows:
--> 542 raise ValueError("all tables must have exactly the same nrows!")
543
544 # select coordinates from the selector table
ValueError: all tables must have exactly the same nrows!
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4698 | 2013-08-27T23:52:04Z | 2013-09-03T11:08:14Z | 2013-09-03T11:08:14Z | 2014-06-13T04:34:46Z |
ENH: Series.str.extract returns regex matches more conveniently | diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index d0156a6e92f0a..fad62c1a17deb 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -975,6 +975,42 @@ Methods like ``replace`` and ``findall`` take regular expressions, too:
s3
s3.str.replace('^.a|dog', 'XX-XX ', case=False)
+The method ``match`` returns the groups in a regular expression in one tuple.
+ Starting in pandas version 0.13, the method ``extract`` is available to
+accomplish this more conveniently.
+
+Extracting a regular expression with one group returns a Series of strings.
+
+.. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)')
+
+Elements that do not match return ``NaN``. Extracting a regular expression
+with more than one group returns a DataFrame with one column per group.
+
+.. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('([ab])(\d)')
+
+Elements that do not match return a row of ``NaN``s.
+Thus, a Series of messy strings can be "converted" into a
+like-indexed Series or DataFrame of cleaned-up or more useful strings,
+without necessitating ``get()`` to access tuples or ``re.match`` objects.
+
+Named groups like
+
+.. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.match('(?P<letter>[ab])(?P<digit>\d)')
+
+and optional groups like
+
+.. ipython:: python
+
+ Series(['a1', 'b2', '3']).str.match('(?P<letter>[ab])?(?P<digit>\d)')
+
+can also be used.
+
Methods like ``contains``, ``startswith``, and ``endswith`` takes an extra
``na`` arguement so missing values can be considered True or False:
@@ -1003,6 +1039,7 @@ Methods like ``contains``, ``startswith``, and ``endswith`` takes an extra
``endswidth``,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."
``len``,Compute string lengths
``strip``,Equivalent to ``str.strip``
``rstrip``,Equivalent to ``str.rstrip``
diff --git a/doc/source/release.rst b/doc/source/release.rst
index f7755afe8caae..cb8c3aea96308 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -59,6 +59,7 @@ New features
- Added ``isin`` method to DataFrame (:issue:`4211`)
- Clipboard functionality now works with PySide (:issue:`4282`)
+ - New ``extract`` string method returns regex matches more conveniently (:issue:`4685`)
Improvements to existing features
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 4d7a3da8ace2b..83df2a6c5ac1c 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -360,6 +360,38 @@ Enhancements
the bandwidth, and to gkde.evaluate() to specify the indicies at which it
is evaluated, respecttively. See scipy docs.
- DataFrame constructor now accepts a numpy masked record array (:issue:`3478`)
+ - The new vectorized string method ``extract`` return regular expression
+ matches more conveniently.
+
+ .. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)')
+
+ Elements that do not match return ``NaN``. Extracting a regular expression
+ with more than one group returns a DataFrame with one column per group.
+
+
+ .. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.extract('([ab])(\d)')
+
+ Elements that do not match return a row of ``NaN``s.
+ Thus, a Series of messy strings can be "converted" into a
+ like-indexed Series or DataFrame of cleaned-up or more useful strings,
+ without necessitating ``get()`` to access tuples or ``re.match`` objects.
+
+ Named groups like
+
+ .. ipython:: python
+
+ Series(['a1', 'b2', 'c3']).str.match('(?P<letter>[ab])(?P<digit>\d)')
+
+ and optional groups like
+
+ .. ipython:: python
+ Series(['a1', 'b2', '3']).str.match('(?P<letter>[ab])?(?P<digit>\d)')
+
+ can also be used.
.. _whatsnew_0130.experimental:
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 4ba77d118d272..a5a9caa4f542d 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -3,6 +3,7 @@
from pandas.compat import zip
from pandas.core.common import isnull, _values_from_object
from pandas.core.series import Series
+from pandas.core.frame import DataFrame
import pandas.compat as compat
import re
import pandas.lib as lib
@@ -328,6 +329,59 @@ def f(x):
return _na_map(f, arr)
+def str_extract(arr, pat, flags=0):
+ """
+ Find groups in each string (from beginning) using passed regular expression
+
+ Parameters
+ ----------
+ pat : string
+ Pattern or regular expression
+ flags : int, default 0 (no flags)
+ re module flags, e.g. re.IGNORECASE
+
+ Returns
+ -------
+ extracted groups : Series (one group) or DataFrame (multiple groups)
+
+
+ Note
+ ----
+ Compare to the string method match, which returns re.match objects.
+ """
+ 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.match(x)
+ if m:
+ return m.groups()[0] # may be None
+ else:
+ return None
+ else:
+ empty_row = Series(regex.groups*[None])
+ def f(x):
+ if not isinstance(x, compat.string_types):
+ return empty_row
+ m = regex.match(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)
+ return result
def str_join(arr, sep):
"""
@@ -675,8 +729,12 @@ def __iter__(self):
g = self.get(i)
def _wrap_result(self, result):
- return Series(result, index=self.series.index,
- name=self.series.name)
+ assert result.ndim < 3
+ if result.ndim == 1:
+ return Series(result, index=self.series.index,
+ name=self.series.name)
+ else:
+ return DataFrame(result, index=self.series.index)
@copy(str_cat)
def cat(self, others=None, sep=None, na_rep=None):
@@ -764,6 +822,7 @@ def rstrip(self, to_strip=None):
endswith = _pat_wrapper(str_endswith, na=True)
findall = _pat_wrapper(str_findall, flags=True)
match = _pat_wrapper(str_match, flags=True)
+ extract = _pat_wrapper(str_extract, flags=True)
len = _noarg_wrapper(str_len)
lower = _noarg_wrapper(str_lower)
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 4170f34c13095..1be9013ce7575 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -415,6 +415,94 @@ def test_match(self):
exp = Series([(u('BAD__'), u('BAD')), NA, []])
tm.assert_series_equal(result, exp)
+ def test_extract(self):
+ # Contains tests like those in test_match and some others.
+
+ values = Series(['fooBAD__barBAD', NA, 'foo'])
+ er = [NA, NA] # empty row
+
+ result = values.str.extract('.*(BAD[_]+).*(BAD)')
+ exp = DataFrame([['BAD__', 'BAD'], er, er])
+ tm.assert_frame_equal(result, exp)
+
+ # mixed
+ mixed = Series(['aBAD_BAD', NA, 'BAD_b_BAD', True, datetime.today(),
+ 'foo', None, 1, 2.])
+
+ rs = Series(mixed).str.extract('.*(BAD[_]+).*(BAD)')
+ exp = DataFrame([['BAD_', 'BAD'], er, ['BAD_', 'BAD'], er, er,
+ er, er, er, er])
+ tm.assert_frame_equal(rs, exp)
+
+ # unicode
+ values = Series([u('fooBAD__barBAD'), NA, u('foo')])
+
+ result = values.str.extract('.*(BAD[_]+).*(BAD)')
+ exp = DataFrame([[u('BAD__'), u('BAD')], er, er])
+ tm.assert_frame_equal(result, exp)
+
+ # no groups
+ s = Series(['A1', 'B2', 'C3'])
+ f = lambda: s.str.extract('[ABC][123]')
+ self.assertRaises(ValueError, f)
+
+ # only non-capturing groups
+ f = lambda: s.str.extract('(?:[AB]).*')
+ self.assertRaises(ValueError, f)
+
+ # one group, no matches
+ result = s.str.extract('(_)')
+ exp = Series([NA, NA, NA])
+ tm.assert_series_equal(result, exp)
+
+ # two groups, no matches
+ result = s.str.extract('(_)(_)')
+ exp = DataFrame([[NA, NA], [NA, NA], [NA, NA]])
+ tm.assert_frame_equal(result, exp)
+
+ # one group, some matches
+ result = s.str.extract('([AB])[123]')
+ exp = Series(['A', 'B', NA])
+ tm.assert_series_equal(result, exp)
+
+ # two groups, some matches
+ result = s.str.extract('([AB])([123])')
+ exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]])
+ tm.assert_frame_equal(result, exp)
+
+ # named group/groups
+ result = s.str.extract('(?P<letter>[AB])(?P<number>[123])')
+ exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]], columns=['letter', 'number'])
+ tm.assert_frame_equal(result, exp)
+ result = s.str.extract('(?P<letter>[AB])')
+ exp = Series(['A', 'B', NA], name='letter')
+ tm.assert_series_equal(result, exp)
+
+ # mix named and unnamed groups
+ result = s.str.extract('([AB])(?P<number>[123])')
+ exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]], columns=[0, 'number'])
+ tm.assert_frame_equal(result, exp)
+
+ # one normal group, one non-capturing group
+ result = s.str.extract('([AB])(?:[123])')
+ exp = Series(['A', 'B', NA])
+ tm.assert_series_equal(result, exp)
+
+ # two normal groups, one non-capturing group
+ result = Series(['A11', 'B22', 'C33']).str.extract('([AB])([123])(?:[123])')
+ exp = DataFrame([['A', '1'], ['B', '2'], [NA, NA]])
+ tm.assert_frame_equal(result, exp)
+
+ # one optional group followed by one normal group
+ result = Series(['A1', 'B2', '3']).str.extract('(?P<letter>[AB])?(?P<number>[123])')
+ exp = DataFrame([['A', '1'], ['B', '2'], [NA, '3']], columns=['letter', 'number'])
+ tm.assert_frame_equal(result, exp)
+
+ # one normal group followed by one optional group
+ result = Series(['A1', 'B2', 'C']).str.extract('(?P<letter>[ABC])(?P<number>[123])?')
+ exp = DataFrame([['A', '1'], ['B', '2'], ['C', NA]], columns=['letter', 'number'])
+ tm.assert_frame_equal(result, exp)
+
def test_join(self):
values = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])
result = values.str.split('_').str.join('_')
| Closes #4685
| https://api.github.com/repos/pandas-dev/pandas/pulls/4696 | 2013-08-27T19:54:13Z | 2013-09-20T14:37:40Z | 2013-09-20T14:37:39Z | 2014-06-19T09:46:22Z |
ENH: GH3371 support timedelta fillna | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 930f100fd86dc..c24ff6ab0ab30 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -67,6 +67,9 @@ pandas 0.13
- A Series of dtype ``timedelta64[ns]`` can now be divided by another
``timedelta64[ns]`` object to yield a ``float64`` dtyped Series. This
is frequency conversion.
+ - Timedelta64 support ``fillna/ffill/bfill`` with an integer interpreted as seconds,
+ or a ``timedelta`` (:issue:`3371`)
+ - Datetime64 support ``ffill/bfill``
- Performance improvements with ``__getitem__`` on ``DataFrames`` with
when the key is a column
- Support for using a ``DatetimeIndex/PeriodsIndex`` directly in a datelike calculation
@@ -154,6 +157,8 @@ pandas 0.13
- Remove undocumented/unused ``kind`` keyword argument from ``read_excel``, and ``ExcelFile``. (:issue:`4713`, :issue:`4712`)
- The ``method`` argument of ``NDFrame.replace()`` is valid again, so that a
a list can be passed to ``to_replace`` (:issue:`4743`).
+ - provide automatic dtype conversions on _reduce operations (:issue:`3371`)
+ - exclude non-numerics if mixed types with datelike in _reduce operations (:issue:`3371`)
**Internal Refactoring**
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst
index e9540365c3dee..1175fe1c5a3a5 100644
--- a/doc/source/timeseries.rst
+++ b/doc/source/timeseries.rst
@@ -1195,6 +1195,15 @@ issues). ``idxmin, idxmax`` are supported as well.
df.min().idxmax()
df.min(axis=1).idxmin()
+You can fillna on timedeltas. Integers will be interpreted as seconds. You can
+pass a timedelta to get a particular value.
+
+.. ipython:: python
+
+ y.fillna(0)
+ y.fillna(10)
+ y.fillna(timedelta(days=-1,seconds=5))
+
.. _timeseries.timedeltas_convert:
Time Deltas & Conversions
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 6b8b7e73f3ac4..a38ff2fa6d457 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -195,6 +195,7 @@ Enhancements
- NaN handing in get_dummies (:issue:`4446`) with `dummy_na`
.. ipython:: python
+
# previously, nan was erroneously counted as 2 here
# now it is not counted at all
get_dummies([1, 2, np.nan])
@@ -237,10 +238,17 @@ Enhancements
from pandas import offsets
td + offsets.Minute(5) + offsets.Milli(5)
- - ``plot(kind='kde')`` now accepts the optional parameters ``bw_method`` and
- ``ind``, passed to scipy.stats.gaussian_kde() (for scipy >= 0.11.0) to set
- the bandwidth, and to gkde.evaluate() to specify the indicies at which it
- is evaluated, respecttively. See scipy docs.
+ - Fillna is now supported for timedeltas
+
+ .. ipython:: python
+
+ td.fillna(0)
+ td.fillna(timedelta(days=1,seconds=5))
+
+ - ``plot(kind='kde')`` now accepts the optional parameters ``bw_method`` and
+ ``ind``, passed to scipy.stats.gaussian_kde() (for scipy >= 0.11.0) to set
+ the bandwidth, and to gkde.evaluate() to specify the indicies at which it
+ is evaluated, respecttively. See scipy docs.
.. _whatsnew_0130.refactoring:
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 8b9ba4d5eea16..54197e86c961d 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -705,6 +705,54 @@ def diff(arr, n, axis=0):
return out_arr
+def _coerce_scalar_to_timedelta_type(r):
+ # kludgy here until we have a timedelta scalar
+ # handle the numpy < 1.7 case
+
+ if is_integer(r):
+ r = timedelta(microseconds=r/1000)
+
+ if _np_version_under1p7:
+ if not isinstance(r, timedelta):
+ raise AssertionError("Invalid type for timedelta scalar: %s" % type(r))
+ if compat.PY3:
+ # convert to microseconds in timedelta64
+ r = np.timedelta64(int(r.total_seconds()*1e9 + r.microseconds*1000))
+ else:
+ return r
+
+ if isinstance(r, timedelta):
+ r = np.timedelta64(r)
+ elif not isinstance(r, np.timedelta64):
+ raise AssertionError("Invalid type for timedelta scalar: %s" % type(r))
+ return r.astype('timedelta64[ns]')
+
+def _coerce_to_dtypes(result, dtypes):
+ """ given a dtypes and a result set, coerce the result elements to the dtypes """
+ if len(result) != len(dtypes):
+ raise AssertionError("_coerce_to_dtypes requires equal len arrays")
+
+ def conv(r,dtype):
+ try:
+ if isnull(r):
+ pass
+ elif dtype == _NS_DTYPE:
+ r = Timestamp(r)
+ elif dtype == _TD_DTYPE:
+ r = _coerce_scalar_to_timedelta_type(r)
+ elif dtype == np.bool_:
+ r = bool(r)
+ elif dtype.kind == 'f':
+ r = float(r)
+ elif dtype.kind == 'i':
+ r = int(r)
+ except:
+ pass
+
+ return r
+
+ return np.array([ conv(r,dtype) for r, dtype in zip(result,dtypes) ])
+
def _infer_dtype_from_scalar(val):
""" interpret the dtype from a scalar, upcast floats and ints
return the new value and the dtype """
@@ -1288,7 +1336,7 @@ def _possibly_cast_to_timedelta(value, coerce=True):
# coercion compatability
if coerce == 'compat' and _np_version_under1p7:
- def convert(td, type):
+ def convert(td, dtype):
# we have an array with a non-object dtype
if hasattr(td,'item'):
@@ -1317,6 +1365,7 @@ def convert(td, type):
# < 1.7 coercion
if not is_list_like(value):
value = np.array([ value ])
+
dtype = value.dtype
return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]')
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index a3eb3ea54c784..52d3a15d8d184 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -23,7 +23,8 @@
from pandas.core.common import (isnull, notnull, PandasError, _try_sort,
_default_index, _maybe_upcast, _is_sequence,
- _infer_dtype_from_scalar, _values_from_object)
+ _infer_dtype_from_scalar, _values_from_object,
+ _coerce_to_dtypes, _DATELIKE_DTYPES)
from pandas.core.generic import NDFrame
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (_NDFrameIndexer, _maybe_droplevels,
@@ -4235,11 +4236,24 @@ def _reduce(self, op, axis=0, skipna=True, numeric_only=None,
axis = self._get_axis_number(axis)
f = lambda x: op(x, axis=axis, skipna=skipna, **kwds)
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):
+ numeric_only = True
+
if numeric_only is None:
try:
values = self.values
result = f(values)
except Exception as e:
+
+ # try by-column first
+ if filter_type is None and axis == 0:
+ try:
+ return self.apply(f).iloc[0]
+ except:
+ pass
+
if filter_type is None or filter_type == 'numeric':
data = self._get_numeric_data()
elif filter_type == 'bool':
@@ -4273,9 +4287,11 @@ def _reduce(self, op, axis=0, skipna=True, numeric_only=None,
result = result.astype(np.float64)
elif filter_type == 'bool' and notnull(result).all():
result = result.astype(np.bool_)
- # otherwise, accept it
except (ValueError, TypeError):
- pass
+
+ # try to coerce to the original dtypes item by item if we can
+ if axis == 0:
+ result = com._coerce_to_dtypes(result, self.dtypes)
return Series(result, index=labels)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3bdfd98127bb7..58e1fbc4f177d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -20,12 +20,9 @@
_infer_dtype_from_scalar, _maybe_promote,
ABCSeries)
-
-
def is_dictlike(x):
return isinstance(x, (dict, com.ABCSeries))
-
def _single_replace(self, to_replace, method, inplace, limit):
orig_dtype = self.dtype
result = self if inplace else self.copy()
@@ -1906,7 +1903,21 @@ def abs(self):
abs: type of caller
"""
obj = np.abs(self)
- obj = com._possibly_cast_to_timedelta(obj, coerce=False)
+
+ # suprimo numpy 1.6 hacking
+ if com._np_version_under1p7:
+ if self.ndim == 1:
+ if obj.dtype == 'm8[us]':
+ obj = obj.astype('m8[ns]')
+ 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 obj
def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index e27430b06c45c..1716980813cea 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1,6 +1,6 @@
import itertools
import re
-from datetime import datetime
+from datetime import datetime, timedelta
import copy
from collections import defaultdict
@@ -41,6 +41,7 @@ class Block(PandasObject):
is_integer = False
is_complex = False
is_datetime = False
+ is_timedelta = False
is_bool = False
is_object = False
is_sparse = False
@@ -326,6 +327,8 @@ def _maybe_downcast(self, blocks, downcast=None):
# unless indicated
if downcast is None and self.is_float:
return blocks
+ elif downcast is None and (self.is_timedelta or self.is_datetime):
+ return blocks
result_blocks = []
for b in blocks:
@@ -485,6 +488,10 @@ def _try_cast_result(self, result, dtype=None):
# may need to change the dtype here
return _possibly_downcast_to_dtype(result, dtype)
+ def _try_operate(self, values):
+ """ return a version to operate on as the input """
+ return values
+
def _try_coerce_args(self, values, other):
""" provide coercion to our input arguments """
return values, other
@@ -703,8 +710,11 @@ def interpolate(self, method='pad', axis=0, inplace=False,
else:
return [self.copy()]
+ fill_value = self._try_fill(fill_value)
values = self.values if inplace else self.values.copy()
+ values = self._try_operate(values)
values = com.interpolate_2d(values, method, axis, limit, fill_value)
+ values = self._try_coerce_result(values)
blocks = [ make_block(values, self.items, self.ref_items, ndim=self.ndim, klass=self.__class__, fastpath=True) ]
return self._maybe_downcast(blocks, downcast)
@@ -1008,6 +1018,57 @@ def _try_cast(self, element):
def should_store(self, value):
return com.is_integer_dtype(value) and value.dtype == self.dtype
+class TimeDeltaBlock(IntBlock):
+ is_timedelta = True
+ _can_hold_na = True
+ is_numeric = False
+
+ def _try_fill(self, value):
+ """ if we are a NaT, return the actual fill value """
+ if isinstance(value, type(tslib.NaT)) or isnull(value):
+ value = tslib.iNaT
+ elif isinstance(value, np.timedelta64):
+ pass
+ elif com.is_integer(value):
+ # coerce to seconds of timedelta
+ value = np.timedelta64(int(value*1e9))
+ elif isinstance(value, timedelta):
+ value = np.timedelta64(value)
+
+ return value
+
+ def _try_operate(self, values):
+ """ return a version to operate on """
+ return values.view('i8')
+
+ def _try_coerce_result(self, result):
+ """ reverse of try_coerce_args / try_operate """
+ if isinstance(result, np.ndarray):
+ if result.dtype.kind in ['i','f','O']:
+ result = result.astype('m8[ns]')
+ elif isinstance(result, np.integer):
+ result = np.timedelta64(result)
+ return result
+
+ def should_store(self, value):
+ return issubclass(value.dtype.type, np.timedelta64)
+
+ def to_native_types(self, slicer=None, na_rep=None, **kwargs):
+ """ convert to our native types format, slicing if desired """
+
+ values = self.values
+ if slicer is not None:
+ values = values[:, slicer]
+ mask = isnull(values)
+
+ rvalues = np.empty(values.shape, dtype=object)
+ if na_rep is None:
+ na_rep = 'NaT'
+ rvalues[mask] = na_rep
+ imask = (-mask).ravel()
+ rvalues.flat[imask] = np.array([lib.repr_timedelta64(val)
+ for val in values.ravel()[imask]], dtype=object)
+ return rvalues.tolist()
class BoolBlock(NumericBlock):
is_bool = True
@@ -1216,6 +1277,10 @@ def _try_cast(self, element):
except:
return element
+ def _try_operate(self, values):
+ """ return a version to operate on """
+ return values.view('i8')
+
def _try_coerce_args(self, values, other):
""" provide coercion to our input arguments
we are going to compare vs i8, so coerce to integer
@@ -1236,17 +1301,20 @@ def _try_coerce_result(self, result):
if result.dtype == 'i8':
result = tslib.array_to_datetime(
result.astype(object).ravel()).reshape(result.shape)
+ elif result.dtype.kind in ['i','f','O']:
+ result = result.astype('M8[ns]')
elif isinstance(result, (np.integer, np.datetime64)):
result = lib.Timestamp(result)
return result
def _try_fill(self, value):
""" if we are a NaT, return the actual fill value """
- if isinstance(value, type(tslib.NaT)):
+ if isinstance(value, type(tslib.NaT)) or isnull(value):
value = tslib.iNaT
return value
def fillna(self, value, inplace=False, downcast=None):
+ # straight putmask here
values = self.values if inplace else self.values.copy()
mask = com.isnull(self.values)
value = self._try_fill(value)
@@ -1267,12 +1335,9 @@ def to_native_types(self, slicer=None, na_rep=None, **kwargs):
na_rep = 'NaT'
rvalues[mask] = na_rep
imask = (-mask).ravel()
- if self.dtype == 'datetime64[ns]':
- rvalues.flat[imask] = np.array(
- [Timestamp(val)._repr_base for val in values.ravel()[imask]], dtype=object)
- elif self.dtype == 'timedelta64[ns]':
- rvalues.flat[imask] = np.array([lib.repr_timedelta64(val)
- for val in values.ravel()[imask]], dtype=object)
+ rvalues.flat[imask] = np.array(
+ [Timestamp(val)._repr_base for val in values.ravel()[imask]], dtype=object)
+
return rvalues.tolist()
def should_store(self, value):
@@ -1551,6 +1616,8 @@ def make_block(values, items, ref_items, klass=None, ndim=None, dtype=None, fast
klass = SparseBlock
elif issubclass(vtype, np.floating):
klass = FloatBlock
+ elif issubclass(vtype, np.integer) and issubclass(vtype, np.timedelta64):
+ klass = TimeDeltaBlock
elif issubclass(vtype, np.integer) and not issubclass(vtype, np.datetime64):
klass = IntBlock
elif dtype == np.bool_:
@@ -3404,12 +3471,13 @@ def _lcd_dtype(l):
have_float = len(counts[FloatBlock]) > 0
have_complex = len(counts[ComplexBlock]) > 0
have_dt64 = len(counts[DatetimeBlock]) > 0
+ have_td64 = len(counts[TimeDeltaBlock]) > 0
have_sparse = len(counts[SparseBlock]) > 0
have_numeric = have_float or have_complex or have_int
if (have_object or
(have_bool and have_numeric) or
- (have_numeric and have_dt64)):
+ (have_numeric and (have_dt64 or have_td64))):
return np.dtype(object)
elif have_bool:
return np.dtype(bool)
@@ -3432,6 +3500,8 @@ def _lcd_dtype(l):
elif have_dt64 and not have_float and not have_complex:
return np.dtype('M8[ns]')
+ elif have_td64 and not have_float and not have_complex:
+ return np.dtype('m8[ns]')
elif have_complex:
return np.dtype('c16')
else:
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 3e247caae9c42..3a185ca83604d 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -287,8 +287,7 @@ def nanmin(values, axis=None, skipna=True):
values, mask, dtype = _get_values(values, skipna, fill_value_typ = '+inf')
# numpy 1.6.1 workaround in Python 3.x
- if (values.dtype == np.object_
- and sys.version_info[0] >= 3): # pragma: no cover
+ if (values.dtype == np.object_ and compat.PY3):
if values.ndim > 1:
apply_ax = axis if axis is not None else 0
result = np.apply_along_axis(builtins.min, apply_ax, values)
@@ -311,8 +310,7 @@ def nanmax(values, axis=None, skipna=True):
values, mask, dtype = _get_values(values, skipna, fill_value_typ ='-inf')
# numpy 1.6.1 workaround in Python 3.x
- if (values.dtype == np.object_
- and sys.version_info[0] >= 3): # pragma: no cover
+ if (values.dtype == np.object_ and compat.PY3):
if values.ndim > 1:
apply_ax = axis if axis is not None else 0
diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx
index 39334e95e8c81..e0bbc1a4e64c1 100644
--- a/pandas/src/inference.pyx
+++ b/pandas/src/inference.pyx
@@ -480,6 +480,9 @@ 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 util.is_integer_object(val):
seen_int = 1
floats[i] = <float64_t> val
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index bb76547da0c28..cefe15952d329 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3232,25 +3232,43 @@ def test_operators_timedelta64(self):
result = diffs.max(axis=1)
self.assert_((result == diffs['A']).all() == True)
- # abs ###### THIS IS BROKEN NOW ###### (results are dtype=timedelta64[us]
- # even though fixed in series
- #result = np.abs(df['A']-df['B'])
- #result = diffs.abs()
- #expected = DataFrame(dict(A = df['A']-df['C'],
- # B = df['B']-df['A']))
- #assert_frame_equal(result,expected)
+ # abs
+ result = diffs.abs()
+ expected = DataFrame(dict(A = df['A']-df['C'],
+ B = df['B']-df['A']))
+ assert_frame_equal(result,expected)
# mixed frame
mixed = diffs.copy()
mixed['C'] = 'foo'
mixed['D'] = 1
mixed['E'] = 1.
+ mixed['F'] = Timestamp('20130101')
- # this is ok
+ # results in an object array
result = mixed.min()
+ expected = Series([com._coerce_scalar_to_timedelta_type(timedelta(seconds=5*60+5)),
+ com._coerce_scalar_to_timedelta_type(timedelta(days=-1)),
+ 'foo',
+ 1,
+ 1.0,
+ Timestamp('20130101')],
+ index=mixed.columns)
+ assert_series_equal(result,expected)
- # this is not
+ # excludes numeric
result = mixed.min(axis=1)
+ expected = Series([1, 1, 1.],index=[0, 1, 2])
+ assert_series_equal(result,expected)
+
+ # works when only those columns are selected
+ result = mixed[['A','B']].min(1)
+ expected = Series([ timedelta(days=-1) ] * 3)
+ assert_series_equal(result,expected)
+
+ result = mixed[['A','B']].min()
+ expected = Series([ timedelta(seconds=5*60+5), timedelta(days=-1) ],index=['A','B'])
+ assert_series_equal(result,expected)
# GH 3106
df = DataFrame({'time' : date_range('20130102',periods=5),
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 4d86e8ae4a25b..b0911ed10be20 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2405,6 +2405,78 @@ def test_timedelta64_functions(self):
expected = Series([timedelta(1)], dtype='timedelta64[ns]')
assert_series_equal(result, expected)
+ def test_timedelta_fillna(self):
+ if com._np_version_under1p7:
+ raise nose.SkipTest("timedelta broken in np 1.6.1")
+
+ #GH 3371
+ from datetime import timedelta
+
+ s = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130102'),Timestamp('20130103 9:01:01')])
+ td = s.diff()
+
+ # reg fillna
+ result = td.fillna(0)
+ expected = Series([timedelta(0),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)])
+ assert_series_equal(result,expected)
+
+ # interprested as seconds
+ result = td.fillna(1)
+ expected = Series([timedelta(seconds=1),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)])
+ assert_series_equal(result,expected)
+
+ result = td.fillna(timedelta(days=1,seconds=1))
+ expected = Series([timedelta(days=1,seconds=1),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)])
+ assert_series_equal(result,expected)
+
+ result = td.fillna(np.timedelta64(int(1e9)))
+ expected = Series([timedelta(seconds=1),timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)])
+ assert_series_equal(result,expected)
+
+ from pandas import tslib
+ result = td.fillna(tslib.NaT)
+ expected = Series([tslib.NaT,timedelta(0),timedelta(1),timedelta(days=1,seconds=9*3600+60+1)],dtype='m8[ns]')
+ assert_series_equal(result,expected)
+
+ # ffill
+ td[2] = np.nan
+ result = td.ffill()
+ expected = td.fillna(0)
+ expected[0] = np.nan
+ assert_series_equal(result,expected)
+
+ # bfill
+ td[2] = np.nan
+ result = td.bfill()
+ expected = td.fillna(0)
+ expected[2] = timedelta(days=1,seconds=9*3600+60+1)
+ assert_series_equal(result,expected)
+
+ def test_datetime64_fillna(self):
+
+ s = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130102'),Timestamp('20130103 9:01:01')])
+ s[2] = np.nan
+
+ # reg fillna
+ result = s.fillna(Timestamp('20130104'))
+ expected = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130104'),Timestamp('20130103 9:01:01')])
+ assert_series_equal(result,expected)
+
+ from pandas import tslib
+ result = s.fillna(tslib.NaT)
+ expected = s
+ assert_series_equal(result,expected)
+
+ # ffill
+ result = s.ffill()
+ expected = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130103 9:01:01')])
+ assert_series_equal(result,expected)
+
+ # bfill
+ result = s.bfill()
+ expected = Series([Timestamp('20130101'),Timestamp('20130101'),Timestamp('20130103 9:01:01'),Timestamp('20130103 9:01:01')])
+ assert_series_equal(result,expected)
+
def test_sub_of_datetime_from_TimeSeries(self):
from pandas.core import common as com
from datetime import datetime
@@ -4205,16 +4277,14 @@ def test_reindex_corner(self):
def test_reindex_pad(self):
- s = Series(np.arange(10), np.arange(10))
+ s = Series(np.arange(10))
s2 = s[::2]
reindexed = s2.reindex(s.index, method='pad')
reindexed2 = s2.reindex(s.index, method='ffill')
assert_series_equal(reindexed, reindexed2)
- # used platform int above, need to pass int explicitly here per #1219
- expected = Series([0, 0, 2, 2, 4, 4, 6, 6, 8, 8], dtype=int,
- index=np.arange(10))
+ expected = Series([0, 0, 2, 2, 4, 4, 6, 6, 8, 8], index=np.arange(10))
assert_series_equal(reindexed, expected)
# GH4604
@@ -4624,7 +4694,7 @@ def test_replace_with_single_list(self):
assert_series_equal(s, ser)
def test_replace_mixed_types(self):
- s = Series(np.arange(5))
+ s = Series(np.arange(5),dtype='int64')
def check_replace(to_rep, val, expected):
sc = s.copy()
| closes #3371
- ENH: GH3371 support timedelta fillna
- BUG: add support for datetime64 ffill/bfill
- INT: add TimeDeltaBlock support in internals
```
In [3]: s = Series([Timestamp('20130101'),Timestamp('20130101'),
Timestamp('20130102'),Timestamp('20130103 9:01:01')])
In [4]: td = s.diff()
In [5]: td
Out[5]:
0 NaT
1 00:00:00
2 1 days, 00:00:00
3 1 days, 09:01:01
dtype: timedelta64[ns]
In [6]: td.fillna(0)
Out[6]:
0 00:00:00
1 00:00:00
2 1 days, 00:00:00
3 1 days, 09:01:01
dtype: timedelta64[ns]
In [7]: from datetime import timedelta
In [8]: td.fillna(timedelta(days=3,seconds=5))
Out[8]:
0 3 days, 00:00:05
1 00:00:00
2 1 days, 00:00:00
3 1 days, 09:01:01
dtype: timedelta64[ns]
```
ffill
```
In [9]: td[2] = np.nan
In [10]: td
Out[10]:
0 NaT
1 00:00:00
2 NaT
3 1 days, 09:01:01
dtype: timedelta64[ns]
In [11]: td.ffill()
Out[11]:
0 NaT
1 00:00:00
2 00:00:00
3 1 days, 09:01:01
dtype: timedelta64[ns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4684 | 2013-08-27T01:48:45Z | 2013-09-08T19:46:53Z | 2013-09-08T19:46:53Z | 2014-09-05T14:39:46Z |
BUG: preserve empty dtype if possible when creating an empty BlockManager | diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index fde9421e4a3f9..4344b2542ffd6 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1582,7 +1582,10 @@ def make_empty(self, axes=None):
""" return an empty BlockManager with the items axis of len 0 """
if axes is None:
axes = [_ensure_index([]) ] + [ _ensure_index(a) for a in self.axes[1:] ]
- return self.__class__(np.array([]), axes)
+
+ # preserve dtype if possible
+ dtype = self.dtype if self.ndim == 1 else object
+ return self.__class__(np.array([],dtype=dtype), axes)
def __nonzero__(self):
return True
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index be27bab46dc47..f388c5d72627c 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -129,6 +129,31 @@ def test_rename_mi(self):
index=MultiIndex.from_tuples([("A",x) for x in ["a","B","c"]]))
result = s.rename(str.lower)
+ def test_get_numeric_data_preserve_dtype(self):
+
+ # get the numeric data
+ o = Series([1,2,3])
+ result = o._get_numeric_data()
+ self._compare(result, o)
+
+ o = Series([1,'2',3.])
+ result = o._get_numeric_data()
+ expected = Series([],dtype=object)
+ self._compare(result, expected)
+
+ o = Series([True,False,True])
+ result = o._get_numeric_data()
+ self._compare(result, o)
+
+ o = Series([True,False,True])
+ result = o._get_bool_data()
+ self._compare(result, o)
+
+ o = Series(date_range('20130101',periods=3))
+ result = o._get_numeric_data()
+ expected = Series([],dtype='M8[ns]')
+ self._compare(result, expected)
+
class TestDataFrame(unittest.TestCase, Generic):
_typ = DataFrame
_comparator = lambda self, x, y: assert_frame_equal(x,y)
@@ -138,6 +163,14 @@ def test_rename_mi(self):
index=MultiIndex.from_tuples([("A",x) for x in ["a","B","c"]]))
result = df.rename(str.lower)
+ def test_get_numeric_data_preserve_dtype(self):
+
+ # get the numeric data
+ o = DataFrame({'A' : [1,'2',3.] })
+ result = o._get_numeric_data()
+ expected = DataFrame(index=[0,1,2],dtype=object)
+ self._compare(result, expected)
+
class TestPanel(unittest.TestCase, Generic):
_typ = Panel
_comparator = lambda self, x, y: assert_panel_equal(x,y)
| https://api.github.com/repos/pandas-dev/pandas/pulls/4677 | 2013-08-26T19:24:58Z | 2013-08-26T19:42:24Z | 2013-08-26T19:42:24Z | 2014-07-16T08:25:08Z | |
BUG: GH 4667 setitem error/dtype wrong with Series/Frame when setting with None | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 721276dd383e8..16179cdeca052 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -285,6 +285,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix an issue with CacheableOffset not properly being used by many DateOffset; this prevented
the DateOffset from being cached (:issue:`4609`)
- Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs (:issue:`4576`)
+ - Fix error/dtype conversion with setitem of ``None`` on ``Series/DataFrame`` (:issue:`4667`)
pandas 0.12
===========
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index cec80b679781c..fde9421e4a3f9 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -564,6 +564,10 @@ def putmask(self, mask, new, inplace=False):
mask = mask.reindex_axis(
self.items, axis=axis, copy=False).values.T
+ # if we are passed a scalar None, convert it here
+ if not is_list_like(new) and isnull(new):
+ new = np.nan
+
if self._can_hold_element(new):
new = self._try_cast(new)
np.putmask(new_values, mask, new)
@@ -578,7 +582,7 @@ def create_block(v, m, n, item, reshape=True):
""" return a new block, try to preserve dtype if possible """
# n should the length of the mask or a scalar here
- if np.isscalar(n):
+ if not is_list_like(n):
n = np.array([n] * len(m))
# see if we are only masking values that if putted
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index c1d5f07bde2f6..8e44cd4812131 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7867,6 +7867,14 @@ def test_where_datetime(self):
expected.loc[[0,1],'A'] = np.nan
assert_frame_equal(result,expected)
+ def test_where_none(self):
+ # GH 4667
+ # setting with None changes dtype
+ df = DataFrame({'series': Series(range(10))}).astype(float)
+ df[df > 7] = None
+ expected = DataFrame({'series': Series([0,1,2,3,4,5,6,7,np.nan,np.nan]) })
+ assert_frame_equal(df, expected)
+
def test_mask(self):
df = DataFrame(np.random.randn(5, 3))
cond = df > 0
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index e0780e8674600..174092cc12e03 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1249,6 +1249,19 @@ def f():
expected = Series([np.nan,np.nan,3,4])
assert_series_equal(result, expected)
+ # GH 4667
+ # setting with None changes dtype
+ s = Series(range(10)).astype(float)
+ s[8] = None
+ result = s[8]
+ self.assert_(isnull(result))
+
+ s = Series(range(10)).astype(float)
+ s[s > 8] = None
+ result = s[isnull(s)]
+ expected = Series(np.nan,index=[9])
+ assert_series_equal(result, expected)
+
def test_where_broadcast(self):
# Test a variety of differently sized series
for size in range(2, 6):
| closes #4667
| https://api.github.com/repos/pandas-dev/pandas/pulls/4676 | 2013-08-26T15:03:13Z | 2013-08-26T15:18:22Z | 2013-08-26T15:18:22Z | 2014-06-23T23:12:27Z |
CLN/API: Refactor of _get_numeric_data/_get_bool_data to core/generic.py, allowing Series/Panel functionaility | diff --git a/doc/source/release.rst b/doc/source/release.rst
index c572aa91c18bb..721276dd383e8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -193,6 +193,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue:`4605`), and adds ``rename``
with the same signature for ``Panel``
- Series (for index) / Panel (for items) now as attribute access to its elements (:issue:`1903`)
+- Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility
**Experimental Features**
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index c0e3f5e6b2f10..16ae57310dae7 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -268,6 +268,7 @@ and behaviors. Series formerly subclassed directly from ``ndarray``. (:issue:`40
- ``Series.copy`` no longer accepts the ``order`` parameter and is now consistent with ``NDFrame`` copy
- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue`4605`), and adds ``rename``
with the same signature for ``Panel``
+- Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility
- ``Series`` (for index) / ``Panel`` (for items) now allow attribute access to its elements (:issue:`1903`)
.. ipython:: python
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 31f7179f8e328..9f470d536e765 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4388,12 +4388,6 @@ def _get_agg_axis(self, axis_num):
else:
raise Exception('Must have 0<= axis <= 1')
- def _get_numeric_data(self):
- return self._constructor(self._data.get_numeric_data(), index=self.index, copy=False)
-
- def _get_bool_data(self):
- return self._constructor(self._data.get_bool_data(), index=self.index, copy=False)
-
def quantile(self, q=0.5, axis=0, numeric_only=True):
"""
Return values at the given quantile over requested axis, a la
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 56c37ff3c7a0a..d15ce05e84d40 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1319,6 +1319,12 @@ def _protect_consolidate(self, f):
self._clear_item_cache()
return result
+ def _get_numeric_data(self):
+ return self._constructor(self._data.get_numeric_data())
+
+ def _get_bool_data(self):
+ return self._constructor(self._data.get_bool_data())
+
#----------------------------------------------------------------------
# Internal Interface Methods
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 5a5c541fc3251..cec80b679781c 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1574,9 +1574,11 @@ def __init__(self, blocks, axes, do_integrity_check=True, fastpath=True):
if not self.items.is_unique:
self._set_ref_locs(do_refs=True)
- @classmethod
- def make_empty(cls):
- return cls([], [[], []])
+ def make_empty(self, axes=None):
+ """ return an empty BlockManager with the items axis of len 0 """
+ if axes is None:
+ axes = [_ensure_index([]) ] + [ _ensure_index(a) for a in self.axes[1:] ]
+ return self.__class__(np.array([]), axes)
def __nonzero__(self):
return True
@@ -2074,7 +2076,7 @@ def get_data(self, copy=False, columns=None, **kwargs):
blocks = self.get_block_map(
typ='list', copy=copy, columns=columns, **kwargs)
if len(blocks) == 0:
- return self.__class__.make_empty()
+ return self.make_empty()
return self.combine(blocks)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index d2ca850f0a1c0..c1d5f07bde2f6 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -10667,8 +10667,8 @@ def test_tslib_tz_convert_trans_pos_plus_1__bug(self):
test_vector = pd.Series([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 5], dtype=int)
hours = idx.hour
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index 9a147b4e69f38..be27bab46dc47 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -36,16 +36,43 @@ def setUp(self):
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning)
+ @property
+ def _ndim(self):
+ return self._typ._AXIS_LEN
+
def _axes(self):
""" return the axes for my object typ """
return self._typ._AXIS_ORDERS
- def _construct(self, shape=None, **kwargs):
- """ construct an object for the given shape """
+ def _construct(self, shape, value=None, **kwargs):
+ """ construct an object for the given shape
+ if value is specified use that if its a scalar
+ if value is an array, repeat it as needed """
if isinstance(shape,int):
- shape = tuple([shape] * self._typ._AXIS_LEN)
- return self._typ(np.random.randn(*shape),**kwargs)
+ shape = tuple([shape] * self._ndim)
+ if value is not None:
+ if np.isscalar(value):
+ if value == 'empty':
+ arr = None
+
+ # remove the info axis
+ kwargs.pop(self._typ._info_axis_name,None)
+ else:
+ arr = np.empty(shape)
+ arr.fill(value)
+ else:
+ fshape = np.prod(shape)
+ arr = value.ravel()
+ new_shape = fshape/arr.shape[0]
+ if fshape % arr.shape[0] != 0:
+ raise Exception("invalid value passed in _construct")
+
+ arr = np.repeat(arr,new_shape).reshape(shape)
+ else:
+ arr = np.random.randn(*shape)
+ return self._typ(arr,**kwargs)
+
def _compare(self, result, expected):
self._comparator(result,expected)
@@ -68,6 +95,31 @@ def test_rename(self):
# multiple axes at once
+ def test_get_numeric_data(self):
+
+ n = 4
+ kwargs = { }
+ for i in range(self._ndim):
+ kwargs[self._typ._AXIS_NAMES[i]] = list(range(n))
+
+ # get the numeric data
+ o = self._construct(n,**kwargs)
+ result = o._get_numeric_data()
+ self._compare(result, o)
+
+ # non-inclusion
+ result = o._get_bool_data()
+ expected = self._construct(n,value='empty',**kwargs)
+ self._compare(result,expected)
+
+ # get the bool data
+ arr = np.array([True,True,False,True])
+ o = self._construct(n,value=arr,**kwargs)
+ result = o._get_numeric_data()
+ self._compare(result, o)
+
+ # _get_numeric_data is includes _get_bool_data, so can't test for non-inclusion
+
class TestSeries(unittest.TestCase, Generic):
_typ = Series
_comparator = lambda self, x, y: assert_series_equal(x,y)
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 9ae88c071eb27..3fbdedf0c5dd0 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -932,21 +932,7 @@ def _get_layout(self):
return (len(self.data.columns), 1)
def _compute_plot_data(self):
- try:
- # might be an ndframe
- numeric_data = self.data._get_numeric_data()
- except AttributeError: # TODO: rm in 0.13 (series-inherit-ndframe)
- numeric_data = self.data
- orig_dtype = numeric_data.dtype
-
- # possible object array of numeric data
- if orig_dtype == np.object_:
- numeric_data = numeric_data.convert_objects() # soft convert
-
- # still an object dtype so we can't plot it
- if numeric_data.dtype == np.object_:
- raise TypeError('Series has object dtype and cannot be'
- ' converted: no numeric data to plot')
+ numeric_data = self.data.convert_objects()._get_numeric_data()
try:
is_empty = numeric_data.empty
| https://api.github.com/repos/pandas-dev/pandas/pulls/4675 | 2013-08-26T14:02:38Z | 2013-08-26T14:42:20Z | 2013-08-26T14:42:20Z | 2014-07-16T08:25:04Z | |
Groupby as index | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 14ed2cab10eac..4d810e834b2a8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -217,6 +217,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
of a duplicate index (:issue:`4359`)
- In ``to_json``, fix date handling so milliseconds are the default timestamp
as the docstring says (:issue:`4362`).
+ - ``as_index`` is no longer ignored when doing groupby apply (:issue:`4648`), (:issue:`3417`)
- JSON NaT handling fixed, NaTs are now serialised to `null` (:issue:`4498`)
- Fixed JSON handling of escapable characters in JSON object keys (:issue:`4593`)
- Fixed passing ``keep_default_na=False`` when ``na_values=None`` (:issue:`4318`)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 1f15f1a8ae10d..f0ba0c3b54f4a 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -516,7 +516,7 @@ def _concat_objects(self, keys, values, not_indexed_same=False):
result = result.reindex(ax)
else:
result = result.reindex_axis(ax, axis=self.axis)
- elif self.group_keys:
+ elif self.group_keys and self.as_index:
group_keys = keys
group_levels = self.grouper.levels
group_names = self.grouper.names
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 9e7cdf9df2c6b..4bd44fcf26bb3 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -12,7 +12,8 @@
from pandas.core.groupby import GroupByError, SpecificationError, DataError
from pandas.core.series import Series
from pandas.util.testing import (assert_panel_equal, assert_frame_equal,
- assert_series_equal, assert_almost_equal)
+ assert_series_equal, assert_almost_equal,
+ assert_index_equal)
from pandas.compat import(
range, long, lrange, StringIO, lmap, lzip, map, zip, builtins, OrderedDict
)
@@ -1178,6 +1179,34 @@ def test_groupby_as_index_corner(self):
self.assertRaises(ValueError, self.df.groupby,
lambda x: x.lower(), as_index=False, axis=1)
+ def test_groupby_as_index_apply(self):
+ # GH #4648 and #3417
+ df = DataFrame({'item_id': ['b', 'b', 'a', 'c', 'a', 'b'],
+ 'user_id': [1,2,1,1,3,1],
+ 'time': range(6)})
+
+ g_as = df.groupby('user_id', as_index=True)
+ g_not_as = df.groupby('user_id', as_index=False)
+
+ res_as = g_as.head(2).index
+ exp_as = MultiIndex.from_tuples([(1, 0), (1, 2), (2, 1), (3, 4)])
+ assert_index_equal(res_as, exp_as)
+
+ res_not_as = g_not_as.head(2).index
+ exp_not_as = Index([0, 2, 1, 4])
+ assert_index_equal(res_not_as, exp_not_as)
+
+ res_as = g_as.apply(lambda x: x.head(2)).index
+ assert_index_equal(res_not_as, exp_not_as)
+
+ res_not_as = g_not_as.apply(lambda x: x.head(2)).index
+ assert_index_equal(res_not_as, exp_not_as)
+
+ ind = Index(list('abcde'))
+ df = DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=ind)
+ res = df.groupby(0, as_index=False).apply(lambda x: x).index
+ assert_index_equal(res, ind)
+
def test_groupby_multiple_key(self):
df = tm.makeTimeDataFrame()
grouped = df.groupby([lambda x: x.year,
| closes #4648
closes #3417
closes #4649 (pr)
```
In [1]: df = pd.DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=list('abcde'))
In [2]: g = df.groupby(0, as_index=False)
In [3]: g.apply(lambda x: x)
Out[3]:
0 1
a 1 2
b 2 3
c 1 4
d 1 5
e 2 6
In [4]: g.head(2)
Out[4]:
0 1
a 1 2
c 1 4
b 2 3
e 2 6
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4670 | 2013-08-25T19:42:22Z | 2013-08-27T00:20:23Z | 2013-08-27T00:20:23Z | 2014-06-24T02:01:04Z |
ENH: In HDFStore, handle a passed Series in table format (GH4330) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 159deaabb943f..64888e2c6a00c 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -83,6 +83,7 @@ pandas 0.13
- ``HDFStore``
+ - handle a passed ``Series`` in table format (:issue:`4330`)
- added an ``is_open`` property to indicate if the underlying file handle is_open;
a closed store will now report 'CLOSED' when viewing the store (rather than raising an error)
(:issue:`4409`)
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 7ccda591da733..5003aa654d9fb 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -39,6 +39,7 @@ API changes
- ``HDFStore``
- Significant table writing performance improvements
+ - handle a passed ``Series`` in table format (:issue:`4330`)
- added an ``is_open`` property to indicate if the underlying file handle is_open;
a closed store will now report 'CLOSED' when viewing the store (rather than raising an error)
(:issue:`4409`)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 3d5ba43943e98..608bbe4703272 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -126,6 +126,8 @@ class DuplicateWarning(Warning):
# table class map
_TABLE_MAP = {
u('generic_table') : 'GenericTable',
+ u('appendable_series') : 'AppendableSeriesTable',
+ u('appendable_multiseries'): 'AppendableMultiSeriesTable',
u('appendable_frame') : 'AppendableFrameTable',
u('appendable_multiframe') : 'AppendableMultiFrameTable',
u('appendable_panel') : 'AppendablePanelTable',
@@ -913,7 +915,14 @@ def error(t):
# if we are a writer, determin the tt
if value is not None:
- if pt == u('frame_table'):
+ if pt == u('series_table'):
+ index = getattr(value,'index',None)
+ if index is not None:
+ if index.nlevels == 1:
+ tt = u('appendable_series')
+ elif index.nlevels > 1:
+ tt = u('appendable_multiseries')
+ elif pt == u('frame_table'):
index = getattr(value,'index',None)
if index is not None:
if index.nlevels == 1:
@@ -1692,6 +1701,10 @@ def copy(self):
new_self = copy.copy(self)
return new_self
+ @property
+ def storage_obj_type(self):
+ return self.obj_type
+
@property
def shape(self):
return self.nrows
@@ -2369,6 +2382,11 @@ def validate(self, other):
# should never get here
raise Exception("invalid combinate of [%s] on appending data [%s] vs current table [%s]" % (c,sv,ov))
+ @property
+ def is_multi_index(self):
+ """ the levels attribute is 1 or a list in the case of a multi-index """
+ return isinstance(self.levels,list)
+
@property
def nrows_expected(self):
""" based on our axes, compute the expected nrows """
@@ -2419,7 +2437,7 @@ def queryables(self):
# compute the values_axes queryables
return dict([(a.cname, a.kind) for a in self.index_axes] +
- [(self.obj_type._AXIS_NAMES[axis], None) for axis, values in self.non_index_axes] +
+ [(self.storage_obj_type._AXIS_NAMES[axis], None) for axis, values in self.non_index_axes] +
[(v.cname, v.kind) for v in self.values_axes if v.name in set(self.data_columns)]
)
@@ -3277,6 +3295,62 @@ def read(self, where=None, columns=None, **kwargs):
return df
+class AppendableSeriesTable(AppendableFrameTable):
+ """ support the new appendable table formats """
+ pandas_kind = u('series_table')
+ table_type = u('appendable_series')
+ ndim = 2
+ obj_type = Series
+ storage_obj_type = DataFrame
+
+ @property
+ def is_transposed(self):
+ return False
+
+ def get_object(self, obj):
+ return obj
+
+ def write(self, obj, data_columns=None, **kwargs):
+ """ we are going to write this as a frame table """
+ if not isinstance(obj, DataFrame):
+ name = obj.name or 'values'
+ obj = DataFrame({ name : obj }, index=obj.index)
+ obj.columns = [name]
+ return super(AppendableSeriesTable, self).write(obj=obj, data_columns=obj.columns, **kwargs)
+
+ def read(self, columns=None, **kwargs):
+
+ is_multi_index = self.is_multi_index
+ if columns is not None and is_multi_index:
+ for n in self.levels:
+ if n not in columns:
+ columns.insert(0, n)
+ s = super(AppendableSeriesTable, self).read(columns=columns, **kwargs)
+ if is_multi_index:
+ s.set_index(self.levels, inplace=True)
+
+ s = s.iloc[:,0]
+
+ # remove the default name
+ if s.name == 'values':
+ s.name = None
+ return s
+
+class AppendableMultiSeriesTable(AppendableSeriesTable):
+ """ support the new appendable table formats """
+ pandas_kind = u('series_table')
+ table_type = u('appendable_multiseries')
+
+ def write(self, obj, **kwargs):
+ """ we are going to write this as a frame table """
+ name = obj.name or 'values'
+ cols = list(obj.index.names)
+ cols.append(name)
+ self.levels = list(obj.index.names)
+ obj = obj.reset_index()
+ obj.columns = cols
+ return super(AppendableMultiSeriesTable, self).write(obj=obj, **kwargs)
+
class GenericTable(AppendableFrameTable):
""" a table that read/writes the generic pytables table format """
pandas_kind = u('frame_table')
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 376bb13b24f96..cfe162c887799 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -580,6 +580,52 @@ def test_append(self):
store.append('uints', uint_data, data_columns=['u08','u16','u32']) # 64-bit indices not yet supported
tm.assert_frame_equal(store['uints'], uint_data)
+ def test_append_series(self):
+
+ with ensure_clean(self.path) as store:
+
+ # basic
+ ss = tm.makeStringSeries()
+ ts = tm.makeTimeSeries()
+ ns = Series(np.arange(100))
+
+ store.append('ss', ss)
+ result = store['ss']
+ tm.assert_series_equal(result, ss)
+ self.assert_(result.name is None)
+
+ store.append('ts', ts)
+ result = store['ts']
+ tm.assert_series_equal(result, ts)
+ self.assert_(result.name is None)
+
+ ns.name = 'foo'
+ store.append('ns', ns)
+ result = store['ns']
+ tm.assert_series_equal(result, ns)
+ self.assert_(result.name == ns.name)
+
+ # select on the values
+ expected = ns[ns>60]
+ result = store.select('ns',Term('foo>60'))
+ tm.assert_series_equal(result,expected)
+
+ # select on the index and values
+ expected = ns[(ns>70) & (ns.index<90)]
+ result = store.select('ns',[Term('foo>70'), Term('index<90')])
+ tm.assert_series_equal(result,expected)
+
+ # multi-index
+ mi = DataFrame(np.random.randn(5,1),columns=['A'])
+ mi['B'] = np.arange(len(mi))
+ mi['C'] = 'foo'
+ mi.loc[3:5,'C'] = 'bar'
+ mi.set_index(['C','B'],inplace=True)
+ s = mi.stack()
+ s.index = s.index.droplevel(2)
+ store.append('mi', s)
+ tm.assert_series_equal(store['mi'], s)
+
def test_encoding(self):
if sys.byteorder != 'little':
@@ -1270,10 +1316,6 @@ def test_append_misc(self):
p4d = tm.makePanel4D()
self.assertRaises(TypeError, store.put,'p4d',p4d)
- # unsupported data type for table
- s = tm.makeStringSeries()
- self.assertRaises(TypeError, store.append,'s',s)
-
# unsuported data types
self.assertRaises(TypeError, store.put,'abc',None)
self.assertRaises(TypeError, store.put,'abc','123')
| closes #4330
| https://api.github.com/repos/pandas-dev/pandas/pulls/4664 | 2013-08-23T22:02:42Z | 2013-08-24T00:12:34Z | 2013-08-24T00:12:33Z | 2014-06-27T09:10:17Z |
Added Stata 13 support | diff --git a/doc/source/io.rst b/doc/source/io.rst
index e2f114a1ffff5..546925cc8c063 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -2754,7 +2754,7 @@ Writing to STATA format
.. _io.stata_writer:
The method :func:`~pandas.core.frame.DataFrame.to_stata` will write a DataFrame
-into a .dta file. The format version of this file is always the latest one, 115.
+into a .dta file. The format version of this file is always 115 (Stata 12).
.. ipython:: python
@@ -2786,7 +2786,7 @@ read and used to create a ``Categorical`` variable from them. Value labels can
also be retrieved by the function ``variable_labels``, which requires data to be
called before (see ``pandas.io.stata.StataReader``).
-The StataReader supports .dta Formats 104, 105, 108, 113-115.
+The StataReader supports .dta Formats 104, 105, 108, 113-115 and 117.
Alternatively, the function :func:`~pandas.io.stata.read_stata` can be used
.. ipython:: python
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 322c4541b5760..630538e74cb80 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -123,6 +123,7 @@ Improvements to existing features
without ``MultiIndex`` raises ``ValueError`` (:issue:`4759`, :issue:`4837`)
- ``read_json`` now raises a (more informative) ``ValueError`` when the dict
contains a bad key and ``orient='split'`` (:issue:`4730`, :issue:`4838`)
+ - Accept Stata 13 format for reading (:issue:`4291`)
API Changes
~~~~~~~~~~~
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index bab90a77c56e8..1d0d1d17ec631 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -20,28 +20,36 @@
from pandas.core.categorical import Categorical
import datetime
from pandas import compat
-from pandas import compat
-from pandas.compat import StringIO, long, lrange, lmap, lzip
+from pandas.compat import long, lrange, lmap, lzip
from pandas import isnull
-from pandas.io.parsers import _parser_params, Appender
-from pandas.io.common import get_filepath_or_buffer, maybe_read_encoded_stream
-
-
-_read_stata_doc = """
-Read Stata file into DataFrame
-
-%s
-""" % (_parser_params)
+from pandas.io.common import get_filepath_or_buffer
-@Appender(_read_stata_doc)
def read_stata(filepath_or_buffer, convert_dates=True, convert_categoricals=True, encoding=None, index=None):
+ """
+ Read Stata file into DataFrame
+
+ Parameters
+ ----------
+ filepath_or_buffer : string or file-like object
+ Path to .dta file or object implementing a binary read() functions
+ convert_dates : boolean, defaults to True
+ Convert date variables to DataFrame time values
+ convert_categoricals : boolean, defaults to True
+ Read value labels and convert columns to Categorical/Factor variables
+ encoding : string, None or encoding
+ Encoding used to parse the files. Note that Stata doesn't
+ support unicode. None defaults to cp1252.
+ index : identifier of index column
+ identifier of column that should be used as index of the DataFrame
+ """
reader = StataReader(filepath_or_buffer, encoding)
return reader.data(convert_dates, convert_categoricals, index)
_date_formats = ["%tc", "%tC", "%td", "%tw", "%tm", "%tq", "%th", "%ty"]
+
def _stata_elapsed_date_to_datetime(date, fmt):
"""
Convert from SIF to datetime. http://www.stata.com/help.cgi?datetime
@@ -205,7 +213,7 @@ def __repr__(self):
class StataParser(object):
_default_encoding = 'cp1252'
- def __init__(self, encoding=None):
+ def __init__(self, encoding):
self._encoding = encoding
#type code.
@@ -234,7 +242,28 @@ def __init__(self, encoding=None):
(255, np.float64)
]
)
+ self.DTYPE_MAP_XML = \
+ dict(
+ [
+ (32768, np.string_),
+ (65526, np.float64),
+ (65527, np.float32),
+ (65528, np.int64),
+ (65529, np.int32),
+ (65530, np.int16)
+ ]
+ )
self.TYPE_MAP = lrange(251) + list('bhlfd')
+ self.TYPE_MAP_XML = \
+ dict(
+ [
+ (65526, 'd'),
+ (65527, 'f'),
+ (65528, 'l'),
+ (65529, 'h'),
+ (65530, 'b')
+ ]
+ )
#NOTE: technically, some of these are wrong. there are more numbers
# that can be represented. it's the 27 ABOVE and BELOW the max listed
# numeric data type in [U] 12.2.2 of the 11.2 manual
@@ -294,7 +323,7 @@ def __init__(self, path_or_buf, encoding='cp1252'):
self._data_read = False
self._value_labels_read = False
if isinstance(path_or_buf, str):
- path_or_buf, encoding = get_filepath_or_buffer(path_or_buf, encoding='cp1252')
+ path_or_buf, encoding = get_filepath_or_buffer(path_or_buf, encoding=self._default_encoding)
if isinstance(path_or_buf, (str, compat.text_type, bytes)):
self.path_or_buf = open(path_or_buf, 'rb')
@@ -304,86 +333,159 @@ def __init__(self, path_or_buf, encoding='cp1252'):
self._read_header()
def _read_header(self):
- # header
- self.format_version = struct.unpack('b', self.path_or_buf.read(1))[0]
- if self.format_version not in [104, 105, 108, 113, 114, 115]:
- raise ValueError("Version of given Stata file is not 104, 105, 108, 113 (Stata 8/9), 114 (Stata 10/11) or 115 (Stata 12)")
- self.byteorder = self.path_or_buf.read(1) == 0x1 and '>' or '<'
- self.filetype = struct.unpack('b', self.path_or_buf.read(1))[0]
- self.path_or_buf.read(1) # unused
-
- self.nvar = struct.unpack(self.byteorder + 'H', self.path_or_buf.read(2))[0]
- self.nobs = struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0]
- if self.format_version > 105:
- self.data_label = self.path_or_buf.read(81)
- else:
- self.data_label = self.path_or_buf.read(32)
- if self.format_version > 104:
- self.time_stamp = self.path_or_buf.read(18)
+ first_char = self.path_or_buf.read(1)
+ if struct.unpack('c', first_char)[0] == b'<': # format 117 or higher (XML like)
+ self.path_or_buf.read(27) # stata_dta><header><release>
+ self.format_version = int(self.path_or_buf.read(3))
+ if self.format_version not in [117]:
+ raise ValueError("Version of given Stata file is not 104, 105, 108, 113 (Stata 8/9), 114 (Stata 10/11), 115 (Stata 12) or 117 (Stata 13)")
+ self.path_or_buf.read(21) # </release><byteorder>
+ self.byteorder = self.path_or_buf.read(3) == "MSF" and '>' or '<'
+ self.path_or_buf.read(15) # </byteorder><K>
+ self.nvar = struct.unpack(self.byteorder + 'H', self.path_or_buf.read(2))[0]
+ self.path_or_buf.read(7) # </K><N>
+ self.nobs = struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0]
+ self.path_or_buf.read(11) # </N><label>
+ strlen = struct.unpack('b', self.path_or_buf.read(1))[0]
+ self.data_label = self.path_or_buf.read(strlen)
+ self.path_or_buf.read(19) # </label><timestamp>
+ strlen = struct.unpack('b', self.path_or_buf.read(1))[0]
+ self.time_stamp = self.path_or_buf.read(strlen)
+ self.path_or_buf.read(26) # </timestamp></header><map>
+ self.path_or_buf.read(8) # 0x0000000000000000
+ self.path_or_buf.read(8) # position of <map>
+ seek_vartypes = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 16
+ seek_varnames = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 10
+ seek_sortlist = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 10
+ seek_formats = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 9
+ seek_value_label_names = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 19
+ seek_variable_labels = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 17
+ self.path_or_buf.read(8) # <characteristics>
+ self.data_location = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 6
+ self.seek_strls = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 7
+ self.seek_value_labels = struct.unpack(self.byteorder + 'q', self.path_or_buf.read(8))[0] + 14
+ #self.path_or_buf.read(8) # </stata_dta>
+ #self.path_or_buf.read(8) # EOF
+ self.path_or_buf.seek(seek_vartypes)
+ typlist = [struct.unpack(self.byteorder + 'H', self.path_or_buf.read(2))[0] for i in range(self.nvar)]
+ self.typlist = [None]*self.nvar
+ try:
+ i = 0
+ for typ in typlist:
+ if typ <= 2045 or typ == 32768:
+ self.typlist[i] = None
+ else:
+ self.typlist[i] = self.TYPE_MAP_XML[typ]
+ i += 1
+ except:
+ raise ValueError("cannot convert stata types [{0}]".format(','.join(typlist)))
+ self.dtyplist = [None]*self.nvar
+ try:
+ i = 0
+ for typ in typlist:
+ if typ <= 2045:
+ self.dtyplist[i] = str(typ)
+ else:
+ self.dtyplist[i] = self.DTYPE_MAP_XML[typ]
+ i += 1
+ except:
+ raise ValueError("cannot convert stata dtypes [{0}]".format(','.join(typlist)))
- # descriptors
- if self.format_version > 108:
- typlist = [ord(self.path_or_buf.read(1)) for i in range(self.nvar)]
- else:
- typlist = [self.OLD_TYPE_MAPPING[self._decode_bytes(self.path_or_buf.read(1))] for i in range(self.nvar)]
-
- try:
- self.typlist = [self.TYPE_MAP[typ] for typ in typlist]
- except:
- raise ValueError("cannot convert stata types [{0}]".format(','.join(typlist)))
- try:
- self.dtyplist = [self.DTYPE_MAP[typ] for typ in typlist]
- except:
- raise ValueError("cannot convert stata dtypes [{0}]".format(','.join(typlist)))
-
- if self.format_version > 108:
+ self.path_or_buf.seek(seek_varnames)
self.varlist = [self._null_terminate(self.path_or_buf.read(33)) for i in range(self.nvar)]
- else:
- self.varlist = [self._null_terminate(self.path_or_buf.read(9)) for i in range(self.nvar)]
- self.srtlist = struct.unpack(self.byteorder + ('h' * (self.nvar + 1)), self.path_or_buf.read(2 * (self.nvar + 1)))[:-1]
- if self.format_version > 113:
+
+ self.path_or_buf.seek(seek_sortlist)
+ self.srtlist = struct.unpack(self.byteorder + ('h' * (self.nvar + 1)), self.path_or_buf.read(2 * (self.nvar + 1)))[:-1]
+
+ self.path_or_buf.seek(seek_formats)
self.fmtlist = [self._null_terminate(self.path_or_buf.read(49)) for i in range(self.nvar)]
- elif self.format_version > 104:
- self.fmtlist = [self._null_terminate(self.path_or_buf.read(12)) for i in range(self.nvar)]
- else:
- self.fmtlist = [self._null_terminate(self.path_or_buf.read(7)) for i in range(self.nvar)]
- if self.format_version > 108:
+
+ self.path_or_buf.seek(seek_value_label_names)
self.lbllist = [self._null_terminate(self.path_or_buf.read(33)) for i in range(self.nvar)]
- else:
- self.lbllist = [self._null_terminate(self.path_or_buf.read(9)) for i in range(self.nvar)]
- if self.format_version > 105:
+
+ self.path_or_buf.seek(seek_variable_labels)
self.vlblist = [self._null_terminate(self.path_or_buf.read(81)) for i in range(self.nvar)]
else:
- self.vlblist = [self._null_terminate(self.path_or_buf.read(32)) for i in range(self.nvar)]
-
- # ignore expansion fields (Format 105 and later)
- # When reading, read five bytes; the last four bytes now tell you the
- # size of the next read, which you discard. You then continue like
- # this until you read 5 bytes of zeros.
-
- if self.format_version > 104:
- while True:
- data_type = struct.unpack(self.byteorder + 'b', self.path_or_buf.read(1))[0]
- if self.format_version > 108:
- data_len = struct.unpack(self.byteorder + 'i', self.path_or_buf.read(4))[0]
- else:
- data_len = struct.unpack(self.byteorder + 'h', self.path_or_buf.read(2))[0]
- if data_type == 0:
- break
- self.path_or_buf.read(data_len)
+ # header
+ self.format_version = struct.unpack('b', first_char)[0]
+ if self.format_version not in [104, 105, 108, 113, 114, 115]:
+ raise ValueError("Version of given Stata file is not 104, 105, 108, 113 (Stata 8/9), 114 (Stata 10/11), 115 (Stata 12) or 117 (Stata 13)")
+ self.byteorder = self.path_or_buf.read(1) == 0x1 and '>' or '<'
+ self.filetype = struct.unpack('b', self.path_or_buf.read(1))[0]
+ self.path_or_buf.read(1) # unused
+
+ self.nvar = struct.unpack(self.byteorder + 'H', self.path_or_buf.read(2))[0]
+ self.nobs = struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0]
+ if self.format_version > 105:
+ self.data_label = self.path_or_buf.read(81)
+ else:
+ self.data_label = self.path_or_buf.read(32)
+ if self.format_version > 104:
+ self.time_stamp = self.path_or_buf.read(18)
+
+ # descriptors
+ if self.format_version > 108:
+ typlist = [ord(self.path_or_buf.read(1)) for i in range(self.nvar)]
+ else:
+ typlist = [self.OLD_TYPE_MAPPING[self._decode_bytes(self.path_or_buf.read(1))] for i in range(self.nvar)]
+
+ try:
+ self.typlist = [self.TYPE_MAP[typ] for typ in typlist]
+ except:
+ raise ValueError("cannot convert stata types [{0}]".format(','.join(typlist)))
+ try:
+ self.dtyplist = [self.DTYPE_MAP[typ] for typ in typlist]
+ except:
+ raise ValueError("cannot convert stata dtypes [{0}]".format(','.join(typlist)))
+
+ if self.format_version > 108:
+ self.varlist = [self._null_terminate(self.path_or_buf.read(33)) for i in range(self.nvar)]
+ else:
+ self.varlist = [self._null_terminate(self.path_or_buf.read(9)) for i in range(self.nvar)]
+ self.srtlist = struct.unpack(self.byteorder + ('h' * (self.nvar + 1)), self.path_or_buf.read(2 * (self.nvar + 1)))[:-1]
+ if self.format_version > 113:
+ self.fmtlist = [self._null_terminate(self.path_or_buf.read(49)) for i in range(self.nvar)]
+ elif self.format_version > 104:
+ self.fmtlist = [self._null_terminate(self.path_or_buf.read(12)) for i in range(self.nvar)]
+ else:
+ self.fmtlist = [self._null_terminate(self.path_or_buf.read(7)) for i in range(self.nvar)]
+ if self.format_version > 108:
+ self.lbllist = [self._null_terminate(self.path_or_buf.read(33)) for i in range(self.nvar)]
+ else:
+ self.lbllist = [self._null_terminate(self.path_or_buf.read(9)) for i in range(self.nvar)]
+ if self.format_version > 105:
+ self.vlblist = [self._null_terminate(self.path_or_buf.read(81)) for i in range(self.nvar)]
+ else:
+ self.vlblist = [self._null_terminate(self.path_or_buf.read(32)) for i in range(self.nvar)]
+
+ # ignore expansion fields (Format 105 and later)
+ # When reading, read five bytes; the last four bytes now tell you the
+ # size of the next read, which you discard. You then continue like
+ # this until you read 5 bytes of zeros.
+
+ if self.format_version > 104:
+ while True:
+ data_type = struct.unpack(self.byteorder + 'b', self.path_or_buf.read(1))[0]
+ if self.format_version > 108:
+ data_len = struct.unpack(self.byteorder + 'i', self.path_or_buf.read(4))[0]
+ else:
+ data_len = struct.unpack(self.byteorder + 'h', self.path_or_buf.read(2))[0]
+ if data_type == 0:
+ break
+ self.path_or_buf.read(data_len)
+
+ # necessary data to continue parsing
+ self.data_location = self.path_or_buf.tell()
- # necessary data to continue parsing
- self.data_location = self.path_or_buf.tell()
self.has_string_data = len([x for x in self.typlist if type(x) is int]) > 0
- self._col_size()
+
+ """Calculate size of a data record."""
+ self.col_sizes = lmap(lambda x: self._calcsize(x), self.typlist)
def _calcsize(self, fmt):
return type(fmt) is int and fmt or struct.calcsize(self.byteorder + fmt)
def _col_size(self, k=None):
- """Calculate size of a data record."""
- if len(self.col_sizes) == 0:
- self.col_sizes = lmap(lambda x: self._calcsize(x), self.typlist)
if k is None:
return self.col_sizes
else:
@@ -427,8 +529,8 @@ def _next(self):
return data
else:
return list(map(lambda i: self._unpack(typlist[i],
- self.path_or_buf.read(self._col_size(i))),
- range(self.nvar)))
+ self.path_or_buf.read(self._col_size(i))),
+ range(self.nvar)))
def _dataset(self):
"""
@@ -450,19 +552,19 @@ def _dataset(self):
be handled by your applcation.
"""
- try:
- self._file.seek(self._data_location)
- except Exception:
- pass
+ self.path_or_buf.seek(self.data_location)
for i in range(self.nobs):
yield self._next()
def _read_value_labels(self):
- if not self._data_read:
- raise Exception("Data has not been read. Because of the layout of Stata files, this is necessary before reading value labels.")
- if self._value_labels_read:
- raise Exception("Value labels have already been read.")
+ if self.format_version >= 117:
+ self.path_or_buf.seek(self.seek_value_labels)
+ else:
+ if not self._data_read:
+ raise Exception("Data has not been read. Because of the layout of Stata files, this is necessary before reading value labels.")
+ if self._value_labels_read:
+ raise Exception("Value labels have already been read.")
self.value_label_dict = dict()
@@ -470,9 +572,13 @@ def _read_value_labels(self):
return # Value labels are not supported in version 108 and earlier.
while True:
+ if self.format_version >= 117:
+ if self.path_or_buf.read(5) == b'</val': # <lbl>
+ break # end o f variable lable table
+
slength = self.path_or_buf.read(4)
if not slength:
- break # end of variable lable table
+ break # end of variable lable table (format < 117)
labname = self._null_terminate(self.path_or_buf.read(33))
self.path_or_buf.read(3) # padding
@@ -488,8 +594,24 @@ def _read_value_labels(self):
self.value_label_dict[labname] = dict()
for i in range(n):
self.value_label_dict[labname][val[i]] = self._null_terminate(txt[off[i]:])
+
+ if self.format_version >= 117:
+ self.path_or_buf.read(6) # </lbl>
self._value_labels_read = True
+ def _read_strls(self):
+ self.path_or_buf.seek(self.seek_strls)
+ self.GSO = dict()
+ while True:
+ if self.path_or_buf.read(3) != b'GSO':
+ break
+
+ v_o = struct.unpack(self.byteorder + 'L', self.path_or_buf.read(8))[0]
+ typ = self.path_or_buf.read(1)
+ length = struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0]
+ self.GSO[v_o] = self.path_or_buf.read(length-1)
+ self.path_or_buf.read(1) # zero-termination
+
def data(self, convert_dates=True, convert_categoricals=True, index=None):
"""
Reads observations from Stata file, converting them into a dataframe
@@ -511,6 +633,9 @@ def data(self, convert_dates=True, convert_categoricals=True, index=None):
raise Exception("Data has already been read.")
self._data_read = True
+ if self.format_version >= 117:
+ self._read_strls()
+
stata_dta = self._dataset()
data = []
diff --git a/pandas/io/tests/data/stata1_v13.dta b/pandas/io/tests/data/stata1_v13.dta
new file mode 100644
index 0000000000000..18014cec77a91
Binary files /dev/null and b/pandas/io/tests/data/stata1_v13.dta differ
diff --git a/pandas/io/tests/data/stata2_v13.dta b/pandas/io/tests/data/stata2_v13.dta
new file mode 100644
index 0000000000000..5e507b38ad56c
Binary files /dev/null and b/pandas/io/tests/data/stata2_v13.dta differ
diff --git a/pandas/io/tests/data/stata3_v13.dta b/pandas/io/tests/data/stata3_v13.dta
new file mode 100644
index 0000000000000..27e38bbed5d46
Binary files /dev/null and b/pandas/io/tests/data/stata3_v13.dta differ
diff --git a/pandas/io/tests/data/stata4_v13.dta b/pandas/io/tests/data/stata4_v13.dta
new file mode 100644
index 0000000000000..412c2c0d7b356
Binary files /dev/null and b/pandas/io/tests/data/stata4_v13.dta differ
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index 77ddafe838da4..0a87ada7097cb 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -33,6 +33,10 @@ def setUp(self):
self.dta9 = os.path.join(self.dirpath, 'lbw.dta')
self.csv9 = os.path.join(self.dirpath, 'lbw.csv')
self.dta_encoding = os.path.join(self.dirpath, 'stata1_encoding.dta')
+ self.dta1_13 = os.path.join(self.dirpath, 'stata1_v13.dta')
+ self.dta2_13 = os.path.join(self.dirpath, 'stata2_v13.dta')
+ self.dta3_13 = os.path.join(self.dirpath, 'stata3_v13.dta')
+ self.dta4_13 = os.path.join(self.dirpath, 'stata4_v13.dta')
def read_dta(self, file):
return read_stata(file, convert_dates=True)
@@ -43,6 +47,8 @@ def read_csv(self, file):
def test_read_dta1(self):
reader = StataReader(self.dta1)
parsed = reader.data()
+ reader_13 = StataReader(self.dta1_13)
+ parsed_13 = reader_13.data()
# Pandas uses np.nan as missing value.
# Thus, all columns will be of type float, regardless of their name.
expected = DataFrame([(np.nan, np.nan, np.nan, np.nan, np.nan)],
@@ -52,7 +58,9 @@ def test_read_dta1(self):
# this is an oddity as really the nan should be float64, but
# the casting doesn't fail so need to match stata here
expected['float_miss'] = expected['float_miss'].astype(np.float32)
+
tm.assert_frame_equal(parsed, expected)
+ tm.assert_frame_equal(parsed_13, expected)
def test_read_dta2(self):
expected = DataFrame.from_records(
@@ -95,25 +103,29 @@ def test_read_dta2(self):
with warnings.catch_warnings(record=True) as w:
parsed = self.read_dta(self.dta2)
+ parsed_13 = self.read_dta(self.dta2_13)
np.testing.assert_equal(
len(w), 1) # should get a warning for that format.
tm.assert_frame_equal(parsed, expected)
+ tm.assert_frame_equal(parsed_13, expected)
def test_read_dta3(self):
-
parsed = self.read_dta(self.dta3)
+ parsed_13 = self.read_dta(self.dta3_13)
# match stata here
expected = self.read_csv(self.csv3)
expected = expected.astype(np.float32)
expected['year'] = expected['year'].astype(np.int32)
- expected['quarter']= expected['quarter'].astype(np.int16)
+ expected['quarter'] = expected['quarter'].astype(np.int16)
- tm.assert_frame_equal(parsed,expected)
+ tm.assert_frame_equal(parsed, expected)
+ tm.assert_frame_equal(parsed_13, expected)
def test_read_dta4(self):
parsed = self.read_dta(self.dta4)
+ parsed_13 = self.read_dta(self.dta4_13)
expected = DataFrame.from_records(
[
["one", "ten", "one", "one", "one"],
@@ -131,6 +143,7 @@ def test_read_dta4(self):
'labeled_with_missings', 'float_labelled'])
tm.assert_frame_equal(parsed, expected)
+ tm.assert_frame_equal(parsed_13, expected)
def test_read_write_dta5(self):
if not is_little_endian():
@@ -178,7 +191,7 @@ def test_read_dta8(self):
def test_read_dta9(self):
expected = read_csv(self.csv9, parse_dates=True, sep='\t')
parsed = self.read_dta(self.dta9)
- assert_frame_equal(parsed, expected)
+ tm.assert_frame_equal(parsed, expected)
def test_read_write_dta10(self):
if not is_little_endian():
@@ -213,11 +226,11 @@ def test_encoding(self):
if compat.PY3:
expected = raw.kreis1849[0]
self.assert_(result == expected)
- self.assert_(isinstance(result,compat.string_types))
+ self.assert_(isinstance(result, compat.string_types))
else:
expected = raw.kreis1849.str.decode("latin-1")[0]
self.assert_(result == expected)
- self.assert_(isinstance(result,unicode))
+ self.assert_(isinstance(result, unicode))
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| Added initial Stata 13 .dta file format support. Newly added string features ("strls") and writing are not supported. Fixes #4291.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4662 | 2013-08-23T20:01:27Z | 2013-09-21T23:29:27Z | 2013-09-21T23:29:27Z | 2014-06-25T22:52:46Z |
BUG: GH4273, appending a 0-len table to HDFStore was raising | diff --git a/doc/source/release.rst b/doc/source/release.rst
index c90d10e5907f4..14ed2cab10eac 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -197,7 +197,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- raising an invalid ``TypeError`` rather than ``ValueError`` when appending
with a different block ordering (:issue:`4096`)
- ``read_hdf`` was not respecting as passed ``mode`` (:issue:`4504`)
- - Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while
+ - appending a 0-len table will work correctly (:issue:`4273`)
+ - Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while
trying to access trans[pos + 1] (:issue:`4496`)
- The ``by`` argument now works correctly with the ``layout`` argument
(:issue:`4102`, :issue:`4014`) in ``*.hist`` plotting methods
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index aee839c354cd3..3d5ba43943e98 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -950,6 +950,11 @@ def _write_to_group(self, key, value, index=True, table=False, append=False,
self._handle.removeNode(group, recursive=True)
group = None
+ # we don't want to store a table node at all if are object is 0-len
+ # as there are not dtypes
+ if getattr(value,'empty',None) and (table or append):
+ return
+
if group is None:
paths = key.split('/')
@@ -982,6 +987,7 @@ def _write_to_group(self, key, value, index=True, table=False, append=False,
if not s.is_table and complib:
raise ValueError('Compression not supported on non-table')
+ # write the object
s.write(obj = value, append=append, complib=complib, **kwargs)
if s.is_table and index:
s.create_index(columns = index)
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 6b9bdf3385732..376bb13b24f96 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -17,8 +17,10 @@
AttributeConflictWarning, DuplicateWarning,
PossibleDataLossError, ClosedFileError)
import pandas.util.testing as tm
-from pandas.tests.test_series import assert_series_equal
-from pandas.tests.test_frame import assert_frame_equal
+from pandas.util.testing import (assert_panel4d_equal,
+ assert_panel_equal,
+ assert_frame_equal,
+ assert_series_equal)
from pandas import concat, Timestamp
from pandas import compat
@@ -134,7 +136,7 @@ def roundtrip(key, obj,**kwargs):
assert_frame_equal(o, roundtrip('frame',o))
o = tm.makePanel()
- tm.assert_panel_equal(o, roundtrip('panel',o))
+ assert_panel_equal(o, roundtrip('panel',o))
# table
df = DataFrame(dict(A=lrange(5), B=lrange(5)))
@@ -521,14 +523,14 @@ def test_append(self):
_maybe_remove(store, 'wp1')
store.append('wp1', wp.ix[:, :10, :])
store.append('wp1', wp.ix[:, 10:, :])
- tm.assert_panel_equal(store['wp1'], wp)
+ assert_panel_equal(store['wp1'], wp)
# ndim
p4d = tm.makePanel4D()
_maybe_remove(store, 'p4d')
store.append('p4d', p4d.ix[:, :, :10, :])
store.append('p4d', p4d.ix[:, :, 10:, :])
- tm.assert_panel4d_equal(store['p4d'], p4d)
+ assert_panel4d_equal(store['p4d'], p4d)
# test using axis labels
_maybe_remove(store, 'p4d')
@@ -536,7 +538,7 @@ def test_append(self):
'items', 'major_axis', 'minor_axis'])
store.append('p4d', p4d.ix[:, :, 10:, :], axes=[
'items', 'major_axis', 'minor_axis'])
- tm.assert_panel4d_equal(store['p4d'], p4d)
+ assert_panel4d_equal(store['p4d'], p4d)
# test using differnt number of items on each axis
p4d2 = p4d.copy()
@@ -545,7 +547,7 @@ def test_append(self):
_maybe_remove(store, 'p4d2')
store.append(
'p4d2', p4d2, axes=['items', 'major_axis', 'minor_axis'])
- tm.assert_panel4d_equal(store['p4d2'], p4d2)
+ assert_panel4d_equal(store['p4d2'], p4d2)
# test using differt order of items on the non-index axes
_maybe_remove(store, 'wp1')
@@ -553,7 +555,7 @@ def test_append(self):
store.append('wp1', wp_append1)
wp_append2 = wp.ix[:, 10:, :].reindex(items=wp.items[::-1])
store.append('wp1', wp_append2)
- tm.assert_panel_equal(store['wp1'], wp)
+ assert_panel_equal(store['wp1'], wp)
# dtype issues - mizxed type in a single object column
df = DataFrame(data=[[1, 2], [0, 1], [1, 2], [0, 0]])
@@ -757,7 +759,7 @@ def check_indexers(key, indexers):
_maybe_remove(store, 'p4d')
store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers)
store.append('p4d', p4d.ix[:, :, 10:, :])
- tm.assert_panel4d_equal(store.select('p4d'), p4d)
+ assert_panel4d_equal(store.select('p4d'), p4d)
check_indexers('p4d', indexers)
# same as above, but try to append with differnt axes
@@ -765,7 +767,7 @@ def check_indexers(key, indexers):
store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers)
store.append('p4d', p4d.ix[:, :, 10:, :], axes=[
'labels', 'items', 'major_axis'])
- tm.assert_panel4d_equal(store.select('p4d'), p4d)
+ assert_panel4d_equal(store.select('p4d'), p4d)
check_indexers('p4d', indexers)
# pass incorrect number of axes
@@ -778,7 +780,7 @@ def check_indexers(key, indexers):
_maybe_remove(store, 'p4d')
store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers)
store.append('p4d', p4d.ix[:, :, 10:, :])
- tm.assert_panel4d_equal(store['p4d'], p4d)
+ assert_panel4d_equal(store['p4d'], p4d)
check_indexers('p4d', indexers)
# different than default indexables #2
@@ -786,26 +788,26 @@ def check_indexers(key, indexers):
_maybe_remove(store, 'p4d')
store.append('p4d', p4d.ix[:, :, :10, :], axes=indexers)
store.append('p4d', p4d.ix[:, :, 10:, :])
- tm.assert_panel4d_equal(store['p4d'], p4d)
+ assert_panel4d_equal(store['p4d'], p4d)
check_indexers('p4d', indexers)
# partial selection
result = store.select('p4d', ['labels=l1'])
expected = p4d.reindex(labels=['l1'])
- tm.assert_panel4d_equal(result, expected)
+ assert_panel4d_equal(result, expected)
# partial selection2
result = store.select('p4d', [Term(
'labels=l1'), Term('items=ItemA'), Term('minor_axis=B')])
expected = p4d.reindex(
labels=['l1'], items=['ItemA'], minor_axis=['B'])
- tm.assert_panel4d_equal(result, expected)
+ assert_panel4d_equal(result, expected)
# non-existant partial selection
result = store.select('p4d', [Term(
'labels=l1'), Term('items=Item1'), Term('minor_axis=B')])
expected = p4d.reindex(labels=['l1'], items=[], minor_axis=['B'])
- tm.assert_panel4d_equal(result, expected)
+ assert_panel4d_equal(result, expected)
def test_append_with_strings(self):
@@ -821,7 +823,7 @@ def check_col(key,name,size):
store.append('s1', wp2)
expected = concat([wp, wp2], axis=2)
expected = expected.reindex(minor_axis=sorted(expected.minor_axis))
- tm.assert_panel_equal(store['s1'], expected)
+ assert_panel_equal(store['s1'], expected)
check_col('s1', 'minor_axis', 20)
# test dict format
@@ -829,7 +831,7 @@ def check_col(key,name,size):
store.append('s2', wp2)
expected = concat([wp, wp2], axis=2)
expected = expected.reindex(minor_axis=sorted(expected.minor_axis))
- tm.assert_panel_equal(store['s2'], expected)
+ assert_panel_equal(store['s2'], expected)
check_col('s2', 'minor_axis', 20)
# apply the wrong field (similar to #1)
@@ -1305,10 +1307,46 @@ def check(obj, comparator):
check(df, tm.assert_frame_equal)
p = tm.makePanel()
- check(p, tm.assert_panel_equal)
+ check(p, assert_panel_equal)
p4d = tm.makePanel4D()
- check(p4d, tm.assert_panel4d_equal)
+ check(p4d, assert_panel4d_equal)
+
+ # empty frame, GH4273
+ with ensure_clean(self.path) as store:
+
+ # 0 len
+ df_empty = DataFrame(columns=list('ABC'))
+ store.append('df',df_empty)
+ self.assertRaises(KeyError,store.select, 'df')
+
+ # repeated append of 0/non-zero frames
+ df = DataFrame(np.random.rand(10,3),columns=list('ABC'))
+ store.append('df',df)
+ assert_frame_equal(store.select('df'),df)
+ store.append('df',df_empty)
+ assert_frame_equal(store.select('df'),df)
+
+ # store
+ df = DataFrame(columns=list('ABC'))
+ store.put('df2',df)
+ assert_frame_equal(store.select('df2'),df)
+
+ # 0 len
+ p_empty = Panel(items=list('ABC'))
+ store.append('p',p_empty)
+ self.assertRaises(KeyError,store.select, 'p')
+
+ # repeated append of 0/non-zero frames
+ p = Panel(np.random.randn(3,4,5),items=list('ABC'))
+ store.append('p',p)
+ assert_panel_equal(store.select('p'),p)
+ store.append('p',p_empty)
+ assert_panel_equal(store.select('p'),p)
+
+ # store
+ store.put('p2',p_empty)
+ assert_panel_equal(store.select('p2'),p_empty)
def test_append_raise(self):
@@ -1433,7 +1471,7 @@ def test_table_mixed_dtypes(self):
with ensure_clean(self.path) as store:
store.append('p1_mixed', wp)
- tm.assert_panel_equal(store.select('p1_mixed'), wp)
+ assert_panel_equal(store.select('p1_mixed'), wp)
# ndim
wp = tm.makePanel4D()
@@ -1447,7 +1485,7 @@ def test_table_mixed_dtypes(self):
with ensure_clean(self.path) as store:
store.append('p4d_mixed', wp)
- tm.assert_panel4d_equal(store.select('p4d_mixed'), wp)
+ assert_panel4d_equal(store.select('p4d_mixed'), wp)
def test_unimplemented_dtypes_table_columns(self):
@@ -1595,7 +1633,7 @@ def test_remove_where(self):
store.remove('wp', [('minor_axis', ['A', 'D'])])
rs = store.select('wp')
expected = wp.reindex(minor_axis=['B', 'C'])
- tm.assert_panel_equal(rs, expected)
+ assert_panel_equal(rs, expected)
# empty where
_maybe_remove(store, 'wp')
@@ -1630,7 +1668,7 @@ def test_remove_crit(self):
assert(n == 36)
result = store.select('wp3')
expected = wp.reindex(major_axis=wp.major_axis - date4)
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
# upper half
store.put('wp', wp, table=True)
@@ -1647,7 +1685,7 @@ def test_remove_crit(self):
result = store['wp']
expected = wp.truncate(after=date).reindex(minor=['B', 'C'])
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
# individual row elements
store.put('wp2', wp, table=True)
@@ -1657,7 +1695,7 @@ def test_remove_crit(self):
store.remove('wp2', where=[crit1])
result = store.select('wp2')
expected = wp.reindex(major_axis=wp.major_axis - date1)
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
date2 = wp.major_axis[5]
crit2 = Term('major_axis', date2)
@@ -1665,7 +1703,7 @@ def test_remove_crit(self):
result = store['wp2']
expected = wp.reindex(
major_axis=wp.major_axis - date1 - Index([date2]))
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
date3 = [wp.major_axis[7], wp.major_axis[9]]
crit3 = Term('major_axis', date3)
@@ -1673,14 +1711,14 @@ def test_remove_crit(self):
result = store['wp2']
expected = wp.reindex(
major_axis=wp.major_axis - date1 - Index([date2]) - Index(date3))
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
# corners
store.put('wp4', wp, table=True)
n = store.remove(
'wp4', where=[Term('major_axis', '>', wp.major_axis[-1])])
result = store.select('wp4')
- tm.assert_panel_equal(result, wp)
+ assert_panel_equal(result, wp)
def test_terms(self):
@@ -1710,7 +1748,7 @@ def test_terms(self):
result = store.select('wp', [Term(
'major_axis<20000108'), Term('minor_axis', '=', ['A', 'B'])])
expected = wp.truncate(after='20000108').reindex(minor=['A', 'B'])
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
# p4d
result = store.select('p4d', [Term('major_axis<20000108'),
@@ -1718,7 +1756,7 @@ def test_terms(self):
Term('items', '=', ['ItemA', 'ItemB'])])
expected = p4d.truncate(after='20000108').reindex(
minor=['A', 'B'], items=['ItemA', 'ItemB'])
- tm.assert_panel4d_equal(result, expected)
+ assert_panel4d_equal(result, expected)
# valid terms
terms = [
@@ -1805,15 +1843,15 @@ def test_sparse_panel(self):
p = Panel(dict((i, tm.makeDataFrame().ix[:2, :2]) for i in items))
sp = p.to_sparse()
- self._check_double_roundtrip(sp, tm.assert_panel_equal,
+ self._check_double_roundtrip(sp, assert_panel_equal,
check_panel_type=True)
sp2 = p.to_sparse(kind='integer')
- self._check_double_roundtrip(sp2, tm.assert_panel_equal,
+ self._check_double_roundtrip(sp2, assert_panel_equal,
check_panel_type=True)
sp3 = p.to_sparse(fill_value=0)
- self._check_double_roundtrip(sp3, tm.assert_panel_equal,
+ self._check_double_roundtrip(sp3, assert_panel_equal,
check_panel_type=True)
def test_float_index(self):
@@ -2034,12 +2072,12 @@ def _make_one():
def test_wide(self):
wp = tm.makePanel()
- self._check_roundtrip(wp, tm.assert_panel_equal)
+ self._check_roundtrip(wp, assert_panel_equal)
def test_wide_table(self):
wp = tm.makePanel()
- self._check_roundtrip_table(wp, tm.assert_panel_equal)
+ self._check_roundtrip_table(wp, assert_panel_equal)
def test_wide_table_dups(self):
wp = tm.makePanel()
@@ -2050,11 +2088,11 @@ def test_wide_table_dups(self):
with tm.assert_produces_warning(expected_warning=DuplicateWarning):
recons = store['panel']
- tm.assert_panel_equal(recons, wp)
+ assert_panel_equal(recons, wp)
def test_long(self):
def _check(left, right):
- tm.assert_panel_equal(left.to_panel(), right.to_panel())
+ assert_panel_equal(left.to_panel(), right.to_panel())
wp = tm.makePanel()
self._check_roundtrip(wp.to_frame(), _check)
@@ -2129,7 +2167,7 @@ def test_select(self):
items = ['Item%03d' % i for i in range(80)]
result = store.select('wp', Term('items', items))
expected = wp.reindex(items=items)
- tm.assert_panel_equal(expected, result)
+ assert_panel_equal(expected, result)
# selectin non-table with a where
# self.assertRaises(ValueError, store.select,
@@ -2414,12 +2452,12 @@ def test_panel_select(self):
result = store.select('wp', [crit1, crit2])
expected = wp.truncate(before=date).reindex(minor=['A', 'D'])
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
result = store.select(
'wp', ['major_axis>=20000124', ('minor_axis', '=', ['A', 'B'])])
expected = wp.truncate(before='20000124').reindex(minor=['A', 'B'])
- tm.assert_panel_equal(result, expected)
+ assert_panel_equal(result, expected)
def test_frame_select(self):
| closes #4273
| https://api.github.com/repos/pandas-dev/pandas/pulls/4660 | 2013-08-23T14:00:48Z | 2013-08-23T14:33:19Z | 2013-08-23T14:33:19Z | 2014-06-20T17:03:22Z |
BUG: Series.reshape to own shape raises TypeError | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 66c3dcd203a6a..eeaa9595252a8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -498,6 +498,8 @@ Bug Fixes
- ``Timestamp`` objects can now appear in the left hand side of a comparison
operation with a ``Series`` or ``DataFrame`` object (:issue:`4982`).
- Fix a bug when indexing with ``np.nan`` via ``iloc/loc`` (:issue:`5016`)
+ - Fix a bug where reshaping a ``Series`` to its own shape raised ``TypeError`` (:issue:`4554`)
+ and other reshaping issues.
pandas 0.12.0
-------------
diff --git a/pandas/core/series.py b/pandas/core/series.py
index aeb63ecbe268f..f1617bffad162 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1152,18 +1152,21 @@ def repeat(self, reps):
new_values = self.values.repeat(reps)
return self._constructor(new_values, index=new_index, name=self.name)
- def reshape(self, newshape, order='C'):
+ def reshape(self, *args, **kwargs):
"""
See numpy.ndarray.reshape
"""
- if order not in ['C', 'F']:
- raise TypeError(
- "must specify a tuple / singular length to reshape")
-
- if isinstance(newshape, tuple) and len(newshape) > 1:
- return self.values.reshape(newshape, order=order)
+ if len(args) == 1 and hasattr(args[0], '__iter__'):
+ shape = args[0]
else:
- return ndarray.reshape(self, newshape, order)
+ shape = args
+
+ if tuple(shape) == self.shape:
+ # XXX ignoring the "order" keyword.
+ return self
+
+ return self.values.reshape(shape, **kwargs)
+
def get(self, label, default=None):
"""
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index f8320149f4ac6..ca9b04cde31b2 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1046,12 +1046,16 @@ def test_basic_getitem_setitem_corner(self):
[5, slice(None, None)], 2)
def test_reshape_non_2d(self):
+ # GH 4554
x = Series(np.random.random(201), name='x')
- self.assertRaises(TypeError, x.reshape, (len(x),))
+ self.assertTrue(x.reshape(x.shape,) is x)
# GH 2719
a = Series([1, 2, 3, 4])
- self.assertRaises(TypeError, a.reshape, 2, 2)
+ result = a.reshape(2, 2)
+ expected = a.values.reshape(2, 2)
+ np.testing.assert_array_equal(result, expected)
+ self.assertTrue(type(result) is type(expected))
def test_reshape_2d_return_array(self):
x = Series(np.random.random(201), name='x')
| closes #4554
I just fixed the call to ndarray.reshape with order as a positional argument, which is wrong. Please note that I had to remove a test.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4659 | 2013-08-23T13:39:07Z | 2013-09-29T22:07:33Z | 2013-09-29T22:07:33Z | 2014-06-20T13:45:34Z |
Boolean indexing on an empty series loses index names (rebase of 4236) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 745876e8c448e..b3436fd4e088f 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -258,6 +258,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix bug in ``pd.read_clipboard`` on windows with PY3 (:issue:`4561`); not decoding properly
- ``tslib.get_period_field()`` and ``tslib.get_period_field_arr()`` now raise
if code argument out of range (:issue:`4519`, :issue:`4520`)
+ - Fix boolean indexing on an empty series loses index names (:issue:`4235`),
+ infer_dtype works with empty arrays.
- Fix reindexing with multiple axes; if an axes match was not replacing the current axes, leading
to a possible lazay frequency inference issue (:issue:`3317`)
- Fixed issue where ``DataFrame.apply`` was reraising exceptions incorrectly
diff --git a/pandas/src/inference.pyx b/pandas/src/inference.pyx
index ecf0949451a80..39334e95e8c81 100644
--- a/pandas/src/inference.pyx
+++ b/pandas/src/inference.pyx
@@ -41,10 +41,6 @@ def infer_dtype(object _values):
_values = list(_values)
values = list_to_object_array(_values)
- n = len(values)
- if n == 0:
- return 'empty'
-
val_kind = values.dtype.type
if val_kind in _TYPE_MAP:
return _TYPE_MAP[val_kind]
@@ -52,6 +48,10 @@ def infer_dtype(object _values):
if values.dtype != np.object_:
values = values.astype('O')
+ n = len(values)
+ if n == 0:
+ return 'empty'
+
val = util.get_value_1d(values, 0)
if util.is_datetime64_object(val):
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 4100185752b8f..579c635da9264 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -740,6 +740,13 @@ def test_getitem_boolean(self):
assert_series_equal(result, expected)
self.assert_(np.array_equal(result.index, s.index[mask]))
+ def test_getitem_boolean_empty(self):
+ s = Series([], dtype=np.int64)
+ s.index.name = 'index_name'
+ s = s[s.isnull()]
+ self.assertEqual(s.index.name, 'index_name')
+ self.assertEqual(s.dtype, np.int64)
+
def test_getitem_generator(self):
gen = (x > 0 for x in self.series)
result = self.series[gen]
diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py
index 6175b358a925c..c1eda35417fd7 100644
--- a/pandas/tests/test_tseries.py
+++ b/pandas/tests/test_tseries.py
@@ -565,9 +565,9 @@ class TestTypeInference(unittest.TestCase):
def test_length_zero(self):
result = lib.infer_dtype(np.array([], dtype='i4'))
- self.assertEqual(result, 'empty')
+ self.assertEqual(result, 'integer')
- result = lib.infer_dtype(np.array([], dtype='O'))
+ result = lib.infer_dtype([])
self.assertEqual(result, 'empty')
def test_integers(self):
| Fixes #4235.
This just adds a release note to #4236: Boolean indexing on an empty series loses index names.
Actually that commit really just adds tests for this, since they now already pass in master. It also, fixes behaviour of `infer_dtype` with empty arrays.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4658 | 2013-08-23T13:00:50Z | 2013-08-23T13:03:32Z | 2013-08-23T13:03:32Z | 2014-06-18T16:11:49Z |
API: GH4633, bool(obj) behavior, raise on __nonzero__ always | diff --git a/doc/source/10min.rst b/doc/source/10min.rst
index 760e6a614fd92..96f9fd912b664 100644
--- a/doc/source/10min.rst
+++ b/doc/source/10min.rst
@@ -269,7 +269,6 @@ A ``where`` operation for getting.
df[df > 0]
-
Setting
~~~~~~~
@@ -708,3 +707,20 @@ Reading from an excel file
:suppress:
os.remove('foo.xlsx')
+
+Gotchas
+-------
+
+If you are trying an operation and you see an exception like:
+
+.. code-block:: python
+
+ >>> if pd.Series([False, True, False]):
+ print("I was true")
+ Traceback
+ ...
+ ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
+
+See :ref:`Comparisons<basics.compare>` for an explanation and what to do.
+
+See :ref:`Gotachas<gotchas>` as well.
diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index a0818831fb988..b75c65ca727f4 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -8,7 +8,7 @@
from pandas import *
randn = np.random.randn
np.set_printoptions(precision=4, suppress=True)
- from pandas.compat import lrange
+ from pandas.compat import lrange
==============================
Essential Basic Functionality
@@ -198,6 +198,9 @@ replace NaN with some other value using ``fillna`` if you wish).
Flexible Comparisons
~~~~~~~~~~~~~~~~~~~~
+
+.. _basics.compare:
+
Starting in v0.8, pandas introduced binary comparison methods eq, ne, lt, gt,
le, and ge to Series and DataFrame whose behavior is analogous to the binary
arithmetic operations described above:
@@ -205,9 +208,52 @@ arithmetic operations described above:
.. ipython:: python
df.gt(df2)
-
df2.ne(df)
+These operations produce a pandas object the same type as the left-hand-side input
+that if of dtype ``bool``. These ``boolean`` objects can be used in indexing operations,
+see :ref:`here<indexing.boolean>`
+
+Furthermore, you can apply the reduction functions: ``any()`` and ``all()`` to provide a
+way to summarize these results.
+
+.. ipython:: python
+
+ (df>0).all()
+ (df>0).any()
+
+Finally you can test if a pandas object is empty, via the ``empty`` property.
+
+.. ipython:: python
+
+ df.empty
+ DataFrame(columns=list('ABC')).empty
+
+.. warning::
+
+ You might be tempted to do the following:
+
+ .. code-block:: python
+
+ >>>if df:
+ ...
+
+ Or
+
+ .. code-block:: python
+
+ >>> df and df2
+
+ These both will raise as you are trying to compare multiple values.
+
+ .. code-block:: python
+
+ ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
+
+
+See :ref:`gotchas<gotchas.truth>` for a more detailed discussion.
+
+
Combining overlapping data sets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/gotchas.rst b/doc/source/gotchas.rst
index 003169839f029..cf3f1be59ac45 100644
--- a/doc/source/gotchas.rst
+++ b/doc/source/gotchas.rst
@@ -15,6 +15,58 @@
Caveats and Gotchas
*******************
+Using If/Truth Statements with Pandas
+-------------------------------------
+
+.. _gotchas.truth:
+
+Pandas follows the numpy convention of raising an error when you try to convert something to a ``bool``.
+This happens in a ``if`` or when using the boolean operations, ``and``, ``or``, or ``not``. It is not clear
+what the result of
+
+.. code-block:: python
+
+ >>> if Series([False, True, False]):
+ ...
+
+should be. Should it be ``True`` because it's not zero-length? ``False`` because there are ``False`` values?
+It is unclear, so instead, pandas raises a ``ValueError``:
+
+.. code-block:: python
+
+ >>> if pd.Series([False, True, False]):
+ print("I was true")
+ Traceback
+ ...
+ ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
+
+
+If you see that, you need to explicitly choose what you want to do with it (e.g., use `any()`, `all()` or `empty`).
+or, you might want to compare if the pandas object is ``None``
+
+.. code-block:: python
+
+ >>> if pd.Series([False, True, False]) is not None:
+ print("I was not None")
+ >>> I was not None
+
+Bitwise boolean
+~~~~~~~~~~~~~~~
+
+Bitwise boolean operators like ``==`` and ``!=`` will return a boolean ``Series``,
+which is almost always what you want anyways.
+
+.. code-block:: python
+
+ >>> s = pd.Series(range(5))
+ >>> s == 4
+ 0 False
+ 1 False
+ 2 False
+ 3 False
+ 4 True
+ dtype: bool
+
``NaN``, Integer ``NA`` values and ``NA`` type promotions
---------------------------------------------------------
@@ -428,7 +480,7 @@ parse HTML tables in the top-level pandas io function ``read_html``.
lxml will work correctly:
.. code-block:: sh
-
+
# remove the included version
conda remove lxml
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 4e6ac7240512c..ccdfe7320f53d 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -130,6 +130,9 @@ pandas 0.13
now returns a ``MultiIndex`` rather than an ``Index``. (:issue:`4039`)
- Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
+ - Factored out excel_value_to_python_value from ExcelFile::_parse_excel (:issue:`4589`)
+ - ``__nonzero__`` for all NDFrame objects, will now raise a ``ValueError``, this reverts back to (:issue:`1073`, :issue:`4633`)
+ behavior.
**Internal Refactoring**
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 022799cd88014..6f34617495c29 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -118,6 +118,18 @@ API changes
index.set_names(["bob", "cranberry"], inplace=True)
- Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
+ - ``__nonzero__`` for all NDFrame objects, will now raise a ``ValueError``, this reverts back to (:issue:`1073`, :issue:`4633`)
+ behavior.
+
+ This prevent behaviors like (which will now all raise ``ValueError``)
+
+ ..code-block ::
+
+ if df:
+ ....
+
+ df1 and df2
+ s1 and s2
Enhancements
~~~~~~~~~~~~
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index d15ce05e84d40..0fecddbd4f617 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -531,7 +531,8 @@ def empty(self):
return not all(len(self._get_axis(a)) > 0 for a in self._AXIS_ORDERS)
def __nonzero__(self):
- return not self.empty
+ raise ValueError("The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().")
+
__bool__ = __nonzero__
#----------------------------------------------------------------------
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index f0ba0c3b54f4a..723ff2fd5ab56 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -2101,9 +2101,22 @@ def filter(self, func, dropna=True, *args, **kwargs):
else:
res = path(group)
- if res:
+ def add_indexer():
indexers.append(self.obj.index.get_indexer(group.index))
+ # interpret the result of the filter
+ if isinstance(res,(bool,np.bool_)):
+ if res:
+ add_indexer()
+ else:
+ if getattr(res,'ndim',None) == 1:
+ if res.ravel()[0]:
+ add_indexer()
+ else:
+
+ # in theory you could do .all() on the boolean result ?
+ raise TypeError("the filter must return a boolean result")
+
if len(indexers) == 0:
filtered = self.obj.take([]) # because np.concatenate would fail
else:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e3f97a28fe8cc..3a8c0ec5e1a0f 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -798,13 +798,6 @@ def __contains__(self, key):
__long__ = _coerce_method(int)
__int__ = _coerce_method(int)
- def __nonzero__(self):
- # special case of a single element bool series degenerating to a scalar
- if self.dtype == np.bool_ and len(self) == 1:
- return bool(self.iloc[0])
- return not self.empty
- __bool__ = __nonzero__
-
# we are preserving name here
def __getstate__(self):
return dict(_data=self._data, name=self.name)
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index e2d9235510f83..b5aaf93831a15 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -1519,11 +1519,11 @@ def test_table_values_dtypes_roundtrip(self):
with ensure_clean(self.path) as store:
df1 = DataFrame({'a': [1, 2, 3]}, dtype='f8')
store.append('df_f8', df1)
- assert df1.dtypes == store['df_f8'].dtypes
+ assert_series_equal(df1.dtypes,store['df_f8'].dtypes)
df2 = DataFrame({'a': [1, 2, 3]}, dtype='i8')
store.append('df_i8', df2)
- assert df2.dtypes == store['df_i8'].dtypes
+ assert_series_equal(df2.dtypes,store['df_i8'].dtypes)
# incompatible dtype
self.assertRaises(ValueError, store.append, 'df_i8', df1)
@@ -1531,7 +1531,7 @@ def test_table_values_dtypes_roundtrip(self):
# check creation/storage/retrieval of float32 (a bit hacky to actually create them thought)
df1 = DataFrame(np.array([[1],[2],[3]],dtype='f4'),columns = ['A'])
store.append('df_f4', df1)
- assert df1.dtypes == store['df_f4'].dtypes
+ assert_series_equal(df1.dtypes,store['df_f4'].dtypes)
assert df1.dtypes[0] == 'float32'
# check with mixed dtypes
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index e31aa5b3f5983..41b705d22b85d 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -10607,13 +10607,10 @@ def test_index_namedtuple(self):
df = DataFrame([(1, 2), (3, 4)], index=index, columns=["A", "B"])
self.assertEqual(df.ix[IndexType("foo", "bar")]["A"], 1)
- def test_bool_empty_nonzero(self):
+ def test_empty_nonzero(self):
df = DataFrame([1, 2, 3])
- self.assertTrue(bool(df))
self.assertFalse(df.empty)
df = DataFrame(index=['a', 'b'], columns=['c', 'd']).dropna()
- self.assertFalse(bool(df))
- self.assertFalse(bool(df.T))
self.assertTrue(df.empty)
self.assertTrue(df.T.empty)
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
index f388c5d72627c..6ea58ec997e23 100644
--- a/pandas/tests/test_generic.py
+++ b/pandas/tests/test_generic.py
@@ -73,7 +73,6 @@ def _construct(self, shape, value=None, **kwargs):
arr = np.random.randn(*shape)
return self._typ(arr,**kwargs)
-
def _compare(self, result, expected):
self._comparator(result,expected)
@@ -82,14 +81,14 @@ def test_rename(self):
# single axis
for axis in self._axes():
kwargs = { axis : list('ABCD') }
- o = self._construct(4,**kwargs)
+ obj = self._construct(4,**kwargs)
# no values passed
#self.assertRaises(Exception, o.rename(str.lower))
# rename a single axis
- result = o.rename(**{ axis : str.lower })
- expected = o.copy()
+ result = obj.rename(**{ axis : str.lower })
+ expected = obj.copy()
setattr(expected,axis,list('abcd'))
self._compare(result, expected)
@@ -119,6 +118,41 @@ def test_get_numeric_data(self):
self._compare(result, o)
# _get_numeric_data is includes _get_bool_data, so can't test for non-inclusion
+ def test_nonzero(self):
+
+ # GH 4633
+ # look at the boolean/nonzero behavior for objects
+ obj = self._construct(shape=4)
+ self.assertRaises(ValueError, lambda : bool(obj == 0))
+ self.assertRaises(ValueError, lambda : bool(obj == 1))
+ self.assertRaises(ValueError, lambda : bool(obj))
+
+ obj = self._construct(shape=4,value=1)
+ self.assertRaises(ValueError, lambda : bool(obj == 0))
+ self.assertRaises(ValueError, lambda : bool(obj == 1))
+ self.assertRaises(ValueError, lambda : bool(obj))
+
+ obj = self._construct(shape=4,value=np.nan)
+ self.assertRaises(ValueError, lambda : bool(obj == 0))
+ self.assertRaises(ValueError, lambda : bool(obj == 1))
+ self.assertRaises(ValueError, lambda : bool(obj))
+
+ # empty
+ obj = self._construct(shape=0)
+ self.assertRaises(ValueError, lambda : bool(obj))
+
+ # invalid behaviors
+
+ obj1 = self._construct(shape=4,value=1)
+ obj2 = self._construct(shape=4,value=1)
+
+ def f():
+ if obj1:
+ print("this works and shouldn't")
+ self.assertRaises(ValueError, f)
+ self.assertRaises(ValueError, lambda : obj1 and obj2)
+ self.assertRaises(ValueError, lambda : obj1 or obj2)
+ self.assertRaises(ValueError, lambda : not obj1)
class TestSeries(unittest.TestCase, Generic):
_typ = Series
@@ -154,6 +188,14 @@ def test_get_numeric_data_preserve_dtype(self):
expected = Series([],dtype='M8[ns]')
self._compare(result, expected)
+ def test_nonzero_single_element(self):
+
+ s = Series([True])
+ self.assertRaises(ValueError, lambda : bool(s))
+
+ s = Series([False])
+ self.assertRaises(ValueError, lambda : bool(s))
+
class TestDataFrame(unittest.TestCase, Generic):
_typ = DataFrame
_comparator = lambda self, x, y: assert_frame_equal(x,y)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 1f7570b7f7887..b2849aeb2fbe8 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -296,12 +296,6 @@ def test_scalar_conversion(self):
self.assert_(int(Series([1.])) == 1)
self.assert_(long(Series([1.])) == 1)
- self.assert_(bool(Series([True])) == True)
- self.assert_(bool(Series([False])) == False)
-
- self.assert_(bool(Series([True,True])) == True)
- self.assert_(bool(Series([False,True])) == True)
-
def test_astype(self):
s = Series(np.random.randn(5),name='foo')
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 172172f667eca..01f573279fe5c 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -256,7 +256,7 @@ def test_indexing(self):
df = DataFrame(randn(5,5),columns=['open','high','low','close','volume'],index=date_range('2012-01-02 18:01:00',periods=5,tz='US/Central',freq='s'))
expected = df.loc[[df.index[2]]]
result = df['2012-01-02 18:01:02']
- self.assert_(result == expected)
+ assert_frame_equal(result,expected)
# this is a single date, so will raise
self.assertRaises(KeyError, df.__getitem__, df.index[2],)
| closes #4633
this is a revert to #1073/#1069
now a call to `__nonzero__` raises `ValueError` ALWAYS
The following is the behavior
```
In [17]: s = Series(randn(4))
In [18]: df = DataFrame(randn(10,2))
In [19]: s_empty = Series()
In [20]: df_empty = DataFrame()
In [5]: bool(s)
Out[5]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [6]: bool(s_empty)
Out[6]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [7]: bool(df)
Out[7]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [8]: bool(df_empty)
Out[8]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
And prevents these fun ones (same for Series/Panel)
```
In [4]: df1 = DataFrame(np.ones((4,4)))
In [5]: df2 = DataFrame(np.zeros((4,4)))
In [6]: df1 and df2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [7]: df1 or df2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [8]: not df1
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [9]: def f():
...: if df1:
...: print("this is cool")
...:
In [10]: f()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4657 | 2013-08-23T12:42:55Z | 2013-08-31T17:51:58Z | 2013-08-31T17:51:58Z | 2014-06-12T13:11:07Z |
API: remove the table keyword, replaced by fmt='s|t' | diff --git a/doc/source/io.rst b/doc/source/io.rst
index f09ae1563f71b..73a7c2d1e1121 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1803,6 +1803,7 @@ The examples above show storing using ``put``, which write the HDF5 to ``PyTable
the ``storer`` format. These types of stores are are **not** appendable once written (though you can simply
remove them and rewrite). Nor are they **queryable**; they must be
retrieved in their entirety. These offer very fast writing and slightly faster reading than ``table`` stores.
+This format is specified by default when using ``put`` or by ``fmt='s'``
.. warning::
@@ -1826,7 +1827,7 @@ Table Format
format. Conceptually a ``table`` is shaped very much like a DataFrame,
with rows and columns. A ``table`` may be appended to in the same or
other sessions. In addition, delete & query type operations are
-supported.
+supported. This format is specified by ``fmt='t'`` to ``append`` or ``put``.
.. ipython:: python
:suppress:
@@ -1853,7 +1854,7 @@ supported.
.. note::
- You can also create a ``table`` by passing ``table=True`` to a ``put`` operation.
+ You can also create a ``table`` by passing ``fmt='t'`` to a ``put`` operation.
.. _io.hdf5-keys:
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 261bbd424478e..21fea6b64c042 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -98,6 +98,7 @@ pandas 0.13
- removed the ``warn`` argument from ``open``. Instead a ``PossibleDataLossError`` exception will
be raised if you try to use ``mode='w'`` with an OPEN file handle (:issue:`4367`)
- allow a passed locations array or mask as a ``where`` condition (:issue:`4467`)
+ - the ``fmt`` keyword now replaces the ``table`` keyword; allowed values are ``s|t``
- ``JSON``
- added ``date_unit`` parameter to specify resolution of timestamps. Options
@@ -200,6 +201,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
with a different block ordering (:issue:`4096`)
- ``read_hdf`` was not respecting as passed ``mode`` (:issue:`4504`)
- appending a 0-len table will work correctly (:issue:`4273`)
+ - ``to_hdf`` was raising when passing both arguments ``append`` and ``table`` (:issue:`4584`)
- Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while
trying to access trans[pos + 1] (:issue:`4496`)
- The ``by`` argument now works correctly with the ``layout`` argument
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 5003aa654d9fb..c0e3f5e6b2f10 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -66,6 +66,12 @@ API changes
store2.close()
store2
+ .. ipython:: python
+ :suppress:
+
+ import os
+ os.remove(path)
+
- removed the ``_quiet`` attribute, replace by a ``DuplicateWarning`` if retrieving
duplicate rows from a table (:issue:`4367`)
- removed the ``warn`` argument from ``open``. Instead a ``PossibleDataLossError`` exception will
@@ -73,6 +79,20 @@ API changes
- allow a passed locations array or mask as a ``where`` condition (:issue:`4467`).
See :ref:`here<io.hdf5-where_mask>` for an example.
+ - the ``fmt`` keyword now replaces the ``table`` keyword; allowed values are ``s|t``
+ the same defaults as prior < 0.13.0 remain, e.g. ``put`` implies 's' (Storer) format
+ and ``append`` imples 't' (Table) format
+
+ .. ipython:: python
+
+ path = 'test.h5'
+ df = DataFrame(randn(10,2))
+ df.to_hdf(path,'df_table',fmt='t')
+ df.to_hdf(path,'df_table2',append=True)
+ df.to_hdf(path,'df_storer')
+ with get_store(path) as store:
+ print store
+
.. ipython:: python
:suppress:
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 608bbe4703272..1eb8b0f266f68 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -64,9 +64,11 @@ def _ensure_encoding(encoding):
class PossibleDataLossError(Exception):
pass
+
class ClosedFileError(Exception):
pass
+
class IncompatibilityWarning(Warning):
pass
@@ -76,6 +78,7 @@ class IncompatibilityWarning(Warning):
the copy_to method)
"""
+
class AttributeConflictWarning(Warning):
pass
@@ -84,6 +87,7 @@ class AttributeConflictWarning(Warning):
[%s], resetting the attribute to None
"""
+
class DuplicateWarning(Warning):
pass
@@ -96,6 +100,23 @@ class DuplicateWarning(Warning):
map directly to c-types [inferred_type->%s,key->%s] [items->%s]
"""
+# formats
+_FORMAT_MAP = {
+ u('s') : 's',
+ u('storer') : 's',
+ u('t') : 't',
+ u('table') : 't',
+ }
+
+fmt_deprecate_doc = """
+the table keyword has been deprecated
+use the fmt='s|t' keyword instead
+ s : specifies the Storer format
+ and is the default for put operations
+ t : specifies the Table format
+ and is the default for append operations
+"""
+
# map object types
_TYPE_MAP = {
@@ -111,30 +132,30 @@ class DuplicateWarning(Warning):
# storer class map
_STORER_MAP = {
- u('TimeSeries') : 'LegacySeriesStorer',
- u('Series') : 'LegacySeriesStorer',
- u('DataFrame') : 'LegacyFrameStorer',
- u('DataMatrix') : 'LegacyFrameStorer',
- u('series') : 'SeriesStorer',
- u('sparse_series') : 'SparseSeriesStorer',
- u('frame') : 'FrameStorer',
- u('sparse_frame') : 'SparseFrameStorer',
- u('wide') : 'PanelStorer',
- u('sparse_panel') : 'SparsePanelStorer',
+ u('TimeSeries'): 'LegacySeriesStorer',
+ u('Series'): 'LegacySeriesStorer',
+ u('DataFrame'): 'LegacyFrameStorer',
+ u('DataMatrix'): 'LegacyFrameStorer',
+ u('series'): 'SeriesStorer',
+ u('sparse_series'): 'SparseSeriesStorer',
+ u('frame'): 'FrameStorer',
+ u('sparse_frame'): 'SparseFrameStorer',
+ u('wide'): 'PanelStorer',
+ u('sparse_panel'): 'SparsePanelStorer',
}
# table class map
_TABLE_MAP = {
- u('generic_table') : 'GenericTable',
+ u('generic_table'): 'GenericTable',
u('appendable_series') : 'AppendableSeriesTable',
u('appendable_multiseries'): 'AppendableMultiSeriesTable',
- u('appendable_frame') : 'AppendableFrameTable',
- u('appendable_multiframe') : 'AppendableMultiFrameTable',
- u('appendable_panel') : 'AppendablePanelTable',
- u('appendable_ndim') : 'AppendableNDimTable',
- u('worm') : 'WORMTable',
- u('legacy_frame') : 'LegacyFrameTable',
- u('legacy_panel') : 'LegacyPanelTable',
+ u('appendable_frame'): 'AppendableFrameTable',
+ u('appendable_multiframe'): 'AppendableMultiFrameTable',
+ u('appendable_panel'): 'AppendablePanelTable',
+ u('appendable_ndim'): 'AppendableNDimTable',
+ u('worm'): 'WORMTable',
+ u('legacy_frame'): 'LegacyFrameTable',
+ u('legacy_panel'): 'LegacyPanelTable',
}
# axes map
@@ -163,6 +184,7 @@ def _tables():
return _table_mod
+
def h5_open(path, mode):
tables = _tables()
return tables.openFile(path, mode)
@@ -192,7 +214,7 @@ def get_store(path, **kwargs):
store.close()
-### interface to/from ###
+# interface to/from ###
def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, append=None, **kwargs):
""" store this object, close it if we opened it """
@@ -207,6 +229,7 @@ def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, app
else:
f(path_or_buf)
+
def read_hdf(path_or_buf, key, **kwargs):
""" read from the store, closeit if we opened it
@@ -231,13 +254,14 @@ def read_hdf(path_or_buf, key, **kwargs):
"""
- f = lambda store, auto_close: store.select(key, auto_close=auto_close, **kwargs)
+ f = lambda store, auto_close: store.select(
+ key, auto_close=auto_close, **kwargs)
if isinstance(path_or_buf, compat.string_types):
# can't auto open/close if we are using an iterator
# so delegate to the iterator
- store = HDFStore(path_or_buf,**kwargs)
+ store = HDFStore(path_or_buf, **kwargs)
try:
return f(store, True)
except:
@@ -253,7 +277,9 @@ def read_hdf(path_or_buf, key, **kwargs):
# a passed store; user controls open/close
f(path_or_buf, False)
+
class HDFStore(StringMixin):
+
"""
dict-like IO interface for storing pandas objects in PyTables
format.
@@ -345,7 +371,8 @@ def __contains__(self, key):
node = self.get_node(key)
if node is not None:
name = node._v_pathname
- if name == key or name[1:] == key: return True
+ if name == key or name[1:] == key:
+ return True
return False
def __len__(self):
@@ -356,7 +383,7 @@ def __unicode__(self):
if self.is_open:
lkeys = list(self.keys())
if len(lkeys):
- keys = []
+ keys = []
values = []
for k in lkeys:
@@ -364,10 +391,12 @@ def __unicode__(self):
s = self.get_storer(k)
if s is not None:
keys.append(pprint_thing(s.pathname or k))
- values.append(pprint_thing(s or 'invalid_HDFStore node'))
+ values.append(
+ pprint_thing(s or 'invalid_HDFStore node'))
except Exception as detail:
keys.append(k)
- values.append("[invalid_HDFStore node: %s]" % pprint_thing(detail))
+ values.append(
+ "[invalid_HDFStore node: %s]" % pprint_thing(detail))
output += adjoin(12, keys, values)
else:
@@ -405,14 +434,14 @@ def open(self, mode='a'):
if self._mode != mode:
# if we are chaning a write mode to read, ok
- if self._mode in ['a','w'] and mode in ['r','r+']:
+ if self._mode in ['a', 'w'] and mode in ['r', 'r+']:
pass
elif mode in ['w']:
# this would truncate, raise here
if self.is_open:
raise PossibleDataLossError("Re-opening the file [{0}] with mode [{1}] "
- "will delete the current file!".format(self._path,self._mode))
+ "will delete the current file!".format(self._path, self._mode))
self._mode = mode
@@ -449,7 +478,8 @@ def is_open(self):
"""
return a boolean indicating whether the file is open
"""
- if self._handle is None: return False
+ if self._handle is None:
+ return False
return bool(self._handle.isopen)
def flush(self):
@@ -511,7 +541,8 @@ def func(_start, _stop):
if iterator or chunksize is not None:
if not s.is_table:
- raise TypeError("can only use an iterator or chunksize on a table")
+ raise TypeError(
+ "can only use an iterator or chunksize on a table")
return TableIterator(self, func, nrows=s.nrows, start=start, stop=stop, chunksize=chunksize, auto_close=auto_close)
return TableIterator(self, func, nrows=s.nrows, start=start, stop=stop, auto_close=auto_close).get_values()
@@ -531,8 +562,8 @@ def select_as_coordinates(self, key, where=None, start=None, stop=None, **kwargs
def unique(self, key, column, **kwargs):
warnings.warn("unique(key,column) is deprecated\n"
- "use select_column(key,column).unique() instead")
- return self.get_storer(key).read_column(column = column, **kwargs).unique()
+ "use select_column(key,column).unique() instead",FutureWarning)
+ return self.get_storer(key).read_column(column=column, **kwargs).unique()
def select_column(self, key, column, **kwargs):
"""
@@ -549,7 +580,7 @@ def select_column(self, key, column, **kwargs):
raises ValueError if the column can not be extracted indivually (it is part of a data block)
"""
- return self.get_storer(key).read_column(column = column, **kwargs)
+ return self.get_storer(key).read_column(column=column, **kwargs)
def select_as_multiple(self, keys, where=None, selector=None, columns=None, start=None, stop=None, iterator=False, chunksize=None, auto_close=False, **kwargs):
""" Retrieve pandas objects from multiple tables
@@ -585,7 +616,7 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, star
selector = keys[0]
# collect the tables
- tbls = [ self.get_storer(k) for k in keys ]
+ tbls = [self.get_storer(k) for k in keys]
# validate rows
nrows = None
@@ -593,16 +624,19 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, star
if t is None:
raise TypeError("Invalid table [%s]" % k)
if not t.is_table:
- raise TypeError("object [%s] is not a table, and cannot be used in all select as multiple" % t.pathname)
+ raise TypeError(
+ "object [%s] is not a table, and cannot be used in all select as multiple" % t.pathname)
if nrows is None:
nrows = t.nrows
elif t.nrows != nrows:
- raise ValueError("all tables must have exactly the same nrows!")
+ raise ValueError(
+ "all tables must have exactly the same nrows!")
# select coordinates from the selector table
try:
- c = self.select_as_coordinates(selector, where, start=start, stop=stop)
+ c = self.select_as_coordinates(
+ selector, where, start=start, stop=stop)
nrows = len(c)
except (Exception) as detail:
raise ValueError("invalid selector [%s]" % selector)
@@ -610,7 +644,8 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, star
def func(_start, _stop):
# collect the returns objs
- objs = [t.read(where=c[_start:_stop], columns=columns) for t in tbls]
+ objs = [t.read(where=c[_start:_stop], columns=columns)
+ for t in tbls]
# axis is the concentation axes
axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0]
@@ -623,8 +658,7 @@ def func(_start, _stop):
return TableIterator(self, func, nrows=nrows, start=start, stop=stop, auto_close=auto_close).get_values()
-
- def put(self, key, value, table=None, append=False, **kwargs):
+ def put(self, key, value, fmt=None, append=False, **kwargs):
"""
Store object in HDFStore
@@ -632,16 +666,20 @@ def put(self, key, value, table=None, append=False, **kwargs):
----------
key : object
value : {Series, DataFrame, Panel}
- table : boolean, default False
- Write as a PyTables Table structure which may perform worse but
- allow more flexible operations like searching / selecting subsets
- of the data
+ fmt : 's|t', default is 's' for storer format
+ s : storer format
+ Fast writing/reading. Not-appendable, nor searchable
+ t : table format
+ Write as a PyTables Table structure which may perform worse but
+ allow more flexible operations like searching / selecting subsets
+ of the data
append : boolean, default False
For table data structures, append the input data to the existing
table
encoding : default None, provide an encoding for strings
"""
- self._write_to_group(key, value, table=table, append=append, **kwargs)
+ kwargs = self._validate_format(fmt or 's', kwargs)
+ self._write_to_group(key, value, append=append, **kwargs)
def remove(self, key, where=None, start=None, stop=None):
"""
@@ -669,7 +707,8 @@ def remove(self, key, where=None, start=None, stop=None):
except:
if where is not None:
- raise ValueError("trying to remove a node with a non-None where clause!")
+ raise ValueError(
+ "trying to remove a node with a non-None where clause!")
# we are actually trying to remove a node (with children)
s = self.get_node(key)
@@ -687,10 +726,11 @@ def remove(self, key, where=None, start=None, stop=None):
# delete from the table
else:
if not s.is_table:
- raise ValueError('can only remove with where on objects written as tables')
- return s.delete(where = where, start=start, stop=stop)
+ raise ValueError(
+ 'can only remove with where on objects written as tables')
+ return s.delete(where=where, start=start, stop=stop)
- def append(self, key, value, columns=None, **kwargs):
+ def append(self, key, value, fmt=None, append=True, columns=None, **kwargs):
"""
Append to Table in file. Node must already exist and be Table
format.
@@ -699,6 +739,12 @@ def append(self, key, value, columns=None, **kwargs):
----------
key : object
value : {Series, DataFrame, Panel, Panel4D}
+ fmt : 't', default is 't' for table format
+ t : table format
+ Write as a PyTables Table structure which may perform worse but
+ allow more flexible operations like searching / selecting subsets
+ of the data
+ append : boolean, default True, append the input data to the existing
data_columns : list of columns to create as data columns, or True to use all columns
min_itemsize : dict of columns that specify minimum string sizes
nan_rep : string to use as string nan represenation
@@ -712,9 +758,11 @@ def append(self, key, value, columns=None, **kwargs):
data in the table, so be careful
"""
if columns is not None:
- raise Exception("columns is not a supported keyword in append, try data_columns")
+ raise Exception(
+ "columns is not a supported keyword in append, try data_columns")
- self._write_to_group(key, value, table=True, append=True, **kwargs)
+ kwargs = self._validate_format(fmt or 't', kwargs)
+ self._write_to_group(key, value, append=append, **kwargs)
def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, **kwargs):
"""
@@ -735,13 +783,16 @@ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, *
"""
if axes is not None:
- raise Exception("axes is currently not accepted as a paremter to append_to_multiple; you can create the tables indepdently instead")
+ raise Exception(
+ "axes is currently not accepted as a paremter to append_to_multiple; you can create the tables indepdently instead")
if not isinstance(d, dict):
- raise ValueError("append_to_multiple must have a dictionary specified as the way to split the value")
+ raise ValueError(
+ "append_to_multiple must have a dictionary specified as the way to split the value")
if selector not in d:
- raise ValueError("append_to_multiple requires a selector that is in passed dict")
+ raise ValueError(
+ "append_to_multiple requires a selector that is in passed dict")
# figure out the splitting axis (the non_index_axis)
axis = list(set(range(value.ndim)) - set(_AXES_MAP[type(value)]))[0]
@@ -752,7 +803,8 @@ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, *
for k, v in d.items():
if v is None:
if remain_key is not None:
- raise ValueError("append_to_multiple can only have one value in d that is None")
+ raise ValueError(
+ "append_to_multiple can only have one value in d that is None")
remain_key = k
else:
remain_values.extend(v)
@@ -793,7 +845,8 @@ def create_table_index(self, key, **kwargs):
raise Exception("PyTables >= 2.3 is required for table indexing")
s = self.get_storer(key)
- if s is None: return
+ if s is None:
+ return
if not s.is_table:
raise TypeError("cannot create table index on a non-table")
@@ -803,8 +856,8 @@ def groups(self):
""" return a list of all the top-level nodes (that are not themselves a pandas storage object) """
_tables()
self._check_if_open()
- return [ g for g in self._handle.walkNodes() if getattr(g._v_attrs,'pandas_type',None) or getattr(
- g,'table',None) or (isinstance(g,_table_mod.table.Table) and g._v_name != u('table')) ]
+ return [g for g in self._handle.walkNodes() if getattr(g._v_attrs, 'pandas_type', None) or getattr(
+ g, 'table', None) or (isinstance(g, _table_mod.table.Table) and g._v_name != u('table'))]
def get_node(self, key):
""" return the node with the key or None if it does not exist """
@@ -825,8 +878,9 @@ def get_storer(self, key):
s.infer_axes()
return s
- def copy(self, file, mode = 'w', propindexes = True, keys = None, complib = None, complevel = None,
- fletcher32 = False, overwrite = True):
+ def copy(
+ self, file, mode='w', propindexes=True, keys=None, complib = None, complevel = None,
+ fletcher32=False, overwrite=True):
""" copy the existing store to a new file, upgrading in place
Parameters
@@ -841,13 +895,14 @@ def copy(self, file, mode = 'w', propindexes = True, keys = None, complib = None
open file handle of the new store
"""
- new_store = HDFStore(file, mode = mode, complib = complib, complevel = complevel, fletcher32 = fletcher32)
+ new_store = HDFStore(
+ file, mode=mode, complib=complib, complevel=complevel, fletcher32 = fletcher32)
if keys is None:
keys = list(self.keys())
- if not isinstance(keys, (tuple,list)):
- keys = [ keys ]
+ if not isinstance(keys, (tuple, list)):
+ keys = [keys]
for k in keys:
- s = self.get_storer(k)
+ s = self.get_storer(k)
if s is not None:
if k in new_store:
@@ -859,38 +914,67 @@ def copy(self, file, mode = 'w', propindexes = True, keys = None, complib = None
index = False
if propindexes:
- index = [ a.name for a in s.axes if a.is_indexed ]
- new_store.append(k, data, index=index, data_columns=getattr(s,'data_columns',None), encoding=s.encoding)
+ index = [a.name for a in s.axes if a.is_indexed]
+ new_store.append(k, data, index=index, data_columns=getattr(
+ s, 'data_columns', None), encoding=s.encoding)
else:
new_store.put(k, data, encoding=s.encoding)
return new_store
- ###### private methods ######
+ # private methods ######
def _check_if_open(self):
if not self.is_open:
raise ClosedFileError("{0} file is not open!".format(self._path))
- def _create_storer(self, group, value = None, table = False, append = False, **kwargs):
+ def _validate_format(self, fmt, kwargs):
+ """ validate / deprecate formats; return the new kwargs """
+ kwargs = kwargs.copy()
+
+ if 'format' in kwargs:
+ raise TypeError("pls specify an object format with the 'fmt' keyword")
+
+ # table arg
+ table = kwargs.pop('table',None)
+
+ if table is not None:
+ warnings.warn(fmt_deprecate_doc,FutureWarning)
+
+ if table:
+ fmt = 't'
+ else:
+ fmt = 's'
+
+ # validate
+ try:
+ kwargs['fmt'] = _FORMAT_MAP[fmt.lower()]
+ except:
+ raise TypeError("invalid HDFStore format specified [{0}]".format(fmt))
+
+ return kwargs
+
+ def _create_storer(self, group, fmt=None, value=None, append=False, **kwargs):
""" return a suitable Storer class to operate """
def error(t):
- raise TypeError("cannot properly create the storer for: [%s] [group->%s,value->%s,table->%s,append->%s,kwargs->%s]" %
- (t,group,type(value),table,append,kwargs))
+ raise TypeError(
+ "cannot properly create the storer for: [%s] [group->%s,value->%s,fmt->%s,append->%s,kwargs->%s]" %
+ (t, group, type(value), fmt, append, kwargs))
- pt = _ensure_decoded(getattr(group._v_attrs,'pandas_type',None))
- tt = _ensure_decoded(getattr(group._v_attrs,'table_type',None))
+ pt = _ensure_decoded(getattr(group._v_attrs, 'pandas_type', None))
+ tt = _ensure_decoded(getattr(group._v_attrs, 'table_type', None))
# infer the pt from the passed value
if pt is None:
if value is None:
_tables()
- if getattr(group,'table',None) or isinstance(group,_table_mod.table.Table):
+ if getattr(group, 'table', None) or isinstance(group, _table_mod.table.Table):
pt = u('frame_table')
tt = u('generic_table')
else:
- raise TypeError("cannot create a storer if the object is not existing nor a value are passed")
+ raise TypeError(
+ "cannot create a storer if the object is not existing nor a value are passed")
else:
try:
@@ -899,7 +983,7 @@ def error(t):
error('_TYPE_MAP')
# we are actually a table
- if table or append:
+ if fmt == 't':
pt += u('_table')
# a storer node
@@ -930,7 +1014,7 @@ def error(t):
elif index.nlevels > 1:
tt = u('appendable_multiframe')
elif pt == u('wide_table'):
- tt = u('appendable_panel')
+ tt = u('appendable_panel')
elif pt == u('ndim_table'):
tt = u('appendable_ndim')
@@ -950,7 +1034,8 @@ def error(t):
except:
error('_TABLE_MAP')
- def _write_to_group(self, key, value, index=True, table=False, append=False,
+ def _write_to_group(
+ self, key, value, fmt, index=True, append=False,
complib=None, encoding=None, **kwargs):
group = self.get_node(key)
@@ -961,7 +1046,7 @@ def _write_to_group(self, key, value, index=True, table=False, append=False,
# we don't want to store a table node at all if are object is 0-len
# as there are not dtypes
- if getattr(value,'empty',None) and (table or append):
+ if getattr(value,'empty',None) and (fmt == 't' or append):
return
if group is None:
@@ -981,12 +1066,12 @@ def _write_to_group(self, key, value, index=True, table=False, append=False,
group = self._handle.createGroup(path, p)
path = new_path
- s = self._create_storer(group, value, table=table, append=append,
+ s = self._create_storer(group, fmt, value, append=append,
encoding=encoding, **kwargs)
if append:
# raise if we are trying to append to a non-table,
# or a table that exists (and we are putting)
- if not s.is_table or (s.is_table and table is None and s.is_exists):
+ if not s.is_table or (s.is_table and fmt == 's' and s.is_exists):
raise ValueError('Can only append to Tables')
if not s.is_exists:
s.set_object_info()
@@ -997,16 +1082,19 @@ def _write_to_group(self, key, value, index=True, table=False, append=False,
raise ValueError('Compression not supported on non-table')
# write the object
- s.write(obj = value, append=append, complib=complib, **kwargs)
+ s.write(obj=value, append=append, complib=complib, **kwargs)
+
if s.is_table and index:
- s.create_index(columns = index)
+ s.create_index(columns=index)
def _read_group(self, group, **kwargs):
s = self._create_storer(group)
s.infer_axes()
return s.read(**kwargs)
+
class TableIterator(object):
+
""" define the iteration interface on a table
Parameters
@@ -1025,13 +1113,13 @@ class TableIterator(object):
def __init__(self, store, func, nrows, start=None, stop=None, chunksize=None, auto_close=False):
self.store = store
- self.func = func
+ self.func = func
self.nrows = nrows or 0
self.start = start or 0
if stop is None:
stop = self.nrows
- self.stop = min(self.nrows,stop)
+ self.stop = min(self.nrows, stop)
if chunksize is None:
chunksize = 100000
@@ -1062,7 +1150,9 @@ def get_values(self):
self.close()
return results
+
class IndexCol(StringMixin):
+
""" an index column description class
Parameters
@@ -1077,9 +1167,10 @@ class IndexCol(StringMixin):
"""
is_an_indexable = True
is_data_indexable = True
- _info_fields = ['freq','tz','index_name']
+ _info_fields = ['freq', 'tz', 'index_name']
- def __init__(self, values=None, kind=None, typ=None, cname=None, itemsize=None,
+ def __init__(
+ self, values=None, kind=None, typ=None, cname=None, itemsize=None,
name=None, axis=None, kind_attr=None, pos=None, freq=None, tz=None,
index_name=None, **kwargs):
self.values = values
@@ -1128,7 +1219,8 @@ def set_table(self, table):
return self
def __unicode__(self):
- temp = tuple(map(pprint_thing, (self.name, self.cname, self.axis, self.pos, self.kind)))
+ temp = tuple(
+ map(pprint_thing, (self.name, self.cname, self.axis, self.pos, self.kind)))
return "name->%s,cname->%s,axis->%s,pos->%s,kind->%s" % temp
def __eq__(self, other):
@@ -1142,7 +1234,7 @@ def __ne__(self, other):
def is_indexed(self):
""" return whether I am an indexed column """
try:
- return getattr(self.table.cols,self.cname).is_indexed
+ return getattr(self.table.cols, self.cname).is_indexed
except:
False
@@ -1164,7 +1256,7 @@ def convert(self, values, nan_rep, encoding):
except:
pass
- values =_maybe_convert(values, self.kind, encoding)
+ values = _maybe_convert(values, self.kind, encoding)
kwargs = dict()
if self.freq is not None:
@@ -1175,15 +1267,18 @@ def convert(self, values, nan_rep, encoding):
self.values = Index(values, **kwargs)
except:
- # if the output freq is different that what we recorded, then infer it
+ # if the output freq is different that what we recorded, then infer
+ # it
if 'freq' in kwargs:
kwargs['freq'] = 'infer'
- self.values = Index(_maybe_convert(values, self.kind, encoding), **kwargs)
+ self.values = Index(
+ _maybe_convert(values, self.kind, encoding), **kwargs)
# set the timezone if indicated
# we stored in utc, so reverse to local timezone
if self.tz is not None:
- self.values = self.values.tz_localize('UTC').tz_convert(_ensure_decoded(self.tz))
+ self.values = self.values.tz_localize(
+ 'UTC').tz_convert(_ensure_decoded(self.tz))
return self
@@ -1246,7 +1341,7 @@ def validate_col(self, itemsize=None):
raise ValueError("Trying to store a string with len [%s] in [%s] column but\n"
"this column has a limit of [%s]!\n"
"Consider using min_itemsize to preset the sizes on these columns"
- % (itemsize,self.cname, c.itemsize))
+ % (itemsize, self.cname, c.itemsize))
return c.itemsize
return None
@@ -1265,7 +1360,7 @@ def update_info(self, info):
for key in self._info_fields:
- value = getattr(self,key,None)
+ value = getattr(self, key, None)
try:
idx = info[self.name]
@@ -1276,18 +1371,18 @@ def update_info(self, info):
if key in idx and value is not None and existing_value != value:
# frequency/name just warn
- if key in ['freq','index_name']:
- ws = attribute_conflict_doc % (key,existing_value,value)
+ if key in ['freq', 'index_name']:
+ ws = attribute_conflict_doc % (key, existing_value, value)
warnings.warn(ws, AttributeConflictWarning)
# reset
idx[key] = None
- setattr(self,key,None)
+ setattr(self, key, None)
else:
raise ValueError("invalid info for [%s] for [%s]"""
", existing_value [%s] conflicts with new value [%s]" % (self.name,
- key,existing_value,value))
+ key, existing_value, value))
else:
if value is not None or existing_value is not None:
idx[key] = value
@@ -1308,7 +1403,9 @@ def set_attr(self):
""" set the kind for this colummn """
setattr(self.attrs, self.kind_attr, self.kind)
+
class GenericIndexCol(IndexCol):
+
""" an index which is not represented in the data of the table """
@property
@@ -1327,7 +1424,9 @@ def get_attr(self):
def set_attr(self):
pass
+
class DataCol(IndexCol):
+
""" a data holding column, by definition this is not indexable
Parameters
@@ -1405,11 +1504,12 @@ def set_kind(self):
elif dtype.startswith(u('bool')):
self.kind = 'bool'
else:
- raise AssertionError("cannot interpret dtype of [%s] in [%s]" % (dtype,self))
+ raise AssertionError(
+ "cannot interpret dtype of [%s] in [%s]" % (dtype, self))
# set my typ if we need
if self.typ is None:
- self.typ = getattr(self.description,self.cname,None)
+ self.typ = getattr(self.description, self.cname, None)
def set_atom(self, block, existing_col, min_itemsize, nan_rep, info, encoding=None, **kwargs):
""" create and setup my atom from the block b """
@@ -1425,7 +1525,7 @@ def set_atom(self, block, existing_col, min_itemsize, nan_rep, info, encoding=No
raise TypeError(
"[date] is not implemented as a table column")
elif inferred_type == 'datetime':
- if getattr(rvalues[0],'tzinfo',None) is not None:
+ if getattr(rvalues[0], 'tzinfo', None) is not None:
# if this block has more than one timezone, raise
if len(set([r.tzinfo for r in rvalues])) != 1:
@@ -1434,7 +1534,7 @@ def set_atom(self, block, existing_col, min_itemsize, nan_rep, info, encoding=No
# convert this column to datetime64[ns] utc, and save the tz
index = DatetimeIndex(rvalues)
- tz = getattr(index,'tz',None)
+ tz = getattr(index, 'tz', None)
if tz is None:
raise TypeError(
"invalid timezone specification")
@@ -1448,7 +1548,8 @@ def set_atom(self, block, existing_col, min_itemsize, nan_rep, info, encoding=No
self.tz = zone
self.update_info(info)
- self.set_atom_datetime64(block, values.reshape(block.values.shape))
+ self.set_atom_datetime64(
+ block, values.reshape(block.values.shape))
else:
raise TypeError(
@@ -1460,7 +1561,8 @@ def set_atom(self, block, existing_col, min_itemsize, nan_rep, info, encoding=No
# this is basically a catchall; if say a datetime64 has nans then will
# end up here ###
elif inferred_type == 'string' or dtype == 'object':
- self.set_atom_string(block, existing_col, min_itemsize, nan_rep, encoding)
+ self.set_atom_string(
+ block, existing_col, min_itemsize, nan_rep, encoding)
else:
self.set_atom_data(block)
@@ -1472,13 +1574,14 @@ def get_atom_string(self, block, itemsize):
def set_atom_string(self, block, existing_col, min_itemsize, nan_rep, encoding):
# fill nan items with myself
block = block.fillna(nan_rep)[0]
- data = block.values
+ data = block.values
# see if we have a valid string type
inferred_type = lib.infer_dtype(data.ravel())
if inferred_type != 'string':
- # we cannot serialize this data, so report an exception on a column by column basis
+ # we cannot serialize this data, so report an exception on a column
+ # by column basis
for item in block.items:
col = block.get(item)
@@ -1486,8 +1589,7 @@ def set_atom_string(self, block, existing_col, min_itemsize, nan_rep, encoding):
if inferred_type != 'string':
raise TypeError("Cannot serialize the column [%s] because\n"
"its data contents are [%s] object dtype" %
- (item,inferred_type))
-
+ (item, inferred_type))
# itemsize is the maximum length of a string (along any dimension)
itemsize = lib.max_len_string_array(com._ensure_object(data.ravel()))
@@ -1532,7 +1634,7 @@ def set_atom_data(self, block):
def get_atom_datetime64(self, block):
return _tables().Int64Col(shape=block.shape[0])
- def set_atom_datetime64(self, block, values = None):
+ def set_atom_datetime64(self, block, values=None):
self.kind = 'datetime64'
self.typ = self.get_atom_datetime64(block)
if values is None:
@@ -1583,8 +1685,10 @@ def convert(self, values, nan_rep, encoding):
# data should be 2-dim here
# we stored as utc, so just set the tz
- index = DatetimeIndex(self.data.ravel(),tz='UTC').tz_convert(self.tz)
- self.data = np.array(index.tolist(),dtype=object).reshape(self.data.shape)
+ index = DatetimeIndex(
+ self.data.ravel(), tz='UTC').tz_convert(self.tz)
+ self.data = np.array(
+ index.tolist(), dtype=object).reshape(self.data.shape)
else:
self.data = np.asarray(self.data, dtype='M8[ns]')
@@ -1605,14 +1709,15 @@ def convert(self, values, nan_rep, encoding):
# convert nans / decode
if _ensure_decoded(self.kind) == u('string'):
- self.data = _unconvert_string_array(self.data, nan_rep=nan_rep, encoding=encoding)
+ self.data = _unconvert_string_array(
+ self.data, nan_rep=nan_rep, encoding=encoding)
return self
def get_attr(self):
""" get the data for this colummn """
self.values = getattr(self.attrs, self.kind_attr, None)
- self.dtype = getattr(self.attrs, self.dtype_attr, None)
+ self.dtype = getattr(self.attrs, self.dtype_attr, None)
self.set_kind()
def set_attr(self):
@@ -1623,6 +1728,7 @@ def set_attr(self):
class DataIndexableCol(DataCol):
+
""" represent a data column that can be indexed """
is_data_indexable = True
@@ -1635,13 +1741,17 @@ def get_atom_data(self, block):
def get_atom_datetime64(self, block):
return _tables().Int64Col()
+
class GenericDataIndexableCol(DataIndexableCol):
+
""" represent a generic pytables data column """
def get_attr(self):
pass
+
class Storer(StringMixin):
+
""" represent an object in my store
facilitate read/write of various types of objects
this is an abstract base class
@@ -1653,14 +1763,14 @@ class Storer(StringMixin):
group : the group node where the table resides
"""
pandas_kind = None
- obj_type = None
- ndim = None
- is_table = False
+ obj_type = None
+ ndim = None
+ is_table = False
def __init__(self, parent, group, encoding=None, **kwargs):
- self.parent = parent
- self.group = group
- self.encoding = _ensure_encoding(encoding)
+ self.parent = parent
+ self.group = group
+ self.encoding = _ensure_encoding(encoding)
self.set_version()
@property
@@ -1669,7 +1779,8 @@ def is_old_version(self):
def set_version(self):
""" compute and set our version """
- version = _ensure_decoded(getattr(self.group._v_attrs,'pandas_version',None))
+ version = _ensure_decoded(
+ getattr(self.group._v_attrs, 'pandas_version', None))
try:
self.version = tuple([int(x) for x in version.split('.')])
if len(self.version) == 2:
@@ -1686,9 +1797,9 @@ def __unicode__(self):
self.infer_axes()
s = self.shape
if s is not None:
- if isinstance(s, (list,tuple)):
+ if isinstance(s, (list, tuple)):
s = "[%s]" % ','.join([pprint_thing(x) for x in s])
- return "%-12.12s (shape->%s)" % (self.pandas_type,s)
+ return "%-12.12s (shape->%s)" % (self.pandas_type, s)
return self.pandas_type
def set_object_info(self):
@@ -1756,14 +1867,15 @@ def is_exists(self):
@property
def nrows(self):
- return getattr(self.storable,'nrows',None)
+ return getattr(self.storable, 'nrows', None)
def validate(self, other):
""" validate against an existing storable """
- if other is None: return
+ if other is None:
+ return
return True
- def validate_version(self, where = None):
+ def validate_version(self, where=None):
""" are we trying to operate on an old version? """
return True
@@ -1778,12 +1890,14 @@ def infer_axes(self):
return True
def read(self, **kwargs):
- raise NotImplementedError("cannot read on an abstract storer: subclasses should implement")
+ raise NotImplementedError(
+ "cannot read on an abstract storer: subclasses should implement")
def write(self, **kwargs):
- raise NotImplementedError("cannot write on an abstract storer: sublcasses should implement")
+ raise NotImplementedError(
+ "cannot write on an abstract storer: sublcasses should implement")
- def delete(self, where = None, **kwargs):
+ def delete(self, where=None, **kwargs):
""" support fully deleting the node in its entirety (only) - where specification must be None """
if where is None:
self._handle.removeNode(self.group, recursive=True)
@@ -1791,11 +1905,14 @@ def delete(self, where = None, **kwargs):
raise TypeError("cannot delete on an abstract storer")
+
class GenericStorer(Storer):
+
""" a generified storer version """
- _index_type_map = { DatetimeIndex: 'datetime',
+ _index_type_map = {DatetimeIndex: 'datetime',
PeriodIndex: 'period'}
- _reverse_index_map = dict([ (v,k) for k, v in compat.iteritems(_index_type_map) ])
+ _reverse_index_map = dict([(v, k)
+ for k, v in compat.iteritems(_index_type_map)])
attributes = []
# indexer helpders
@@ -1804,7 +1921,8 @@ def _class_to_alias(self, cls):
def _alias_to_class(self, alias):
if isinstance(alias, type): # pragma: no cover
- return alias # compat: for a short period of time master stored types
+ # compat: for a short period of time master stored types
+ return alias
return self._reverse_index_map.get(alias, Index)
def _get_index_factory(self, klass):
@@ -1833,9 +1951,9 @@ def set_attrs(self):
def get_attrs(self):
""" retrieve our attributes """
- self.encoding = _ensure_encoding(getattr(self.attrs,'encoding',None))
+ self.encoding = _ensure_encoding(getattr(self.attrs, 'encoding', None))
for n in self.attributes:
- setattr(self,n,_ensure_decoded(getattr(self.attrs, n, None)))
+ setattr(self, n, _ensure_decoded(getattr(self.attrs, n, None)))
def write(self, obj, **kwargs):
self.set_attrs()
@@ -1896,7 +2014,7 @@ def write_index(self, key, index):
self.write_sparse_intindex(key, index)
else:
setattr(self.attrs, '%s_variety' % key, 'regular')
- converted = _convert_index(index,self.encoding).set_name('index')
+ converted = _convert_index(index, self.encoding).set_name('index')
self.write_array(key, converted.values)
node = getattr(self.group, key)
node._v_attrs.kind = converted.kind
@@ -1914,7 +2032,6 @@ def write_index(self, key, index):
zone = tslib.tot_seconds(index.tz.utcoffset())
node._v_attrs.tz = zone
-
def write_block_index(self, key, index):
self.write_array('%s_blocs' % key, index.blocs)
self.write_array('%s_blengths' % key, index.blengths)
@@ -1994,10 +2111,12 @@ def read_index_node(self, node):
kwargs['tz'] = node._v_attrs['tz']
if kind in (u('date'), u('datetime')):
- index = factory(_unconvert_index(data, kind, encoding=self.encoding), dtype=object,
+ index = factory(
+ _unconvert_index(data, kind, encoding=self.encoding), dtype=object,
**kwargs)
else:
- index = factory(_unconvert_index(data, kind, encoding=self.encoding), **kwargs)
+ index = factory(
+ _unconvert_index(data, kind, encoding=self.encoding), **kwargs)
index.name = name
@@ -2048,7 +2167,8 @@ def write_array(self, key, value, items=None):
if value.dtype.type == np.object_:
- # infer the type, warn if we have a non-string type here (for performance)
+ # infer the type, warn if we have a non-string type here (for
+ # performance)
inferred_type = lib.infer_dtype(value.ravel())
if empty_array:
pass
@@ -2059,7 +2179,7 @@ def write_array(self, key, value, items=None):
items = list(items)
except:
pass
- ws = performance_doc % (inferred_type,key,items)
+ ws = performance_doc % (inferred_type, key, items)
warnings.warn(ws, PerformanceWarning)
vlarr = self._handle.createVLArray(self.group, key,
@@ -2076,14 +2196,16 @@ def write_array(self, key, value, items=None):
getattr(self.group, key)._v_attrs.transposed = transposed
+
class LegacyStorer(GenericStorer):
def read_index_legacy(self, key):
- node = getattr(self.group,key)
+ node = getattr(self.group, key)
data = node[:]
kind = node._v_attrs.kind
return _unconvert_index_legacy(data, kind, encoding=self.encoding)
+
class LegacySeriesStorer(LegacyStorer):
def read(self, **kwargs):
@@ -2092,6 +2214,7 @@ def read(self, **kwargs):
values = self.read_array('values')
return Series(values, index=index)
+
class LegacyFrameStorer(LegacyStorer):
def read(self, **kwargs):
@@ -2101,6 +2224,7 @@ def read(self, **kwargs):
values = self.read_array('values')
return DataFrame(values, index=index, columns=columns)
+
class SeriesStorer(GenericStorer):
pandas_kind = u('series')
attributes = ['name']
@@ -2108,7 +2232,7 @@ class SeriesStorer(GenericStorer):
@property
def shape(self):
try:
- return len(getattr(self.group,'values')),
+ return len(getattr(self.group, 'values')),
except:
return None
@@ -2128,9 +2252,10 @@ def write(self, obj, **kwargs):
self.write_array('values', obj.values)
self.attrs.name = obj.name
+
class SparseSeriesStorer(GenericStorer):
pandas_kind = u('sparse_series')
- attributes = ['name','fill_value','kind']
+ attributes = ['name', 'fill_value', 'kind']
def read(self, **kwargs):
self.validate_read(kwargs)
@@ -2150,9 +2275,10 @@ def write(self, obj, **kwargs):
self.attrs.fill_value = obj.fill_value
self.attrs.kind = obj.kind
+
class SparseFrameStorer(GenericStorer):
pandas_kind = u('sparse_frame')
- attributes = ['default_kind','default_fill_value']
+ attributes = ['default_kind', 'default_fill_value']
def read(self, **kwargs):
self.validate_read(kwargs)
@@ -2160,7 +2286,7 @@ def read(self, **kwargs):
sdict = {}
for c in columns:
key = 'sparse_series_%s' % c
- s = SparseSeriesStorer(self.parent, getattr(self.group,key))
+ s = SparseSeriesStorer(self.parent, getattr(self.group, key))
s.infer_axes()
sdict[c] = s.read()
return SparseDataFrame(sdict, columns=columns,
@@ -2179,12 +2305,13 @@ def write(self, obj, **kwargs):
s = SparseSeriesStorer(self.parent, node)
s.write(ss)
self.attrs.default_fill_value = obj.default_fill_value
- self.attrs.default_kind = obj.default_kind
+ self.attrs.default_kind = obj.default_kind
self.write_index('columns', obj.columns)
+
class SparsePanelStorer(GenericStorer):
pandas_kind = u('sparse_panel')
- attributes = ['default_kind','default_fill_value']
+ attributes = ['default_kind', 'default_fill_value']
def read(self, **kwargs):
self.validate_read(kwargs)
@@ -2194,7 +2321,7 @@ def read(self, **kwargs):
for name in items:
key = 'sparse_frame_%s' % name
node = getattr(self.group, key)
- s = SparseFrameStorer(self.parent, getattr(self.group,key))
+ s = SparseFrameStorer(self.parent, getattr(self.group, key))
s.infer_axes()
sdict[name] = s.read()
return SparsePanel(sdict, items=items, default_kind=self.default_kind,
@@ -2203,7 +2330,7 @@ def read(self, **kwargs):
def write(self, obj, **kwargs):
super(SparsePanelStorer, self).write(obj, **kwargs)
self.attrs.default_fill_value = obj.default_fill_value
- self.attrs.default_kind = obj.default_kind
+ self.attrs.default_kind = obj.default_kind
self.write_index('items', obj.items)
for name, sdf in compat.iteritems(obj):
@@ -2215,8 +2342,9 @@ def write(self, obj, **kwargs):
s = SparseFrameStorer(self.parent, node)
s.write(sdf)
+
class BlockManagerStorer(GenericStorer):
- attributes = ['ndim','nblocks']
+ attributes = ['ndim', 'nblocks']
is_shape_reversed = False
@property
@@ -2228,15 +2356,15 @@ def shape(self):
items = 0
for i in range(self.nblocks):
node = getattr(self.group, 'block%d_items' % i)
- shape = getattr(node,'shape',None)
+ shape = getattr(node, 'shape', None)
if shape is not None:
items += shape[0]
# data shape
node = getattr(self.group, 'block0_values')
- shape = getattr(node,'shape',None)
+ shape = getattr(node, 'shape', None)
if shape is not None:
- shape = list(shape[0:(ndim-1)])
+ shape = list(shape[0:(ndim - 1)])
else:
shape = []
@@ -2286,20 +2414,24 @@ def write(self, obj, **kwargs):
self.write_array('block%d_values' % i, blk.values, items=blk.items)
self.write_index('block%d_items' % i, blk.items)
+
class FrameStorer(BlockManagerStorer):
pandas_kind = u('frame')
- obj_type = DataFrame
+ obj_type = DataFrame
+
class PanelStorer(BlockManagerStorer):
pandas_kind = u('wide')
- obj_type = Panel
+ obj_type = Panel
is_shape_reversed = True
def write(self, obj, **kwargs):
obj._consolidate_inplace()
return super(PanelStorer, self).write(obj, **kwargs)
+
class Table(Storer):
+
""" represent a table:
facilitate read/write of various types of tables
@@ -2317,20 +2449,20 @@ class Table(Storer):
"""
pandas_kind = u('wide_table')
- table_type = None
- levels = 1
- is_table = True
+ table_type = None
+ levels = 1
+ is_table = True
is_shape_reversed = False
def __init__(self, *args, **kwargs):
super(Table, self).__init__(*args, **kwargs)
- self.index_axes = []
+ self.index_axes = []
self.non_index_axes = []
- self.values_axes = []
- self.data_columns = []
- self.info = dict()
- self.nan_rep = None
- self.selection = None
+ self.values_axes = []
+ self.data_columns = []
+ self.info = dict()
+ self.nan_rep = None
+ self.selection = None
@property
def table_type_short(self):
@@ -2339,18 +2471,20 @@ def table_type_short(self):
def __unicode__(self):
""" return a pretty representatgion of myself """
self.infer_axes()
- dc = ",dc->[%s]" % ','.join(self.data_columns) if len(self.data_columns) else ''
+ dc = ",dc->[%s]" % ','.join(
+ self.data_columns) if len(self.data_columns) else ''
ver = ''
if self.is_old_version:
- ver = "[%s]" % '.'.join([ str(x) for x in self.version ])
+ ver = "[%s]" % '.'.join([str(x) for x in self.version])
return "%-12.12s%s (typ->%s,nrows->%s,ncols->%s,indexers->[%s]%s)" % (self.pandas_type,
ver,
self.table_type_short,
self.nrows,
self.ncols,
- ','.join([ a.name for a in self.index_axes ]),
+ ','.join(
+ [a.name for a in self.index_axes]),
dc)
def __getitem__(self, c):
@@ -2362,25 +2496,28 @@ def __getitem__(self, c):
def validate(self, other):
""" validate against an existing table """
- if other is None: return
+ if other is None:
+ return
if other.table_type != self.table_type:
raise TypeError("incompatible table_type with existing [%s - %s]" %
(other.table_type, self.table_type))
- for c in ['index_axes','non_index_axes','values_axes']:
- sv = getattr(self,c,None)
- ov = getattr(other,c,None)
+ for c in ['index_axes', 'non_index_axes', 'values_axes']:
+ sv = getattr(self, c, None)
+ ov = getattr(other, c, None)
if sv != ov:
# show the error for the specific axes
for i, sax in enumerate(sv):
oax = ov[i]
if sax != oax:
- raise ValueError("invalid combinate of [%s] on appending data [%s] vs current table [%s]" % (c,sax,oax))
+ raise ValueError(
+ "invalid combinate of [%s] on appending data [%s] vs current table [%s]" % (c, sax, oax))
# should never get here
- raise Exception("invalid combinate of [%s] on appending data [%s] vs current table [%s]" % (c,sv,ov))
+ raise Exception(
+ "invalid combinate of [%s] on appending data [%s] vs current table [%s]" % (c, sv, ov))
@property
def is_multi_index(self):
@@ -2390,7 +2527,7 @@ def is_multi_index(self):
@property
def nrows_expected(self):
""" based on our axes, compute the expected nrows """
- return np.prod([ i.cvalues.shape[0] for i in self.index_axes ])
+ return np.prod([i.cvalues.shape[0] for i in self.index_axes])
@property
def is_exists(self):
@@ -2399,7 +2536,7 @@ def is_exists(self):
@property
def storable(self):
- return getattr(self.group,'table',None)
+ return getattr(self.group, 'table', None)
@property
def table(self):
@@ -2421,7 +2558,7 @@ def axes(self):
@property
def ncols(self):
""" the number of total columns in the values axes """
- return sum([ len(a.values) for a in self.values_axes ])
+ return sum([len(a.values) for a in self.values_axes])
@property
def is_transposed(self):
@@ -2451,44 +2588,54 @@ def values_cols(self):
def set_info(self):
""" update our table index info """
- self.attrs.info = self.info
+ self.attrs.info = self.info
def set_attrs(self):
""" set our table type & indexables """
- self.attrs.table_type = str(self.table_type)
- self.attrs.index_cols = self.index_cols()
- self.attrs.values_cols = self.values_cols()
+ self.attrs.table_type = str(self.table_type)
+ self.attrs.index_cols = self.index_cols()
+ self.attrs.values_cols = self.values_cols()
self.attrs.non_index_axes = self.non_index_axes
self.attrs.data_columns = self.data_columns
- self.attrs.nan_rep = self.nan_rep
- self.attrs.encoding = self.encoding
- self.attrs.levels = self.levels
+ self.attrs.nan_rep = self.nan_rep
+ self.attrs.encoding = self.encoding
+ self.attrs.levels = self.levels
self.set_info()
def get_attrs(self):
""" retrieve our attributes """
- self.non_index_axes = getattr(self.attrs,'non_index_axes',None) or []
- self.data_columns = getattr(self.attrs,'data_columns',None) or []
- self.info = getattr(self.attrs,'info',None) or dict()
- self.nan_rep = getattr(self.attrs,'nan_rep',None)
- self.encoding = _ensure_encoding(getattr(self.attrs,'encoding',None))
- self.levels = getattr(self.attrs,'levels',None) or []
+ self.non_index_axes = getattr(
+ self.attrs, 'non_index_axes', None) or []
+ self.data_columns = getattr(
+ self.attrs, 'data_columns', None) or []
+ self.info = getattr(
+ self.attrs, 'info', None) or dict()
+ self.nan_rep = getattr(self.attrs, 'nan_rep', None)
+ self.encoding = _ensure_encoding(
+ getattr(self.attrs, 'encoding', None))
+ self.levels = getattr(
+ self.attrs, 'levels', None) or []
t = self.table
- self.index_axes = [ a.infer(t) for a in self.indexables if a.is_an_indexable ]
- self.values_axes = [ a.infer(t) for a in self.indexables if not a.is_an_indexable ]
+ self.index_axes = [a.infer(t)
+ for a in self.indexables if a.is_an_indexable]
+ self.values_axes = [a.infer(t)
+ for a in self.indexables if not a.is_an_indexable]
- def validate_version(self, where = None):
+ def validate_version(self, where=None):
""" are we trying to operate on an old version? """
if where is not None:
if self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1:
- ws = incompatibility_doc % '.'.join([ str(x) for x in self.version ])
+ ws = incompatibility_doc % '.'.join(
+ [str(x) for x in self.version])
warnings.warn(ws, IncompatibilityWarning)
def validate_min_itemsize(self, min_itemsize):
""" validate the min_itemisze doesn't contain items that are not in the axes
this needs data_columns to be defined """
- if min_itemsize is None: return
- if not isinstance(min_itemsize, dict): return
+ if min_itemsize is None:
+ return
+ if not isinstance(min_itemsize, dict):
+ return
q = self.queryables()
for k, v in min_itemsize.items():
@@ -2497,7 +2644,8 @@ def validate_min_itemsize(self, min_itemsize):
if k == 'values':
continue
if k not in q:
- raise ValueError("min_itemsize has the key [%s] which is not an axis or data_column" % k)
+ raise ValueError(
+ "min_itemsize has the key [%s] which is not an axis or data_column" % k)
@property
def indexables(self):
@@ -2508,7 +2656,8 @@ def indexables(self):
self._indexables = []
# index columns
- self._indexables.extend([ IndexCol(name=name,axis=axis,pos=i) for i, (axis, name) in enumerate(self.attrs.index_cols)])
+ self._indexables.extend([IndexCol(name=name, axis=axis, pos=i)
+ for i, (axis, name) in enumerate(self.attrs.index_cols)])
# values columns
dc = set(self.data_columns)
@@ -2626,10 +2775,11 @@ def validate_data_columns(self, data_columns, min_itemsize):
data_columns = []
# if min_itemsize is a dict, add the keys (exclude 'values')
- if isinstance(min_itemsize,dict):
+ if isinstance(min_itemsize, dict):
existing_data_columns = set(data_columns)
- data_columns.extend([ k for k in min_itemsize.keys() if k != 'values' and k not in existing_data_columns ])
+ data_columns.extend(
+ [k for k in min_itemsize.keys() if k != 'values' and k not in existing_data_columns])
# return valid columns in the order of our axis
return [c for c in data_columns if c in axis_labels]
@@ -2655,8 +2805,9 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
try:
axes = _AXES_MAP[type(obj)]
except:
- raise TypeError("cannot properly create the storer for: [group->%s,value->%s]" %
- (self.group._v_name,type(obj)))
+ raise TypeError(
+ "cannot properly create the storer for: [group->%s,value->%s]" %
+ (self.group._v_name, type(obj)))
# map axes to numbers
axes = [obj._get_axis_number(a) for a in axes]
@@ -2665,17 +2816,18 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
if self.infer_axes():
existing_table = self.copy()
existing_table.infer_axes()
- axes = [ a.axis for a in existing_table.index_axes]
- data_columns = existing_table.data_columns
- nan_rep = existing_table.nan_rep
+ axes = [a.axis for a in existing_table.index_axes]
+ data_columns = existing_table.data_columns
+ nan_rep = existing_table.nan_rep
self.encoding = existing_table.encoding
- self.info = copy.copy(existing_table.info)
+ self.info = copy.copy(existing_table.info)
else:
existing_table = None
# currently support on ndim-1 axes
if len(axes) != self.ndim - 1:
- raise ValueError("currently only support ndim-1 indexers in an AppendableTable")
+ raise ValueError(
+ "currently only support ndim-1 indexers in an AppendableTable")
# create according to the new data
self.non_index_axes = []
@@ -2712,7 +2864,8 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
self.non_index_axes.append((i, append_axis))
# set axis positions (based on the axes)
- self.index_axes = [index_axes_map[a].set_pos(j).update_info(self.info) for j,
+ self.index_axes = [index_axes_map[a].set_pos(
+ j).update_info(self.info) for j,
a in enumerate(axes)]
j = len(self.index_axes)
@@ -2732,7 +2885,8 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
blocks = block_obj._data.blocks
if len(self.non_index_axes):
axis, axis_labels = self.non_index_axes[0]
- data_columns = self.validate_data_columns(data_columns, min_itemsize)
+ data_columns = self.validate_data_columns(
+ data_columns, min_itemsize)
if len(data_columns):
blocks = block_obj.reindex_axis(Index(axis_labels) - Index(
data_columns), axis=axis)._data.blocks
@@ -2742,7 +2896,7 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
# reorder the blocks in the same order as the existing_table if we can
if existing_table is not None:
- by_items = dict([ (tuple(b.items.tolist()),b) for b in blocks ])
+ by_items = dict([(tuple(b.items.tolist()), b) for b in blocks])
new_blocks = []
for ea in existing_table.values_axes:
items = tuple(ea.values)
@@ -2750,7 +2904,8 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
b = by_items.pop(items)
new_blocks.append(b)
except:
- raise ValueError("cannot match existing table structure for [%s] on appending data" % ','.join(items))
+ raise ValueError(
+ "cannot match existing table structure for [%s] on appending data" % ','.join(items))
blocks = new_blocks
# add my values
@@ -2773,8 +2928,9 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
try:
existing_col = existing_table.values_axes[i]
except:
- raise ValueError("Incompatible appended table [%s] with existing table [%s]" %
- (blocks,existing_table.values_axes))
+ raise ValueError(
+ "Incompatible appended table [%s] with existing table [%s]" %
+ (blocks, existing_table.values_axes))
else:
existing_col = None
@@ -2794,7 +2950,8 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None,
except (NotImplementedError, ValueError, TypeError) as e:
raise e
except (Exception) as detail:
- raise Exception("cannot find the correct atom type -> [dtype->%s,items->%s] %s" % (b.dtype.name, b.items, str(detail)))
+ raise Exception("cannot find the correct atom type -> [dtype->%s,items->%s] %s" % (
+ b.dtype.name, b.items, str(detail)))
j += 1
# validate our min_itemsize
@@ -2827,23 +2984,24 @@ def process_filter(field, filt):
# see if the field is the name of an axis
if field == axis_name:
- takers = op(axis_values,filt)
- return obj.ix._getitem_axis(takers,axis=axis_number)
+ takers = op(axis_values, filt)
+ return obj.ix._getitem_axis(takers, axis=axis_number)
# this might be the name of a file IN an axis
elif field in axis_values:
# we need to filter on this dimension
- values = _ensure_index(getattr(obj,field).values)
- filt = _ensure_index(filt)
+ values = _ensure_index(getattr(obj, field).values)
+ filt = _ensure_index(filt)
# hack until we support reversed dim flags
- if isinstance(obj,DataFrame):
- axis_number = 1-axis_number
- takers = op(values,filt)
- return obj.ix._getitem_axis(takers,axis=axis_number)
+ if isinstance(obj, DataFrame):
+ axis_number = 1 - axis_number
+ takers = op(values, filt)
+ return obj.ix._getitem_axis(takers, axis=axis_number)
- raise ValueError("cannot find the field [%s] for filtering!" % field)
+ raise ValueError(
+ "cannot find the field [%s] for filtering!" % field)
obj = process_filter(field, filt)
@@ -2883,10 +3041,11 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
return False
# create the selection
- self.selection = Selection(self, where=where, start=start, stop=stop, **kwargs)
+ self.selection = Selection(
+ self, where=where, start=start, stop=stop, **kwargs)
return Coordinates(self.selection.select_coords(), group=self.group, where=where)
- def read_column(self, column, where = None, **kwargs):
+ def read_column(self, column, where=None, **kwargs):
""" return a single column from the table, generally only indexables are interesting """
# validate the version
@@ -2897,14 +3056,16 @@ def read_column(self, column, where = None, **kwargs):
return False
if where is not None:
- raise Exception("read_column does not currently accept a where clause")
+ raise Exception(
+ "read_column does not currently accept a where clause")
# find the axes
for a in self.axes:
if column == a.name:
if not a.is_data_indexable:
- raise ValueError("column [%s] can not be extracted individually; it is not data indexable" % column)
+ raise ValueError(
+ "column [%s] can not be extracted individually; it is not data indexable" % column)
# column must be an indexable or a data column
c = getattr(self.table.cols, column)
@@ -2913,7 +3074,9 @@ def read_column(self, column, where = None, **kwargs):
raise KeyError("column [%s] not found in the table" % column)
+
class WORMTable(Table):
+
""" a write-once read-many table: this format DOES NOT ALLOW appending to a
table. writing is a one-time operation the data are stored in a format
that allows for searching the data on disk
@@ -2933,6 +3096,7 @@ def write(self, **kwargs):
class LegacyTable(Table):
+
""" an appendable table: allow append/query/delete operations to a
(possibily) already existing appendable table this table ALLOWS
append (but doesn't require them), and stores the data in a format
@@ -3030,6 +3194,7 @@ def read(self, where=None, columns=None, **kwargs):
class LegacyFrameTable(LegacyTable):
+
""" support the legacy frame table """
pandas_kind = u('frame_table')
table_type = u('legacy_frame')
@@ -3040,12 +3205,14 @@ def read(self, *args, **kwargs):
class LegacyPanelTable(LegacyTable):
+
""" support the legacy panel table """
table_type = u('legacy_panel')
obj_type = Panel
class AppendableTable(LegacyTable):
+
""" suppor the new appendable table formats """
_indexables = None
table_type = u('appendable')
@@ -3112,26 +3279,29 @@ def write_data(self, chunksize):
mask = mask.ravel()
# broadcast the indexes if needed
- indexes = [ a.cvalues for a in self.index_axes ]
+ indexes = [a.cvalues for a in self.index_axes]
nindexes = len(indexes)
bindexes = []
for i, idx in enumerate(indexes):
# broadcast to all other indexes except myself
if i > 0 and i < nindexes:
- repeater = np.prod([indexes[bi].shape[0] for bi in range(0,i)])
- idx = np.tile(idx,repeater)
+ repeater = np.prod(
+ [indexes[bi].shape[0] for bi in range(0, i)])
+ idx = np.tile(idx, repeater)
- if i < nindexes-1:
- repeater = np.prod([indexes[bi].shape[0] for bi in range(i+1,nindexes)])
- idx = np.repeat(idx,repeater)
+ if i < nindexes - 1:
+ repeater = np.prod([indexes[bi].shape[0]
+ for bi in range(i + 1, nindexes)])
+ idx = np.repeat(idx, repeater)
bindexes.append(idx)
# transpose the values so first dimension is last
# reshape the values if needed
- values = [ a.take_data() for a in self.values_axes]
- values = [ v.transpose(np.roll(np.arange(v.ndim),v.ndim-1)) for v in values ]
+ values = [a.take_data() for a in self.values_axes]
+ values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1))
+ for v in values]
bvalues = []
for i, v in enumerate(values):
new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
@@ -3162,7 +3332,7 @@ def write_data_chunk(self, indexes, mask, values):
try:
nrows = indexes[0].shape[0]
- rows = np.empty(nrows,dtype=self.dtype)
+ rows = np.empty(nrows, dtype=self.dtype)
names = self.dtype.names
nindexes = len(indexes)
@@ -3172,7 +3342,7 @@ def write_data_chunk(self, indexes, mask, values):
# values
for i, v in enumerate(values):
- rows[names[i+nindexes]] = v
+ rows[names[i + nindexes]] = v
# mask
rows = rows[~mask.ravel().astype(bool)]
@@ -3185,7 +3355,8 @@ def write_data_chunk(self, indexes, mask, values):
self.table.append(rows)
self.table.flush()
except Exception as detail:
- raise Exception("tables cannot write this data -> %s" % str(detail))
+ raise Exception(
+ "tables cannot write this data -> %s" % str(detail))
def delete(self, where=None, **kwargs):
@@ -3241,6 +3412,7 @@ def delete(self, where=None, **kwargs):
class AppendableFrameTable(AppendableTable):
+
""" suppor the new appendable table formats """
pandas_kind = u('frame_table')
table_type = u('appendable_frame')
@@ -3270,10 +3442,10 @@ def read(self, where=None, columns=None, **kwargs):
if self.is_transposed:
values = a.cvalues
index_ = cols
- cols_ = Index(index,name=getattr(index,'name',None))
+ cols_ = Index(index, name=getattr(index, 'name', None))
else:
values = a.cvalues.T
- index_ = Index(index,name=getattr(index,'name',None))
+ index_ = Index(index, name=getattr(index, 'name', None))
cols_ = cols
# if we have a DataIndexableCol, its shape will only be 1 dim
@@ -3352,6 +3524,7 @@ def write(self, obj, **kwargs):
return super(AppendableMultiSeriesTable, self).write(obj=obj, **kwargs)
class GenericTable(AppendableFrameTable):
+
""" a table that read/writes the generic pytables table format """
pandas_kind = u('frame_table')
table_type = u('generic_table')
@@ -3364,17 +3537,19 @@ def pandas_type(self):
@property
def storable(self):
- return getattr(self.group,'table',None) or self.group
+ return getattr(self.group, 'table', None) or self.group
def get_attrs(self):
""" retrieve our attributes """
- self.non_index_axes = []
- self.nan_rep = None
- self.levels = []
+ self.non_index_axes = []
+ self.nan_rep = None
+ self.levels = []
t = self.table
- self.index_axes = [ a.infer(t) for a in self.indexables if a.is_an_indexable ]
- self.values_axes = [ a.infer(t) for a in self.indexables if not a.is_an_indexable ]
- self.data_columns = [ a.name for a in self.values_axes ]
+ self.index_axes = [a.infer(t)
+ for a in self.indexables if a.is_an_indexable]
+ self.values_axes = [a.infer(t)
+ for a in self.indexables if not a.is_an_indexable]
+ self.data_columns = [a.name for a in self.values_axes]
@property
def indexables(self):
@@ -3384,11 +3559,12 @@ def indexables(self):
d = self.description
# the index columns is just a simple index
- self._indexables = [ GenericIndexCol(name='index',axis=0) ]
+ self._indexables = [GenericIndexCol(name='index', axis=0)]
for i, n in enumerate(d._v_names):
- dc = GenericDataIndexableCol(name = n, pos=i, values = [ n ], version = self.version)
+ dc = GenericDataIndexableCol(
+ name=n, pos=i, values=[n], version = self.version)
self._indexables.append(dc)
return self._indexables
@@ -3396,7 +3572,9 @@ def indexables(self):
def write(self, **kwargs):
raise NotImplementedError("cannot write on an generic table")
+
class AppendableMultiFrameTable(AppendableFrameTable):
+
""" a frame with a multi-index """
table_type = u('appendable_multiframe')
obj_type = DataFrame
@@ -3422,12 +3600,14 @@ def read(self, columns=None, **kwargs):
for n in self.levels:
if n not in columns:
columns.insert(0, n)
- df = super(AppendableMultiFrameTable, self).read(columns=columns, **kwargs)
+ df = super(AppendableMultiFrameTable, self).read(
+ columns=columns, **kwargs)
df.set_index(self.levels, inplace=True)
return df
class AppendablePanelTable(AppendableTable):
+
""" suppor the new appendable table formats """
table_type = u('appendable_panel')
ndim = 3
@@ -3445,22 +3625,25 @@ def is_transposed(self):
class AppendableNDimTable(AppendablePanelTable):
+
""" suppor the new appendable table formats """
table_type = u('appendable_ndim')
ndim = 4
obj_type = Panel4D
+
def _convert_index(index, encoding=None):
- index_name = getattr(index,'name',None)
+ index_name = getattr(index, 'name', None)
if isinstance(index, DatetimeIndex):
converted = index.asi8
return IndexCol(converted, 'datetime64', _tables().Int64Col(),
- freq=getattr(index,'freq',None), tz=getattr(index,'tz',None),
+ freq=getattr(index, 'freq', None), tz=getattr(index, 'tz', None),
index_name=index_name)
elif isinstance(index, (Int64Index, PeriodIndex)):
atom = _tables().Int64Col()
- return IndexCol(index.values, 'integer', atom, freq=getattr(index,'freq',None),
+ return IndexCol(
+ index.values, 'integer', atom, freq=getattr(index, 'freq', None),
index_name=index_name)
if isinstance(index, MultiIndex):
@@ -3473,7 +3656,7 @@ def _convert_index(index, encoding=None):
if inferred_type == 'datetime64':
converted = values.view('i8')
return IndexCol(converted, 'datetime64', _tables().Int64Col(),
- freq=getattr(index,'freq',None), tz=getattr(index,'tz',None),
+ freq=getattr(index, 'freq', None), tz=getattr(index, 'tz', None),
index_name=index_name)
elif inferred_type == 'datetime':
converted = np.array([(time.mktime(v.timetuple()) +
@@ -3492,7 +3675,8 @@ def _convert_index(index, encoding=None):
converted = _convert_string_array(values, encoding)
itemsize = converted.dtype.itemsize
- return IndexCol(converted, 'string', _tables().StringCol(itemsize), itemsize=itemsize,
+ return IndexCol(
+ converted, 'string', _tables().StringCol(itemsize), itemsize=itemsize,
index_name=index_name)
elif inferred_type == 'unicode':
atom = _tables().ObjectAtom()
@@ -3512,6 +3696,7 @@ def _convert_index(index, encoding=None):
return IndexCol(np.asarray(values, dtype='O'), 'object', atom,
index_name=index_name)
+
def _unconvert_index(data, kind, encoding=None):
kind = _ensure_decoded(kind)
if kind == u('datetime64'):
@@ -3531,6 +3716,7 @@ def _unconvert_index(data, kind, encoding=None):
raise ValueError('unrecognized index type %s' % kind)
return index
+
def _unconvert_index_legacy(data, kind, legacy=False, encoding=None):
kind = _ensure_decoded(kind)
if kind == u('datetime'):
@@ -3543,6 +3729,7 @@ def _unconvert_index_legacy(data, kind, legacy=False, encoding=None):
raise ValueError('unrecognized index type %s' % kind)
return index
+
def _convert_string_array(data, encoding, itemsize=None):
# encode if needed
@@ -3554,19 +3741,20 @@ def _convert_string_array(data, encoding, itemsize=None):
if itemsize is None:
itemsize = lib.max_len_string_array(com._ensure_object(data.ravel()))
- data = np.array(data,dtype="S%d" % itemsize)
+ data = np.array(data, dtype="S%d" % itemsize)
return data
+
def _unconvert_string_array(data, nan_rep=None, encoding=None):
""" deserialize a string array, possibly decoding """
shape = data.shape
- data = np.array(data.ravel(),dtype=object)
+ data = np.array(data.ravel(), dtype=object)
# guard against a None encoding in PY3 (because of a legacy
# where the passed encoding is actually None)
encoding = _ensure_encoding(encoding)
if encoding is not None and len(data):
- f = np.vectorize(lambda x: x.decode(encoding),otypes=[np.object])
+ f = np.vectorize(lambda x: x.decode(encoding), otypes=[np.object])
data = f(data)
if nan_rep is None:
@@ -3575,6 +3763,7 @@ def _unconvert_string_array(data, nan_rep=None, encoding=None):
data = lib.string_array_replace_from_nan_rep(data, nan_rep)
return data.reshape(shape)
+
def _maybe_convert(values, val_kind, encoding):
if _need_convert(val_kind):
conv = _get_converter(val_kind, encoding)
@@ -3582,6 +3771,7 @@ def _maybe_convert(values, val_kind, encoding):
values = conv(values)
return values
+
def _get_converter(kind, encoding):
kind = _ensure_decoded(kind)
if kind == 'datetime64':
@@ -3589,17 +3779,20 @@ def _get_converter(kind, encoding):
elif kind == 'datetime':
return lib.convert_timestamps
elif kind == 'string':
- return lambda x: _unconvert_string_array(x,encoding=encoding)
+ return lambda x: _unconvert_string_array(x, encoding=encoding)
else: # pragma: no cover
raise ValueError('invalid kind %s' % kind)
+
def _need_convert(kind):
kind = _ensure_decoded(kind)
if kind in (u('datetime'), u('datetime64'), u('string')):
return True
return False
+
class Term(StringMixin):
+
"""create a term object that holds a field, op, and value
Parameters
@@ -3627,7 +3820,8 @@ class Term(StringMixin):
"""
_ops = ['<=', '<', '>=', '>', '!=', '==', '=']
- _search = re.compile("^\s*(?P<field>\w+)\s*(?P<op>%s)\s*(?P<value>.+)\s*$" % '|'.join(_ops))
+ _search = re.compile(
+ "^\s*(?P<field>\w+)\s*(?P<op>%s)\s*(?P<value>.+)\s*$" % '|'.join(_ops))
_max_selectors = 31
def __init__(self, field, op=None, value=None, queryables=None, encoding=None):
@@ -3695,8 +3889,9 @@ def __init__(self, field, op=None, value=None, queryables=None, encoding=None):
# we have valid conditions
if self.op in ['>', '>=', '<', '<=']:
- if hasattr(self.value, '__iter__') and len(self.value) > 1 and not isinstance(self.value,compat.string_types):
- raise ValueError("an inequality condition cannot have multiple values [%s]" % str(self))
+ if hasattr(self.value, '__iter__') and len(self.value) > 1 and not isinstance(self.value, compat.string_types):
+ raise ValueError(
+ "an inequality condition cannot have multiple values [%s]" % str(self))
if not is_list_like(self.value):
self.value = [self.value]
@@ -3738,7 +3933,7 @@ def eval(self):
if self.is_in_table:
values = [self.convert_value(v) for v in self.value]
else:
- values = [TermValue(v,v,self.kind) for v in self.value]
+ values = [TermValue(v, v, self.kind) for v in self.value]
# equality conditions
if self.op in ['==', '!=']:
@@ -3749,21 +3944,22 @@ def eval(self):
else:
filter_op = lambda axis, vals: axis.isin(vals)
-
if self.is_in_table:
# too many values to create the expression?
if len(values) <= self._max_selectors:
- vs = [ self.generate(v) for v in values ]
+ vs = [self.generate(v) for v in values]
self.condition = "(%s)" % ' | '.join(vs)
# use a filter after reading
else:
- self.filter = (self.field, filter_op, Index([v.value for v in values]))
+ self.filter = (
+ self.field, filter_op, Index([v.value for v in values]))
else:
- self.filter = (self.field, filter_op, Index([v.value for v in values]))
+ self.filter = (
+ self.field, filter_op, Index([v.value for v in values]))
else:
@@ -3773,7 +3969,8 @@ def eval(self):
else:
- raise TypeError("passing a filterable condition to a non-table indexer [%s]" % str(self))
+ raise TypeError(
+ "passing a filterable condition to a non-table indexer [%s]" % str(self))
def convert_value(self, v):
""" convert the expression that is in the term to something that is accepted by pytables """
@@ -3789,17 +3986,17 @@ def stringify(value):
v = lib.Timestamp(v)
if v.tz is not None:
v = v.tz_convert('UTC')
- return TermValue(v,v.value,kind)
+ return TermValue(v, v.value, kind)
elif (isinstance(v, datetime) or hasattr(v, 'timetuple')
or kind == u('date')):
v = time.mktime(v.timetuple())
- return TermValue(v,Timestamp(v),kind)
+ return TermValue(v, Timestamp(v), kind)
elif kind == u('integer'):
v = int(float(v))
- return TermValue(v,v,kind)
+ return TermValue(v, v, kind)
elif kind == u('float'):
v = float(v)
- return TermValue(v,v,kind)
+ return TermValue(v, v, kind)
elif kind == u('bool'):
if isinstance(v, compat.string_types):
poss_vals = [u('false'), u('f'), u('no'),
@@ -3808,15 +4005,17 @@ def stringify(value):
v = not v.strip().lower() in poss_vals
else:
v = bool(v)
- return TermValue(v,v,kind)
+ return TermValue(v, v, kind)
elif not isinstance(v, compat.string_types):
v = stringify(v)
- return TermValue(v,stringify(v),u('string'))
+ return TermValue(v, stringify(v), u('string'))
# string quoting
- return TermValue(v,stringify(v),u('string'))
+ return TermValue(v, stringify(v), u('string'))
+
class TermValue(object):
+
""" hold a term value the we use to construct a condition/filter """
def __init__(self, value, converted, kind):
@@ -3833,7 +4032,9 @@ def tostring(self, encoding):
return '"%s"' % self.converted
return self.converted
+
class Coordinates(object):
+
""" holds a returned coordinates list, useful to select the same rows from different tables
coordinates : holds the array of coordinates
@@ -3853,7 +4054,9 @@ def __getitem__(self, key):
""" return a new coordinates object, sliced by the key """
return Coordinates(self.values[key], self.group, self.where)
+
class Selection(object):
+
"""
Carries out a selection operation on a tables.Table object.
@@ -3864,6 +4067,7 @@ class Selection(object):
start, stop: indicies to start and/or stop selection
"""
+
def __init__(self, table, where=None, start=None, stop=None, **kwargs):
self.table = table
self.where = where
@@ -3883,7 +4087,7 @@ def __init__(self, table, where=None, start=None, stop=None, **kwargs):
# see if we have a passed coordinate like
try:
inferred = lib.infer_dtype(where)
- if inferred=='integer' or inferred=='boolean':
+ if inferred == 'integer' or inferred == 'boolean':
where = np.array(where)
if where.dtype == np.bool_:
start, stop = self.start, self.stop
@@ -3891,10 +4095,11 @@ def __init__(self, table, where=None, start=None, stop=None, **kwargs):
start = 0
if stop is None:
stop = self.table.nrows
- self.coordinates = np.arange(start,stop)[where]
- elif issubclass(where.dtype.type,np.integer):
- if (self.start is not None and (where<self.start).any()) or (self.stop is not None and (where>=self.stop).any()):
- raise ValueError("where must have index locations >= start and < stop")
+ self.coordinates = np.arange(start, stop)[where]
+ elif issubclass(where.dtype.type, np.integer):
+ if (self.start is not None and (where < self.start).any()) or (self.stop is not None and (where >= self.stop).any()):
+ raise ValueError(
+ "where must have index locations >= start and < stop")
self.coordinates = where
except:
@@ -3906,9 +4111,10 @@ def __init__(self, table, where=None, start=None, stop=None, **kwargs):
# create the numexpr & the filter
if self.terms:
- terms = [ t for t in self.terms if t.condition is not None ]
+ terms = [t for t in self.terms if t.condition is not None]
if len(terms):
- self.condition = "(%s)" % ' & '.join([ t.condition for t in terms ])
+ self.condition = "(%s)" % ' & '.join(
+ [t.condition for t in terms])
self.filter = []
for t in self.terms:
if t.filter is not None:
@@ -3953,13 +4159,13 @@ def select_coords(self):
return self.table.table.getWhereList(self.condition, start=self.start, stop=self.stop, sort=True)
-### utilities ###
+# utilities ###
-def timeit(key,df,fn=None,remove=True,**kwargs):
+def timeit(key, df, fn=None, remove=True, **kwargs):
if fn is None:
fn = 'timeit.h5'
- store = HDFStore(fn,mode='w')
- store.append(key,df,**kwargs)
+ store = HDFStore(fn, mode='w')
+ store.append(key, df, **kwargs)
store.close()
if remove:
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index cfe162c887799..e2d9235510f83 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -147,6 +147,81 @@ def roundtrip(key, obj,**kwargs):
finally:
safe_remove(self.path)
+ def test_api(self):
+
+ # GH4584
+ # API issue when to_hdf doesn't acdept append AND table args
+ with tm.ensure_clean(self.path) as path:
+
+ df = tm.makeDataFrame()
+ df.iloc[:10].to_hdf(path,'df',append=True,table=True)
+ df.iloc[10:].to_hdf(path,'df',append=True,table=True)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ # append to False
+ df.iloc[:10].to_hdf(path,'df',append=False,table=True)
+ df.iloc[10:].to_hdf(path,'df',append=True,table=True)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ with tm.ensure_clean(self.path) as path:
+
+ df = tm.makeDataFrame()
+ df.iloc[:10].to_hdf(path,'df',append=True)
+ df.iloc[10:].to_hdf(path,'df',append=True,table='t')
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ # append to False
+ df.iloc[:10].to_hdf(path,'df',append=False,table='t')
+ df.iloc[10:].to_hdf(path,'df',append=True)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ with tm.ensure_clean(self.path) as path:
+
+ df = tm.makeDataFrame()
+ df.to_hdf(path,'df',append=False,table=False)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ df.to_hdf(path,'df',append=False,fmt='s')
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ df.to_hdf(path,'df',append=False)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ df.to_hdf(path,'df')
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ with ensure_clean(self.path) as store:
+
+ df = tm.makeDataFrame()
+ store.append('df',df.iloc[:10],append=True,table=True)
+ store.append('df',df.iloc[10:],append=True,table=True)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ # append to False
+ store.append('df',df.iloc[:10],append=False,table=True)
+ store.append('df',df.iloc[10:],append=True,table=True)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ # formats
+ store.append('df',df.iloc[:10],append=False,fmt='t')
+ store.append('df',df.iloc[10:],append=True,fmt='t')
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ _maybe_remove(store,'df')
+ store.append('df',df.iloc[:10],append=False,fmt='t')
+ store.append('df',df.iloc[10:],append=True,fmt=None)
+ assert_frame_equal(read_hdf(path,'df'),df)
+
+ with tm.ensure_clean(self.path) as path:
+
+ # invalid
+ df = tm.makeDataFrame()
+ self.assertRaises(ValueError, df.to_hdf, path,'df',append=True,fmt='s')
+
+ self.assertRaises(TypeError, df.to_hdf, path,'df',append=True,fmt='foo')
+ self.assertRaises(TypeError, df.to_hdf, path,'df',append=False,fmt='bar')
+ self.assertRaises(TypeError, df.to_hdf, path,'df',format='s')
+
def test_keys(self):
with ensure_clean(self.path) as store:
@@ -1671,7 +1746,7 @@ def test_remove_where(self):
# try to remove non-table (with crit)
# non-table ok (where = None)
wp = tm.makePanel()
- store.put('wp', wp, table=True)
+ store.put('wp', wp, fmt='t')
store.remove('wp', [('minor_axis', ['A', 'D'])])
rs = store.select('wp')
expected = wp.reindex(minor_axis=['B', 'C'])
@@ -1679,7 +1754,7 @@ def test_remove_where(self):
# empty where
_maybe_remove(store, 'wp')
- store.put('wp', wp, table=True)
+ store.put('wp', wp, fmt='t')
# deleted number (entire table)
n = store.remove('wp', [])
@@ -1687,12 +1762,12 @@ def test_remove_where(self):
# non - empty where
_maybe_remove(store, 'wp')
- store.put('wp', wp, table=True)
+ store.put('wp', wp, fmt='t')
self.assertRaises(ValueError, store.remove,
'wp', ['foo'])
# selectin non-table with a where
- # store.put('wp2', wp, table=False)
+ # store.put('wp2', wp, fmt='s')
# self.assertRaises(ValueError, store.remove,
# 'wp2', [('column', ['A', 'D'])])
@@ -1705,7 +1780,7 @@ def test_remove_crit(self):
# group row removal
date4 = wp.major_axis.take([0, 1, 2, 4, 5, 6, 8, 9, 10])
crit4 = Term('major_axis', date4)
- store.put('wp3', wp, table=True)
+ store.put('wp3', wp, fmt='t')
n = store.remove('wp3', where=[crit4])
assert(n == 36)
result = store.select('wp3')
@@ -1713,7 +1788,7 @@ def test_remove_crit(self):
assert_panel_equal(result, expected)
# upper half
- store.put('wp', wp, table=True)
+ store.put('wp', wp, fmt='t')
date = wp.major_axis[len(wp.major_axis) // 2]
crit1 = Term('major_axis', '>', date)
@@ -1730,7 +1805,7 @@ def test_remove_crit(self):
assert_panel_equal(result, expected)
# individual row elements
- store.put('wp2', wp, table=True)
+ store.put('wp2', wp, fmt='t')
date1 = wp.major_axis[1:3]
crit1 = Term('major_axis', date1)
@@ -1756,7 +1831,7 @@ def test_remove_crit(self):
assert_panel_equal(result, expected)
# corners
- store.put('wp4', wp, table=True)
+ store.put('wp4', wp, fmt='t')
n = store.remove(
'wp4', where=[Term('major_axis', '>', wp.major_axis[-1])])
result = store.select('wp4')
@@ -1768,8 +1843,8 @@ def test_terms(self):
wp = tm.makePanel()
p4d = tm.makePanel4D()
- store.put('wp', wp, table=True)
- store.put('p4d', p4d, table=True)
+ store.put('wp', wp, fmt='t')
+ store.put('p4d', p4d, fmt='t')
# some invalid terms
terms = [
@@ -2124,8 +2199,8 @@ def test_wide_table(self):
def test_wide_table_dups(self):
wp = tm.makePanel()
with ensure_clean(self.path) as store:
- store.put('panel', wp, table=True)
- store.put('panel', wp, table=True, append=True)
+ store.put('panel', wp, fmt='t')
+ store.put('panel', wp, fmt='t', append=True)
with tm.assert_produces_warning(expected_warning=DuplicateWarning):
recons = store['panel']
@@ -2191,12 +2266,12 @@ def test_select(self):
# put/select ok
_maybe_remove(store, 'wp')
- store.put('wp', wp, table=True)
+ store.put('wp', wp, fmt='t')
store.select('wp')
# non-table ok (where = None)
_maybe_remove(store, 'wp')
- store.put('wp2', wp, table=False)
+ store.put('wp2', wp)
store.select('wp2')
# selection on the non-indexable with a large number of columns
@@ -2377,7 +2452,7 @@ def test_select_iterator(self):
with tm.ensure_clean(self.path) as path:
df = tm.makeTimeDataFrame(500)
- df.to_hdf(path,'df',table=True)
+ df.to_hdf(path,'df',fmt='t')
results = []
for x in read_hdf(path,'df',chunksize=100):
@@ -2428,7 +2503,7 @@ def test_retain_index_attributes(self):
with ensure_clean(self.path) as store:
_maybe_remove(store,'data')
- store.put('data', df, table=True)
+ store.put('data', df, fmt='t')
result = store.get('data')
tm.assert_frame_equal(df,result)
@@ -2486,7 +2561,7 @@ def test_panel_select(self):
wp = tm.makePanel()
with ensure_clean(self.path) as store:
- store.put('wp', wp, table=True)
+ store.put('wp', wp, fmt='t')
date = wp.major_axis[len(wp.major_axis) // 2]
crit1 = ('major_axis', '>=', date)
@@ -2506,7 +2581,7 @@ def test_frame_select(self):
df = tm.makeTimeDataFrame()
with ensure_clean(self.path) as store:
- store.put('frame', df, table=True)
+ store.put('frame', df,fmt='t')
date = df.index[len(df) // 2]
crit1 = ('index', '>=', date)
@@ -2814,7 +2889,7 @@ def test_select_filter_corner(self):
df.columns = ['%.3d' % c for c in df.columns]
with ensure_clean(self.path) as store:
- store.put('frame', df, table=True)
+ store.put('frame', df, fmt='t')
crit = Term('columns', df.columns[:75])
result = store.select('frame', [crit])
@@ -2852,7 +2927,7 @@ def _check_roundtrip_table(self, obj, comparator, compression=False):
options['complib'] = _default_compressor
with ensure_clean(self.path, 'w', **options) as store:
- store.put('obj', obj, table=True)
+ store.put('obj', obj, fmt='t')
retrieved = store['obj']
# sorted_obj = _test_sort(obj)
comparator(retrieved, obj)
@@ -2863,7 +2938,7 @@ def test_multiple_open_close(self):
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
- df.to_hdf(path,'df',mode='w',table=True)
+ df.to_hdf(path,'df',mode='w',fmt='t')
# single
store = HDFStore(path)
@@ -2925,7 +3000,7 @@ def test_multiple_open_close(self):
with tm.ensure_clean(self.path) as path:
df = tm.makeDataFrame()
- df.to_hdf(path,'df',mode='w',table=True)
+ df.to_hdf(path,'df',mode='w',fmt='t')
store = HDFStore(path)
store.close()
@@ -3168,7 +3243,7 @@ def test_store_datetime_mixed(self):
# index=[np.arange(5).repeat(2),
# np.tile(np.arange(2), 5)])
- # self.assertRaises(Exception, store.put, 'foo', df, table=True)
+ # self.assertRaises(Exception, store.put, 'foo', df, fmt='t')
def _test_sort(obj):
| - API: the `fmt` keyword now replaces the table keyword; allowed values are `s|t`
the same defaults as prior < 0.13.0 remain, e.g. `put` implies 's' (Storer) format
and `append` imples 't' (Table) format
closes #4584 as well
| https://api.github.com/repos/pandas-dev/pandas/pulls/4645 | 2013-08-22T22:05:30Z | 2013-08-26T12:43:52Z | 2013-08-26T12:43:52Z | 2014-06-13T00:06:16Z |
test_perf fixes, restore clobbered pickle compare cmdargs, restore back_compat | diff --git a/vb_suite/test_perf.py b/vb_suite/test_perf.py
index ca98b94e4fbbd..b39dfdcaae94b 100755
--- a/vb_suite/test_perf.py
+++ b/vb_suite/test_perf.py
@@ -26,6 +26,21 @@
"""
+# IMPORTANT NOTE
+#
+# This script should run on pandas versions at least as far back as 0.9.1.
+# devs should be able to use the latest version of this script with
+# any dusty old commit and expect it to "just work".
+# One way in which this is useful is when collecting historical data,
+# where writing some logic around this script may prove easier
+# in some cases then running vbench directly (think perf bisection).
+#
+# *please*, when you modify this script for whatever reason,
+# make sure you do not break it's functionality when running under older
+# pandas versions.
+# Note that depreaction warnings are turned off in main(), so there's
+# no need to change the actual code to supress such warnings.
+
import shutil
import os
import sys
@@ -37,14 +52,20 @@
import random
import numpy as np
+import pandas as pd
from pandas import DataFrame, Series
from suite import REPO_PATH
-
+VB_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_MIN_DURATION = 0.01
HEAD_COL="head[ms]"
BASE_COL="base[ms]"
+try:
+ import git # gitpython
+except Exception:
+ print("Error: Please install the `gitpython` package\n")
+ sys.exit(1)
class RevParseAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
@@ -66,6 +87,14 @@ def __call__(self, parser, namespace, values, option_string=None):
parser.add_argument('-t', '--target-commit',
help='The commit to compare against the baseline (default: HEAD).',
type=str, action=RevParseAction)
+parser.add_argument('--base-pickle',
+ help='name of pickle file with timings data generated by a former `-H -d FILE` run. '\
+ 'filename must be of the form <hash>-*.* or specify --base-commit seperately',
+ type=str)
+parser.add_argument('--target-pickle',
+ help='name of pickle file with timings data generated by a former `-H -d FILE` run '\
+ 'filename must be of the form <hash>-*.* or specify --target-commit seperately',
+ type=str)
parser.add_argument('-m', '--min-duration',
help='Minimum duration (in ms) of baseline test for inclusion in report (default: %.3f).' % DEFAULT_MIN_DURATION,
type=float,
@@ -213,30 +242,82 @@ def profile_comparative(benchmarks):
head_res = get_results_df(db, h_head)
baseline_res = get_results_df(db, h_baseline)
- ratio = head_res['timing'] / baseline_res['timing']
- totals = DataFrame({HEAD_COL:head_res['timing'],
- BASE_COL:baseline_res['timing'],
- 'ratio':ratio,
- 'name':baseline_res.name},
- columns=[HEAD_COL, BASE_COL, "ratio", "name"])
- totals = totals.ix[totals[HEAD_COL] > args.min_duration]
- # ignore below threshold
- totals = totals.dropna(
- ).sort("ratio").set_index('name') # sort in ascending order
-
- h_msg = repo.messages.get(h_head, "")
- b_msg = repo.messages.get(h_baseline, "")
-
- print_report(totals,h_head=h_head,h_msg=h_msg,
- h_baseline=h_baseline,b_msg=b_msg)
-
- if args.outdf:
- prprint("The results DataFrame was written to '%s'\n" % args.outdf)
- totals.save(args.outdf)
+
+ report_comparative(head_res,baseline_res)
+
finally:
# print("Disposing of TMP_DIR: %s" % TMP_DIR)
shutil.rmtree(TMP_DIR)
+def prep_pickle_for_total(df, agg_name='median'):
+ """
+ accepts a datafram resulting from invocation with -H -d o.pickle
+ If multiple data columns are present (-N was used), the
+ `agg_name` attr of the datafram will be used to reduce
+ them to a single value per vbench, df.median is used by defa
+ ult.
+
+ Returns a datadrame of the form expected by prep_totals
+ """
+ def prep(df):
+ agg = getattr(df,agg_name)
+ df = DataFrame(agg(1))
+ cols = list(df.columns)
+ cols[0]='timing'
+ df.columns=cols
+ df['name'] = list(df.index)
+ return df
+
+ return prep(df)
+
+def prep_totals(head_res, baseline_res):
+ """
+ Each argument should be a dataframe with 'timing' and 'name' columns
+ where name is the name of the vbench.
+
+ returns a 'totals' dataframe, suitable as input for print_report.
+ """
+ head_res, baseline_res = head_res.align(baseline_res)
+ ratio = head_res['timing'] / baseline_res['timing']
+ totals = DataFrame({HEAD_COL:head_res['timing'],
+ BASE_COL:baseline_res['timing'],
+ 'ratio':ratio,
+ 'name':baseline_res.name},
+ columns=[HEAD_COL, BASE_COL, "ratio", "name"])
+ totals = totals.ix[totals[HEAD_COL] > args.min_duration]
+ # ignore below threshold
+ totals = totals.dropna(
+ ).sort("ratio").set_index('name') # sort in ascending order
+ return totals
+
+def report_comparative(head_res,baseline_res):
+ try:
+ r=git.Repo(VB_DIR)
+ except:
+ import pdb
+ pdb.set_trace()
+
+ totals = prep_totals(head_res,baseline_res)
+
+ h_head = args.target_commit
+ h_baseline = args.base_commit
+ h_msg = b_msg = "Unknown"
+ try:
+ h_msg = r.commit(h_head).message.strip()
+ except git.exc.BadObject:
+ pass
+ try:
+ b_msg = r.commit(h_baseline).message.strip()
+ except git.exc.BadObject:
+ pass
+
+
+ print_report(totals,h_head=h_head,h_msg=h_msg,
+ h_baseline=h_baseline,b_msg=b_msg)
+
+ if args.outdf:
+ prprint("The results DataFrame was written to '%s'\n" % args.outdf)
+ totals.save(args.outdf)
def profile_head_single(benchmark):
import gc
@@ -395,38 +476,22 @@ def main():
random.seed(args.seed)
np.random.seed(args.seed)
- affinity_set = False
+ if args.base_pickle and args.target_pickle:
+ baseline_res = prep_pickle_for_total(pd.load(args.base_pickle))
+ target_res = prep_pickle_for_total(pd.load(args.target_pickle))
- # try psutil first since it is more commonly present and better
- # maintained. Some people experienced problems with affinity package
- # (see https://code.google.com/p/psutil/issues/detail?id=238 for more references)
- try:
- import psutil
- if hasattr(psutil.Process, 'set_cpu_affinity'):
- psutil.Process(os.getpid()).set_cpu_affinity([args.affinity])
- affinity_set = True
- except ImportError:
- pass
+ report_comparative(target_res, baseline_res)
+ sys.exit(0)
- if not affinity_set:
- try:
- import affinity
- affinity.set_process_affinity_mask(0, args.affinity)
- assert affinity.get_process_affinity_mask(0) == args.affinity
- affinity_set = True
+ if args.affinity is not None:
+ try: # use psutil rather then stale affinity module. Thanks @yarikoptic
+ import psutil
+ if hasattr(psutil.Process, 'set_cpu_affinity'):
+ psutil.Process(os.getpid()).set_cpu_affinity([args.affinity])
+ print("CPU affinity set to %d" % args.affinity)
except ImportError:
- pass
-
- if not affinity_set:
- import warnings
- warnings.warn("\n\n"
- "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
- "The 'affinity' or 'psutil' >= 0.5.0 modules are not available, results may be unreliable\n"
- "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"
- )
- time.sleep(2)
- else:
- print("CPU affinity set to %d" % args.affinity)
+ print("-a/--affinity specified, but the 'psutil' module is not available, aborting.\n")
+ sys.exit(1)
print("\n")
prprint("LOG_FILE = %s" % args.log_file)
@@ -508,10 +573,39 @@ def inner(repo_path):
if __name__ == '__main__':
args = parser.parse_args()
- if not args.head and (not args.base_commit and not args.target_commit):
+ if (not args.head
+ and not (args.base_commit and args.target_commit)
+ and not (args.base_pickle and args.target_pickle)):
parser.print_help()
- else:
- import warnings
- warnings.filterwarnings('ignore',category=FutureWarning)
- warnings.filterwarnings('ignore',category=DeprecationWarning)
- main()
+ sys.exit(1)
+ elif ((args.base_pickle or args.target_pickle) and not
+ (args.base_pickle and args.target_pickle)):
+ print("Must specify Both --base-pickle and --target-pickle.")
+ sys.exit(1)
+
+ if ((args.base_pickle or args.target_pickle) and not
+ (args.base_commit and args.target_commit)):
+ if not args.base_commit:
+ print("base_commit not specified, Assuming base_pickle is named <commit>-foo.*")
+ args.base_commit = args.base_pickle.split('-')[0]
+ if not args.target_commit:
+ print("target_commit not specified, Assuming target_pickle is named <commit>-foo.*")
+ args.target_commit = args.target_pickle.split('-')[0]
+
+ import warnings
+ warnings.filterwarnings('ignore',category=FutureWarning)
+ warnings.filterwarnings('ignore',category=DeprecationWarning)
+
+ if args.base_commit and args.target_commit:
+ print("Verifying specified commits exist in repo...")
+ r=git.Repo(VB_DIR)
+ for c in [ args.base_commit, args.target_commit ]:
+ try:
+ msg = r.commit(c).message.strip()
+ except git.BadObject:
+ print("The commit '%s' was not found, aborting..." % c)
+ sys.exit(1)
+ else:
+ print("%s: %s" % (c,msg))
+
+ main()
| https://api.github.com/repos/pandas-dev/pandas/pulls/4644 | 2013-08-22T19:36:36Z | 2013-08-22T19:36:42Z | 2013-08-22T19:36:42Z | 2014-06-26T11:55:38Z | |
BUG: (GH4626) Fix decoding based on a passed in non-default encoding in pd.read_stata | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 16179cdeca052..929c167cd1340 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -286,6 +286,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
the DateOffset from being cached (:issue:`4609`)
- Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs (:issue:`4576`)
- Fix error/dtype conversion with setitem of ``None`` on ``Series/DataFrame`` (:issue:`4667`)
+ - Fix decoding based on a passed in non-default encoding in ``pd.read_stata`` (:issue:`4626`)
pandas 0.12
===========
diff --git a/pandas/io/common.py b/pandas/io/common.py
index f4a4ef789510c..02242c5a91493 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -66,6 +66,32 @@ def _is_s3_url(url):
return False
+def maybe_read_encoded_stream(reader, encoding=None):
+ """ read an encoded stream from the reader and transform the bytes to unicode
+ if required based on the encoding
+
+ Parameters
+ ----------
+ reader : a streamable file-like object
+ encoding : optional, the encoding to attempt to read
+
+ Returns
+ -------
+ a tuple of (a stream of decoded bytes, the encoding which was used)
+
+ """
+
+ if compat.PY3 or encoding is not None: # pragma: no cover
+ if encoding:
+ errors = 'strict'
+ else:
+ errors = 'replace'
+ encoding = 'utf-8'
+ reader = StringIO(reader.read().decode(encoding, errors))
+ else:
+ encoding = None
+ return reader, encoding
+
def get_filepath_or_buffer(filepath_or_buffer, encoding=None):
"""
If the filepath_or_buffer is a url, translate and return the buffer
@@ -83,17 +109,7 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None):
if _is_url(filepath_or_buffer):
req = _urlopen(str(filepath_or_buffer))
- if compat.PY3: # pragma: no cover
- if encoding:
- errors = 'strict'
- else:
- errors = 'replace'
- encoding = 'utf-8'
- out = StringIO(req.read().decode(encoding, errors))
- else:
- encoding = None
- out = req
- return out, encoding
+ return maybe_read_encoded_stream(req,encoding)
if _is_s3_url(filepath_or_buffer):
try:
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 9d21e10d69982..bab90a77c56e8 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -24,7 +24,7 @@
from pandas.compat import StringIO, long, lrange, lmap, lzip
from pandas import isnull
from pandas.io.parsers import _parser_params, Appender
-from pandas.io.common import get_filepath_or_buffer
+from pandas.io.common import get_filepath_or_buffer, maybe_read_encoded_stream
_read_stata_doc = """
@@ -203,11 +203,10 @@ def __repr__(self):
class StataParser(object):
- def __init__(self, encoding):
- if(encoding is None):
- self._encoding = 'cp1252'
- else:
- self._encoding = encoding
+ _default_encoding = 'cp1252'
+
+ def __init__(self, encoding=None):
+ self._encoding = encoding
#type code.
#--------------------
@@ -256,7 +255,7 @@ def __init__(self, encoding):
}
def _decode_bytes(self, str, errors=None):
- if compat.PY3:
+ if compat.PY3 or self._encoding is not None:
return str.decode(self._encoding, errors)
else:
return str
@@ -286,7 +285,8 @@ class StataReader(StataParser):
Encoding used to parse the files. Note that Stata doesn't
support unicode. None defaults to cp1252.
"""
- def __init__(self, path_or_buf, encoding=None):
+
+ def __init__(self, path_or_buf, encoding='cp1252'):
super(StataReader, self).__init__(encoding)
self.col_sizes = ()
self._has_string_data = False
@@ -295,8 +295,6 @@ def __init__(self, path_or_buf, encoding=None):
self._value_labels_read = False
if isinstance(path_or_buf, str):
path_or_buf, encoding = get_filepath_or_buffer(path_or_buf, encoding='cp1252')
- if encoding is not None:
- self._encoding = encoding
if isinstance(path_or_buf, (str, compat.text_type, bytes)):
self.path_or_buf = open(path_or_buf, 'rb')
@@ -403,13 +401,13 @@ def _unpack(self, fmt, byt):
return d
def _null_terminate(self, s):
- if compat.PY3: # have bytes not strings, so must decode
+ if compat.PY3 or self._encoding is not None: # have bytes not strings, so must decode
null_byte = b"\0"
try:
s = s[:s.index(null_byte)]
except:
pass
- return s.decode(self._encoding)
+ return s.decode(self._encoding or self._default_encoding)
else:
null_byte = "\0"
try:
@@ -744,7 +742,7 @@ def __init__(self, fname, data, convert_dates=None, write_index=True, encoding="
if byteorder is None:
byteorder = sys.byteorder
self._byteorder = _set_endianness(byteorder)
- self._file = _open_file_binary_write(fname, self._encoding)
+ self._file = _open_file_binary_write(fname, self._encoding or self._default_encoding)
self.type_converters = {253: np.long, 252: int}
def _write(self, to_write):
@@ -752,7 +750,7 @@ def _write(self, to_write):
Helper to call encode before writing to file for Python 3 compat.
"""
if compat.PY3:
- self._file.write(to_write.encode(self._encoding))
+ self._file.write(to_write.encode(self._encoding or self._default_encoding))
else:
self._file.write(to_write)
diff --git a/pandas/io/tests/data/stata1_encoding.dta b/pandas/io/tests/data/stata1_encoding.dta
new file mode 100644
index 0000000000000..b4230eda73e06
Binary files /dev/null and b/pandas/io/tests/data/stata1_encoding.dta differ
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index 31472dc667847..77ddafe838da4 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -13,7 +13,7 @@
from pandas.io.stata import read_stata, StataReader
import pandas.util.testing as tm
from pandas.util.misc import is_little_endian
-
+from pandas import compat
class StataTests(unittest.TestCase):
@@ -32,6 +32,7 @@ def setUp(self):
self.csv8 = os.path.join(self.dirpath, 'tbl19-3.csv')
self.dta9 = os.path.join(self.dirpath, 'lbw.dta')
self.csv9 = os.path.join(self.dirpath, 'lbw.csv')
+ self.dta_encoding = os.path.join(self.dirpath, 'stata1_encoding.dta')
def read_dta(self, file):
return read_stata(file, convert_dates=True)
@@ -202,6 +203,21 @@ def test_stata_doc_examples(self):
df = DataFrame(np.random.randn(10, 2), columns=list('AB'))
df.to_stata(path)
+ def test_encoding(self):
+
+ # GH 4626, proper encoding handling
+ raw = read_stata(self.dta_encoding)
+ encoded = read_stata(self.dta_encoding, encoding="latin-1")
+ result = encoded.kreis1849[0]
+
+ if compat.PY3:
+ expected = raw.kreis1849[0]
+ self.assert_(result == expected)
+ self.assert_(isinstance(result,compat.string_types))
+ else:
+ expected = raw.kreis1849.str.decode("latin-1")[0]
+ self.assert_(result == expected)
+ self.assert_(isinstance(result,unicode))
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| closes #4626
| https://api.github.com/repos/pandas-dev/pandas/pulls/4643 | 2013-08-22T17:41:00Z | 2013-08-26T15:21:56Z | 2013-08-26T15:21:56Z | 2014-06-24T15:12:52Z |
ENH: (GH4629) Support for using a DatetimeIndex/PeriodsIndex directly in a datelike calculation | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 578e235b0f88b..dbfd5bf717cbe 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -61,6 +61,8 @@ pandas 0.13
is frequency conversion.
- Performance improvements with ``__getitem__`` on ``DataFrames`` with
when the key is a column
+ - Support for using a ``DatetimeIndex/PeriodsIndex`` directly in a datelike calculation
+ e.g. s-s.index (:issue:`4629`)
**API Changes**
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 0fc3341c52117..050a9de2b23dc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -103,7 +103,7 @@ def wrapper(self, other, name=name):
coerce = 'compat' if _np_version_under1p7 else True
# convert the argument to an ndarray
- def convert_to_array(values):
+ def convert_to_array(values, other=None):
if not is_list_like(values):
values = np.array([values])
inferred_type = lib.infer_dtype(values)
@@ -111,6 +111,8 @@ def convert_to_array(values):
# a datetlike
if not (isinstance(values, (pa.Array, Series)) and com.is_datetime64_dtype(values)):
values = tslib.array_to_datetime(values)
+ elif isinstance(values, DatetimeIndex):
+ other = values = values.to_series()
elif inferred_type in set(['timedelta']):
# have a timedelta, convert to to ns here
values = com._possibly_cast_to_timedelta(values, coerce=coerce)
@@ -121,6 +123,8 @@ def convert_to_array(values):
# py3 compat where dtype is 'm' but is an integer
if values.dtype.kind == 'm':
values = values.astype('timedelta64[ns]')
+ elif isinstance(values, PeriodIndex):
+ other = values = values.to_timestamp().to_series()
elif name not in ['__truediv__','__div__','__mul__']:
raise TypeError("incompatible type for a datetime/timedelta operation [{0}]".format(name))
elif isinstance(values[0],DateOffset):
@@ -134,11 +138,11 @@ def convert_to_array(values):
else:
raise TypeError("incompatible type [{0}] for a datetime/timedelta operation".format(pa.array(values).dtype))
- return values
+ return values, other
# convert lhs and rhs
- lvalues = convert_to_array(lvalues)
- rvalues = convert_to_array(rvalues)
+ lvalues,_ = convert_to_array(lvalues)
+ rvalues,other = convert_to_array(rvalues,other)
is_datetime_rhs = com.is_datetime64_dtype(rvalues)
is_timedelta_rhs = com.is_timedelta64_dtype(rvalues) or (not is_datetime_rhs and _np_version_under1p7)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 4100185752b8f..a6e7d7cbc1773 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2319,6 +2319,30 @@ def test_sub_of_datetime_from_TimeSeries(self):
result = com._possibly_cast_to_timedelta(np.abs(a - b))
self.assert_(result.dtype == 'timedelta64[ns]')
+ def test_datetime64_with_index(self):
+
+ # arithmetic integer ops with an index
+ s = Series(np.random.randn(5))
+ expected = s-s.index.to_series()
+ result = s-s.index
+ assert_series_equal(result,expected)
+
+ # GH 4629
+ # arithmetic datetime64 ops with an index
+ s = Series(date_range('20130101',periods=5),index=date_range('20130101',periods=5))
+ expected = s-s.index.to_series()
+ result = s-s.index
+ assert_series_equal(result,expected)
+
+ result = s-s.index.to_period()
+ assert_series_equal(result,expected)
+
+ df = DataFrame(np.random.randn(5,2),index=date_range('20130101',periods=5))
+ df['date'] = Timestamp('20130102')
+ df['expected'] = df['date']-df.index.to_series()
+ df['result'] = df['date']-df.index
+ assert_series_equal(df['result'],df['expected'])
+
def test_timedelta64_nan(self):
from pandas import tslib
| closes #4629
```
In [1]: s = Series(date_range('20130101',periods=5),index=date_range('20130102',periods=5))
In [2]: s
Out[2]:
2013-01-02 2013-01-01 00:00:00
2013-01-03 2013-01-02 00:00:00
2013-01-04 2013-01-03 00:00:00
2013-01-05 2013-01-04 00:00:00
2013-01-06 2013-01-05 00:00:00
Freq: D, dtype: datetime64[ns]
In [3]: s-s.index
Out[3]:
2013-01-02 -1 days, 00:00:00
2013-01-03 -1 days, 00:00:00
2013-01-04 -1 days, 00:00:00
2013-01-05 -1 days, 00:00:00
2013-01-06 -1 days, 00:00:00
Freq: D, dtype: timedelta64[ns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4641 | 2013-08-22T15:23:10Z | 2013-08-24T00:15:30Z | 2013-08-24T00:15:29Z | 2014-07-16T08:24:21Z |
PERF: optimize __getitem__ in DataFrame for columns lookup | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 745876e8c448e..578e235b0f88b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -59,6 +59,8 @@ pandas 0.13
- A Series of dtype ``timedelta64[ns]`` can now be divided by another
``timedelta64[ns]`` object to yield a ``float64`` dtyped Series. This
is frequency conversion.
+ - Performance improvements with ``__getitem__`` on ``DataFrames`` with
+ when the key is a column
**API Changes**
@@ -183,7 +185,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Refactor ``Series.reindex`` to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
on a Series to work
- ``Series.copy`` no longer accepts the ``order`` parameter and is now consistent with ``NDFrame`` copy
-- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue`4605`), and adds ``rename``
+- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue:`4605`), and adds ``rename``
with the same signature for ``Panel``
**Experimental Features**
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index fce6896027867..31f7179f8e328 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1810,6 +1810,14 @@ def iget_value(self, i, j):
def __getitem__(self, key):
+ # shortcut if we are an actual column
+ is_mi_columns = isinstance(self.columns, MultiIndex)
+ try:
+ if key in self.columns and not is_mi_columns:
+ return self._getitem_column(key)
+ except:
+ pass
+
# see if we can slice the rows
indexer = _convert_to_index_sliceable(self, key)
if indexer is not None:
@@ -1820,15 +1828,20 @@ def __getitem__(self, key):
return self._getitem_array(key)
elif isinstance(key, DataFrame):
return self._getitem_frame(key)
- elif isinstance(self.columns, MultiIndex):
+ elif is_mi_columns:
return self._getitem_multilevel(key)
else:
- # get column
- if self.columns.is_unique:
- return self._get_item_cache(key)
+ return self._getitem_column(key)
+
+ def _getitem_column(self, key):
+ """ return the actual column """
+
+ # get column
+ if self.columns.is_unique:
+ return self._get_item_cache(key)
- # duplicate columns
- return self._constructor(self._data.get(key))
+ # duplicate columns
+ return self._constructor(self._data.get(key))
def _getitem_slice(self, key):
return self._slice(key, axis=0)
diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py
index f6909802f2d77..67c0aa227f886 100644
--- a/vb_suite/frame_methods.py
+++ b/vb_suite/frame_methods.py
@@ -84,6 +84,8 @@
setup = common_setup + """
df = DataFrame(randn(10000, 1000))
+df2 = DataFrame(randn(3000,1),columns=['A'])
+df3 = DataFrame(randn(3000,1))
def f():
if hasattr(df, '_item_cache'):
@@ -94,6 +96,15 @@ def f():
def g():
for name, col in df.iteritems():
pass
+
+def h():
+ for i in xrange(10000):
+ df2['A']
+
+def j():
+ for i in xrange(10000):
+ df3[0]
+
"""
# as far back as the earliest test currently in the suite
@@ -103,6 +114,12 @@ def g():
frame_iteritems_cached = Benchmark('g()', setup,
start_date=datetime(2010, 6, 1))
+frame_getitem_single_column = Benchmark('h()', setup,
+ start_date=datetime(2010, 6, 1))
+
+frame_getitem_single_column2 = Benchmark('j()', setup,
+ start_date=datetime(2010, 6, 1))
+
#----------------------------------------------------------------------
# to_string
| ```
In [1]: df2 = DataFrame(randn(3000,1),columns=['A'])
In [2]: df3 = DataFrame(randn(3000,1))
In [3]: def h():
...: for i in xrange(10000):
...: df2['A']
...:
In [4]: def j():
...: for i in xrange(10000):
...: df3[0]
...:
```
0.12
```
In [5]: %timeit h()
%time10 loops, best of 3: 39.8 ms per loop
In [6]: %timeit j()
10 loops, best of 3: 31.8 ms per loop
```
with PR
```
In [8]: %timeit h()
10 loops, best of 3: 25.5 ms per loop
In [9]: %timeit j()
10 loops, best of 3: 27.4 ms per loop
```
and the vbench
```
-------------------------------------------------------------------------------
Test name | head[ms] | base[ms] | ratio |
-------------------------------------------------------------------------------
frame_getitem_single_column | 25.5514 | 43.3776 | 0.5890 |
frame_getitem_single_column2 | 27.3627 | 32.4320 | 0.8437 |
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4639 | 2013-08-22T12:28:40Z | 2013-08-23T01:43:33Z | 2013-08-23T01:43:33Z | 2014-07-14T11:47:18Z |
excel reader & skip row between data & header & docs | the merge conflict chaos was too hard ;-(
This is a continuation of:
https://github.com/pydata/pandas/pull/4404
Because:
- we hit aparently a GitHub bug
- the branches diverged too much.
I shall fix:
- in the excel.py there is a fix enabling reading xlsx files with both
datemodes: (see #4332)
- in the parsers.py there is the fix for readinh the header even if there
are additional rows (to be skipped) between a header and the data (see: #4340)
- a few doc improvements
| https://api.github.com/repos/pandas-dev/pandas/pulls/4631 | 2013-08-21T23:44:51Z | 2013-09-25T17:12:44Z | 2013-09-25T17:12:44Z | 2013-10-08T16:27:17Z | |
API/CLN: make rename and copy consistent across NDFrame | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 7e863a4429487..a377fa3960d4c 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -730,6 +730,7 @@ Reindexing / Selection / Label manipulation
Panel.reindex
Panel.reindex_axis
Panel.reindex_like
+ Panel.rename
Panel.select
Panel.take
Panel.truncate
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9be9a03b0346e..0ca8437bb53d8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -172,21 +172,19 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- added ``ftypes`` method to Series/DataFame, similar to ``dtypes``, but indicates
if the underlying is sparse/dense (as well as the dtype)
-
- All ``NDFrame`` objects now have a ``_prop_attributes``, which can be used to indcated various
values to propogate to a new object from an existing (e.g. name in ``Series`` will follow
more automatically now)
-
- Internal type checking is now done via a suite of generated classes, allowing ``isinstance(value, klass)``
without having to directly import the klass, courtesy of @jtratner
-
- Bug in Series update where the parent frame is not updating its cache based on
changes (:issue:`4080`) or types (:issue:`3217`), fillna (:issue:`3386`)
-
- Indexing with dtype conversions fixed (:issue:`4463`, :issue:`4204`)
-
-- Refactor Series.reindex to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
+- Refactor ``Series.reindex`` to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
on a Series to work
+- ``Series.copy`` no longer accepts the ``order`` parameter and is now consistent with ``NDFrame`` copy
+- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue`4605`), and adds ``rename``
+ with the same signature for ``Panel``
**Experimental Features**
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index ffa71cbe97ce0..67d676618deb3 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -226,21 +226,19 @@ and behaviors. Series formerly subclassed directly from ``ndarray``. (:issue:`40
- added ``ftypes`` method to Series/DataFame, similar to ``dtypes``, but indicates
if the underlying is sparse/dense (as well as the dtype)
-
- All ``NDFrame`` objects now have a ``_prop_attributes``, which can be used to indcated various
values to propogate to a new object from an existing (e.g. name in ``Series`` will follow
more automatically now)
-
- Internal type checking is now done via a suite of generated classes, allowing ``isinstance(value, klass)``
without having to directly import the klass, courtesy of @jtratner
-
- Bug in Series update where the parent frame is not updating its cache based on
changes (:issue:`4080`) or types (:issue:`3217`), fillna (:issue:`3386`)
-
- Indexing with dtype conversions fixed (:issue:`4463`, :issue:`4204`)
-
-- Refactor Series.reindex to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
+- Refactor ``Series.reindex`` to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
on a Series to work
+- ``Series.copy`` no longer accepts the ``order`` parameter and is now consistent with ``NDFrame`` copy
+- Refactor ``rename`` methods to core/generic.py; fixes ``Series.rename`` for (:issue`4605`), and adds ``rename``
+ with the same signature for ``Panel``
Bug Fixes
~~~~~~~~~
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 413cb0b6ef3d0..fce6896027867 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2897,64 +2897,6 @@ def reorder_levels(self, order, axis=0):
result.columns = result.columns.reorder_levels(order)
return result
- #----------------------------------------------------------------------
- # Rename
-
- def rename(self, index=None, columns=None, copy=True, inplace=False):
- """
- Alter index and / or columns using input function or
- functions. Function / dict values must be unique (1-to-1). Labels not
- contained in a dict / Series will be left as-is.
-
- Parameters
- ----------
- index : dict-like or function, optional
- Transformation to apply to index values
- columns : dict-like or function, optional
- Transformation to apply to column values
- copy : boolean, default True
- Also copy underlying data
- inplace : boolean, default False
- Whether to return a new DataFrame. If True then value of copy is
- ignored.
-
- See also
- --------
- Series.rename
-
- Returns
- -------
- renamed : DataFrame (new object)
- """
- from pandas.core.series import _get_rename_function
-
- if index is None and columns is None:
- raise Exception('must pass either index or columns')
-
- index_f = _get_rename_function(index)
- columns_f = _get_rename_function(columns)
-
- self._consolidate_inplace()
-
- result = self if inplace else self.copy(deep=copy)
-
- if index is not None:
- result._rename_index_inplace(index_f)
-
- if columns is not None:
- result._rename_columns_inplace(columns_f)
-
- if not inplace:
- return result
-
- def _rename_index_inplace(self, mapper):
- self._data = self._data.rename_axis(mapper, axis=1)
- self._clear_item_cache()
-
- def _rename_columns_inplace(self, mapper):
- self._data = self._data.rename_items(mapper, copydata=False)
- self._clear_item_cache()
-
#----------------------------------------------------------------------
# Arithmetic / combination related
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index dccf3c9b8d36a..56c37ff3c7a0a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -13,10 +13,11 @@
from pandas.core.internals import BlockManager
import pandas.core.common as com
from pandas import compat
-from pandas.compat import map, zip
+from pandas.compat import map, zip, lrange
from pandas.core.common import (isnull, notnull, is_list_like,
_values_from_object,
- _infer_dtype_from_scalar, _maybe_promote)
+ _infer_dtype_from_scalar, _maybe_promote,
+ ABCSeries)
class NDFrame(PandasObject):
@@ -382,7 +383,77 @@ def swaplevel(self, i, j, axis=0):
result._data.set_axis(axis, labels.swaplevel(i, j))
return result
- def rename_axis(self, mapper, axis=0, copy=True):
+ #----------------------------------------------------------------------
+ # Rename
+
+ def rename(self, *args, **kwargs):
+ """
+ Alter axes input function or
+ functions. Function / dict values must be unique (1-to-1). Labels not
+ contained in a dict / Series will be left as-is.
+
+ Parameters
+ ----------
+ axis keywords for this object
+ (e.g. index for Series,
+ index,columns for DataFrame,
+ items,major_axis,minor_axis for Panel)
+ : dict-like or function, optional
+ Transformation to apply to that axis values
+
+ copy : boolean, default True
+ Also copy underlying data
+ inplace : boolean, default False
+ Whether to return a new PandasObject. If True then value of copy is
+ ignored.
+
+ Returns
+ -------
+ renamed : PandasObject (new object)
+ """
+
+ axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
+ copy = kwargs.get('copy', True)
+ inplace = kwargs.get('inplace', False)
+
+ if (com._count_not_none(*axes.values()) == 0):
+ raise Exception('must pass an index to rename')
+
+ # renamer function if passed a dict
+ def _get_rename_function(mapper):
+ if isinstance(mapper, (dict, ABCSeries)):
+ def f(x):
+ if x in mapper:
+ return mapper[x]
+ else:
+ return x
+ else:
+ f = mapper
+
+ return f
+
+
+ self._consolidate_inplace()
+ result = self if inplace else self.copy(deep=copy)
+
+ # start in the axis order to eliminate too many copies
+ for axis in lrange(self._AXIS_LEN):
+ v = axes.get(self._AXIS_NAMES[axis])
+ if v is None: continue
+ f = _get_rename_function(v)
+
+ baxis = self._get_block_manager_axis(axis)
+ result._data = result._data.rename(f, axis=baxis, copy=copy)
+ result._clear_item_cache()
+
+ if inplace:
+ self._data = result._data
+ self._clear_item_cache()
+
+ else:
+ return result._propogate_attributes(self)
+
+ def rename_axis(self, mapper, axis=0, copy=True, inplace=False):
"""
Alter index and / or columns using input function or functions.
Function / dict values must be unique (1-to-1). Labels not contained in
@@ -394,24 +465,16 @@ def rename_axis(self, mapper, axis=0, copy=True):
axis : int, default 0
copy : boolean, default True
Also copy underlying data
+ inplace : boolean, default False
Returns
-------
renamed : type of caller
"""
- # should move this at some point
- from pandas.core.series import _get_rename_function
-
- mapper_f = _get_rename_function(mapper)
-
- if axis == 0:
- new_data = self._data.rename_items(mapper_f, copydata=copy)
- else:
- new_data = self._data.rename_axis(mapper_f, axis=axis)
- if copy:
- new_data = new_data.copy()
-
- return self._constructor(new_data)
+ axis = self._AXIS_NAMES[axis]
+ d = { 'copy' : copy, 'inplace' : inplace }
+ d[axis] = mapper
+ return self.rename(**d)
#----------------------------------------------------------------------
# Comparisons
@@ -1373,7 +1436,7 @@ def copy(self, deep=True):
data = self._data
if deep:
data = data.copy()
- return self._constructor(data)
+ return self._constructor(data)._propogate_attributes(self)
def convert_objects(self, convert_dates=True, convert_numeric=False, copy=True):
"""
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index ecce508284fc1..82877d1ddae7e 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -2758,8 +2758,8 @@ def rrenamer(x):
return '%s%s' % (x, rsuffix)
return x
- this = self.rename_items(lrenamer, copydata=copydata)
- other = other.rename_items(rrenamer, copydata=copydata)
+ this = self.rename_items(lrenamer, copy=copydata)
+ other = other.rename_items(rrenamer, copy=copydata)
else:
this = self
@@ -2777,6 +2777,13 @@ def _is_indexed_like(self, other):
return False
return True
+ def rename(self, mapper, axis, copy=False):
+ """ generic rename """
+
+ if axis == 0:
+ return self.rename_items(mapper, copy=copy)
+ return self.rename_axis(mapper, axis=axis)
+
def rename_axis(self, mapper, axis=1):
index = self.axes[axis]
@@ -2793,7 +2800,7 @@ def rename_axis(self, mapper, axis=1):
new_axes[axis] = new_axis
return self.__class__(self.blocks, new_axes)
- def rename_items(self, mapper, copydata=True):
+ def rename_items(self, mapper, copy=True):
if isinstance(self.items, MultiIndex):
items = [tuple(mapper(y) for y in x) for x in self.items]
new_items = MultiIndex.from_tuples(items, names=self.items.names)
@@ -2803,7 +2810,7 @@ def rename_items(self, mapper, copydata=True):
new_blocks = []
for block in self.blocks:
- newb = block.copy(deep=copydata)
+ newb = block.copy(deep=copy)
newb.set_ref_items(new_items, maybe_rename=True)
new_blocks.append(newb)
new_axes = list(self.axes)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 051b445638f5b..0fc3341c52117 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1437,32 +1437,6 @@ def values(self):
"""
return self._data.values
- def copy(self, order='C', deep=False):
- """
- Return new Series with copy of underlying values
-
- Parameters
- ----------
- deep : boolean, default False
- deep copy index along with data
- order : boolean, default 'C'
- order for underlying numpy array
-
- Returns
- -------
- cp : Series
- """
- if deep:
- from copy import deepcopy
- index = self.index.copy(deep=deep)
- name = deepcopy(self.name)
- else:
- index = self.index
- name = self.name
-
- return Series(self.values.copy(order), index=index,
- name=name)
-
def get_values(self):
""" same as values (but handles sparseness conversions); is a view """
return self._data.values
@@ -3090,48 +3064,6 @@ def interpolate(self, method='linear'):
return self._constructor(result, index=self.index, name=self.name)
- def rename(self, mapper, inplace=False):
- """
- Alter Series index using dict or function
-
- Parameters
- ----------
- mapper : dict-like or function
- Transformation to apply to each index
-
- Notes
- -----
- Function / dict values must be unique (1-to-1)
-
- Examples
- --------
- >>> x
- foo 1
- bar 2
- baz 3
-
- >>> x.rename(str.upper)
- FOO 1
- BAR 2
- BAZ 3
-
- >>> x.rename({'foo' : 'a', 'bar' : 'b', 'baz' : 'c'})
- a 1
- b 2
- c 3
-
- Returns
- -------
- renamed : Series (new object)
- """
- mapper_f = _get_rename_function(mapper)
- result = self if inplace else self.copy()
- result.index = Index([mapper_f(x)
- for x in self.index], name=self.index.name)
-
- if not inplace:
- return result
-
@property
def weekday(self):
return self._constructor([d.weekday() for d in self.index], index=self.index)
@@ -3379,20 +3311,6 @@ def _try_cast(arr, take_fast_path):
return subarr
-
-def _get_rename_function(mapper):
- if isinstance(mapper, (dict, Series)):
- def f(x):
- if x in mapper:
- return mapper[x]
- else:
- return x
- else:
- f = mapper
-
- return f
-
-
def _resolve_offset(freq, kwds):
if 'timeRule' in kwds or 'offset' in kwds:
offset = kwds.get('offset', None)
diff --git a/pandas/tests/test_generic.py b/pandas/tests/test_generic.py
new file mode 100644
index 0000000000000..9a147b4e69f38
--- /dev/null
+++ b/pandas/tests/test_generic.py
@@ -0,0 +1,95 @@
+# pylint: disable-msg=E1101,W0612
+
+from datetime import datetime, timedelta
+import operator
+import unittest
+import nose
+
+import numpy as np
+import pandas as pd
+
+from pandas import (Index, Series, DataFrame, Panel,
+ isnull, notnull,date_range)
+from pandas.core.index import Index, MultiIndex
+from pandas.tseries.index import Timestamp, DatetimeIndex
+
+import pandas.core.common as com
+
+from pandas.compat import StringIO, lrange, range, zip, u, OrderedDict, long
+from pandas import compat
+from pandas.util.testing import (assert_series_equal,
+ assert_frame_equal,
+ assert_panel_equal,
+ assert_almost_equal,
+ ensure_clean)
+import pandas.util.testing as tm
+
+#------------------------------------------------------------------------------
+# Generic types test cases
+
+
+class Generic(object):
+
+ _multiprocess_can_split_ = True
+
+ def setUp(self):
+ import warnings
+ warnings.filterwarnings(action='ignore', category=FutureWarning)
+
+ def _axes(self):
+ """ return the axes for my object typ """
+ return self._typ._AXIS_ORDERS
+
+ def _construct(self, shape=None, **kwargs):
+ """ construct an object for the given shape """
+
+ if isinstance(shape,int):
+ shape = tuple([shape] * self._typ._AXIS_LEN)
+ return self._typ(np.random.randn(*shape),**kwargs)
+
+ def _compare(self, result, expected):
+ self._comparator(result,expected)
+
+ def test_rename(self):
+
+ # single axis
+ for axis in self._axes():
+ kwargs = { axis : list('ABCD') }
+ o = self._construct(4,**kwargs)
+
+ # no values passed
+ #self.assertRaises(Exception, o.rename(str.lower))
+
+ # rename a single axis
+ result = o.rename(**{ axis : str.lower })
+ expected = o.copy()
+ setattr(expected,axis,list('abcd'))
+ self._compare(result, expected)
+
+ # multiple axes at once
+
+class TestSeries(unittest.TestCase, Generic):
+ _typ = Series
+ _comparator = lambda self, x, y: assert_series_equal(x,y)
+
+ def test_rename_mi(self):
+ s = Series([11,21,31],
+ index=MultiIndex.from_tuples([("A",x) for x in ["a","B","c"]]))
+ result = s.rename(str.lower)
+
+class TestDataFrame(unittest.TestCase, Generic):
+ _typ = DataFrame
+ _comparator = lambda self, x, y: assert_frame_equal(x,y)
+
+ def test_rename_mi(self):
+ df = DataFrame([11,21,31],
+ index=MultiIndex.from_tuples([("A",x) for x in ["a","B","c"]]))
+ result = df.rename(str.lower)
+
+class TestPanel(unittest.TestCase, Generic):
+ _typ = Panel
+ _comparator = lambda self, x, y: assert_panel_equal(x,y)
+
+if __name__ == '__main__':
+ nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
+ exit=False)
| verifies #2721, #4039
closes #4605
TST: add tests/test_generic.py
API/CLN: Refactor rename methods to core/generic.py; fixes Series.rename for (GH4605), and adds rename
with the same signature for `Panel`
API/CLN: Refactor Series.copy to core/generic.py; removes the order argument from Series.copy (inconsistent)
| https://api.github.com/repos/pandas-dev/pandas/pulls/4627 | 2013-08-21T22:53:40Z | 2013-08-21T23:46:11Z | 2013-08-21T23:46:11Z | 2014-06-12T11:52:22Z |
API/CLN: setitem in Series now consistent with DataFrame | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9be9a03b0346e..b69c6aefd07d3 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -265,6 +265,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fixed issue where ``DataFrame.apply`` was reraising exceptions incorrectly
(causing the original stack trace to be truncated).
- Fix selection with ``ix/loc`` and non_unique selectors (:issue:`4619`)
+ - Fix assignment with iloc/loc involving a dtype change in an existing column (:issue:`4312`)
+ have internal setitem_with_indexer in core/indexing to use Block.setitem
pandas 0.12
===========
diff --git a/pandas/core/common.py b/pandas/core/common.py
index e46abb4aa83a6..0d3bd1a0c6de2 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -891,42 +891,6 @@ def changeit():
return result, False
-
-def _maybe_upcast_indexer(result, indexer, other, dtype=None):
- """ a safe version of setitem that (potentially upcasts the result
- return the result and a changed flag
- """
-
- other = _maybe_cast_scalar(result.dtype, other)
- original_dtype = result.dtype
-
- def changeit():
- # our type is wrong here, need to upcast
- r, fill_value = _maybe_upcast(
- result, fill_value=other, dtype=dtype, copy=True)
- try:
- r[indexer] = other
- except:
-
- # if we hit this then we still have an incompatible type
- r[indexer] = fill_value
-
- # if we have changed to floats, might want to cast back if we can
- r = _possibly_downcast_to_dtype(r, original_dtype)
- return r, True
-
- new_dtype, fill_value = _maybe_promote(original_dtype, other)
- if new_dtype != result.dtype:
- return changeit()
-
- try:
- result[indexer] = other
- except:
- return changeit()
-
- return result, False
-
-
def _maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False):
""" provide explicty type promotion and coercion
@@ -987,6 +951,12 @@ def _possibly_downcast_to_dtype(result, dtype):
dtype = np.dtype(dtype)
try:
+
+ # don't allow upcasts here
+ if dtype.kind == result.dtype.kind:
+ if result.dtype.itemsize <= dtype.itemsize:
+ return result
+
if issubclass(dtype.type, np.floating):
return result.astype(dtype)
elif dtype == np.bool_ or issubclass(dtype.type, np.integer):
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index d85ef1abd0fbc..1f15f1a8ae10d 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1557,7 +1557,9 @@ def transform(self, func, *args, **kwargs):
# need to do a safe put here, as the dtype may be different
# this needs to be an ndarray
- result,_ = com._maybe_upcast_indexer(result, indexer, res)
+ result = Series(result)
+ result.loc[indexer] = res
+ result = result.values
# downcast if we can (and need)
result = _possibly_downcast_to_dtype(result, dtype)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 3a0123b40aa39..64760cdba60ff 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -124,11 +124,13 @@ def _setitem_with_indexer(self, indexer, value):
item_labels = self.obj._get_axis(info_axis)
def setter(item, v):
- data = self.obj[item]
- values = data.values
- if np.prod(values.shape):
- result, changed = com._maybe_upcast_indexer(values,plane_indexer,v,dtype=getattr(data,'dtype',None))
- self.obj[item] = result
+ s = self.obj[item]
+ pi = plane_indexer[0] if len(plane_indexer) == 1 else plane_indexer
+
+ # set the item, possibly having a dtype change
+ s = s.copy()
+ s._data = s._data.setitem(pi,v)
+ self.obj[item] = s
labels = item_labels[info_idx]
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index ecce508284fc1..9ca4dcda361ba 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -39,6 +39,7 @@ class Block(PandasObject):
is_float = False
is_integer = False
is_complex = False
+ is_datetime = False
is_bool = False
is_object = False
is_sparse = False
@@ -453,10 +454,19 @@ def _can_hold_element(self, value):
def _try_cast(self, value):
raise NotImplementedError()
- def _try_cast_result(self, result):
+ def _try_cast_result(self, result, dtype=None):
""" try to cast the result to our original type,
we may have roundtripped thru object in the mean-time """
- return result
+ if dtype is None:
+ dtype = self.dtype
+
+ if self.is_integer or self.is_bool or self.is_datetime:
+ pass
+ elif self.is_float and result.dtype == self.dtype:
+ return result
+
+ # may need to change the dtype here
+ return _possibly_downcast_to_dtype(result, dtype)
def _try_coerce_args(self, values, other):
""" provide coercion to our input arguments """
@@ -513,27 +523,29 @@ def setitem(self, indexer, value):
""" set the value inplace; return a new block (of a possibly different dtype)
indexer is a direct slice/positional indexer; value must be a compaitable shape """
- values = self.values
- if self.ndim == 2:
- values = values.T
+ # coerce args
+ values, value = self._try_coerce_args(self.values, value)
+ arr_value = np.array(value)
- # 2-d (DataFrame) are represented as a transposed array
- if self._can_hold_element(value):
- try:
- values[indexer] = value
- return [ self ]
- except (IndexError):
- return [ self ]
- except:
- pass
+ # cast the values to a type that can hold nan (if necessary)
+ if not self._can_hold_element(value):
+ dtype, _ = com._maybe_promote(arr_value.dtype)
+ values = values.astype(dtype)
- # create an indexing mask, the putmask which potentially changes the dtype
- indices = np.arange(np.prod(values.shape)).reshape(values.shape)
- mask = indices[indexer] == indices
- if self.ndim == 2:
- mask = mask.T
+ try:
+ # set and return a block
+ transf = (lambda x: x.T) if self.ndim == 2 else (lambda x: x)
+ values = transf(values)
+ values[indexer] = value
+
+ # coerce and try to infer the dtypes of the result
+ values = self._try_coerce_result(values)
+ values = self._try_cast_result(values, 'infer')
+ return [make_block(transf(values), self.items, self.ref_items, ndim=self.ndim, fastpath=True)]
+ except:
+ pass
- return self.putmask(mask, value, inplace=True)
+ return [ self ]
def putmask(self, mask, new, inplace=False):
""" putmask the data to the block; it is possible that we may create a new dtype of block
@@ -585,7 +597,10 @@ def create_block(v, m, n, item, reshape=True):
if nv is None:
dtype, _ = com._maybe_promote(n.dtype)
nv = v.astype(dtype)
- np.putmask(nv, m, n)
+ try:
+ nv[m] = n
+ except:
+ np.putmask(nv, m, n)
if reshape:
nv = _block_shape(nv)
@@ -842,10 +857,6 @@ class NumericBlock(Block):
is_numeric = True
_can_hold_na = True
- def _try_cast_result(self, result):
- return _possibly_downcast_to_dtype(result, self.dtype)
-
-
class FloatBlock(NumericBlock):
is_float = True
_downcast_dtype = 'int64'
@@ -1104,6 +1115,7 @@ def re_replacer(s):
class DatetimeBlock(Block):
+ is_datetime = True
_can_hold_na = True
def __init__(self, values, items, ref_items, fastpath=False, placement=None, **kwargs):
@@ -1119,8 +1131,8 @@ def _gi(self, arg):
def _can_hold_element(self, element):
if is_list_like(element):
element = np.array(element)
- return element.dtype == _NS_DTYPE
- return com.is_integer(element) or isinstance(element, datetime)
+ return element.dtype == _NS_DTYPE or element.dtype == np.int64
+ return com.is_integer(element) or isinstance(element, datetime) or isnull(element)
def _try_cast(self, element):
try:
@@ -1133,10 +1145,10 @@ def _try_coerce_args(self, values, other):
we are going to compare vs i8, so coerce to integer
values is always ndarra like, other may not be """
values = values.view('i8')
- if isinstance(other, datetime):
- other = lib.Timestamp(other).asm8.view('i8')
- elif isnull(other):
+ if isnull(other) or (np.isscalar(other) and other == tslib.iNaT):
other = tslib.iNaT
+ elif isinstance(other, datetime):
+ other = lib.Timestamp(other).asm8.view('i8')
else:
other = other.view('i8')
@@ -1438,6 +1450,8 @@ def split_block_at(self, item):
return []
return super(SparseBlock, self).split_block_at(self, item)
+ def _try_cast_result(self, result, dtype=None):
+ return result
def make_block(values, items, ref_items, klass=None, ndim=None, dtype=None, fastpath=False, placement=None):
diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py
index 946e640d331cc..799cdd31c0a65 100644
--- a/pandas/tests/test_common.py
+++ b/pandas/tests/test_common.py
@@ -127,14 +127,14 @@ def test_nan_to_nat_conversions():
result = df.loc[4,'B'].value
assert(result == iNaT)
- values = df['B'].values
- result, changed = com._maybe_upcast_indexer(values,tuple([slice(8,9)]),np.nan)
- assert(isnull(result[8]))
+ s = df['B'].copy()
+ s._data = s._data.setitem(tuple([slice(8,9)]),np.nan)
+ assert(isnull(s[8]))
# numpy < 1.7.0 is wrong
from distutils.version import LooseVersion
if LooseVersion(np.__version__) >= '1.7.0':
- assert(result[8] == np.datetime64('NaT'))
+ assert(s[8].value == np.datetime64('NaT').astype(np.int64))
def test_any_none():
assert(com._any_none(1, 2, 3, None))
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 1a65eec8557c0..c8f87a19a5f34 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7669,10 +7669,9 @@ def _check_get(df, cond, check_dtypes = True):
# upcasting case (GH # 2794)
df = DataFrame(dict([ (c,Series([1]*3,dtype=c)) for c in ['int64','int32','float32','float64'] ]))
df.ix[1,:] = 0
-
result = df.where(df>=0).get_dtype_counts()
- #### when we don't preserver boolean casts ####
+ #### when we don't preserve boolean casts ####
#expected = Series({ 'float32' : 1, 'float64' : 3 })
expected = Series({ 'float32' : 1, 'float64' : 1, 'int32' : 1, 'int64' : 1 })
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 26cef3acbfad1..76003de65180f 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -942,6 +942,7 @@ def test_multi_assign(self):
# frame on rhs
df2.ix[mask, cols]= dft.ix[mask, cols]
assert_frame_equal(df2,expected)
+
df2.ix[mask, cols]= dft.ix[mask, cols]
assert_frame_equal(df2,expected)
@@ -964,11 +965,12 @@ def test_ix_assign_column_mixed(self):
# GH 3668, mixed frame with series value
df = DataFrame({'x':lrange(10), 'y':lrange(10,20),'z' : 'bar'})
expected = df.copy()
- expected.ix[0, 'y'] = 1000
- expected.ix[2, 'y'] = 1200
- expected.ix[4, 'y'] = 1400
- expected.ix[6, 'y'] = 1600
- expected.ix[8, 'y'] = 1800
+
+ for i in range(5):
+ indexer = i*2
+ v = 1000 + i*200
+ expected.ix[indexer, 'y'] = v
+ self.assert_(expected.ix[indexer, 'y'] == v)
df.ix[df.x % 2 == 0, 'y'] = df.ix[df.x % 2 == 0, 'y'] * 100
assert_frame_equal(df,expected)
@@ -1197,6 +1199,22 @@ def gen_expected(df,mask):
expected = gen_expected(df,mask)
assert_frame_equal(result,expected)
+ def test_astype_assignment_with_iloc(self):
+
+ # GH4312
+ df_orig = DataFrame([['1','2','3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
+
+ df = df_orig.copy()
+ df.iloc[:,0:3] = df.iloc[:,0:3].astype(int)
+ result = df.get_dtype_counts().sort_index()
+ expected = Series({ 'int64' : 4, 'float64' : 1, 'object' : 2 }).sort_index()
+ assert_series_equal(result,expected)
+
+ df = df_orig.copy()
+ df.iloc[:,0:3] = df.iloc[:,0:3].convert_objects(convert_numeric=True)
+ result = df.get_dtype_counts().sort_index()
+ expected = Series({ 'int64' : 4, 'float64' : 1, 'object' : 2 }).sort_index()
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| closes #4312
setitem in a frame that can change dtype
setitem_with_indexer now uses the Block.setitem machinery
| https://api.github.com/repos/pandas-dev/pandas/pulls/4624 | 2013-08-21T20:40:34Z | 2013-08-21T23:15:01Z | 2013-08-21T23:15:01Z | 2014-06-16T23:53:39Z |
BUG: Fix selection with ``ix/loc`` and non_unique selectors (GH4619) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 8fba8618fd860..9be9a03b0346e 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -264,6 +264,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
to a possible lazay frequency inference issue (:issue:`3317`)
- Fixed issue where ``DataFrame.apply`` was reraising exceptions incorrectly
(causing the original stack trace to be truncated).
+ - Fix selection with ``ix/loc`` and non_unique selectors (:issue:`4619`)
pandas 0.12
===========
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 11818a4fea7c8..3a0123b40aa39 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -476,8 +476,12 @@ def _reindex(keys, level=None):
else:
level = None
- if labels.is_unique and Index(keyarr).is_unique:
+ keyarr_is_unique = Index(keyarr).is_unique
+
+ # existing labels are unique and indexer is unique
+ if labels.is_unique and keyarr_is_unique:
return _reindex(keyarr, level=level)
+
else:
indexer, missing = labels.get_indexer_non_unique(keyarr)
check = indexer != -1
@@ -496,8 +500,15 @@ def _reindex(keys, level=None):
new_labels = np.empty(tuple([len(indexer)]),dtype=object)
new_labels[cur_indexer] = cur_labels
new_labels[missing_indexer] = missing_labels
- new_indexer = (Index(cur_indexer) + Index(missing_indexer)).values
- new_indexer[missing_indexer] = -1
+
+ # a unique indexer
+ if keyarr_is_unique:
+ new_indexer = (Index(cur_indexer) + Index(missing_indexer)).values
+ new_indexer[missing_indexer] = -1
+
+ # we have a non_unique selector, need to use the original indexer here
+ else:
+ new_indexer = indexer
# reindex with the specified axis
ndim = self.obj.ndim
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 101cbd9d6baf8..26cef3acbfad1 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -796,20 +796,21 @@ def test_dups_fancy_indexing(self):
assert_frame_equal(df,result)
# GH 3561, dups not in selected order
- ind = ['A', 'A', 'B', 'C']
- df = DataFrame({'test':lrange(len(ind))}, index=ind)
+ df = DataFrame({'test': [5,7,9,11]}, index=['A', 'A', 'B', 'C'])
rows = ['C', 'B']
- res = df.ix[rows]
- self.assert_(rows == list(res.index))
+ expected = DataFrame({'test' : [11,9]},index=rows)
+ result = df.ix[rows]
+ assert_frame_equal(result, expected)
- res = df.ix[Index(rows)]
- self.assert_(Index(rows).equals(res.index))
+ result = df.ix[Index(rows)]
+ assert_frame_equal(result, expected)
rows = ['C','B','E']
- res = df.ix[rows]
- self.assert_(rows == list(res.index))
+ expected = DataFrame({'test' : [11,9,np.nan]},index=rows)
+ result = df.ix[rows]
+ assert_frame_equal(result, expected)
- # inconcistent returns for unique/duplicate indices when values are missing
+ # inconsistent returns for unique/duplicate indices when values are missing
df = DataFrame(randn(4,3),index=list('ABCD'))
expected = df.ix[['E']]
@@ -817,6 +818,23 @@ def test_dups_fancy_indexing(self):
result = dfnu.ix[['E']]
assert_frame_equal(result, expected)
+ # GH 4619; duplicate indexer with missing label
+ df = DataFrame({"A": [0, 1, 2]})
+ result = df.ix[[0,8,0]]
+ expected = DataFrame({"A": [0, np.nan, 0]},index=[0,8,0])
+ assert_frame_equal(result,expected)
+
+ df = DataFrame({"A": list('abc')})
+ result = df.ix[[0,8,0]]
+ expected = DataFrame({"A": ['a', np.nan, 'a']},index=[0,8,0])
+ assert_frame_equal(result,expected)
+
+ # non unique with non unique selector
+ df = DataFrame({'test': [5,7,9,11]}, index=['A','A','B','C'])
+ expected = DataFrame({'test' : [5,7,5,7,np.nan]},index=['A','A','A','A','E'])
+ result = df.ix[['A','A','E']]
+ assert_frame_equal(result, expected)
+
def test_indexing_mixed_frame_bug(self):
# GH3492
| closes #4619
```
In [7]: df = DataFrame({"A": [0, 1, 2]})
In [8]: df
Out[8]:
A
0 0
1 1
2 2
In [9]: df.ix[[0,8,0]]
Out[9]:
A
0 0
8 NaN
0 0
In [10]: df = DataFrame({"A": list('abc')})
In [12]: df
Out[12]:
A
0 a
1 b
2 c
In [11]: df.ix[[0,8,0]]
Out[11]:
A
0 a
8 NaN
0 a
```
and this beauty here!
```
In [13]: df = DataFrame({'test': [5,7,9,11]}, index=['A','A','B','C'])
In [14]: df
Out[14]:
test
A 5
A 7
B 9
C 11
In [15]: df.ix[['A','A','E']]
Out[15]:
test
A 5
A 7
A 5
A 7
E NaN
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4622 | 2013-08-21T16:00:40Z | 2013-08-21T18:22:24Z | 2013-08-21T18:22:24Z | 2014-06-23T06:54:56Z |
Fixes usage of CacheableOffset | diff --git a/doc/source/release.rst b/doc/source/release.rst
index a2b525a737879..c779a4fd3dfea 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -98,6 +98,8 @@ pandas 0.13
with the usecols parameter (:issue: `3192`)
- Fix an issue in merging blocks where the resulting DataFrame had partially
set _ref_locs (:issue:`4403`)
+ - Fix an issue with CacheableOffset not properly being used by many DateOffset; this prevented
+ the DateOffset from being cached (:issue:`4609`)
pandas 0.12
===========
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 17d357370c078..1105da2ecb986 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -341,9 +341,7 @@ def _generate(cls, start, end, periods, name, offset,
if end.tz is None and start.tz is not None:
end = end.tz_localize(start.tz)
- if (offset._should_cache() and
- not (offset._normalize_cache and not _normalized) and
- _naive_in_cache_range(start, end)):
+ if _use_cached_range(offset, _normalized, start, end):
index = cls._cached_range(start, end, periods=periods,
offset=offset, name=name)
else:
@@ -366,9 +364,7 @@ def _generate(cls, start, end, periods, name, offset,
if end.tz is None and start.tz is not None:
start = start.replace(tzinfo=None)
- if (offset._should_cache() and
- not (offset._normalize_cache and not _normalized) and
- _naive_in_cache_range(start, end)):
+ if _use_cached_range(offset, _normalized, start, end):
index = cls._cached_range(start, end, periods=periods,
offset=offset, name=name)
else:
@@ -1835,6 +1831,10 @@ def _naive_in_cache_range(start, end):
def _in_range(start, end, rng_start, rng_end):
return start > rng_start and end < rng_end
+def _use_cached_range(offset, _normalized, start, end):
+ return (offset._should_cache() and
+ not (offset._normalize_cache and not _normalized) and
+ _naive_in_cache_range(start, end))
def _time_to_micros(time):
seconds = time.hour * 60 * 60 + 60 * time.minute + time.second
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index b78fa52f0be03..bef54a0b37f21 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -477,7 +477,7 @@ def onOffset(self, dt):
return np.is_busday(day64, busdaycal=self.busdaycalendar)
-class MonthEnd(DateOffset, CacheableOffset):
+class MonthEnd(CacheableOffset, DateOffset):
"""DateOffset of one month end"""
def apply(self, other):
@@ -502,7 +502,7 @@ def rule_code(self):
return 'M'
-class MonthBegin(DateOffset, CacheableOffset):
+class MonthBegin(CacheableOffset, DateOffset):
"""DateOffset of one month at beginning"""
def apply(self, other):
@@ -553,7 +553,7 @@ def rule_code(self):
return 'BM'
-class BusinessMonthBegin(DateOffset, CacheableOffset):
+class BusinessMonthBegin(CacheableOffset, DateOffset):
"""DateOffset of one business month at beginning"""
def apply(self, other):
@@ -590,7 +590,7 @@ def rule_code(self):
return 'BMS'
-class Week(DateOffset, CacheableOffset):
+class Week(CacheableOffset, DateOffset):
"""
Weekly offset
@@ -656,7 +656,7 @@ def rule_code(self):
}
-class WeekOfMonth(DateOffset, CacheableOffset):
+class WeekOfMonth(CacheableOffset, DateOffset):
"""
Describes monthly dates like "the Tuesday of the 2nd week of each month"
@@ -729,7 +729,7 @@ def rule_code(self):
return 'WOM' + suffix
-class BQuarterEnd(DateOffset, CacheableOffset):
+class BQuarterEnd(CacheableOffset, DateOffset):
"""DateOffset increments between business Quarter dates
startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ...
startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ...
@@ -796,7 +796,7 @@ def rule_code(self):
}
-class BQuarterBegin(DateOffset, CacheableOffset):
+class BQuarterBegin(CacheableOffset, DateOffset):
_outputName = "BusinessQuarterBegin"
def __init__(self, n=1, **kwds):
@@ -843,7 +843,7 @@ def rule_code(self):
return 'BQS' + suffix
-class QuarterEnd(DateOffset, CacheableOffset):
+class QuarterEnd(CacheableOffset, DateOffset):
"""DateOffset increments between business Quarter dates
startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ...
startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ...
@@ -887,7 +887,7 @@ def rule_code(self):
return 'Q' + suffix
-class QuarterBegin(DateOffset, CacheableOffset):
+class QuarterBegin(CacheableOffset, DateOffset):
_outputName = 'QuarterBegin'
def __init__(self, n=1, **kwds):
@@ -924,7 +924,7 @@ def rule_code(self):
return 'QS' + suffix
-class BYearEnd(DateOffset, CacheableOffset):
+class BYearEnd(CacheableOffset, DateOffset):
"""DateOffset increments between business EOM dates"""
_outputName = 'BusinessYearEnd'
@@ -971,7 +971,7 @@ def rule_code(self):
return 'BA' + suffix
-class BYearBegin(DateOffset, CacheableOffset):
+class BYearBegin(CacheableOffset, DateOffset):
"""DateOffset increments between business year begin dates"""
_outputName = 'BusinessYearBegin'
@@ -1013,7 +1013,7 @@ def rule_code(self):
return 'BAS' + suffix
-class YearEnd(DateOffset, CacheableOffset):
+class YearEnd(CacheableOffset, DateOffset):
"""DateOffset increments between calendar year ends"""
def __init__(self, n=1, **kwds):
@@ -1080,7 +1080,7 @@ def rule_code(self):
return 'A' + suffix
-class YearBegin(DateOffset, CacheableOffset):
+class YearBegin(CacheableOffset, DateOffset):
"""DateOffset increments between calendar year begin dates"""
def __init__(self, n=1, **kwds):
@@ -1251,7 +1251,7 @@ def _delta_to_nanoseconds(delta):
+ delta.microseconds) * 1000
-class Day(Tick, CacheableOffset):
+class Day(CacheableOffset, Tick):
_inc = timedelta(1)
_rule_base = 'D'
diff --git a/pandas/tseries/tests/test_offsets.py b/pandas/tseries/tests/test_offsets.py
index 7d026a46dde15..c248e0a5e0de3 100644
--- a/pandas/tseries/tests/test_offsets.py
+++ b/pandas/tseries/tests/test_offsets.py
@@ -17,7 +17,7 @@
get_standard_freq)
from pandas.tseries.frequencies import _offset_map
-from pandas.tseries.index import _to_m8
+from pandas.tseries.index import _to_m8, DatetimeIndex, _daterange_cache
from pandas.tseries.tools import parse_time_string
import pandas.tseries.offsets as offsets
@@ -25,6 +25,7 @@
from pandas.lib import Timestamp
from pandas.util.testing import assertRaisesRegexp
import pandas.util.testing as tm
+from pandas.tseries.offsets import BusinessMonthEnd, CacheableOffset
_multiprocess_can_split_ = True
@@ -1789,7 +1790,60 @@ def test_freq_offsets():
off = BDay(1, offset=timedelta(0, -1800))
assert(off.freqstr == 'B-30Min')
-
+
+def get_all_subclasses(cls):
+ ret = set()
+ this_subclasses = cls.__subclasses__()
+ ret = ret | set(this_subclasses)
+ for this_subclass in this_subclasses:
+ ret | get_all_subclasses(this_subclass)
+ return ret
+
+class TestCaching(unittest.TestCase):
+ def test_should_cache_month_end(self):
+ self.assertTrue(MonthEnd()._should_cache())
+
+ def test_should_cache_bmonth_end(self):
+ self.assertTrue(BusinessMonthEnd()._should_cache())
+
+ def test_should_cache_week_month(self):
+ self.assertTrue(WeekOfMonth(weekday=1, week=2)._should_cache())
+
+ def test_all_cacheableoffsets(self):
+ for subclass in get_all_subclasses(CacheableOffset):
+ if subclass in [WeekOfMonth]:
+ continue
+ self.run_X_index_creation(subclass)
+
+ def setUp(self):
+ _daterange_cache.clear()
+
+ def run_X_index_creation(self, cls):
+ inst1 = cls()
+ if not inst1.isAnchored():
+ self.assertFalse(inst1._should_cache(), cls)
+ return
+
+ self.assertTrue(inst1._should_cache(), cls)
+
+ DatetimeIndex(start=datetime(2013,1,31), end=datetime(2013,3,31), freq=inst1, normalize=True)
+ self.assertTrue(cls() in _daterange_cache, cls)
+
+ def test_month_end_index_creation(self):
+ DatetimeIndex(start=datetime(2013,1,31), end=datetime(2013,3,31), freq=MonthEnd(), normalize=True)
+ self.assertTrue(MonthEnd() in _daterange_cache)
+
+ def test_bmonth_end_index_creation(self):
+ DatetimeIndex(start=datetime(2013,1,31), end=datetime(2013,3,29), freq=BusinessMonthEnd(), normalize=True)
+ self.assertTrue(BusinessMonthEnd() in _daterange_cache)
+
+ def test_week_of_month_index_creation(self):
+ inst1 = WeekOfMonth(weekday=1, week=2)
+ DatetimeIndex(start=datetime(2013,1,31), end=datetime(2013,3,29), freq=inst1, normalize=True)
+ inst2 = WeekOfMonth(weekday=1, week=2)
+ self.assertTrue(inst2 in _daterange_cache)
+
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
| `CacheableOffset` should be first parent class when sub-classing both `CacheableOffset` and `DateOffset`
Closes #4609
| https://api.github.com/repos/pandas-dev/pandas/pulls/4614 | 2013-08-20T04:07:57Z | 2013-08-24T00:11:41Z | 2013-08-24T00:11:41Z | 2014-06-21T13:19:40Z |
CLN: Refactor series datetime arithmetic | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 87688612294a8..6e5ff20b294ea 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -200,6 +200,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
with the same signature for ``Panel``
- Series (for index) / Panel (for items) now as attribute access to its elements (:issue:`1903`)
- Refactor of ``_get_numeric_data/_get_bool_data`` to core/generic.py, allowing Series/Panel functionaility
+- Refactor of Series arithmetic with time-like objects (datetime/timedelta/time
+ etc.) into a separate, cleaned up wrapper class. (:issue:`4613`)
**Experimental Features**
diff --git a/pandas/core/series.py b/pandas/core/series.py
index ad4295d05fca7..e3f97a28fe8cc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -59,10 +59,178 @@
_SHOW_WARNINGS = True
+class _TimeOp(object):
+ """
+ Wrapper around Series datetime/time/timedelta arithmetic operations.
+ Generally, you should use classmethod ``maybe_convert_for_time_op`` as an
+ entry point.
+ """
+ fill_value = tslib.iNaT
+ wrap_results = staticmethod(lambda x: x)
+ dtype = None
+
+ def __init__(self, left, right, name):
+ self.name = name
+
+ lvalues = self._convert_to_array(left, name=name)
+ rvalues = self._convert_to_array(right, name=name)
+
+ self.is_timedelta_lhs = com.is_timedelta64_dtype(left)
+ self.is_datetime_lhs = com.is_datetime64_dtype(left)
+ self.is_integer_lhs = left.dtype.kind in ['i','u']
+ self.is_datetime_rhs = com.is_datetime64_dtype(rvalues)
+ self.is_timedelta_rhs = com.is_timedelta64_dtype(rvalues) or (not self.is_datetime_rhs and _np_version_under1p7)
+ self.is_integer_rhs = rvalues.dtype.kind in ('i','u')
+
+ self._validate()
+
+ self._convert_for_datetime(lvalues, rvalues)
+
+ def _validate(self):
+ # timedelta and integer mul/div
+
+ if (self.is_timedelta_lhs and self.is_integer_rhs) or\
+ (self.is_integer_lhs and self.is_timedelta_rhs):
+
+ if self.name not in ('__truediv__','__div__','__mul__'):
+ raise TypeError("can only operate on a timedelta and an integer for "
+ "division, but the operator [%s] was passed" % self.name)
+
+ # 2 datetimes
+ elif self.is_datetime_lhs and self.is_datetime_rhs:
+ if self.name != '__sub__':
+ raise TypeError("can only operate on a datetimes for subtraction, "
+ "but the operator [%s] was passed" % self.name)
+
+
+ # 2 timedeltas
+ elif self.is_timedelta_lhs and self.is_timedelta_rhs:
+
+ if self.name not in ('__div__', '__truediv__', '__add__', '__sub__'):
+ raise TypeError("can only operate on a timedeltas for "
+ "addition, subtraction, and division, but the operator [%s] was passed" % self.name)
+
+ # datetime and timedelta
+ elif self.is_datetime_lhs and self.is_timedelta_rhs:
+
+ if self.name not in ('__add__','__sub__'):
+ raise TypeError("can only operate on a datetime with a rhs of a timedelta for "
+ "addition and subtraction, but the operator [%s] was passed" % self.name)
+
+ elif self.is_timedelta_lhs and self.is_datetime_rhs:
+
+ if self.name != '__add__':
+ raise TypeError("can only operate on a timedelta and a datetime for "
+ "addition, but the operator [%s] was passed" % self.name)
+ else:
+ raise TypeError('cannot operate on a series with out a rhs '
+ 'of a series/ndarray of type datetime64[ns] '
+ 'or a timedelta')
+
+ def _convert_to_array(self, values, name=None):
+ """converts values to ndarray"""
+ coerce = 'compat' if _np_version_under1p7 else True
+ if not is_list_like(values):
+ values = np.array([values])
+ inferred_type = lib.infer_dtype(values)
+ if inferred_type in ('datetime64','datetime','date','time'):
+ # a datetlike
+ if not (isinstance(values, (pa.Array, Series)) and com.is_datetime64_dtype(values)):
+ values = tslib.array_to_datetime(values)
+ elif isinstance(values, DatetimeIndex):
+ values = values.to_series()
+ elif inferred_type in ('timedelta', 'timedelta64'):
+ # have a timedelta, convert to to ns here
+ values = com._possibly_cast_to_timedelta(values, coerce=coerce)
+ elif inferred_type == 'integer':
+ # py3 compat where dtype is 'm' but is an integer
+ if values.dtype.kind == 'm':
+ values = values.astype('timedelta64[ns]')
+ elif isinstance(values, PeriodIndex):
+ values = values.to_timestamp().to_series()
+ elif name not in ('__truediv__','__div__','__mul__'):
+ raise TypeError("incompatible type for a datetime/timedelta "
+ "operation [{0}]".format(name))
+ elif isinstance(values[0],DateOffset):
+ # handle DateOffsets
+ os = pa.array([ getattr(v,'delta',None) for v in values ])
+ mask = isnull(os)
+ if mask.any():
+ raise TypeError("cannot use a non-absolute DateOffset in "
+ "datetime/timedelta operations [{0}]".format(
+ ','.join([ com.pprint_thing(v) for v in values[mask] ])))
+ values = com._possibly_cast_to_timedelta(os, coerce=coerce)
+ else:
+ raise TypeError("incompatible type [{0}] for a datetime/timedelta operation".format(pa.array(values).dtype))
+
+ return values
+
+ def _convert_for_datetime(self, lvalues, rvalues):
+ mask = None
+ # datetimes require views
+ if self.is_datetime_lhs or self.is_datetime_rhs:
+ # datetime subtraction means timedelta
+ if self.is_datetime_lhs and self.is_datetime_rhs:
+ self.dtype = 'timedelta64[ns]'
+ else:
+ self.dtype = 'datetime64[ns]'
+ mask = isnull(lvalues) | isnull(rvalues)
+ lvalues = lvalues.view(np.int64)
+ rvalues = rvalues.view(np.int64)
+
+ # otherwise it's a timedelta
+ else:
+ self.dtype = 'timedelta64[ns]'
+ mask = isnull(lvalues) | isnull(rvalues)
+ lvalues = lvalues.astype(np.int64)
+ rvalues = rvalues.astype(np.int64)
+
+ # time delta division -> unit less
+ # integer gets converted to timedelta in np < 1.6
+ if (self.is_timedelta_lhs and self.is_timedelta_rhs) and\
+ not self.is_integer_rhs and\
+ not self.is_integer_lhs and\
+ self.name in ('__div__', '__truediv__'):
+ self.dtype = 'float64'
+ self.fill_value = np.nan
+ lvalues = lvalues.astype(np.float64)
+ rvalues = rvalues.astype(np.float64)
+
+ # if we need to mask the results
+ if mask is not None:
+ if mask.any():
+ def f(x):
+ x = pa.array(x,dtype=self.dtype)
+ np.putmask(x,mask,self.fill_value)
+ return x
+ self.wrap_results = f
+ self.lvalues = lvalues
+ self.rvalues = rvalues
+
+ @classmethod
+ def maybe_convert_for_time_op(cls, left, right, name):
+ """
+ if ``left`` and ``right`` are appropriate for datetime arithmetic with
+ operation ``name``, processes them and returns a ``_TimeOp`` object
+ that stores all the required values. Otherwise, it will generate
+ either a ``NotImplementedError`` or ``None``, indicating that the
+ operation is unsupported for datetimes (e.g., an unsupported r_op) or
+ that the data is not the right type for time ops.
+ """
+ # decide if we can do it
+ is_timedelta_lhs = com.is_timedelta64_dtype(left)
+ is_datetime_lhs = com.is_datetime64_dtype(left)
+ if not (is_datetime_lhs or is_timedelta_lhs):
+ return None
+ # rops currently disabled
+ if name.startswith('__r'):
+ return NotImplemented
+
+ return cls(left, right, name)
+
#----------------------------------------------------------------------
# Wrapper function for Series arithmetic methods
-
def _arith_method(op, name, fill_zeros=None):
"""
Wrapper function for Series arithmetic operations, to avoid
@@ -87,178 +255,54 @@ def na_op(x, y):
return result
- def wrapper(self, other, name=name):
+ def wrapper(left, right, name=name):
from pandas.core.frame import DataFrame
- dtype = None
- fill_value = tslib.iNaT
- wrap_results = lambda x: x
-
- lvalues, rvalues = self, other
-
- is_timedelta_lhs = com.is_timedelta64_dtype(self)
- is_datetime_lhs = com.is_datetime64_dtype(self)
- is_integer_lhs = lvalues.dtype.kind in ['i','u']
-
- if is_datetime_lhs or is_timedelta_lhs:
-
- coerce = 'compat' if _np_version_under1p7 else True
-
- # convert the argument to an ndarray
- def convert_to_array(values, other=None):
- if not is_list_like(values):
- values = np.array([values])
- inferred_type = lib.infer_dtype(values)
- if inferred_type in set(['datetime64','datetime','date','time']):
- # a datetlike
- if not (isinstance(values, (pa.Array, Series)) and com.is_datetime64_dtype(values)):
- values = tslib.array_to_datetime(values)
- elif isinstance(values, DatetimeIndex):
- other = values = values.to_series()
- elif inferred_type in set(['timedelta']):
- # have a timedelta, convert to to ns here
- values = com._possibly_cast_to_timedelta(values, coerce=coerce)
- elif inferred_type in set(['timedelta64']):
- # have a timedelta64, make sure dtype dtype is ns
- values = com._possibly_cast_to_timedelta(values, coerce=coerce)
- elif inferred_type in set(['integer']):
- # py3 compat where dtype is 'm' but is an integer
- if values.dtype.kind == 'm':
- values = values.astype('timedelta64[ns]')
- elif isinstance(values, PeriodIndex):
- other = values = values.to_timestamp().to_series()
- elif name not in ['__truediv__','__div__','__mul__']:
- raise TypeError("incompatible type for a datetime/timedelta operation [{0}]".format(name))
- elif isinstance(values[0],DateOffset):
- # handle DateOffsets
- os = pa.array([ getattr(v,'delta',None) for v in values ])
- mask = isnull(os)
- if mask.any():
- raise TypeError("cannot use a non-absolute DateOffset in "
- "datetime/timedelta operations [{0}]".format(','.join([ com.pprint_thing(v) for v in values[mask] ])))
- values = com._possibly_cast_to_timedelta(os, coerce=coerce)
- else:
- raise TypeError("incompatible type [{0}] for a datetime/timedelta operation".format(pa.array(values).dtype))
-
- return values, other
-
- # convert lhs and rhs
- lvalues,_ = convert_to_array(lvalues)
- rvalues,other = convert_to_array(rvalues,other)
-
- is_datetime_rhs = com.is_datetime64_dtype(rvalues)
- is_timedelta_rhs = com.is_timedelta64_dtype(rvalues) or (not is_datetime_rhs and _np_version_under1p7)
- is_integer_rhs = rvalues.dtype.kind in ['i','u']
- mask = None
-
- # timedelta and integer mul/div
- if (is_timedelta_lhs and is_integer_rhs) or (is_integer_lhs and is_timedelta_rhs):
-
- if name not in ['__truediv__','__div__','__mul__']:
- raise TypeError("can only operate on a timedelta and an integer for "
- "division, but the operator [%s] was passed" % name)
- dtype = 'timedelta64[ns]'
- mask = isnull(lvalues) | isnull(rvalues)
- lvalues = lvalues.astype(np.int64)
- rvalues = rvalues.astype(np.int64)
-
- # 2 datetimes
- elif is_datetime_lhs and is_datetime_rhs:
- if name != '__sub__':
- raise TypeError("can only operate on a datetimes for subtraction, "
- "but the operator [%s] was passed" % name)
-
- dtype = 'timedelta64[ns]'
- mask = isnull(lvalues) | isnull(rvalues)
- lvalues = lvalues.view('i8')
- rvalues = rvalues.view('i8')
-
- # 2 timedeltas
- elif is_timedelta_lhs and is_timedelta_rhs:
- mask = isnull(lvalues) | isnull(rvalues)
-
- # time delta division -> unit less
- if name in ['__div__','__truediv__']:
- dtype = 'float64'
- fill_value = np.nan
- lvalues = lvalues.astype(np.int64).astype(np.float64)
- rvalues = rvalues.astype(np.int64).astype(np.float64)
-
- # another timedelta
- elif name in ['__add__','__sub__']:
- dtype = 'timedelta64[ns]'
- lvalues = lvalues.astype(np.int64)
- rvalues = rvalues.astype(np.int64)
-
- else:
- raise TypeError("can only operate on a timedeltas for "
- "addition, subtraction, and division, but the operator [%s] was passed" % name)
- # datetime and timedelta
- elif is_timedelta_rhs and is_datetime_lhs:
+ time_converted = _TimeOp.maybe_convert_for_time_op(left, right, name)
- if name not in ['__add__','__sub__']:
- raise TypeError("can only operate on a datetime with a rhs of a timedelta for "
- "addition and subtraction, but the operator [%s] was passed" % name)
- dtype = 'M8[ns]'
- lvalues = lvalues.view('i8')
- rvalues = rvalues.view('i8')
-
- elif is_timedelta_lhs and is_datetime_rhs:
-
- if name not in ['__add__']:
- raise TypeError("can only operate on a timedelta and a datetime for "
- "addition, but the operator [%s] was passed" % name)
- dtype = 'M8[ns]'
- lvalues = lvalues.view('i8')
- rvalues = rvalues.view('i8')
-
- else:
- raise TypeError('cannot operate on a series with out a rhs '
- 'of a series/ndarray of type datetime64[ns] '
- 'or a timedelta')
-
- # if we need to mask the results
- if mask is not None:
- if mask.any():
- def f(x):
- x = pa.array(x,dtype=dtype)
- np.putmask(x,mask,fill_value)
- return x
- wrap_results = f
+ if time_converted is None:
+ lvalues, rvalues = left, right
+ dtype = None
+ wrap_results = lambda x: x
+ elif time_converted == NotImplemented:
+ return NotImplemented
+ else:
+ lvalues = time_converted.lvalues
+ rvalues = time_converted.rvalues
+ dtype = time_converted.dtype
+ wrap_results = time_converted.wrap_results
if isinstance(rvalues, Series):
- if hasattr(lvalues,'values'):
- lvalues = lvalues.values
- if hasattr(rvalues,'values'):
- rvalues = rvalues.values
-
- if self.index.equals(other.index):
- name = _maybe_match_name(self, other)
- return self._constructor(wrap_results(na_op(lvalues, rvalues)),
- index=self.index, dtype=dtype, name=name)
-
- join_idx, lidx, ridx = self.index.join(other.index, how='outer',
+ join_idx, lidx, ridx = left.index.join(rvalues.index, how='outer',
return_indexers=True)
+ rindex = rvalues.index
+ name = _maybe_match_name(left, rvalues)
+ lvalues = getattr(lvalues, 'values', lvalues)
+ rvalues = getattr(rvalues, 'values', rvalues)
+ if left.index.equals(rindex):
+ index = left.index
+ else:
+ index = join_idx
- if lidx is not None:
- lvalues = com.take_1d(lvalues, lidx)
+ if lidx is not None:
+ lvalues = com.take_1d(lvalues, lidx)
- if ridx is not None:
- rvalues = com.take_1d(rvalues, ridx)
+ if ridx is not None:
+ rvalues = com.take_1d(rvalues, ridx)
arr = na_op(lvalues, rvalues)
- name = _maybe_match_name(self, other)
- return self._constructor(wrap_results(arr), index=join_idx, name=name, dtype=dtype)
- elif isinstance(other, DataFrame):
+ return left._constructor(wrap_results(arr), index=index,
+ name=name, dtype=dtype)
+ elif isinstance(right, DataFrame):
return NotImplemented
else:
# scalars
if hasattr(lvalues, 'values'):
lvalues = lvalues.values
- return self._constructor(wrap_results(na_op(lvalues, rvalues)),
- index=self.index, name=self.name, dtype=dtype)
+ return left._constructor(wrap_results(na_op(lvalues, rvalues)),
+ index=left.index, name=left.name, dtype=dtype)
return wrapper
| This is a prelude to the larger refactoring of arithmetic into core/ops,
etc. It doesn't change any external behavior (and I'm relatively confident that
the test suite covers all the branches).
The complexity of the time arithmetic code was making it hard to tweak,
so I decided to change it up. It's not that complicated, but wanted to
run it by you all in an easy-to-read diff before I change its files.
Specifically it:
1. Moves Series time arithmetic out of `_arith_method` into a encapsulated `_TimeOp` class.
2. Consolidates the previously repeated type conversions into one.
3. Separates validations from type conversions, which makes the function
easier to follow and write.
4. Changes all obscure character codes to clear ones.
5. Removes the unnecessary `set()` calls in convert_to_array.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4613 | 2013-08-20T03:15:21Z | 2013-08-27T13:39:59Z | 2013-08-27T13:39:59Z | 2014-06-12T13:19:05Z |
CLN: refactor Series.reindex to core/generic | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 390c6e857ba32..932b93a634051 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -115,6 +115,8 @@ pandas 0.13
- ``MultiIndex.astype()`` now only allows ``np.object_``-like dtypes and
now returns a ``MultiIndex`` rather than an ``Index``. (:issue:`4039`)
+ - Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
+
**Internal Refactoring**
In 0.13.0 there is a major refactor primarily to subclass ``Series`` from ``NDFrame``,
@@ -144,8 +146,6 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- support attribute access for setting
- filter supports same api as original ``DataFrame`` filter
-- Reindex called with no arguments will now return a copy of the input object
-
- Series now inherits from ``NDFrame`` rather than directly from ``ndarray``.
There are several minor changes that affect the API.
@@ -185,6 +185,9 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Indexing with dtype conversions fixed (:issue:`4463`, :issue:`4204`)
+- Refactor Series.reindex to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
+ on a Series to work
+
**Experimental Features**
**Bug Fixes**
@@ -210,7 +213,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- In ``to_json``, raise if a passed ``orient`` would cause loss of data because
of a duplicate index (:issue:`4359`)
- In ``to_json``, fix date handling so milliseconds are the default timestamp
- as the docstring says (:issue:`4362`).
+ as the docstring says (:issue:`4362`).
- JSON NaT handling fixed, NaTs are now serialised to `null` (:issue:`4498`)
- Fixed passing ``keep_default_na=False`` when ``na_values=None`` (:issue:`4318`)
- Fixed bug with ``values`` raising an error on a DataFrame with duplicate columns and mixed
@@ -256,6 +259,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix bug in ``pd.read_clipboard`` on windows with PY3 (:issue:`4561`); not decoding properly
- ``tslib.get_period_field()`` and ``tslib.get_period_field_arr()`` now raise
if code argument out of range (:issue:`4519`, :issue:`4520`)
+ - Fix reindexing with multiple axes; if an axes match was not replacing the current axes, leading
+ to a possible lazay frequency inference issue (:issue:`3317`)
pandas 0.12
===========
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 9776c3e4662ec..ffa71cbe97ce0 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -96,6 +96,8 @@ API changes
# and all methods take an inplace kwarg
index.set_names(["bob", "cranberry"], inplace=True)
+ - Infer and downcast dtype if ``downcast='infer'`` is passed to ``fillna/ffill/bfill`` (:issue:`4604`)
+
Enhancements
~~~~~~~~~~~~
@@ -237,6 +239,9 @@ and behaviors. Series formerly subclassed directly from ``ndarray``. (:issue:`40
- Indexing with dtype conversions fixed (:issue:`4463`, :issue:`4204`)
+- Refactor Series.reindex to core/generic.py (:issue:`4604`, :issue:`4618`), allow ``method=`` in reindexing
+ on a Series to work
+
Bug Fixes
~~~~~~~~~
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 5765340f2906a..e46abb4aa83a6 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -961,14 +961,47 @@ def _possibly_downcast_to_dtype(result, dtype):
""" try to cast to the specified dtype (e.g. convert back to bool/int
or could be an astype of float64->float32 """
- if np.isscalar(result):
+ if np.isscalar(result) or not len(result):
return result
+ if isinstance(dtype, compat.string_types):
+ if dtype == 'infer':
+ inferred_type = lib.infer_dtype(_ensure_object(result.ravel()))
+ if inferred_type == 'boolean':
+ dtype = 'bool'
+ elif inferred_type == 'integer':
+ dtype = 'int64'
+ elif inferred_type == 'datetime64':
+ dtype = 'datetime64[ns]'
+ elif inferred_type == 'timedelta64':
+ dtype = 'timedelta64[ns]'
+
+ # try to upcast here
+ elif inferred_type == 'floating':
+ dtype = 'int64'
+
+ else:
+ dtype = 'object'
+
+ if isinstance(dtype, compat.string_types):
+ dtype = np.dtype(dtype)
+
try:
if issubclass(dtype.type, np.floating):
return result.astype(dtype)
elif dtype == np.bool_ or issubclass(dtype.type, np.integer):
- if issubclass(result.dtype.type, np.number) and notnull(result).all():
+
+ # do a test on the first element, if it fails then we are done
+ r = result.ravel()
+ arr = np.array([ r[0] ])
+ if (arr != arr.astype(dtype)).item():
+ return result
+
+ # a comparable, e.g. a Decimal may slip in here
+ elif not isinstance(r[0], (np.integer,np.floating,np.bool,int,float,bool)):
+ return result
+
+ if issubclass(result.dtype.type, (np.object_,np.number)) and notnull(result).all():
new_result = result.astype(dtype)
if (new_result == result).all():
return new_result
@@ -1052,6 +1085,9 @@ def pad_1d(values, limit=None, mask=None):
_method = getattr(algos, 'pad_inplace_%s' % dtype, None)
elif is_datetime64_dtype(values):
_method = _pad_1d_datetime
+ elif is_integer_dtype(values):
+ values = _ensure_float64(values)
+ _method = algos.pad_inplace_float64
elif values.dtype == np.object_:
_method = algos.pad_inplace_object
@@ -1062,7 +1098,7 @@ def pad_1d(values, limit=None, mask=None):
mask = isnull(values)
mask = mask.view(np.uint8)
_method(values, mask, limit=limit)
-
+ return values
def backfill_1d(values, limit=None, mask=None):
@@ -1072,6 +1108,9 @@ def backfill_1d(values, limit=None, mask=None):
_method = getattr(algos, 'backfill_inplace_%s' % dtype, None)
elif is_datetime64_dtype(values):
_method = _backfill_1d_datetime
+ elif is_integer_dtype(values):
+ values = _ensure_float64(values)
+ _method = algos.backfill_inplace_float64
elif values.dtype == np.object_:
_method = algos.backfill_inplace_object
@@ -1083,7 +1122,7 @@ def backfill_1d(values, limit=None, mask=None):
mask = mask.view(np.uint8)
_method(values, mask, limit=limit)
-
+ return values
def pad_2d(values, limit=None, mask=None):
@@ -1093,6 +1132,9 @@ def pad_2d(values, limit=None, mask=None):
_method = getattr(algos, 'pad_2d_inplace_%s' % dtype, None)
elif is_datetime64_dtype(values):
_method = _pad_2d_datetime
+ elif is_integer_dtype(values):
+ values = _ensure_float64(values)
+ _method = algos.pad_2d_inplace_float64
elif values.dtype == np.object_:
_method = algos.pad_2d_inplace_object
@@ -1108,7 +1150,7 @@ def pad_2d(values, limit=None, mask=None):
else:
# for test coverage
pass
-
+ return values
def backfill_2d(values, limit=None, mask=None):
@@ -1118,6 +1160,9 @@ def backfill_2d(values, limit=None, mask=None):
_method = getattr(algos, 'backfill_2d_inplace_%s' % dtype, None)
elif is_datetime64_dtype(values):
_method = _backfill_2d_datetime
+ elif is_integer_dtype(values):
+ values = _ensure_float64(values)
+ _method = algos.backfill_2d_inplace_float64
elif values.dtype == np.object_:
_method = algos.backfill_2d_inplace_object
@@ -1133,9 +1178,9 @@ def backfill_2d(values, limit=None, mask=None):
else:
# for test coverage
pass
+ return values
-
-def interpolate_2d(values, method='pad', axis=0, limit=None, missing=None):
+def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None):
""" perform an actual interpolation of values, values will be make 2-d if needed
fills inplace, returns the result """
@@ -1148,15 +1193,16 @@ def interpolate_2d(values, method='pad', axis=0, limit=None, missing=None):
raise Exception("cannot interpolate on a ndim == 1 with axis != 0")
values = values.reshape(tuple((1,) + values.shape))
- if missing is None:
+ if fill_value is None:
mask = None
else: # todo create faster fill func without masking
- mask = mask_missing(transf(values), missing)
+ mask = mask_missing(transf(values), fill_value)
+ method = _clean_fill_method(method)
if method == 'pad':
- pad_2d(transf(values), limit=limit, mask=mask)
+ values = transf(pad_2d(transf(values), limit=limit, mask=mask))
else:
- backfill_2d(transf(values), limit=limit, mask=mask)
+ values = transf(backfill_2d(transf(values), limit=limit, mask=mask))
# reshape back
if ndim == 1:
@@ -1830,6 +1876,7 @@ def _astype_nansafe(arr, dtype, copy=True):
def _clean_fill_method(method):
+ if method is None: return None
method = method.lower()
if method == 'ffill':
method = 'pad'
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 200e4ce9322fd..d032bbf66f95e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2280,12 +2280,9 @@ def _reindex_multi(self, axes, copy, fill_value):
fill_value=fill_value)
return self._constructor(new_values, index=new_index,
columns=new_columns)
- elif row_indexer is not None:
- return self._reindex_with_indexers({0: [new_index, row_indexer]}, copy=copy, fill_value=fill_value)
- elif col_indexer is not None:
- return self._reindex_with_indexers({1: [new_columns, col_indexer]}, copy=copy, fill_value=fill_value)
else:
- return self.copy() if copy else self
+ return self._reindex_with_indexers({0: [new_index, row_indexer],
+ 1: [new_columns, col_indexer]}, copy=copy, fill_value=fill_value)
def reindex_like(self, other, method=None, copy=True, limit=None,
fill_value=NA):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 91c5804d48a78..dccf3c9b8d36a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -987,7 +987,7 @@ def reindex(self, *args, **kwargs):
# construct the args
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
- method = kwargs.get('method')
+ method = com._clean_fill_method(kwargs.get('method'))
level = kwargs.get('level')
copy = kwargs.get('copy', True)
limit = kwargs.get('limit')
@@ -1003,11 +1003,15 @@ def reindex(self, *args, **kwargs):
except:
pass
- # perform the reindex on the axes
- if copy and not com._count_not_none(*axes.values()):
- return self.copy()
+ # if all axes that are requested to reindex are equal, then only copy if indicated
+ # must have index names equal here as well as values
+ if all([ self._get_axis(axis).identical(ax) for axis, ax in axes.items() if ax is not None ]):
+ if copy:
+ return self.copy()
+ return self
- return self._reindex_axes(axes, level, limit, method, fill_value, copy, takeable=takeable)
+ # perform the reindex on the axes
+ return self._reindex_axes(axes, level, limit, method, fill_value, copy, takeable=takeable)._propogate_attributes(self)
def _reindex_axes(self, axes, level, limit, method, fill_value, copy, takeable=False):
""" perform the reinxed for all the axes """
@@ -1025,7 +1029,8 @@ def _reindex_axes(self, axes, level, limit, method, fill_value, copy, takeable=F
new_index, indexer = self._get_axis(a).reindex(
labels, level=level, limit=limit, takeable=takeable)
obj = obj._reindex_with_indexers(
- {axis: [labels, indexer]}, method, fill_value, copy)
+ {axis: [new_index, indexer]}, method=method, fill_value=fill_value,
+ limit=limit, copy=copy)
return obj
@@ -1077,11 +1082,13 @@ def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,
axis_name = self._get_axis_name(axis)
axis_values = self._get_axis(axis_name)
+ method = com._clean_fill_method(method)
new_index, indexer = axis_values.reindex(labels, method, level,
limit=limit, copy_if_needed=True)
- return self._reindex_with_indexers({axis: [new_index, indexer]}, method, fill_value, copy)
+ return self._reindex_with_indexers({axis: [new_index, indexer]}, method=method, fill_value=fill_value,
+ limit=limit, copy=copy)._propogate_attributes(self)
- def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, copy=False):
+ def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, limit=None, copy=False):
# reindex doing multiple operations on different axes if indiciated
new_data = self._data
@@ -1089,11 +1096,15 @@ def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, cop
index, indexer = reindexers[axis]
baxis = self._get_block_manager_axis(axis)
+ if index is None:
+ continue
+ index = _ensure_index(index)
+
# reindex the axis
if method is not None:
new_data = new_data.reindex_axis(
- index, method=method, axis=baxis,
- fill_value=fill_value, copy=copy)
+ index, indexer=indexer, method=method, axis=baxis,
+ fill_value=fill_value, limit=limit, copy=copy)
elif indexer is not None:
# TODO: speed up on homogeneous DataFrame objects
@@ -1409,7 +1420,8 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
limit : int, default None
Maximum size gap to forward or backward fill
downcast : dict, default is None, a dict of item->dtype of what to
- downcast if possible
+ downcast if possible, or the string 'infer' which will try to
+ downcast to an appropriate equal type (e.g. float64 to int64 if possible)
See also
--------
@@ -1428,6 +1440,7 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
if axis + 1 > self._AXIS_LEN:
raise ValueError(
"invalid axis passed for object type {0}".format(type(self)))
+ method = com._clean_fill_method(method)
if value is None:
if method is None:
@@ -1435,14 +1448,20 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
if self._is_mixed_type and axis == 1:
if inplace:
raise NotImplementedError()
- return self.T.fillna(method=method, limit=limit).T
+ result = self.T.fillna(method=method, limit=limit).T
+
+ # need to downcast here because of all of the transposes
+ result._data = result._data.downcast()
+
+ return result
method = com._clean_fill_method(method)
new_data = self._data.interpolate(method=method,
axis=axis,
limit=limit,
inplace=inplace,
- coerce=True)
+ coerce=True,
+ downcast=downcast)
else:
if method is not None:
raise ValueError('cannot specify both a fill method and value')
@@ -1472,13 +1491,13 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
else:
return self._constructor(new_data)
- def ffill(self, axis=0, inplace=False, limit=None):
+ def ffill(self, axis=0, inplace=False, limit=None, downcast=None):
return self.fillna(method='ffill', axis=axis, inplace=inplace,
- limit=limit)
+ limit=limit, downcast=downcast)
- def bfill(self, axis=0, inplace=False, limit=None):
+ def bfill(self, axis=0, inplace=False, limit=None, downcast=None):
return self.fillna(method='bfill', axis=axis, inplace=inplace,
- limit=limit)
+ limit=limit, downcast=downcast)
def replace(self, to_replace=None, value=None, inplace=False, limit=None,
regex=False, method=None, axis=None):
@@ -2030,6 +2049,7 @@ def align(self, other, join='outer', axis=None, level=None, copy=True,
Aligned objects
"""
from pandas import DataFrame, Series
+ method = com._clean_fill_method(method)
if isinstance(other, DataFrame):
return self._align_frame(other, join=join, axis=axis, level=level,
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 73aff7bcab953..22bd7f318a237 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -83,6 +83,7 @@ class Index(FrozenNDArray):
name = None
asi8 = None
+ _comparables = ['name']
_engine_type = _index.ObjectEngine
@@ -545,6 +546,13 @@ def equals(self, other):
return np.array_equal(self, other)
+ def identical(self, other):
+ """
+ Similar to equals, but check that other comparable attributes are also equal
+ """
+ return self.equals(other) and all(
+ ( getattr(self,c,None) == getattr(other,c,None) for c in self._comparables ))
+
def asof(self, label):
"""
For a sorted index, return the most recent label up to and including
@@ -1547,6 +1555,7 @@ class MultiIndex(Index):
_names = FrozenList()
_levels = FrozenList()
_labels = FrozenList()
+ _comparables = ['names']
def __new__(cls, levels=None, labels=None, sortorder=None, names=None,
copy=False):
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index f1578303e6db0..ecce508284fc1 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -7,8 +7,8 @@
import numpy as np
from pandas.core.base import PandasObject
-from pandas.core.common import (_possibly_downcast_to_dtype, isnull, _NS_DTYPE,
- _TD_DTYPE, ABCSeries, ABCSparseSeries,
+from pandas.core.common import (_possibly_downcast_to_dtype, isnull, notnull,
+ _NS_DTYPE, _TD_DTYPE, ABCSeries, ABCSparseSeries,
is_list_like)
from pandas.core.index import (Index, MultiIndex, _ensure_index,
_handle_legacy_indexes)
@@ -36,6 +36,9 @@ class Block(PandasObject):
"""
__slots__ = ['items', 'ref_items', '_ref_locs', 'values', 'ndim']
is_numeric = False
+ is_float = False
+ is_integer = False
+ is_complex = False
is_bool = False
is_object = False
is_sparse = False
@@ -203,7 +206,7 @@ def reindex_axis(self, indexer, method=None, axis=1, fill_value=None, limit=None
new_values, self.items, self.ref_items, ndim=self.ndim, fastpath=True,
placement=self._ref_locs)
- def reindex_items_from(self, new_ref_items, copy=True):
+ def reindex_items_from(self, new_ref_items, indexer=None, method=None, fill_value=None, limit=None, copy=True):
"""
Reindex to only those items contained in the input set of items
@@ -214,17 +217,41 @@ def reindex_items_from(self, new_ref_items, copy=True):
-------
reindexed : Block
"""
- new_ref_items, indexer = self.items.reindex(new_ref_items)
+ if indexer is None:
+ new_ref_items, indexer = self.items.reindex(new_ref_items, limit=limit)
+ if fill_value is None:
+ fill_value = self.fill_value
+
+ new_items = new_ref_items
if indexer is None:
- new_items = new_ref_items
new_values = self.values.copy() if copy else self.values
+
else:
- masked_idx = indexer[indexer != -1]
- new_values = com.take_nd(self.values, masked_idx, axis=0,
- allow_fill=False)
- new_items = self.items.take(masked_idx)
- return make_block(new_values, new_items, new_ref_items, ndim=self.ndim, fastpath=True)
+
+ # single block reindex
+ if self.ndim == 1:
+ new_values = com.take_1d(self.values, indexer,
+ fill_value=fill_value)
+ else:
+
+ masked_idx = indexer[indexer != -1]
+ new_values = com.take_nd(self.values, masked_idx, axis=0,
+ allow_fill=False)
+ new_items = self.items.take(masked_idx)
+
+ # fill if needed
+ fill_method = method is not None or limit is not None
+ if fill_method:
+ new_values = com.interpolate_2d(new_values, method=method, limit=limit, fill_value=fill_value)
+
+ block = make_block(new_values, new_items, new_ref_items, ndim=self.ndim, fastpath=True)
+
+ # down cast if needed
+ if not self.is_float and (fill_method or notnull(fill_value)):
+ block = block.downcast()
+
+ return block
def get(self, item):
loc = self.items.get_loc(item)
@@ -291,36 +318,64 @@ def fillna(self, value, inplace=False, downcast=None):
mask = com.isnull(self.values)
value = self._try_fill(value)
blocks = self.putmask(mask, value, inplace=inplace)
+ return self._maybe_downcast(blocks, downcast)
- # possibily downcast the blocks
- if not downcast:
+ def _maybe_downcast(self, blocks, downcast=None):
+
+ # no need to downcast our float
+ # unless indicated
+ if downcast is None and self.is_float:
return blocks
result_blocks = []
for b in blocks:
- result_blocks.extend(b.downcast())
+ result_blocks.extend(b.downcast(downcast))
return result_blocks
def downcast(self, dtypes=None):
""" try to downcast each item to the dict of dtypes if present """
- if dtypes is None:
- dtypes = dict()
+ # turn it off completely
+ if dtypes is False:
+ return [ self ]
values = self.values
+
+ # single block handling
+ if self._is_single_block:
+
+ # try to cast all non-floats here
+ if dtypes is None:
+ dtypes = 'infer'
+
+ nv = _possibly_downcast_to_dtype(values, dtypes)
+ return [ make_block(nv, self.items, self.ref_items, ndim=self.ndim, fastpath=True) ]
+
+ # ndim > 1
+ if dtypes is None:
+ return [ self ]
+
+ if not (dtypes == 'infer' or isinstance(dtypes, dict)):
+ raise ValueError("downcast must have a dictionary or 'infer' as its argument")
+
+ # item-by-item
+ # this is expensive as it splits the blocks items-by-item
blocks = []
for i, item in enumerate(self.items):
- dtype = dtypes.get(item, self._downcast_dtype)
+ if dtypes == 'infer':
+ dtype = 'infer'
+ else:
+ dtype = dtypes.get(item, self._downcast_dtype)
+
if dtype is None:
nv = _block_shape(values[i])
- blocks.append(make_block(nv, [item], self.ref_items))
- continue
+ else:
+ nv = _possibly_downcast_to_dtype(values[i], dtype)
+ nv = _block_shape(nv)
- nv = _possibly_downcast_to_dtype(values[i], np.dtype(dtype))
- nv = _block_shape(nv)
- blocks.append(make_block(nv, [item], self.ref_items))
+ blocks.append(make_block(nv, Index([item]), self.ref_items, ndim=self.ndim, fastpath=True))
return blocks
@@ -578,7 +633,8 @@ def create_block(v, m, n, item, reshape=True):
return [make_block(new_values, self.items, self.ref_items, fastpath=True)]
def interpolate(self, method='pad', axis=0, inplace=False,
- limit=None, missing=None, coerce=False):
+ limit=None, fill_value=None, coerce=False,
+ downcast=None):
# if we are coercing, then don't force the conversion
# if the block can't hold the type
@@ -590,8 +646,10 @@ def interpolate(self, method='pad', axis=0, inplace=False,
return [self.copy()]
values = self.values if inplace else self.values.copy()
- values = com.interpolate_2d(values, method, axis, limit, missing)
- return [make_block(values, self.items, self.ref_items, ndim=self.ndim, klass=self.__class__, fastpath=True)]
+ values = com.interpolate_2d(values, method, axis, limit, fill_value)
+
+ blocks = [ make_block(values, self.items, self.ref_items, ndim=self.ndim, klass=self.__class__, fastpath=True) ]
+ return self._maybe_downcast(blocks, downcast)
def take(self, indexer, ref_items, axis=1):
if axis < 1:
@@ -789,6 +847,7 @@ def _try_cast_result(self, result):
class FloatBlock(NumericBlock):
+ is_float = True
_downcast_dtype = 'int64'
def _can_hold_element(self, element):
@@ -825,6 +884,7 @@ def should_store(self, value):
class ComplexBlock(NumericBlock):
+ is_complex = True
def _can_hold_element(self, element):
return isinstance(element, complex)
@@ -840,6 +900,7 @@ def should_store(self, value):
class IntBlock(NumericBlock):
+ is_integer = True
_can_hold_na = False
def _can_hold_element(self, element):
@@ -1290,10 +1351,10 @@ def make_block(
return make_block(new_values, items, ref_items, ndim=self.ndim, fastpath=fastpath)
def interpolate(self, method='pad', axis=0, inplace=False,
- limit=None, missing=None, **kwargs):
+ limit=None, fill_value=None, **kwargs):
values = com.interpolate_2d(
- self.values.to_dense(), method, axis, limit, missing)
+ self.values.to_dense(), method, axis, limit, fill_value)
return self.make_block(values, self.items, self.ref_items)
def fillna(self, value, inplace=False, downcast=None):
@@ -1336,7 +1397,7 @@ def reindex_axis(self, indexer, method=None, axis=1, fill_value=None, limit=None
fill_value = self.fill_value
return self.make_block(self.values.take(indexer), items=self.items, fill_value=fill_value)
- def reindex_items_from(self, new_ref_items, copy=True):
+ def reindex_items_from(self, new_ref_items, indexer=None, method=None, fill_value=None, limit=None, copy=True):
"""
Reindex to only those items contained in the input set of items
@@ -1348,18 +1409,21 @@ def reindex_items_from(self, new_ref_items, copy=True):
reindexed : Block
"""
- # 2-d
- if self.ndim >= 2:
- if self.items[0] not in self.ref_items:
- return None
- return self.make_block(self.values, ref_items=new_ref_items, copy=copy)
-
- # 1-d
- new_ref_items, indexer = self.items.reindex(new_ref_items)
+ # 1-d always
+ if indexer is None:
+ new_ref_items, indexer = self.items.reindex(new_ref_items, limit=limit)
if indexer is None:
indexer = np.arange(len(self.items))
- return self.make_block(com.take_1d(self.values.values, indexer), items=new_ref_items, ref_items=new_ref_items, copy=copy)
+ new_values = com.take_1d(self.values.values, indexer)
+
+ # fill if needed
+ if method is not None or limit is not None:
+ if fill_value is None:
+ fill_value = self.fill_value
+ new_values = com.interpolate_2d(new_values, method=method, limit=limit, fill_value=fill_value)
+
+ return self.make_block(new_values, items=new_ref_items, ref_items=new_ref_items, copy=copy)
def sparse_reindex(self, new_index):
""" sparse reindex and return a new block
@@ -2502,7 +2566,7 @@ def _check_have(self, item):
if item not in self.items:
raise KeyError('no item named %s' % com.pprint_thing(item))
- def reindex_axis(self, new_axis, method=None, axis=0, fill_value=None, limit=None, copy=True):
+ def reindex_axis(self, new_axis, indexer=None, method=None, axis=0, fill_value=None, limit=None, copy=True):
new_axis = _ensure_index(new_axis)
cur_axis = self.axes[axis]
@@ -2522,15 +2586,19 @@ def reindex_axis(self, new_axis, method=None, axis=0, fill_value=None, limit=Non
return self
if axis == 0:
- if method is not None:
- raise AssertionError('method argument not supported for '
- 'axis == 0')
+ if method is not None or limit is not None:
+ return self.reindex_axis0_with_method(new_axis, indexer=indexer,
+ method=method, fill_value=fill_value, limit=limit, copy=copy)
return self.reindex_items(new_axis, copy=copy, fill_value=fill_value)
new_axis, indexer = cur_axis.reindex(
new_axis, method, copy_if_needed=True)
return self.reindex_indexer(new_axis, indexer, axis=axis, fill_value=fill_value)
+ def reindex_axis0_with_method(self, new_axis, indexer=None, method=None, fill_value=None, limit=None, copy=True):
+ raise AssertionError('method argument not supported for '
+ 'axis == 0')
+
def reindex_indexer(self, new_axis, indexer, axis=1, fill_value=None):
"""
pandas-indexer with -1's only.
@@ -2843,19 +2911,27 @@ def shape(self):
self._shape = tuple([len(self.axes[0])])
return self._shape
- def reindex(self, new_axis, method=None, limit=None, copy=True):
+ def reindex(self, new_axis, indexer=None, method=None, fill_value=None, limit=None, copy=True):
# if we are the same and don't copy, just return
if not copy and self.index.equals(new_axis):
return self
- block = self._block.reindex_items_from(new_axis, copy=copy)
- if method is not None or limit is not None:
- block = block.interpolate(method=method, limit=limit)
+ block = self._block.reindex_items_from(new_axis, indexer=indexer, method=method,
+ fill_value=fill_value, limit=limit, copy=copy)
mgr = SingleBlockManager(block, new_axis)
mgr._consolidate_inplace()
return mgr
+ def _reindex_indexer_items(self, new_items, indexer, fill_value):
+ # equiv to a reindex
+ return self.reindex(new_items, indexer=indexer, fill_value=fill_value, copy=False)
+
+ def reindex_axis0_with_method(self, new_axis, indexer=None, method=None, fill_value=None, limit=None, copy=True):
+ if method is None:
+ indexer = None
+ return self.reindex(new_axis, indexer=indexer, method=method, fill_value=fill_value, limit=limit, copy=copy)
+
def get_slice(self, slobj, raise_on_error=False):
if raise_on_error:
_check_slice_bounds(slobj, self.index)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 2e2026dfdb8ae..051b445638f5b 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2737,77 +2737,18 @@ def align(self, other, join='outer', level=None, copy=True,
return left, right
def _reindex_indexer(self, new_index, indexer, copy):
- if indexer is not None:
- new_values = com.take_1d(self.values, indexer)
- else:
+ if indexer is None:
if copy:
- result = self.copy()
- else:
- result = self
- return result
+ return self.copy()
+ return self
# be subclass-friendly
+ new_values = com.take_1d(self.get_values(), indexer)
return self._constructor(new_values, new_index, name=self.name)
- def reindex(self, index=None, method=None, level=None, fill_value=pa.NA,
- limit=None, copy=True, takeable=False):
- """Conform Series to new index with optional filling logic, placing
- NA/NaN in locations having no value in the previous index. A new object
- is produced unless the new index is equivalent to the current one and
- copy=False
-
- Parameters
- ----------
- index : array-like or Index
- New labels / index to conform to. Preferably an Index object to
- avoid duplicating data
- 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 gap
- copy : boolean, default True
- Return a new object, even if the passed indexes are the same
- level : int or name
- Broadcast across a level, matching Index values on the
- passed MultiIndex level
- fill_value : scalar, default NaN
- Value to use for missing values. Defaults to NaN, but can be any
- "compatible" value
- limit : int, default None
- Maximum size gap to forward or backward fill
- takeable : the labels are locations (and not labels)
-
- Returns
- -------
- reindexed : Series
- """
- if index is None:
- raise ValueError('Must pass Index or sequence, not None')
-
- index = _ensure_index(index)
- if self.index.equals(index):
- if copy:
- result = self.copy()
- result.index = index
- return result
- else:
- return self
-
- if len(self.index) == 0:
- return self._constructor(nan, index=index, name=self.name)
-
- new_index, indexer = self.index.reindex(index, method=method,
- level=level, limit=limit,
- takeable=takeable)
-
- # GH4246 (dispatch to a common method with frame to handle possibly
- # duplicate index)
- return self._reindex_with_indexers({ 0 : [new_index, indexer] }, copy=copy, fill_value=fill_value)
-
- def _reindex_with_indexers(self, reindexers, copy, fill_value=None):
- index, indexer = reindexers[0]
- new_values = com.take_1d(self.values, indexer, fill_value=fill_value)
- return self._constructor(new_values, index=index, name=self.name)
+ def _needs_reindex_multi(self, axes, method, level):
+ """ check if we do need a multi reindex; this is for compat with higher dims """
+ return False
def reindex_axis(self, labels, axis=0, **kwargs):
""" for compatibility with higher dims """
@@ -3472,14 +3413,6 @@ def _resolve_offset(freq, kwds):
return offset
-def _get_fill_func(method):
- method = com._clean_fill_method(method)
- if method == 'pad':
- fill_f = com.pad_1d
- elif method == 'backfill':
- fill_f = com.backfill_1d
- return fill_f
-
# backwards compatiblity
TimeSeries = Series
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 41345352b5ec5..787682f340250 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -774,7 +774,7 @@ def test_parse_dates_string(self):
"""
rs = self.read_csv(
StringIO(data), index_col='date', parse_dates='date')
- idx = date_range('1/1/2009', periods=3).asobject
+ idx = date_range('1/1/2009', periods=3)
idx.name = 'date'
xp = DataFrame({'A': ['a', 'b', 'c'],
'B': [1, 3, 4],
diff --git a/pandas/sparse/frame.py b/pandas/sparse/frame.py
index 00a9d41112154..dd7bd52076e06 100644
--- a/pandas/sparse/frame.py
+++ b/pandas/sparse/frame.py
@@ -573,7 +573,10 @@ def _reindex_columns(self, columns, copy, level, fill_value, limit=None,
return SparseDataFrame(sdict, index=self.index, columns=columns,
default_fill_value=self._default_fill_value)
- def _reindex_with_indexers(self, reindexers, method=None, copy=False, fill_value=np.nan):
+ def _reindex_with_indexers(self, reindexers, method=None, fill_value=np.nan, limit=None, copy=False):
+
+ if method is not None or limit is not None:
+ raise NotImplementedError("cannot reindex with a method or limit with sparse")
index, row_indexer = reindexers.get(0, (None, None))
columns, col_indexer = reindexers.get(1, (None, None))
diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py
index 6d7e4994f3694..21a054e6fe1a3 100644
--- a/pandas/sparse/series.py
+++ b/pandas/sparse/series.py
@@ -565,19 +565,6 @@ def sparse_reindex(self, new_index):
sparse_index=new_index,
fill_value=self.fill_value)
- def _reindex_indexer(self, new_index, indexer, copy):
- if indexer is not None:
- new_values = com.take_1d(self.values.values, indexer)
- else:
- if copy:
- result = self.copy()
- else:
- result = self
- return result
-
- # be subclass-friendly
- return self._constructor(new_values, new_index, name=self.name)
-
def take(self, indices, axis=0, convert=True):
"""
Sparse-compatible version of ndarray.take
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index b84115bd3e6b4..1a65eec8557c0 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -4218,8 +4218,17 @@ def test_logical_with_nas(self):
expected = Series([np.nan, True])
assert_series_equal(result, expected)
+ # GH4604, automatic casting here
result = d['a'].fillna(False) | d['b']
- expected = Series([True, True], dtype=object)
+ expected = Series([True, True])
+ assert_series_equal(result, expected)
+
+ result = d['a'].fillna(False,downcast=False) | d['b']
+ expected = Series([True, True],dtype=object)
+ assert_series_equal(result, expected)
+
+ result = (d['a'].fillna(False,downcast=False) | d['b']).convert_objects()
+ expected = Series([True, True])
assert_series_equal(result, expected)
def test_neg(self):
@@ -7411,6 +7420,20 @@ def test_reindex_columns(self):
newFrame = self.frame.reindex(columns=[])
self.assert_(newFrame.empty)
+ def test_reindex_axes(self):
+
+ # GH 3317, reindexing by both axes loses freq of the index
+ from datetime import datetime
+ df = DataFrame(np.ones((3, 3)), index=[datetime(2012, 1, 1), datetime(2012, 1, 2), datetime(2012, 1, 3)], columns=['a', 'b', 'c'])
+ time_freq = date_range('2012-01-01', '2012-01-03', freq='d')
+ some_cols = ['a', 'b']
+
+ index_freq = df.reindex(index=time_freq).index.freq
+ both_freq = df.reindex(index=time_freq, columns=some_cols).index.freq
+ seq_freq = df.reindex(index=time_freq).reindex(columns=some_cols).index.freq
+ self.assert_(index_freq == both_freq)
+ self.assert_(index_freq == seq_freq)
+
def test_reindex_fill_value(self):
df = DataFrame(np.random.randn(10, 4))
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index ae81752c11b29..16f3026896d4f 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -151,6 +151,21 @@ def test_equals(self):
# Must also be an Index
self.assertFalse(Index(['a', 'b', 'c']).equals(['a', 'b', 'c']))
+ def test_identical(self):
+
+ # index
+ i1 = Index(['a', 'b', 'c'])
+ i2 = Index(['a', 'b', 'c'])
+
+ self.assert_(i1.identical(i2))
+
+ i1 = i1.rename('foo')
+ self.assert_(i1.equals(i2))
+ self.assert_(not i1.identical(i2))
+
+ i2 = i2.rename('foo')
+ self.assert_(i1.identical(i2))
+
def test_asof(self):
d = self.dateIndex[0]
self.assert_(self.dateIndex.asof(d) is d)
@@ -660,6 +675,20 @@ def test_equals(self):
self.assert_(self.index.equals(same_values))
self.assert_(same_values.equals(self.index))
+ def test_identical(self):
+
+ i = self.index.copy()
+ same_values = Index(i, dtype=object)
+ self.assert_(i.identical(same_values))
+
+ i = self.index.copy()
+ i = i.rename('foo')
+ same_values = Index(i, dtype=object)
+ self.assert_(same_values.identical(self.index))
+
+ self.assertFalse(i.identical(self.index))
+ self.assert_(Index(same_values, name='foo').identical(i))
+
def test_get_indexer(self):
target = Int64Index(np.arange(10))
indexer = self.index.get_indexer(target)
@@ -1604,6 +1633,18 @@ def test_equals(self):
labels=[major_labels, minor_labels])
self.assert_(not self.index.equals(index))
+ def test_identical(self):
+ mi = self.index.copy()
+ mi2 = self.index.copy()
+ self.assert_(mi.identical(mi2))
+
+ mi = mi.set_names(['new1','new2'])
+ self.assert_(mi.equals(mi2))
+ self.assert_(not mi.identical(mi2))
+
+ mi2 = mi2.set_names(['new1','new2'])
+ self.assert_(mi.identical(mi2))
+
def test_union(self):
piece1 = self.index[:5][::-1]
piece2 = self.index[3:]
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 430e5df839e18..8ad88374f40f6 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -1051,7 +1051,7 @@ def test_reindex(self):
# don't necessarily copy
result = self.panel.reindex(major=self.panel.major_axis, copy=False)
assert_panel_equal(result,self.panel)
- self.assert_((result is self.panel) == False)
+ self.assert_((result is self.panel) == True)
def test_reindex_like(self):
# reindex_like
diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py
index add8ebf73f85f..9b34631ecc894 100644
--- a/pandas/tests/test_panel4d.py
+++ b/pandas/tests/test_panel4d.py
@@ -786,7 +786,7 @@ def test_reindex(self):
result = self.panel4d.reindex(
major=self.panel4d.major_axis, copy=False)
assert_panel4d_equal(result,self.panel4d)
- self.assert_((result is self.panel4d) == False)
+ self.assert_((result is self.panel4d) == True)
def test_not_hashable(self):
p4D_empty = Panel4D()
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 094a68a4c658d..4100185752b8f 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -4034,7 +4034,9 @@ def test_reindex(self):
for idx, val in compat.iteritems(subNonContig):
self.assertEqual(val, self.ts[idx])
- self.assertRaises(ValueError, self.ts.reindex)
+ # return a copy the same index here
+ result = self.ts.reindex()
+ self.assert_((result is self.ts) == False)
def test_reindex_corner(self):
# (don't forget to fix this) I think it's fixed
@@ -4052,8 +4054,8 @@ def test_reindex_corner(self):
self.assertRaises(Exception, ts.reindex, self.ts.index, method='foo')
def test_reindex_pad(self):
- s = Series(np.arange(10), np.arange(10))
+ s = Series(np.arange(10), np.arange(10))
s2 = s[::2]
reindexed = s2.reindex(s.index, method='pad')
@@ -4065,6 +4067,35 @@ def test_reindex_pad(self):
index=np.arange(10))
assert_series_equal(reindexed, expected)
+ # GH4604
+ s = Series([1,2,3,4,5], index=['a', 'b', 'c', 'd', 'e'])
+ new_index = ['a','g','c','f']
+ expected = Series([1,1,3,3],index=new_index)
+
+ # this changes dtype because the ffill happens after
+ result = s.reindex(new_index).ffill()
+ assert_series_equal(result, expected.astype('float64'))
+
+ result = s.reindex(new_index).ffill(downcast='infer')
+ assert_series_equal(result, expected)
+
+ # this preserves dtype
+ result = s.reindex(new_index, method='ffill')
+ assert_series_equal(result, expected)
+
+ # inferrence of new dtype
+ s = Series([True,False,False,True],index=list('abcd'))
+ new_index='agc'
+ result = s.reindex(list(new_index)).ffill()
+ expected = Series([True,True,False],index=list(new_index))
+ assert_series_equal(result, expected)
+
+ # GH4618 shifted series downcasting
+ s = Series(False,index=lrange(0,5))
+ result = s.shift(1).fillna(method='bfill')
+ expected = Series(False,index=lrange(0,5))
+ assert_series_equal(result, expected)
+
def test_reindex_backfill(self):
pass
diff --git a/pandas/tools/pivot.py b/pandas/tools/pivot.py
index 9bca698cd4304..c11ec9f338f88 100644
--- a/pandas/tools/pivot.py
+++ b/pandas/tools/pivot.py
@@ -129,7 +129,7 @@ def pivot_table(data, values=None, rows=None, cols=None, aggfunc='mean',
table = table.sort_index(axis=1)
if fill_value is not None:
- table = table.fillna(value=fill_value, downcast=True)
+ table = table.fillna(value=fill_value, downcast='infer')
if margins:
table = _add_margins(table, data, values, rows=rows,
diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py
index 67adc6bf8e7f2..5cfe22781f362 100644
--- a/pandas/tools/tests/test_merge.py
+++ b/pandas/tools/tests/test_merge.py
@@ -316,6 +316,7 @@ def test_join_index_mixed(self):
df2['float'] = 1.
for kind in JOIN_TYPES:
+
joined = df1.join(df2, how=kind)
expected = _join_by_hand(df1, df2, how=kind)
assert_frame_equal(joined, expected)
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 7af1dd657267a..1b5c9a8b5ebd3 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -139,6 +139,7 @@ class DatetimeIndex(Int64Index):
_engine_type = _index.DatetimeEngine
offset = None
+ _comparables = ['name','freqstr','tz']
def __new__(cls, data=None,
freq=None, start=None, end=None, periods=None,
@@ -154,6 +155,8 @@ def __new__(cls, data=None,
freq_infer = False
if not isinstance(freq, DateOffset):
+
+ # if a passed freq is None, don't infer automatically
if freq != 'infer':
freq = to_offset(freq)
else:
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index bf9d7b2cf0b24..b28da7c9d7e0b 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -61,6 +61,7 @@ class Period(PandasObject):
second : int, default 0
"""
__slots__ = ['freq', 'ordinal']
+ _comparables = ['name','freqstr']
def __init__(self, value=None, freq=None, ordinal=None,
year=None, month=1, quarter=None, day=1,
diff --git a/pandas/tseries/tests/test_daterange.py b/pandas/tseries/tests/test_daterange.py
index 536d718d72eba..d17b42c1e23c9 100644
--- a/pandas/tseries/tests/test_daterange.py
+++ b/pandas/tseries/tests/test_daterange.py
@@ -316,6 +316,23 @@ def test_date_parse_failure(self):
def test_equals(self):
self.assertFalse(self.rng.equals(list(self.rng)))
+ def test_identical(self):
+ t1 = self.rng.copy()
+ t2 = self.rng.copy()
+ self.assert_(t1.identical(t2))
+
+ # name
+ t1 = t1.rename('foo')
+ self.assert_(t1.equals(t2))
+ self.assert_(not t1.identical(t2))
+ t2 = t2.rename('foo')
+ self.assert_(t1.identical(t2))
+
+ # freq
+ t2v = Index(t2.values)
+ self.assert_(t1.equals(t2v))
+ self.assert_(not t1.identical(t2v))
+
def test_daterange_bug_456(self):
# GH #456
rng1 = bdate_range('12/5/2011', '12/5/2011')
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py
index 357c64407dc49..3fdeacad5ffcd 100644
--- a/pandas/tseries/tests/test_resample.py
+++ b/pandas/tseries/tests/test_resample.py
@@ -566,19 +566,19 @@ def test_resample_median_bug_1688(self):
def test_how_lambda_functions(self):
ts = _simple_ts('1/1/2000', '4/1/2000')
-
+
result = ts.resample('M', how=lambda x: x.mean())
exp = ts.resample('M', how='mean')
tm.assert_series_equal(result, exp)
-
+
self.assertRaises(Exception, ts.resample, 'M',
how=[lambda x: x.mean(), lambda x: x.std(ddof=1)])
-
+
result = ts.resample('M', how={'foo': lambda x: x.mean(),
'bar': lambda x: x.std(ddof=1)})
foo_exp = ts.resample('M', how='mean')
bar_exp = ts.resample('M', how='std')
-
+
tm.assert_series_equal(result['foo'], foo_exp)
tm.assert_series_equal(result['bar'], bar_exp)
@@ -771,7 +771,7 @@ def test_resample_to_quarterly(self):
ts.index[-1].asfreq('D', 'end'),
freq='Q-%s' % month)
- expected = stamps.reindex(qdates.to_timestamp('D', 'e'),
+ expected = stamps.reindex(qdates.to_timestamp('D', 's'),
method='ffill')
expected.index = qdates
diff --git a/vb_suite/reindex.py b/vb_suite/reindex.py
index acf8f6f043bad..de0f397334e94 100644
--- a/vb_suite/reindex.py
+++ b/vb_suite/reindex.py
@@ -51,7 +51,7 @@
# Pad / backfill
setup = common_setup + """
-rng = DateRange('1/1/2000', periods=10000, offset=datetools.Minute())
+rng = DateRange('1/1/2000', periods=100000, offset=datetools.Minute())
ts = Series(np.random.randn(len(rng)), index=rng)
ts2 = ts[::2]
| closes #4604, #3317, #4618
Incorrect results
```
In [1]: s = pd.Series([1,2,3,4,5], index=['a', 'b', 'c', 'd', 'e'])
In [2]: s.reindex(['a', 'g', 'c', 'f'], method='ffill')
Out[2]:
a 1
g 5
c NaN
f 5
dtype: float64
```
Fixed (and happens to automatically cast as well back to the original dtype)
(this was broken in 0.12)
```
In [2]: s.reindex(['a', 'g', 'c', 'f'], method='ffill')
Out[2]:
a 1
g 1
c 3
f 3
dtype: int64
```
This does NOT automatically downcast here as this is a major
performance bottleneck if we did (this is the same result as in 0.12)
```
In [3]: >>> s.reindex(['a', 'g', 'c', 'f']).ffill()
Out[3]:
a 1
g 1
c 3
f 3
dtype: float64
```
You can force downcasting by passing 'infer' if you want
(this option was not available in 0.12 for Series)
```
In [4]: >>> s.reindex(['a', 'g', 'c', 'f']).ffill(downcast='infer')
Out[4]:
a 1
g 1
c 3
f 3
dtype: int64
```
TST: GH4604, reindexing with a method of 'ffill' gives incorrect results
BUG/CLN: (GH4604) Refactor Series.reindex to core/generic.py allow method= in reindexing
on a Series to work
API/CLN: GH4604 Infer and downcast dtype if appropriate on ffill/bfill
this is for consistency when doing: df.reindex().ffill() and df.reindex(method='ffill')
CLN: allow backfill/pad/interpolate to operate on integers (by float conversion)
provide downcasting back to original dtype where needed core.internals.interpolate
ENH: provide core.index.identical method to compare values and attributes similar to .equals
API: changed back to pre-GH3482 where a reindex with no args will by default copy
| https://api.github.com/repos/pandas-dev/pandas/pulls/4610 | 2013-08-19T22:16:17Z | 2013-08-21T12:44:43Z | 2013-08-21T12:44:43Z | 2014-06-18T12:22:45Z |
Fixes issue with TextFileReader using python engine and thousands != "," | diff --git a/doc/source/release.rst b/doc/source/release.rst
index d747505593c94..4224880d3fde0 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -429,7 +429,9 @@ Bug Fixes
``ascending`` was being interpreted as ``True`` (:issue:`4839`,
:issue:`4846`)
- Fixed ``Panel.tshift`` not working. Added `freq` support to ``Panel.shift`` (:issue:`4853`)
-
+ - Fix an issue in TextFileReader w/ Python engine (i.e. PythonParser)
+ with thousands != "," (:issue:`4596`)
+
pandas 0.12.0
-------------
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 5554bef4acf98..c4ea76585df83 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1538,7 +1538,7 @@ def _check_thousands(self, lines):
nonnum.search(x.strip())):
rl.append(x)
else:
- rl.append(x.replace(',', ''))
+ rl.append(x.replace(self.thousands, ''))
ret.append(rl)
return ret
diff --git a/pandas/io/tests/test_cparser.py b/pandas/io/tests/test_cparser.py
index d5f62cf909513..8db9c7de6cbcd 100644
--- a/pandas/io/tests/test_cparser.py
+++ b/pandas/io/tests/test_cparser.py
@@ -19,7 +19,7 @@
from pandas import DataFrame, Series, Index, isnull, MultiIndex
import pandas.io.parsers as parsers
from pandas.io.parsers import (read_csv, read_table, read_fwf,
- TextParser)
+ TextParser, TextFileReader)
from pandas.util.testing import (assert_almost_equal, assert_frame_equal,
assert_series_equal, network)
import pandas.lib as lib
@@ -132,6 +132,16 @@ def test_integer_thousands(self):
expected = [123456, 12500]
tm.assert_almost_equal(result[0], expected)
+
+ def test_integer_thousands_alt(self):
+ data = '123.456\n12.500'
+
+ reader = TextFileReader(StringIO(data), delimiter=':',
+ thousands='.', header=None)
+ result = reader.read()
+
+ expected = [123456, 12500]
+ tm.assert_almost_equal(result[0], expected)
def test_skip_bad_lines(self):
# too many lines, see #2430 for why
| Fixes #4596
| https://api.github.com/repos/pandas-dev/pandas/pulls/4602 | 2013-08-18T18:03:34Z | 2013-09-19T12:24:50Z | 2013-09-19T12:24:50Z | 2014-06-13T17:28:42Z |
csv_import: Thousands separator works in floating point numbers | diff --git a/doc/source/io.rst b/doc/source/io.rst
index ba68943f1324a..f09ae1563f71b 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -118,9 +118,11 @@ They can take a number of arguments:
date_converters.py
- ``dayfirst``: if True then uses the DD/MM international/European date format
(This is False by default)
- - ``thousands``: sepcifies the thousands separator. If not None, then parser
- will try to look for it in the output and parse relevant data to integers.
- Because it has to essentially scan through the data again, this causes a
+ - ``thousands``: specifies the thousands separator. If not None, this character will
+ be stripped from numeric dtypes. However, if it is the first character in a field,
+ that column will be imported as a string. In the PythonParser, if not None,
+ then parser will try to look for it in the output and parse relevant data to numeric
+ dtypes. Because it has to essentially scan through the data again, this causes a
significant performance hit so only use if necessary.
- ``lineterminator`` : string (length 1), default ``None``, Character to break file into lines. Only valid with C parser
- ``quotechar`` : string, The character to used to denote the start and end of a quoted item.
@@ -506,8 +508,8 @@ DD/MM/YYYY instead. For convenience, a ``dayfirst`` keyword is provided:
Thousand Separators
~~~~~~~~~~~~~~~~~~~
-For large integers that have been written with a thousands separator, you can
-set the ``thousands`` keyword to ``True`` so that integers will be parsed
+For large numbers that have been written with a thousands separator, you can
+set the ``thousands`` keyword to a string of length 1 so that integers will be parsed
correctly:
.. ipython:: python
@@ -521,7 +523,7 @@ correctly:
with open('tmp.csv', 'w') as fh:
fh.write(data)
-By default, integers with a thousands separator will be parsed as strings
+By default, numbers with a thousands separator will be parsed as strings
.. ipython:: python
@@ -1123,7 +1125,7 @@ is ``None``. To explicity force ``Series`` parsing, pass ``typ=series``
- ``numpy`` : direct decoding to numpy arrays. default is False;
Note that the JSON ordering **MUST** be the same for each term if ``numpy=True``
- ``precise_float`` : boolean, default ``False``. Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (``False``) is to use fast but less precise builtin functionality
-- ``date_unit`` : string, the timestamp unit to detect if converting dates. Default
+- ``date_unit`` : string, the timestamp unit to detect if converting dates. Default
None. By default the timestamp precision will be detected, if this is not desired
then pass one of 's', 'ms', 'us' or 'ns' to force timestamp precision to
seconds, milliseconds, microseconds or nanoseconds respectively.
@@ -1201,11 +1203,11 @@ nanoseconds
dfju
# Let Pandas detect the correct precision
- dfju = pd.read_json(json)
+ dfju = pd.read_json(json)
dfju
# Or specify that all timestamps are in nanoseconds
- dfju = pd.read_json(json, date_unit='ns')
+ dfju = pd.read_json(json, date_unit='ns')
dfju
.. ipython:: python
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 14ed2cab10eac..c7a3eb34d07f9 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -272,6 +272,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- Fix selection with ``ix/loc`` and non_unique selectors (:issue:`4619`)
- Fix assignment with iloc/loc involving a dtype change in an existing column (:issue:`4312`)
have internal setitem_with_indexer in core/indexing to use Block.setitem
+ - Fixed bug where thousands operator was not handled correctly for floating point numbers
+ in csv_import (:issue:`4322`)
pandas 0.12
===========
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 6e735fb5de1e5..fea84f83daa46 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -278,6 +278,9 @@ Bug Fixes
- Suppressed DeprecationWarning associated with internal calls issued by repr() (:issue:`4391`)
+ - Fixed bug where thousands operator was not handled correctly for floating point numbers
+ in csv_import (:issue:`4322`)
+
See the :ref:`full release notes
<release>` or issue tracker
on GitHub for a complete list.
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 787682f340250..6668cfd73a6b7 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -13,17 +13,13 @@
from pandas import DataFrame, Series, Index, MultiIndex, DatetimeIndex
from pandas.compat import(
- StringIO, BytesIO, PY3, range, long, lrange, lmap, u, map, StringIO
+ StringIO, BytesIO, PY3, range, long, lrange, lmap, u
)
from pandas.io.common import urlopen, URLError
import pandas.io.parsers as parsers
from pandas.io.parsers import (read_csv, read_table, read_fwf,
TextFileReader, TextParser)
-from pandas.util.testing import (assert_almost_equal,
- assert_series_equal,
- makeCustomDataframe as mkdf,
- network,
- ensure_clean)
+
import pandas.util.testing as tm
import pandas as pd
@@ -67,6 +63,35 @@ def setUp(self):
self.csv2 = os.path.join(self.dirpath, 'test2.csv')
self.xls1 = os.path.join(self.dirpath, 'test.xls')
+ def test_multi_character_decimal_marker(self):
+ data = """A|B|C
+1|2,334|5
+10|13|10.
+"""
+ self.assertRaises(ValueError, read_csv, StringIO(data), decimal=',,')
+
+ def test_empty_decimal_marker(self):
+ data = """A|B|C
+1|2,334|5
+10|13|10.
+"""
+ self.assertRaises(ValueError, read_csv, StringIO(data), decimal='')
+
+ def test_empty_thousands_marker(self):
+ data = """A|B|C
+1|2,334|5
+10|13|10.
+"""
+ self.assertRaises(ValueError, read_csv, StringIO(data), thousands='')
+
+
+ def test_multi_character_decimal_marker(self):
+ data = """A|B|C
+1|2,334|5
+10|13|10.
+"""
+ self.assertRaises(ValueError, read_csv, StringIO(data), thousands=',,')
+
def test_empty_string(self):
data = """\
One,Two,Three
@@ -164,14 +189,48 @@ def test_1000_sep(self):
1|2,334|5
10|13|10.
"""
- expected = [[1, 2334., 5],
- [10, 13, 10]]
+ expected = DataFrame({
+ 'A': [1, 10],
+ 'B': [2334, 13],
+ 'C': [5, 10.]
+ })
df = self.read_csv(StringIO(data), sep='|', thousands=',')
- assert_almost_equal(df.values, expected)
+ tm.assert_frame_equal(df, expected)
df = self.read_table(StringIO(data), sep='|', thousands=',')
- assert_almost_equal(df.values, expected)
+ tm.assert_frame_equal(df, expected)
+
+ def test_1000_sep_with_decimal(self):
+ data = """A|B|C
+1|2,334.01|5
+10|13|10.
+"""
+ expected = DataFrame({
+ 'A': [1, 10],
+ 'B': [2334.01, 13],
+ 'C': [5, 10.]
+ })
+
+ tm.assert_equal(expected.A.dtype, 'int64')
+ tm.assert_equal(expected.B.dtype, 'float')
+ tm.assert_equal(expected.C.dtype, 'float')
+
+ df = self.read_csv(StringIO(data), sep='|', thousands=',', decimal='.')
+ tm.assert_frame_equal(df, expected)
+
+ df = self.read_table(StringIO(data), sep='|', thousands=',', decimal='.')
+ tm.assert_frame_equal(df, expected)
+
+ data_with_odd_sep = """A|B|C
+1|2.334,01|5
+10|13|10,
+"""
+ df = self.read_csv(StringIO(data_with_odd_sep), sep='|', thousands='.', decimal=',')
+ tm.assert_frame_equal(df, expected)
+
+ df = self.read_table(StringIO(data_with_odd_sep), sep='|', thousands='.', decimal=',')
+ tm.assert_frame_equal(df, expected)
def test_squeeze(self):
data = """\
@@ -183,7 +242,7 @@ def test_squeeze(self):
result = self.read_table(StringIO(data), sep=',', index_col=0,
header=None, squeeze=True)
tm.assert_isinstance(result, Series)
- assert_series_equal(result, expected)
+ tm.assert_series_equal(result, expected)
def test_inf_parsing(self):
data = """\
@@ -201,9 +260,9 @@ def test_inf_parsing(self):
inf = float('inf')
expected = Series([inf, -inf] * 5)
df = read_csv(StringIO(data), index_col=0)
- assert_almost_equal(df['A'].values, expected.values)
+ tm.assert_almost_equal(df['A'].values, expected.values)
df = read_csv(StringIO(data), index_col=0, na_filter=False)
- assert_almost_equal(df['A'].values, expected.values)
+ tm.assert_almost_equal(df['A'].values, expected.values)
def test_multiple_date_col(self):
# Can use multiple date parsers
@@ -524,7 +583,7 @@ def test_passing_dtype(self):
df = DataFrame(np.random.rand(5,2),columns=list('AB'),index=['1A','1B','1C','1D','1E'])
- with ensure_clean('__passing_str_as_dtype__.csv') as path:
+ with tm.ensure_clean('__passing_str_as_dtype__.csv') as path:
df.to_csv(path)
# GH 3795
@@ -566,7 +625,7 @@ def test_quoting(self):
def test_non_string_na_values(self):
# GH3611, na_values that are not a string are an issue
- with ensure_clean('__non_string_na_values__.csv') as path:
+ with tm.ensure_clean('__non_string_na_values__.csv') as path:
df = DataFrame({'A' : [-999, 2, 3], 'B' : [1.2, -999, 4.5]})
df.to_csv(path, sep=' ', index=False)
result1 = read_csv(path, sep= ' ', header=0, na_values=['-999.0','-999'])
@@ -617,15 +676,15 @@ def test_custom_na_values(self):
[7, 8, nan]]
df = self.read_csv(StringIO(data), na_values=['baz'], skiprows=[1])
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
df2 = self.read_table(StringIO(data), sep=',', na_values=['baz'],
skiprows=[1])
- assert_almost_equal(df2.values, expected)
+ tm.assert_almost_equal(df2.values, expected)
df3 = self.read_table(StringIO(data), sep=',', na_values='baz',
skiprows=[1])
- assert_almost_equal(df3.values, expected)
+ tm.assert_almost_equal(df3.values, expected)
def test_nat_parse(self):
@@ -635,7 +694,7 @@ def test_nat_parse(self):
'B' : pd.Timestamp('20010101') }))
df.iloc[3:6,:] = np.nan
- with ensure_clean('__nat_parse_.csv') as path:
+ with tm.ensure_clean('__nat_parse_.csv') as path:
df.to_csv(path)
result = read_csv(path,index_col=0,parse_dates=['B'])
tm.assert_frame_equal(result,df)
@@ -686,7 +745,7 @@ def test_detect_string_na(self):
[nan, nan]]
df = self.read_csv(StringIO(data))
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
def test_unnamed_columns(self):
data = """A,B,C,,
@@ -698,7 +757,7 @@ def test_unnamed_columns(self):
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
df = self.read_table(StringIO(data), sep=',')
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
self.assert_(np.array_equal(df.columns,
['A', 'B', 'C', 'Unnamed: 3',
'Unnamed: 4']))
@@ -849,8 +908,8 @@ def test_no_header(self):
expected = [[1, 2, 3, 4, 5.],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
- assert_almost_equal(df.values, expected)
- assert_almost_equal(df.values, df2.values)
+ tm.assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, df2.values)
self.assert_(np.array_equal(df_pref.columns,
['X0', 'X1', 'X2', 'X3', 'X4']))
@@ -1113,7 +1172,7 @@ def test_header_not_first_line(self):
tm.assert_frame_equal(df, expected)
def test_header_multi_index(self):
- expected = mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
+ expected = tm.makeCustomDataframe(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
data = """\
C0,,C_l0_g0,C_l0_g1,C_l0_g2
@@ -1413,7 +1472,7 @@ def test_na_value_dict(self):
tm.assert_frame_equal(df, xp)
@slow
- @network
+ @tm.network
def test_url(self):
try:
# HTTP(S)
@@ -1428,7 +1487,7 @@ def test_url(self):
except URLError:
try:
- with closing(urlopen('http://www.google.com')) as resp:
+ with tm.closing(urlopen('http://www.google.com')) as resp:
pass
except URLError:
raise nose.SkipTest
@@ -1533,11 +1592,11 @@ def test_comment(self):
expected = [[1., 2., 4.],
[5., np.nan, 10.]]
df = self.read_csv(StringIO(data), comment='#')
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
df = self.read_table(StringIO(data), sep=',', comment='#',
na_values=['NaN'])
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
def test_bool_na_values(self):
data = """A,B,C
@@ -1595,7 +1654,7 @@ def test_utf16_bom_skiprows(self):
path = '__%s__.csv' % tm.rands(10)
- with ensure_clean(path) as path:
+ with tm.ensure_clean(path) as path:
for sep, dat in [('\t', data), (',', data2)]:
for enc in ['utf-16', 'utf-16le', 'utf-16be']:
bytes = dat.encode(enc)
@@ -1860,7 +1919,25 @@ def test_1000_fwf(self):
[10, 13, 10]]
df = read_fwf(StringIO(data), colspecs=[(0, 3), (3, 11), (12, 16)],
thousands=',')
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
+
+ def test_1000_sep_with_decimal(self):
+ data = """A|B|C
+1|2,334.01|5
+10|13|10.
+"""
+
+ expected = DataFrame({
+ 'A': [1, 10],
+ 'B': [2334.01, 13],
+ 'C': [5, 10.]
+ })
+
+ df = self.read_csv(StringIO(data), sep='|', thousands=',')
+ tm.assert_frame_equal(df, expected)
+
+ df = self.read_table(StringIO(data), sep='|', thousands=',')
+ tm.assert_frame_equal(df, expected)
def test_comment_fwf(self):
data = """
@@ -1871,7 +1948,7 @@ def test_comment_fwf(self):
[5, np.nan, 10.]]
df = read_fwf(StringIO(data), colspecs=[(0, 3), (4, 9), (9, 25)],
comment='#')
- assert_almost_equal(df.values, expected)
+ tm.assert_almost_equal(df.values, expected)
def test_fwf(self):
data_expected = """\
@@ -1993,7 +2070,7 @@ def test_iteration_open_handle(self):
if PY3:
raise nose.SkipTest
- with ensure_clean() as path:
+ with tm.ensure_clean() as path:
with open(path, 'wb') as f:
f.write('AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG')
@@ -2212,7 +2289,7 @@ def test_decompression(self):
data = open(self.csv1, 'rb').read()
expected = self.read_csv(self.csv1)
- with ensure_clean() as path:
+ with tm.ensure_clean() as path:
tmp = gzip.GzipFile(path, mode='wb')
tmp.write(data)
tmp.close()
@@ -2223,7 +2300,7 @@ def test_decompression(self):
result = self.read_csv(open(path, 'rb'), compression='gzip')
tm.assert_frame_equal(result, expected)
- with ensure_clean() as path:
+ with tm.ensure_clean() as path:
tmp = bz2.BZ2File(path, mode='wb')
tmp.write(data)
tmp.close()
@@ -2248,7 +2325,7 @@ def test_decompression_regex_sep(self):
data = data.replace(b',', b'::')
expected = self.read_csv(self.csv1)
- with ensure_clean() as path:
+ with tm.ensure_clean() as path:
tmp = gzip.GzipFile(path, mode='wb')
tmp.write(data)
tmp.close()
@@ -2256,7 +2333,7 @@ def test_decompression_regex_sep(self):
result = self.read_csv(path, sep='::', compression='gzip')
tm.assert_frame_equal(result, expected)
- with ensure_clean() as path:
+ with tm.ensure_clean() as path:
tmp = bz2.BZ2File(path, mode='wb')
tmp.write(data)
tmp.close()
@@ -2470,7 +2547,7 @@ def test_convert_sql_column_decimals(self):
def assert_same_values_and_dtype(res, exp):
assert(res.dtype == exp.dtype)
- assert_almost_equal(res, exp)
+ tm.assert_almost_equal(res, exp)
if __name__ == '__main__':
diff --git a/pandas/parser.pyx b/pandas/parser.pyx
index 36055e681a706..8b90e76fa4bf3 100644
--- a/pandas/parser.pyx
+++ b/pandas/parser.pyx
@@ -186,7 +186,7 @@ cdef extern from "parser/tokenizer.h":
uint64_t str_to_uint64(char *p_item, uint64_t uint_max, int *error)
inline int to_double(char *item, double *p_value,
- char sci, char decimal)
+ char sci, char decimal, char thousands)
inline int to_complex(char *item, double *p_real,
double *p_imag, char sci, char decimal)
inline int to_longlong(char *item, long long *p_value)
@@ -355,7 +355,7 @@ cdef class TextReader:
if thousands is not None:
if len(thousands) != 1:
- raise ValueError('Only length-1 decimal markers supported')
+ raise ValueError('Only length-1 thousands markers supported')
self.parser.thousands = ord(thousands)
if escapechar is not None:
@@ -1397,7 +1397,7 @@ cdef _try_double(parser_t *parser, int col, int line_start, int line_end,
na_count += 1
data[0] = NA
else:
- error = to_double(word, data, parser.sci, parser.decimal)
+ error = to_double(word, data, parser.sci, parser.decimal, parser.thousands)
if error != 1:
if strcasecmp(word, cinf) == 0:
data[0] = INF
@@ -1413,7 +1413,7 @@ cdef _try_double(parser_t *parser, int col, int line_start, int line_end,
else:
for i in range(lines):
word = COLITER_NEXT(it)
- error = to_double(word, data, parser.sci, parser.decimal)
+ error = to_double(word, data, parser.sci, parser.decimal, parser.thousands)
if error != 1:
if strcasecmp(word, cinf) == 0:
data[0] = INF
diff --git a/pandas/src/parser/tokenizer.c b/pandas/src/parser/tokenizer.c
index cad5d98dde53a..45b8b9263e9cd 100644
--- a/pandas/src/parser/tokenizer.c
+++ b/pandas/src/parser/tokenizer.c
@@ -1633,7 +1633,7 @@ void test_count_lines(char *fname) {
// forward declaration
-static double xstrtod(const char *p, char **q, char decimal, char sci, int skip_trailing);
+static double xstrtod(const char *p, char **q, char decimal, char sci, char tsep, int skip_trailing);
P_INLINE void lowercase(char *p) {
@@ -1661,11 +1661,11 @@ P_INLINE void uppercase(char *p) {
*
*/
-int to_double(char *item, double *p_value, char sci, char decimal)
+int to_double(char *item, double *p_value, char sci, char decimal, char tsep)
{
char *p_end;
- *p_value = xstrtod(item, &p_end, decimal, sci, TRUE);
+ *p_value = xstrtod(item, &p_end, decimal, sci, tsep, TRUE);
return (errno == 0) && (!*p_end);
}
@@ -1675,7 +1675,7 @@ int P_INLINE to_complex(char *item, double *p_real, double *p_imag, char sci, ch
{
char *p_end;
- *p_real = xstrtod(item, &p_end, decimal, sci, FALSE);
+ *p_real = xstrtod(item, &p_end, decimal, sci, '\0', FALSE);
if (*p_end == '\0') {
*p_imag = 0.0;
return errno == 0;
@@ -1689,7 +1689,7 @@ int P_INLINE to_complex(char *item, double *p_real, double *p_imag, char sci, ch
if (*p_end == '+') {
++p_end;
}
- *p_imag = xstrtod(p_end, &p_end, decimal, sci, FALSE);
+ *p_imag = xstrtod(p_end, &p_end, decimal, sci, '\0', FALSE);
if (errno || ((*p_end != 'i') && (*p_end != 'j'))) {
return FALSE;
}
@@ -1856,10 +1856,12 @@ int main(int argc, char *argv[])
// * Added decimal and sci arguments.
// * Skip trailing spaces.
// * Commented out the other functions.
+// Modifications by Richard T Guy, August 2013:
+// * Add tsep argument for thousands separator
//
static double xstrtod(const char *str, char **endptr, char decimal,
- char sci, int skip_trailing)
+ char sci, char tsep, int skip_trailing)
{
double number;
int exponent;
@@ -1894,6 +1896,8 @@ static double xstrtod(const char *str, char **endptr, char decimal,
number = number * 10. + (*p - '0');
p++;
num_digits++;
+
+ p += (tsep != '\0' & *p == tsep);
}
// Process decimal part
diff --git a/pandas/src/parser/tokenizer.h b/pandas/src/parser/tokenizer.h
index 01f9397685da6..69f627dda554c 100644
--- a/pandas/src/parser/tokenizer.h
+++ b/pandas/src/parser/tokenizer.h
@@ -255,7 +255,7 @@ int64_t str_to_int64(const char *p_item, int64_t int_min,
int64_t int_max, int *error, char tsep);
uint64_t str_to_uint64(const char *p_item, uint64_t uint_max, int *error);
-int P_INLINE to_double(char *item, double *p_value, char sci, char decimal);
+int P_INLINE to_double(char *item, double *p_value, char sci, char decimal, char tsep);
int P_INLINE to_complex(char *item, double *p_real, double *p_imag, char sci, char decimal);
int P_INLINE to_longlong(char *item, long long *p_value);
int P_INLINE to_longlong_thousands(char *item, long long *p_value, char tsep);
| Closes issue #4322
Adds support for the thousands character in csv parser for floats.
Previously, the thousands separator character did not pass into the core floating point number parsing algorithm:
https://github.com/pydata/pandas/blob/master/pandas/src/parser/tokenizer.c#L1861
I added an argument to this function and provided a test. Now, in a file like this:
```
A|B|C
1|2,334.01|5
10|13|10
```
Column B would import as float type.
Also related to issue #2594
| https://api.github.com/repos/pandas-dev/pandas/pulls/4598 | 2013-08-18T15:13:06Z | 2013-08-23T17:51:35Z | 2013-08-23T17:51:35Z | 2014-06-22T08:32:53Z |
BUG: ujson labels are encoded twice | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 390c6e857ba32..009b5183c5632 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -212,6 +212,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- In ``to_json``, fix date handling so milliseconds are the default timestamp
as the docstring says (:issue:`4362`).
- JSON NaT handling fixed, NaTs are now serialised to `null` (:issue:`4498`)
+ - Fixed JSON handling of escapable characters in JSON object keys (:issue:`4593`)
- Fixed passing ``keep_default_na=False`` when ``na_values=None`` (:issue:`4318`)
- Fixed bug with ``values`` raising an error on a DataFrame with duplicate columns and mixed
dtypes, surfaced in (:issue:`4377`)
diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py
index 1f79f5670cc75..108e779129672 100644
--- a/pandas/io/tests/test_json/test_pandas.py
+++ b/pandas/io/tests/test_json/test_pandas.py
@@ -14,7 +14,7 @@
from pandas.util.testing import (assert_almost_equal, assert_frame_equal,
assert_series_equal, network,
- ensure_clean)
+ ensure_clean, assert_index_equal)
import pandas.util.testing as tm
from numpy.testing.decorators import slow
@@ -53,6 +53,21 @@ def setUp(self):
self.tsframe = _tsframe.copy()
self.mixed_frame = _mixed_frame.copy()
+ def test_frame_double_encoded_labels(self):
+ df = DataFrame([['a', 'b'], ['c', 'd']],
+ index=['index " 1', 'index / 2'],
+ columns=['a \\ b', 'y / z'])
+
+ assert_frame_equal(
+ df, read_json(df.to_json(orient='split'), orient='split'))
+ assert_frame_equal(
+ df, read_json(df.to_json(orient='columns'), orient='columns'))
+ assert_frame_equal(
+ df, read_json(df.to_json(orient='index'), orient='index'))
+ df_unser = read_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)
+
def test_frame_non_unique_index(self):
df = DataFrame([['a', 'b'], ['c', 'd']], index=[1, 1],
columns=['x', 'y'])
diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c
index 22f9cf8d7667a..715fbbcaa8856 100644
--- a/pandas/src/ujson/python/objToJSON.c
+++ b/pandas/src/ujson/python/objToJSON.c
@@ -488,6 +488,7 @@ JSOBJ NpyArr_iterGetValue(JSOBJ obj, JSONTypeContext *tc)
char *NpyArr_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
+ JSONObjectEncoder* enc = (JSONObjectEncoder*) tc->encoder;
NpyArrContext* npyarr;
npy_intp idx;
PRINTMARK();
@@ -496,13 +497,19 @@ char *NpyArr_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
idx = npyarr->index[npyarr->stridedim] - 1;
*outLen = strlen(npyarr->columnLabels[idx]);
- return npyarr->columnLabels[idx];
+ memcpy(enc->offset, npyarr->columnLabels[idx], sizeof(char)*(*outLen));
+ enc->offset += *outLen;
+ *outLen = 0;
+ return NULL;
}
else
{
idx = npyarr->index[npyarr->stridedim - npyarr->inc] - 1;
*outLen = strlen(npyarr->rowLabels[idx]);
- return npyarr->rowLabels[idx];
+ memcpy(enc->offset, npyarr->rowLabels[idx], sizeof(char)*(*outLen));
+ enc->offset += *outLen;
+ *outLen = 0;
+ return NULL;
}
}
@@ -1064,7 +1071,7 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in
// NOTE this function steals a reference to labels.
PyArrayObject* labelsTmp = NULL;
PyObject* item = NULL;
- npy_intp i, stride, len;
+ npy_intp i, stride, len, need_quotes;
char** ret;
char *dataptr, *cLabel, *origend, *origst, *origoffset;
char labelBuffer[NPY_JSON_BUFSIZE];
@@ -1117,15 +1124,8 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in
break;
}
- // trim off any quotes surrounding the result
- if (*cLabel == '\"')
- {
- cLabel++;
- enc->offset -= 2;
- *(enc->offset) = '\0';
- }
-
- len = enc->offset - cLabel + 1;
+ need_quotes = ((*cLabel) != '"');
+ len = enc->offset - cLabel + 1 + 2 * need_quotes;
ret[i] = PyObject_Malloc(sizeof(char)*len);
if (!ret[i])
@@ -1135,7 +1135,18 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in
break;
}
- memcpy(ret[i], cLabel, sizeof(char)*len);
+ if (need_quotes)
+ {
+ ret[i][0] = '"';
+ memcpy(ret[i]+1, cLabel, sizeof(char)*(len-4));
+ ret[i][len-3] = '"';
+ }
+ else
+ {
+ memcpy(ret[i], cLabel, sizeof(char)*(len-2));
+ }
+ ret[i][len-2] = ':';
+ ret[i][len-1] = '\0';
dataptr += stride;
}
| With its current handling ujson ends up encoding labels twice, which can cause problems if they contain escapable characters:
``` python
In [16]: df = DataFrame([['a', 'b'], ['c', 'd']], index=['index " 1', 'index / 2'], columns=['a \\ b', 'y / z'])
In [17]: df
Out[17]:
a \ b y / z
index " 1 a b
index / 2 c d
In [18]: json = df.to_json()
In [19]: json
Out[19]: '{"a \\\\\\\\ b":{"index \\\\\\" 1":"a","index \\\\\\/ 2":"c"},"y \\\\\\/ z":{"index \\\\\\" 1":"b","index \\\\\\/ 2":"d"}}'
In [20]: pd.read_json(json)
Out[20]:
a \\ b y \/ z
index \" 1 a b
index \/ 2 c d
```
This PR fixes this behaviour so labels are only encoded a single time.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4593 | 2013-08-17T13:52:57Z | 2013-08-21T02:01:54Z | 2013-08-21T02:01:54Z | 2014-06-22T10:10:15Z |
TST: fix ujson's intermittently failing date unit test | diff --git a/pandas/io/tests/test_json/test_ujson.py b/pandas/io/tests/test_json/test_ujson.py
index 3b9c89e098740..4d6218d3dbc35 100644
--- a/pandas/io/tests/test_json/test_ujson.py
+++ b/pandas/io/tests/test_json/test_ujson.py
@@ -356,20 +356,19 @@ def test_npy_nat(self):
assert ujson.encode(input) == 'null', "Expected null"
def test_datetime_units(self):
- raise nose.SkipTest("skipping for now, test is buggy, pls fix me")
from pandas.lib import Timestamp
- val = datetime.datetime.now()
+ val = datetime.datetime(2013, 8, 17, 21, 17, 12, 215504)
stamp = Timestamp(val)
roundtrip = ujson.decode(ujson.encode(val, date_unit='s'))
- self.assert_(roundtrip == stamp.value // 1e9)
+ self.assert_(roundtrip == stamp.value // 10**9)
roundtrip = ujson.decode(ujson.encode(val, date_unit='ms'))
- self.assert_(roundtrip == stamp.value // 1e6)
+ self.assert_(roundtrip == stamp.value // 10**6)
roundtrip = ujson.decode(ujson.encode(val, date_unit='us'))
- self.assert_(roundtrip == stamp.value / 1e3)
+ self.assert_(roundtrip == stamp.value // 10**3)
roundtrip = ujson.decode(ujson.encode(val, date_unit='ns'))
self.assert_(roundtrip == stamp.value)
| Fixes #4575.
As you surmised @jreback it looks like unnecessary float arithmetic was causing the test failure. I fixed this up and in the interest of consistency removed the dependence on `datetime.now()`
Example
``` python
In [8]: val = 1376774232215504000
In [9]: val / 1000
Out[9]: 1376774232215504
In [10]: val / 1e3
Out[10]: 1376774232215503.8
In [11]: val // 1e3
Out[11]: 1376774232215503.0
In [12]: val / 1000.0
Out[12]: 1376774232215503.8
In [13]: val / 10**3
Out[13]: 1376774232215504
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4592 | 2013-08-17T11:28:32Z | 2013-08-17T14:10:00Z | 2013-08-17T14:10:00Z | 2014-07-01T09:00:09Z |
ENH Factored out excel_value_to_python_value from ExcelFile::_parse_exce... | diff --git a/doc/source/release.rst b/doc/source/release.rst
index a2b525a737879..275717ef984ea 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -44,7 +44,8 @@ pandas 0.13
- Text parser now treats anything that reads like inf ("inf", "Inf", "-Inf",
"iNf", etc.) to infinity. (:issue:`4220`, :issue:`4219`), affecting
``read_table``, ``read_csv``, etc.
-
+ - Factored out excel_value_to_python_value from ExcelFile::_parse_excel (:issue:`4589`)
+
**API Changes**
- ``pandas`` now is Python 2/3 compatible without the need for 2to3 thanks to
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index 534a88e303dbf..aa89264cfc695 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -53,6 +53,23 @@ def read_excel(path_or_buf, sheetname, kind=None, **kwds):
return ExcelFile(path_or_buf, kind=kind).parse(sheetname=sheetname,
kind=kind, **kwds)
+def excel_value_to_python_value(value, typ, datemode):
+ from xlrd import (xldate_as_tuple, XL_CELL_DATE,
+ XL_CELL_ERROR, XL_CELL_BOOLEAN)
+
+ if typ == XL_CELL_DATE:
+ dt = xldate_as_tuple(value, datemode)
+ # how to produce this first case?
+ if dt[0] < datetime.MINYEAR: # pragma: no cover
+ value = datetime.time(*dt[3:])
+ else:
+ value = datetime.datetime(*dt)
+ elif typ == XL_CELL_ERROR:
+ value = np.nan
+ elif typ == XL_CELL_BOOLEAN:
+ value = bool(value)
+
+ return value
class ExcelFile(object):
"""
@@ -174,8 +191,6 @@ def _parse_excel(self, sheetname, header=0, skiprows=None, skip_footer=0,
index_col=None, has_index_names=None, parse_cols=None,
parse_dates=False, date_parser=None, na_values=None,
thousands=None, chunksize=None, **kwds):
- from xlrd import (xldate_as_tuple, XL_CELL_DATE,
- XL_CELL_ERROR, XL_CELL_BOOLEAN)
datemode = self.book.datemode
if isinstance(sheetname, compat.string_types):
@@ -193,17 +208,7 @@ def _parse_excel(self, sheetname, header=0, skiprows=None, skip_footer=0,
should_parse[j] = self._should_parse(j, parse_cols)
if parse_cols is None or should_parse[j]:
- if typ == XL_CELL_DATE:
- dt = xldate_as_tuple(value, datemode)
- # how to produce this first case?
- if dt[0] < datetime.MINYEAR: # pragma: no cover
- value = datetime.time(*dt[3:])
- else:
- value = datetime.datetime(*dt)
- elif typ == XL_CELL_ERROR:
- value = np.nan
- elif typ == XL_CELL_BOOLEAN:
- value = bool(value)
+ value = excel_value_to_python_value(value=value, typ=typ, datemode=datemode)
row.append(value)
data.append(row)
diff --git a/pandas/io/tests/data/types.xls b/pandas/io/tests/data/types.xls
new file mode 100755
index 0000000000000..232a88609df92
Binary files /dev/null and b/pandas/io/tests/data/types.xls differ
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 1ac4d4e31ed10..f5db9d0c016af 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -18,7 +18,8 @@
import pandas.io.parsers as parsers
from pandas.io.parsers import (read_csv, read_table, read_fwf,
TextParser, TextFileReader)
-from pandas.io.excel import ExcelFile, ExcelWriter, read_excel
+from pandas.io.excel import ExcelFile, ExcelWriter, read_excel,\
+ excel_value_to_python_value
from pandas.util.testing import (assert_almost_equal,
assert_series_equal,
network,
@@ -260,6 +261,32 @@ def test_excel_table(self):
tm.assert_frame_equal(df4, df.ix[:-1])
tm.assert_frame_equal(df4, df5)
+ def test_excel_value_to_python_value(self):
+ _skip_if_no_xlrd()
+
+ pth = os.path.join(self.dirpath, 'types.xls')
+ xls = ExcelFile(pth)
+ book = xls.book
+ sheet = book.sheet_by_index(0)
+
+ cell = sheet.cell(0, 0)
+ self.assertEquals(excel_value_to_python_value(value=cell.value, typ=cell.ctype, datemode=book.datemode), 'date')
+
+ cell = sheet.cell(0, 1)
+ self.assertEquals(excel_value_to_python_value(value=cell.value, typ=cell.ctype, datemode=book.datemode), datetime(year=2013, month=4, day=1))
+
+ cell = sheet.cell(1, 1)
+ self.assertEquals(excel_value_to_python_value(value=cell.value, typ=cell.ctype, datemode=book.datemode), True)
+
+ cell = sheet.cell(2, 1)
+ self.assertEquals(excel_value_to_python_value(value=cell.value, typ=cell.ctype, datemode=book.datemode), 1)
+
+ cell = sheet.cell(3, 1)
+ self.assertEquals(excel_value_to_python_value(value=cell.value, typ=cell.ctype, datemode=book.datemode), 1.1)
+
+ cell = sheet.cell(4, 1)
+ self.assertIs(excel_value_to_python_value(value=cell.value, typ=cell.ctype, datemode=book.datemode), np.nan) #We need to use is here because value is NaN
+
def test_excel_read_buffer(self):
_skip_if_no_xlrd()
_skip_if_no_openpyxl()
| ...l (GH4589)
closes #4589
| https://api.github.com/repos/pandas-dev/pandas/pulls/4590 | 2013-08-17T00:03:41Z | 2013-08-26T12:36:36Z | 2013-08-26T12:36:36Z | 2013-08-26T23:00:09Z |
BUG: fix erroneous call to prrint_thing -> pprint_thing | diff --git a/pandas/core/series.py b/pandas/core/series.py
index 4f9c1e430d154..2e2026dfdb8ae 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1264,7 +1264,7 @@ def _repr_footer(self):
else:
freqstr = u('')
- namestr = u("Name: %s, ") % com.prrint_thing(
+ namestr = u("Name: %s, ") % com.pprint_thing(
self.name) if self.name is not None else ""
return u('%s%sLength: %d') % (freqstr, namestr, len(self))
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 9d6311b7e2118..094a68a4c658d 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -186,6 +186,9 @@ def test_name_printing(self):
s.name = None
self.assert_(not "Name:" in repr(s))
+ s = Series(index=date_range('20010101', '20020101'), name='test')
+ self.assert_("Name: test" in repr(s))
+
def test_pickle_preserve_name(self):
unpickled = self._pickle_roundtrip_name(self.ts)
self.assertEquals(unpickled.name, self.ts.name)
| https://api.github.com/repos/pandas-dev/pandas/pulls/4586 | 2013-08-16T21:26:57Z | 2013-08-16T21:41:25Z | 2013-08-16T21:41:25Z | 2014-06-21T02:58:13Z | |
BUG: Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs GH4576 | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9504b7165aa4a..c572aa91c18bb 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -283,6 +283,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
in csv_import (:issue:`4322`)
- Fix an issue with CacheableOffset not properly being used by many DateOffset; this prevented
the DateOffset from being cached (:issue:`4609`)
+ - Fix boolean comparison with a DataFrame on the lhs, and a list/tuple on the rhs (:issue:`4576`)
pandas 0.12
===========
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 1d47250eb8233..5a5c541fc3251 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -723,29 +723,65 @@ def eval(self, func, other, raise_on_error=True, try_cast=False):
# make sure that we can broadcast
is_transposed = False
if hasattr(other, 'ndim') and hasattr(values, 'ndim'):
- if values.ndim != other.ndim or values.shape == other.shape[::-1]:
- values = values.T
- is_transposed = True
+ if values.ndim != other.ndim:
+ is_transposed = True
+ else:
+ if values.shape == other.shape[::-1]:
+ is_transposed = True
+ elif values.shape[0] == other.shape[-1]:
+ is_transposed = True
+ else:
+ # this is a broadcast error heree
+ raise ValueError("cannot broadcast shape [%s] with block values [%s]"
+ % (values.T.shape,other.shape))
+
+ transf = (lambda x: x.T) if is_transposed else (lambda x: x)
+
+ # coerce/transpose the args if needed
+ values, other = self._try_coerce_args(transf(values), other)
+
+ # get the result, may need to transpose the other
+ def get_result(other):
+ return self._try_coerce_result(func(values, other))
+
+ # error handler if we have an issue operating with the function
+ def handle_error():
- values, other = self._try_coerce_args(values, other)
- args = [values, other]
- try:
- result = self._try_coerce_result(func(*args))
- except (Exception) as detail:
if raise_on_error:
- raise TypeError('Could not operate [%s] with block values [%s]'
+ raise TypeError('Could not operate %s with block values %s'
% (repr(other), str(detail)))
else:
# return the values
result = np.empty(values.shape, dtype='O')
result.fill(np.nan)
+ return result
+
+ # get the result
+ try:
+ result = get_result(other)
+
+ # if we have an invalid shape/broadcast error
+ # GH4576, so raise instead of allowing to pass thru
+ except (ValueError) as detail:
+ raise
+ except (Exception) as detail:
+ result = handle_error()
+ # technically a broadcast error in numpy can 'work' by returning a boolean False
if not isinstance(result, np.ndarray):
- raise TypeError('Could not compare [%s] with block values'
- % repr(other))
+ if not isinstance(result, np.ndarray):
+
+ # differentiate between an invalid ndarray-ndarray comparsion and
+ # an invalid type comparison
+ if isinstance(values, np.ndarray) and is_list_like(other):
+ raise ValueError('Invalid broadcasting comparison [%s] with block values'
+ % repr(other))
+
+ raise TypeError('Could not compare [%s] with block values'
+ % repr(other))
- if is_transposed:
- result = result.T
+ # transpose if needed
+ result = transf(result)
# try to cast if requested
if try_cast:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 517c984fa0e64..d2ca850f0a1c0 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -4709,6 +4709,75 @@ def test_float_none_comparison(self):
self.assertRaises(TypeError, df.__eq__, None)
+ def test_boolean_comparison(self):
+
+ # GH 4576
+ # boolean comparisons with a tuple/list give unexpected results
+ df = DataFrame(np.arange(6).reshape((3,2)))
+ b = np.array([2, 2])
+ b_r = np.atleast_2d([2,2])
+ b_c = b_r.T
+ l = (2,2,2)
+ tup = tuple(l)
+
+ # gt
+ expected = DataFrame([[False,False],[False,True],[True,True]])
+ result = df>b
+ assert_frame_equal(result,expected)
+
+ result = df.values>b
+ assert_array_equal(result,expected.values)
+
+ result = df>l
+ assert_frame_equal(result,expected)
+
+ result = df>tup
+ assert_frame_equal(result,expected)
+
+ result = df>b_r
+ assert_frame_equal(result,expected)
+
+ result = df.values>b_r
+ assert_array_equal(result,expected.values)
+
+ self.assertRaises(ValueError, df.__gt__, b_c)
+ self.assertRaises(ValueError, df.values.__gt__, b_c)
+
+ # ==
+ expected = DataFrame([[False,False],[True,False],[False,False]])
+ result = df == b
+ assert_frame_equal(result,expected)
+
+ result = df==l
+ assert_frame_equal(result,expected)
+
+ result = df==tup
+ assert_frame_equal(result,expected)
+
+ result = df == b_r
+ assert_frame_equal(result,expected)
+
+ result = df.values == b_r
+ assert_array_equal(result,expected.values)
+
+ self.assertRaises(ValueError, lambda : df == b_c)
+ self.assert_((df.values == b_c) is False)
+
+ # with alignment
+ df = DataFrame(np.arange(6).reshape((3,2)),columns=list('AB'),index=list('abc'))
+ expected.index=df.index
+ expected.columns=df.columns
+
+ result = df==l
+ assert_frame_equal(result,expected)
+
+ result = df==tup
+ assert_frame_equal(result,expected)
+
+ # not shape compatible
+ self.assertRaises(ValueError, lambda : df == (2,2))
+ self.assertRaises(ValueError, lambda : df == [2,2])
+
def test_to_csv_deprecated_options(self):
pname = '__tmp_to_csv_deprecated_options__'
| closes #4576
```
In [1]: df = DataFrame(np.arange(6).reshape((3,2)))
In [2]: b = np.array([2, 2])
In [3]: b_r = np.atleast_2d([2,2])
In [4]: b_c = b_r.T
In [5]: df>b
Out[5]:
0 1
0 False False
1 False True
2 True True
In [6]: df.values>b
Out[6]:
array([[False, False],
[False, True],
[ True, True]], dtype=bool)
In [7]: df>b_r
Out[7]:
0 1
0 False False
1 False True
2 True True
In [8]: df.values>b_r
Out[8]:
array([[False, False],
[False, True],
[ True, True]], dtype=bool)
In [9]: df>b_c
ValueError: cannot broadcast shape [(3, 2)] with block values [(2, 1)]
In [10]: df.values>b_c
ValueError: operands could not be broadcast together with shapes (3,2) (2,1)
In [11]: df == b
Out[11]:
0 1
0 False False
1 True False
2 False False
In [12]: df.values == b
Out[12]:
array([[False, False],
[ True, False],
[False, False]], dtype=bool)
In [13]: df==b_r
Out[13]:
0 1
0 False False
1 True False
2 False False
In [14]: df.values==b_r
Out[14]:
array([[False, False],
[ True, False],
[False, False]], dtype=bool)
```
Numpy does weird things like this (bottom example), but we will raise
I believe it is actually a NotImplemented Type which is interpreted as False (but still very weird)
```
In [15]: df==b_c
ValueError: cannot broadcast shape [(3, 2)] with block values [(2, 1)]
In [16]: df.values==b_c
Out[16]: False
```
with list/tuple
```
In [2]: df>(2,2)
ValueError: operands could not be broadcast together with shapes (2,3) (2)
In [3]: df>(2,2,2)
Out[3]:
0 1
0 False False
1 False True
2 True True
In [4]: df>[2,2,2]
Out[4]:
0 1
0 False False
1 False True
2 True True
In [5]: df==[2,2,2]
Out[5]:
0 1
0 False False
1 True False
2 False False
```
This will work with a frame with non integer labels too
```
In [6]: df = DataFrame(np.arange(6).reshape((3,2)),columns=list('AB'),index=list('abc'))
In [7]: df==[2,2,2]
Out[7]:
A B
a False False
b True False
c False False
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4585 | 2013-08-16T20:58:01Z | 2013-08-26T12:45:17Z | 2013-08-26T12:45:17Z | 2014-07-16T08:23:30Z |
BUG: DatetimeIndex uses the wrong union if the operands overlap | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 12787c5d04b45..1ee6571c41a52 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -462,6 +462,7 @@ Bug Fixes
- Fixed ``copy()`` to shallow copy axes/indices as well and thereby keep
separate metadata. (:issue:`4202`, :issue:`4830`)
- Fixed skiprows option in Python parser for read_csv (:issue:`4382`)
+ - Fixed wrong check for overlapping in ``DatetimeIndex.union`` (:issue:`4564`)
pandas 0.12.0
-------------
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index b9e8684dfa856..76433cf0c8f88 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -986,11 +986,11 @@ def _can_fast_union(self, other):
else:
left, right = other, self
- left_end = left[-1]
right_start = right[0]
+ left_end = left[-1]
# Only need to "adjoin", not overlap
- return (left_end + offset) >= right_start
+ return (right_start == left_end + offset) or right_start in left
def _fast_union(self, other):
if len(other) == 0:
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 2b2513b37bab6..51a010f9d4ead 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -1859,6 +1859,15 @@ def test_union_bug_1745(self):
exp = DatetimeIndex(sorted(set(list(left)) | set(list(right))))
self.assert_(result.equals(exp))
+ def test_union_bug_4564(self):
+ from pandas import DateOffset
+ left = date_range("2013-01-01", "2013-02-01")
+ right = left + DateOffset(minutes=15)
+
+ result = left.union(right)
+ exp = DatetimeIndex(sorted(set(list(left)) | set(list(right))))
+ self.assert_(result.equals(exp))
+
def test_intersection_bug_1708(self):
from pandas import DateOffset
index_1 = date_range('1/1/2012', periods=4, freq='12H')
| This pretty much boils down to this line: https://github.com/pydata/pandas/blob/master/pandas/tseries/index.py#L987
You can easily reproduce the error using the following code:
```
r = pd.date_range("2013-01-01", "2013-02-01")
r2 = r + pd.DateOffset(minutes=15)
r | r2 # Results in the index r having "2013-01-31 00:15" appended
```
This happens because the check on the given line does not take into account, that two indices with the same offset do not necessarily have to be aligned. If they are the `_fast_union`-method can be used, if not it should fall back to the `Index` implementation.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4564 | 2013-08-15T08:12:10Z | 2013-09-26T00:49:44Z | 2013-09-26T00:49:44Z | 2015-01-06T14:43:46Z |
BUG: Fix incorrect urlparse in _is_s3_url | diff --git a/pandas/io/common.py b/pandas/io/common.py
index a2cf057c8f531..f4a4ef789510c 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -61,7 +61,7 @@ def _is_url(url):
def _is_s3_url(url):
"""Check for an s3 url"""
try:
- return urlparse.urlparse(url).scheme == 's3'
+ return parse_url(url).scheme == 's3'
except:
return False
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py
index c85fd61e975e9..34b2811876f30 100644
--- a/pandas/io/tests/test_data.py
+++ b/pandas/io/tests/test_data.py
@@ -332,6 +332,10 @@ def test_get_put_data_warning(self):
class TestDataReader(unittest.TestCase):
+ def test_is_s3_url(self):
+ from pandas.io.common import _is_s3_url
+ self.assert_(_is_s3_url("s3://pandas/somethingelse.com"))
+
@network
def test_read_yahoo(self):
gs = DataReader("GS", "yahoo")
| Guess this got reverted/messed up during rebasing, but needs to be
changed - urlparse is no longer imported in io/common (in favor of py2/3
compatible methods).
I added a dumb test case so it at least gets called going forward.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4573 | 2013-08-14T22:45:08Z | 2013-08-14T23:54:39Z | 2013-08-14T23:54:39Z | 2014-07-02T21:24:33Z |
BUG: Fix bug in pd.read_clipboard on windows with PY3 (GH4561); not decoding properly | diff --git a/doc/source/release.rst b/doc/source/release.rst
index e0532b6be136f..584cc0c8d2b7a 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -175,6 +175,7 @@ pandas 0.13
with datetimes (:issue:`4532`)
- Fix arithmetic with series/datetimeindex and ``np.timedelta64`` not working the same (:issue:`4134`)
and buggy timedelta in numpy 1.6 (:issue:`4135`)
+ - Fix bug in ``pd.read_clipboard`` on windows with PY3 (:issue:`4561`); not decoding properly
pandas 0.12
===========
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py
index 6070c0e9c5379..7a444ab01e10a 100644
--- a/pandas/compat/__init__.py
+++ b/pandas/compat/__init__.py
@@ -55,11 +55,11 @@
def isidentifier(s):
return s.isidentifier()
- def str_to_bytes(s, encoding='ascii'):
- return s.encode(encoding)
+ def str_to_bytes(s, encoding=None):
+ return s.encode(encoding or 'ascii')
- def bytes_to_str(b, encoding='utf-8'):
- return b.decode(encoding)
+ def bytes_to_str(b, encoding=None):
+ return b.decode(encoding or 'utf-8')
# have to explicitly put builtins into the namespace
range = range
diff --git a/pandas/io/clipboard.py b/pandas/io/clipboard.py
index 798f30e85544f..c4bea55ce2714 100644
--- a/pandas/io/clipboard.py
+++ b/pandas/io/clipboard.py
@@ -1,4 +1,5 @@
""" io on the clipboard """
+from pandas import compat, get_option
from pandas.compat import StringIO
def read_clipboard(**kwargs): # pragma: no cover
@@ -15,6 +16,13 @@ def read_clipboard(**kwargs): # pragma: no cover
from pandas.util.clipboard import clipboard_get
from pandas.io.parsers import read_table
text = clipboard_get()
+
+ # try to decode (if needed on PY3)
+ if compat.PY3:
+ try:
+ text = compat.bytes_to_str(text,encoding=kwargs.get('encoding') or get_option('display.encoding'))
+ except:
+ pass
return read_table(StringIO(text), **kwargs)
| closes #4561
| https://api.github.com/repos/pandas-dev/pandas/pulls/4571 | 2013-08-14T20:16:11Z | 2013-08-15T11:50:48Z | 2013-08-15T11:50:48Z | 2014-06-23T13:06:27Z |
BUG: Fix Segfault with pd.tslib.get_period_field (GH4519, GH4520) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 153b4c4f464be..d761f1f008754 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -184,6 +184,8 @@ pandas 0.13
- Fix arithmetic with series/datetimeindex and ``np.timedelta64`` not working the same (:issue:`4134`)
and buggy timedelta in numpy 1.6 (:issue:`4135`)
- Fix bug in ``pd.read_clipboard`` on windows with PY3 (:issue:`4561`); not decoding properly
+ - ``tslib.get_period_field()`` and ``tslib.get_period_field_arr()`` now raise
+ if code argument out of range (:issue:`4519`, :issue:`4520`)
pandas 0.12
===========
diff --git a/pandas/tests/test_tseries.py b/pandas/tests/test_tseries.py
index 1ed6dd4469f4d..6175b358a925c 100644
--- a/pandas/tests/test_tseries.py
+++ b/pandas/tests/test_tseries.py
@@ -700,6 +700,16 @@ def test_to_datetime_bijective(self):
self.assertEqual(Timestamp(Timestamp.max.to_pydatetime()).value/1000, Timestamp.max.value/1000)
self.assertEqual(Timestamp(Timestamp.min.to_pydatetime()).value/1000, Timestamp.min.value/1000)
+class TestPeriodField(unittest.TestCase):
+
+ def test_get_period_field_raises_on_out_of_range(self):
+ from pandas import tslib
+ self.assertRaises(ValueError, tslib.get_period_field, -1, 0, 0)
+
+ def test_get_period_field_array_raises_on_out_of_range(self):
+ from pandas import tslib
+ self.assertRaises(ValueError, tslib.get_period_field_arr, -1, np.empty(1), 0)
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 698d9a81af387..18917fdd82d1b 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -2419,6 +2419,8 @@ ctypedef int (*accessor)(int64_t ordinal, int freq) except INT32_MIN
def get_period_field(int code, int64_t value, int freq):
cdef accessor f = _get_accessor_func(code)
+ if f is NULL:
+ raise ValueError('Unrecognized period code: %d' % code)
return f(value, freq)
def get_period_field_arr(int code, ndarray[int64_t] arr, int freq):
@@ -2428,6 +2430,8 @@ def get_period_field_arr(int code, ndarray[int64_t] arr, int freq):
accessor f
f = _get_accessor_func(code)
+ if f is NULL:
+ raise ValueError('Unrecognized period code: %d' % code)
sz = len(arr)
out = np.empty(sz, dtype=np.int64)
@@ -2462,8 +2466,7 @@ cdef accessor _get_accessor_func(int code):
return &pday_of_year
elif code == 10:
return &pweekday
- else:
- raise ValueError('Unrecognized code: %s' % code)
+ return NULL
def extract_ordinals(ndarray[object] values, freq):
| Fixes the following problem (issues #4519, #4520):
``` python
>>> import pandas as pd
>>> pd.tslib.get_period_field(11, 1, 1)
Exception ValueError: ValueError('Unrecognized code: 11',) in 'pandas.tslib._get_accessor_func' ignored
Segmentation fault
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4562 | 2013-08-14T11:09:00Z | 2013-08-15T17:23:31Z | 2013-08-15T17:23:31Z | 2014-07-02T22:36:41Z |
ENH/API: Keep original traceback in DataFrame.apply | diff --git a/doc/source/release.rst b/doc/source/release.rst
index bb82a055dcd8d..8fba8618fd860 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -262,6 +262,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
if code argument out of range (:issue:`4519`, :issue:`4520`)
- Fix reindexing with multiple axes; if an axes match was not replacing the current axes, leading
to a possible lazay frequency inference issue (:issue:`3317`)
+ - Fixed issue where ``DataFrame.apply`` was reraising exceptions incorrectly
+ (causing the original stack trace to be truncated).
pandas 0.12
===========
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index d032bbf66f95e..413cb0b6ef3d0 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3632,7 +3632,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
except (NameError, UnboundLocalError): # pragma: no cover
# no k defined yet
pass
- raise e
+ raise
if len(results) > 0 and _is_sequence(results[0]):
if not isinstance(results[0], Series):
| When "raise <exception instance>" is used inside a try/except block, the
original stacktrace (containing the code path that raised the original
exception). This makes debugging difficult since all we know is that an error
occured when `frame._apply_standard` attempted to call the provided function.
Preserve the original stacktrace by using "raise" instead of "raise <exception
instance>". This facilitates debugginb by allowing us to see where (in the
provided callable) the exception occured.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4549 | 2013-08-13T12:49:27Z | 2013-08-21T13:42:36Z | 2013-08-21T13:42:36Z | 2014-06-19T20:26:24Z |
BUG/API: Fix operating with timedelta64/pd.offsets on rhs of a datelike series/index | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 0bcdd2276a94c..e0532b6be136f 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -53,6 +53,11 @@ pandas 0.13
- Add ``rename`` and ``set_names`` methods to ``Index`` as well as
``set_names``, ``set_levels``, ``set_labels`` to ``MultiIndex``.
(:issue:`4039`)
+ - A Series of dtype ``timedelta64[ns]`` can now be divided/multiplied
+ by an integer series (:issue`4521`)
+ - A Series of dtype ``timedelta64[ns]`` can now be divided by another
+ ``timedelta64[ns]`` object to yield a ``float64`` dtyped Series. This
+ is frequency conversion.
**API Changes**
@@ -166,6 +171,10 @@ pandas 0.13
- Fixed issue where individual ``names``, ``levels`` and ``labels`` could be
set on ``MultiIndex`` without validation (:issue:`3714`, :issue:`4039`)
- Fixed (:issue:`3334`) in pivot_table. Margins did not compute if values is the index.
+ - Fix bug in having a rhs of ``np.timedelta64`` or ``np.offsets.DateOffset`` when operating
+ with datetimes (:issue:`4532`)
+ - Fix arithmetic with series/datetimeindex and ``np.timedelta64`` not working the same (:issue:`4134`)
+ and buggy timedelta in numpy 1.6 (:issue:`4135`)
pandas 0.12
===========
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst
index 78c3e832bf0f9..e9540365c3dee 100644
--- a/doc/source/timeseries.rst
+++ b/doc/source/timeseries.rst
@@ -170,7 +170,7 @@ Take care, ``to_datetime`` may not act as you expect on mixed data:
.. ipython:: python
- pd.to_datetime([1, '1'])
+ to_datetime([1, '1'])
.. _timeseries.daterange:
@@ -297,7 +297,7 @@ the year or year and month as strings:
ts['2011-6']
-This type of slicing will work on a DataFrame with a ``DateTimeIndex`` as well. Since the
+This type of slicing will work on a DataFrame with a ``DateTimeIndex`` as well. Since the
partial string selection is a form of label slicing, the endpoints **will be** included. This
would include matching times on an included date. Here's an example:
@@ -1112,7 +1112,8 @@ Time Deltas
-----------
Timedeltas are differences in times, expressed in difference units, e.g. days,hours,minutes,seconds.
-They can be both positive and negative.
+They can be both positive and negative. :ref:`DateOffsets<timeseries.offsets>` that are absolute in nature
+(``Day, Hour, Minute, Second, Milli, Micro, Nano``) can be used as ``timedeltas``.
.. ipython:: python
@@ -1128,41 +1129,16 @@ They can be both positive and negative.
s - s.max()
s - datetime(2011,1,1,3,5)
s + timedelta(minutes=5)
+ s + Minute(5)
+ s + Minute(5) + Milli(5)
Getting scalar results from a ``timedelta64[ns]`` series
-.. ipython:: python
- :suppress:
-
- from distutils.version import LooseVersion
-
.. ipython:: python
y = s - s[0]
y
-.. code-block:: python
-
- if LooseVersion(np.__version__) <= '1.6.2':
- y.apply(lambda x: x.item().total_seconds())
- y.apply(lambda x: x.item().days)
- else:
- y.apply(lambda x: x / np.timedelta64(1, 's'))
- y.apply(lambda x: x / np.timedelta64(1, 'D'))
-
-.. note::
-
- As you can see from the conditional statement above, these operations are
- different in numpy 1.6.2 and in numpy >= 1.7. The ``timedelta64[ns]`` scalar
- type in 1.6.2 is much like a ``datetime.timedelta``, while in 1.7 it is a
- nanosecond based integer. A future version of pandas will make this
- transparent.
-
-.. note::
-
- In numpy >= 1.7 dividing a ``timedelta64`` array by another ``timedelta64``
- array will yield an array with dtype ``np.float64``.
-
Series of timedeltas with ``NaT`` values are supported
.. ipython:: python
@@ -1218,3 +1194,55 @@ issues). ``idxmin, idxmax`` are supported as well.
df.min().idxmax()
df.min(axis=1).idxmin()
+
+.. _timeseries.timedeltas_convert:
+
+Time Deltas & Conversions
+-------------------------
+
+.. versionadded:: 0.13
+
+Timedeltas can be converted to other 'frequencies' by dividing by another timedelta.
+These operations yield ``float64`` dtyped Series.
+
+.. ipython:: python
+
+ td = Series(date_range('20130101',periods=4))-Series(date_range('20121201',periods=4))
+ td[2] += np.timedelta64(timedelta(minutes=5,seconds=3))
+ td[3] = np.nan
+ td
+
+ # to days
+ td / np.timedelta64(1,'D')
+
+ # to seconds
+ td / np.timedelta64(1,'s')
+
+Dividing or multiplying a ``timedelta64[ns]`` Series by an integer or integer Series
+yields another ``timedelta64[ns]`` dtypes Series.
+
+.. ipython:: python
+
+ td * -1
+ td * Series([1,2,3,4])
+
+Numpy < 1.7 Compatibility
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Numpy < 1.7 has a broken ``timedelta64`` type that does not correctly work
+for arithmetic. Pandas bypasses this, but for frequency conversion as above,
+you need to create the divisor yourself. The ``np.timetimedelta64`` type only
+has 1 argument, the number of **micro** seconds.
+
+The following are equivalent statements in the two versions of numpy.
+
+.. code-block:: python
+
+ from distutils.version import LooseVersion
+ if LooseVersion(np.__version__) <= '1.6.2':
+ y / np.timedelta(86400*int(1e6))
+ y / np.timedelta(int(1e6))
+ else:
+ y / np.timedelta64(1,'D')
+ y / np.timedelta64(1,'s')
+
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 8ded258dc98b7..bac8cb3193527 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -100,6 +100,40 @@ Enhancements
- Added a more informative error message when plot arguments contain
overlapping color and style arguments (:issue:`4402`)
+ - ``timedelta64[ns]`` operations
+
+ - A Series of dtype ``timedelta64[ns]`` can now be divided by another
+ ``timedelta64[ns]`` object to yield a ``float64`` dtyped Series. This
+ is frequency conversion. See :ref:`here<timeseries.timedeltas_convert>` for the docs.
+
+ .. ipython:: python
+
+ from datetime import timedelta
+ td = Series(date_range('20130101',periods=4))-Series(date_range('20121201',periods=4))
+ td[2] += np.timedelta64(timedelta(minutes=5,seconds=3))
+ td[3] = np.nan
+ td
+
+ # to days
+ td / np.timedelta64(1,'D')
+
+ # to seconds
+ td / np.timedelta64(1,'s')
+
+ - Dividing or multiplying a ``timedelta64[ns]`` Series by an integer or integer Series
+
+ .. ipython:: python
+
+ td * -1
+ td * Series([1,2,3,4])
+
+ - Absolute ``DateOffset`` objects can act equivalenty to ``timedeltas``
+
+ .. ipython:: python
+
+ from pandas import offsets
+ td + offsets.Minute(5) + offsets.Milli(5)
+
Bug Fixes
~~~~~~~~~
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 9a90c66902376..c34486fc28025 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -11,9 +11,11 @@
import pandas.algos as algos
import pandas.lib as lib
import pandas.tslib as tslib
-
+from distutils.version import LooseVersion
from pandas import compat
from pandas.compat import StringIO, BytesIO, range, long, u, zip, map
+from datetime import timedelta
+
from pandas.core.config import get_option
from pandas.core import array as pa
@@ -33,6 +35,10 @@ class PandasError(Exception):
class AmbiguousIndexError(PandasError, KeyError):
pass
+# versioning
+_np_version = np.version.short_version
+_np_version_under1p6 = LooseVersion(_np_version) < '1.6'
+_np_version_under1p7 = LooseVersion(_np_version) < '1.7'
_POSSIBLY_CAST_DTYPES = set([ np.dtype(t) for t in ['M8[ns]','m8[ns]','O','int8','uint8','int16','uint16','int32','uint32','int64','uint64'] ])
_NS_DTYPE = np.dtype('M8[ns]')
@@ -1144,7 +1150,45 @@ def _possibly_convert_platform(values):
def _possibly_cast_to_timedelta(value, coerce=True):
""" try to cast to timedelta64, if already a timedeltalike, then make
sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards,
- don't force the conversion unless coerce is True """
+ don't force the conversion unless coerce is True
+
+ if coerce='compat' force a compatibilty coercerion (to timedeltas) if needeed
+ """
+
+ # coercion compatability
+ if coerce == 'compat' and _np_version_under1p7:
+
+ def convert(td, type):
+
+ # we have an array with a non-object dtype
+ if hasattr(td,'item'):
+ td = td.astype(np.int64).item()
+ if td == tslib.iNaT:
+ return td
+ if dtype == 'm8[us]':
+ td *= 1000
+ return td
+
+ if td == tslib.compat_NaT:
+ return tslib.iNaT
+
+ # convert td value to a nanosecond value
+ d = td.days
+ s = td.seconds
+ us = td.microseconds
+
+ if dtype == 'object' or dtype == 'm8[ns]':
+ td = 1000*us + (s + d * 24 * 3600) * 10 ** 9
+ else:
+ raise ValueError("invalid conversion of dtype in np < 1.7 [%s]" % dtype)
+
+ return td
+
+ # < 1.7 coercion
+ if not is_list_like(value):
+ value = np.array([ value ])
+ dtype = value.dtype
+ return np.array([ convert(v,dtype) for v in value ], dtype='m8[ns]')
# deal with numpy not being able to handle certain timedelta operations
if isinstance(value,np.ndarray) and value.dtype.kind == 'm':
@@ -1154,6 +1198,7 @@ def _possibly_cast_to_timedelta(value, coerce=True):
# we don't have a timedelta, but we want to try to convert to one (but don't force it)
if coerce:
+
new_value = tslib.array_to_timedelta64(value.astype(object), coerce=False)
if new_value.dtype == 'i8':
value = np.array(new_value,dtype='timedelta64[ns]')
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e283058209e79..d35e251a2bde2 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -23,6 +23,7 @@
_ensure_index, _handle_legacy_indexes)
from pandas.core.indexing import (_SeriesIndexer, _check_bool_indexer,
_check_slice_bounds, _maybe_convert_indices)
+from pandas.tseries.offsets import DateOffset
from pandas.tseries.index import DatetimeIndex
from pandas.tseries.period import PeriodIndex, Period
from pandas import compat
@@ -84,81 +85,144 @@ def na_op(x, y):
def wrapper(self, other, name=name):
from pandas.core.frame import DataFrame
dtype = None
+ fill_value = tslib.iNaT
wrap_results = lambda x: x
lvalues, rvalues = self, other
is_timedelta_lhs = com.is_timedelta64_dtype(self)
is_datetime_lhs = com.is_datetime64_dtype(self)
+ is_integer_lhs = lvalues.dtype.kind in ['i','u']
if is_datetime_lhs or is_timedelta_lhs:
+ coerce = 'compat' if _np_version_under1p7 else True
+
# convert the argument to an ndarray
def convert_to_array(values):
if not is_list_like(values):
values = np.array([values])
inferred_type = lib.infer_dtype(values)
if inferred_type in set(['datetime64','datetime','date','time']):
+ # a datetlike
if not (isinstance(values, pa.Array) and com.is_datetime64_dtype(values)):
values = tslib.array_to_datetime(values)
- elif inferred_type in set(['timedelta','timedelta64']):
- # need to convert timedelta to ns here
- # safest to convert it to an object arrany to process
- if not (isinstance(values, pa.Array) and com.is_timedelta64_dtype(values)):
- values = com._possibly_cast_to_timedelta(values)
+ elif inferred_type in set(['timedelta']):
+ # have a timedelta, convert to to ns here
+ values = com._possibly_cast_to_timedelta(values, coerce=coerce)
+ elif inferred_type in set(['timedelta64']):
+ # have a timedelta64, make sure dtype dtype is ns
+ values = com._possibly_cast_to_timedelta(values, coerce=coerce)
elif inferred_type in set(['integer']):
+ # py3 compat where dtype is 'm' but is an integer
if values.dtype.kind == 'm':
values = values.astype('timedelta64[ns]')
+ elif name not in ['__truediv__','__div__','__mul__']:
+ raise TypeError("incompatible type for a datetime/timedelta operation [{0}]".format(name))
+ elif isinstance(values[0],DateOffset):
+ # handle DateOffsets
+ os = pa.array([ getattr(v,'delta',None) for v in values ])
+ mask = isnull(os)
+ if mask.any():
+ raise TypeError("cannot use a non-absolute DateOffset in "
+ "datetime/timedelta operations [{0}]".format(','.join([ com.pprint_thing(v) for v in values[mask] ])))
+ values = com._possibly_cast_to_timedelta(os, coerce=coerce)
else:
- values = pa.array(values)
+ raise TypeError("incompatible type [{0}] for a datetime/timedelta operation".format(pa.array(values).dtype))
+
return values
# convert lhs and rhs
lvalues = convert_to_array(lvalues)
rvalues = convert_to_array(rvalues)
- is_timedelta_rhs = com.is_timedelta64_dtype(rvalues)
is_datetime_rhs = com.is_datetime64_dtype(rvalues)
+ is_timedelta_rhs = com.is_timedelta64_dtype(rvalues) or (not is_datetime_rhs and _np_version_under1p7)
+ is_integer_rhs = rvalues.dtype.kind in ['i','u']
+ mask = None
- # 2 datetimes or 2 timedeltas
- if (is_timedelta_lhs and is_timedelta_rhs) or (is_datetime_lhs and
- is_datetime_rhs):
- if is_datetime_lhs and name != '__sub__':
+ # timedelta and integer mul/div
+ if (is_timedelta_lhs and is_integer_rhs) or (is_integer_lhs and is_timedelta_rhs):
+
+ if name not in ['__truediv__','__div__','__mul__']:
+ raise TypeError("can only operate on a timedelta and an integer for "
+ "division, but the operator [%s] was passed" % name)
+ dtype = 'timedelta64[ns]'
+ mask = isnull(lvalues) | isnull(rvalues)
+ lvalues = lvalues.astype(np.int64)
+ rvalues = rvalues.astype(np.int64)
+
+ # 2 datetimes
+ elif is_datetime_lhs and is_datetime_rhs:
+ if name != '__sub__':
raise TypeError("can only operate on a datetimes for subtraction, "
"but the operator [%s] was passed" % name)
- elif is_timedelta_lhs and name not in ['__add__','__sub__']:
- raise TypeError("can only operate on a timedeltas for "
- "addition and subtraction, but the operator [%s] was passed" % name)
dtype = 'timedelta64[ns]'
+ mask = isnull(lvalues) | isnull(rvalues)
+ lvalues = lvalues.view('i8')
+ rvalues = rvalues.view('i8')
- # we may have to convert to object unfortunately here
+ # 2 timedeltas
+ elif is_timedelta_lhs and is_timedelta_rhs:
mask = isnull(lvalues) | isnull(rvalues)
- if mask.any():
- def wrap_results(x):
- x = pa.array(x,dtype='timedelta64[ns]')
- np.putmask(x,mask,tslib.iNaT)
- return x
+
+ # time delta division -> unit less
+ if name in ['__div__','__truediv__']:
+ dtype = 'float64'
+ fill_value = np.nan
+ lvalues = lvalues.astype(np.int64).astype(np.float64)
+ rvalues = rvalues.astype(np.int64).astype(np.float64)
+
+ # another timedelta
+ elif name in ['__add__','__sub__']:
+ dtype = 'timedelta64[ns]'
+ lvalues = lvalues.astype(np.int64)
+ rvalues = rvalues.astype(np.int64)
+
+ else:
+ raise TypeError("can only operate on a timedeltas for "
+ "addition, subtraction, and division, but the operator [%s] was passed" % name)
# datetime and timedelta
- elif (is_timedelta_lhs and is_datetime_rhs) or (is_timedelta_rhs and is_datetime_lhs):
+ elif is_timedelta_rhs and is_datetime_lhs:
if name not in ['__add__','__sub__']:
- raise TypeError("can only operate on a timedelta and a datetime for "
+ raise TypeError("can only operate on a datetime with a rhs of a timedelta for "
"addition and subtraction, but the operator [%s] was passed" % name)
dtype = 'M8[ns]'
+ lvalues = lvalues.view('i8')
+ rvalues = rvalues.view('i8')
+
+ elif is_timedelta_lhs and is_datetime_rhs:
+
+ if name not in ['__add__']:
+ raise TypeError("can only operate on a timedelta and a datetime for "
+ "addition, but the operator [%s] was passed" % name)
+ dtype = 'M8[ns]'
+ lvalues = lvalues.view('i8')
+ rvalues = rvalues.view('i8')
else:
- raise ValueError('cannot operate on a series with out a rhs '
- 'of a series/ndarray of type datetime64[ns] '
- 'or a timedelta')
+ raise TypeError('cannot operate on a series with out a rhs '
+ 'of a series/ndarray of type datetime64[ns] '
+ 'or a timedelta')
- lvalues = lvalues.view('i8')
- rvalues = rvalues.view('i8')
+ # if we need to mask the results
+ if mask is not None:
+ if mask.any():
+ def f(x):
+ x = pa.array(x,dtype=dtype)
+ np.putmask(x,mask,fill_value)
+ return x
+ wrap_results = f
if isinstance(rvalues, Series):
- lvalues = lvalues.values
- rvalues = rvalues.values
+
+ if hasattr(lvalues,'values'):
+ lvalues = lvalues.values
+ if hasattr(rvalues,'values'):
+ rvalues = rvalues.values
if self.index.equals(other.index):
name = _maybe_match_name(self, other)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index b192aded45074..9a959fa789e05 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1,10 +1,10 @@
# pylint: disable-msg=E1101,W0612
-from datetime import datetime, timedelta, date
-import os
+from datetime import datetime, timedelta
import operator
import unittest
import string
+from itertools import product, starmap
import nose
@@ -21,6 +21,7 @@
import pandas.core.series as smod
import pandas.lib as lib
+import pandas.core.common as com
import pandas.core.datetools as datetools
import pandas.core.nanops as nanops
@@ -38,6 +39,7 @@ def _skip_if_no_scipy():
except ImportError:
raise nose.SkipTest
+
def _skip_if_no_pytz():
try:
import pytz
@@ -63,8 +65,8 @@ def test_copy_name(self):
self.assertEquals(result.name, self.ts.name)
# def test_copy_index_name_checking(self):
- # # don't want to be able to modify the index stored elsewhere after
- # # making a copy
+ # don't want to be able to modify the index stored elsewhere after
+ # making a copy
# self.ts.index.name = None
# cp = self.ts.copy()
@@ -313,7 +315,7 @@ def test_constructor(self):
self.assertEqual(rs, xp)
# raise on MultiIndex GH4187
- m = MultiIndex.from_arrays([[1, 2], [3,4]])
+ m = MultiIndex.from_arrays([[1, 2], [3, 4]])
self.assertRaises(NotImplementedError, Series, m)
def test_constructor_empty(self):
@@ -445,7 +447,7 @@ def test_constructor_cast(self):
self.assertRaises(ValueError, Series, ['a', 'b', 'c'], dtype=float)
def test_constructor_dtype_nocast(self):
- # #1572
+ # 1572
s = Series([1, 2, 3])
s2 = Series(s, dtype=np.int64)
@@ -459,8 +461,8 @@ def test_constructor_dtype_datetime64(self):
s = Series(tslib.iNaT, dtype='M8[ns]', index=lrange(5))
self.assert_(isnull(s).all() == True)
- #### in theory this should be all nulls, but since
- #### we are not specifying a dtype is ambiguous
+ # in theory this should be all nulls, but since
+ # we are not specifying a dtype is ambiguous
s = Series(tslib.iNaT, index=lrange(5))
self.assert_(isnull(s).all() == False)
@@ -489,12 +491,14 @@ def test_constructor_dtype_datetime64(self):
self.assert_(s.dtype == 'M8[ns]')
# invalid astypes
- for t in ['s','D','us','ms']:
+ for t in ['s', 'D', 'us', 'ms']:
self.assertRaises(TypeError, s.astype, 'M8[%s]' % t)
# GH3414 related
- self.assertRaises(TypeError, lambda x: Series(Series(dates).astype('int')/1000000,dtype='M8[ms]'))
- self.assertRaises(TypeError, lambda x: Series(dates, dtype='datetime64'))
+ self.assertRaises(TypeError, lambda x: Series(
+ Series(dates).astype('int') / 1000000, dtype='M8[ms]'))
+ self.assertRaises(
+ TypeError, lambda x: Series(dates, dtype='datetime64'))
def test_constructor_dict(self):
d = {'a': 0., 'b': 1., 'c': 2.}
@@ -518,14 +522,17 @@ def test_constructor_subclass_dict(self):
def test_orderedDict_ctor(self):
# GH3283
- import pandas, random
+ import pandas
+ import random
data = OrderedDict([('col%s' % i, random.random()) for i in range(12)])
s = pandas.Series(data)
self.assertTrue(all(s.values == list(data.values())))
def test_orderedDict_subclass_ctor(self):
# GH3283
- import pandas, random
+ import pandas
+ import random
+
class A(OrderedDict):
pass
data = A([('col%s' % i, random.random()) for i in range(12)])
@@ -631,7 +638,8 @@ def test_getitem_get(self):
self.assertEqual(self.series[idx1], self.series[5])
self.assertEqual(self.objSeries[idx2], self.objSeries[5])
- self.assertEqual(self.series.get(-1), self.series.get(self.series.index[-1]))
+ self.assertEqual(
+ self.series.get(-1), self.series.get(self.series.index[-1]))
self.assertEqual(self.series[5], self.series.get(self.series.index[5]))
# missing
@@ -792,10 +800,10 @@ def test_getitem_dups_with_missing(self):
# breaks reindex, so need to use .ix internally
# GH 4246
- s = Series([1,2,3,4],['foo','bar','foo','bah'])
- expected = s.ix[['foo','bar','bah','bam']]
- result = s[['foo','bar','bah','bam']]
- assert_series_equal(result,expected)
+ s = Series([1, 2, 3, 4], ['foo', 'bar', 'foo', 'bah'])
+ expected = s.ix[['foo', 'bar', 'bah', 'bam']]
+ result = s[['foo', 'bar', 'bah', 'bam']]
+ assert_series_equal(result, expected)
def test_setitem_ambiguous_keyerror(self):
s = Series(lrange(10), index=lrange(0, 20, 2))
@@ -944,8 +952,8 @@ def test_reshape_non_2d(self):
self.assertRaises(TypeError, x.reshape, (len(x),))
# GH 2719
- a = Series([1,2,3,4])
- self.assertRaises(TypeError,a.reshape, 2, 2)
+ a = Series([1, 2, 3, 4])
+ self.assertRaises(TypeError, a.reshape, 2, 2)
def test_reshape_2d_return_array(self):
x = Series(np.random.random(201), name='x')
@@ -1098,76 +1106,83 @@ def test_where(self):
self.assertRaises(ValueError, s.where, cond[:3].values, -s)
# GH 2745
- s = Series([1,2])
- s[[True, False]] = [0,1]
- expected = Series([0,2])
- assert_series_equal(s,expected)
+ s = Series([1, 2])
+ s[[True, False]] = [0, 1]
+ expected = Series([0, 2])
+ assert_series_equal(s, expected)
# failures
- self.assertRaises(ValueError, s.__setitem__, tuple([[[True, False]]]), [0,2,3])
- self.assertRaises(ValueError, s.__setitem__, tuple([[[True, False]]]), [])
+ self.assertRaises(
+ ValueError, s.__setitem__, tuple([[[True, False]]]), [0, 2, 3])
+ self.assertRaises(
+ ValueError, s.__setitem__, tuple([[[True, False]]]), [])
# unsafe dtype changes
- for dtype in [ np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64 ]:
+ for dtype in [np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64]:
s = Series(np.arange(10), dtype=dtype)
mask = s < 5
- s[mask] = lrange(2,7)
- expected = Series(lrange(2,7) + lrange(5,10), dtype=dtype)
+ s[mask] = lrange(2, 7)
+ expected = Series(lrange(2, 7) + lrange(5, 10), dtype=dtype)
assert_series_equal(s, expected)
self.assertEquals(s.dtype, expected.dtype)
# these are allowed operations, but are upcasted
- for dtype in [ np.int64, np.float64 ]:
+ for dtype in [np.int64, np.float64]:
s = Series(np.arange(10), dtype=dtype)
mask = s < 5
- values = [2.5,3.5,4.5,5.5,6.5]
+ values = [2.5, 3.5, 4.5, 5.5, 6.5]
s[mask] = values
- expected = Series(values + lrange(5,10), dtype='float64')
+ expected = Series(values + lrange(5, 10), dtype='float64')
assert_series_equal(s, expected)
self.assertEquals(s.dtype, expected.dtype)
- # can't do these as we are forced to change the itemsize of the input to something we cannot
- for dtype in [ np.int8, np.int16, np.int32, np.float16, np.float32 ]:
+ # can't do these as we are forced to change the itemsize of the input
+ # to something we cannot
+ for dtype in [np.int8, np.int16, np.int32, np.float16, np.float32]:
s = Series(np.arange(10), dtype=dtype)
mask = s < 5
- values = [2.5,3.5,4.5,5.5,6.5]
+ values = [2.5, 3.5, 4.5, 5.5, 6.5]
self.assertRaises(Exception, s.__setitem__, tuple(mask), values)
# GH3235
- s = Series(np.arange(10),dtype='int64')
+ s = Series(np.arange(10), dtype='int64')
mask = s < 5
- s[mask] = lrange(2,7)
- expected = Series(lrange(2,7) + lrange(5,10),dtype='int64')
+ s[mask] = lrange(2, 7)
+ expected = Series(lrange(2, 7) + lrange(5, 10), dtype='int64')
assert_series_equal(s, expected)
self.assertEquals(s.dtype, expected.dtype)
- s = Series(np.arange(10),dtype='int64')
+ s = Series(np.arange(10), dtype='int64')
mask = s > 5
- s[mask] = [0]*4
- expected = Series([0,1,2,3,4,5] + [0]*4,dtype='int64')
- assert_series_equal(s,expected)
+ s[mask] = [0] * 4
+ expected = Series([0, 1, 2, 3, 4, 5] + [0] * 4, dtype='int64')
+ assert_series_equal(s, expected)
s = Series(np.arange(10))
mask = s > 5
- self.assertRaises(ValueError, s.__setitem__, mask, ([0]*5,))
+ self.assertRaises(ValueError, s.__setitem__, mask, ([0] * 5,))
def test_where_broadcast(self):
# Test a variety of differently sized series
for size in range(2, 6):
# Test a variety of boolean indices
- for selection in [np.resize([True, False, False, False, False], size), # First element should be set
- np.resize([True, False], size), # Set alternating elements]
- np.resize([False], size)]: # No element should be set
+ for selection in [np.resize([True, False, False, False, False], size), # First element should be set
+ # Set alternating elements]
+ np.resize([True, False], size),
+ np.resize([False], size)]: # No element should be set
# Test a variety of different numbers as content
for item in [2.0, np.nan, np.finfo(np.float).max, np.finfo(np.float).min]:
- # Test numpy arrays, lists and tuples as the input to be broadcast
+ # Test numpy arrays, lists and tuples as the input to be
+ # broadcast
for arr in [np.array([item]), [item], (item,)]:
data = np.arange(size, dtype=float)
s = Series(data)
s[selection] = arr
- # Construct the expected series by taking the source data or item based on the selection
- expected = Series([item if use_item else data[i] for i, use_item in enumerate(selection)])
- assert_series_equal(s,expected)
+ # Construct the expected series by taking the source
+ # data or item based on the selection
+ expected = Series([item if use_item else data[i]
+ for i, use_item in enumerate(selection)])
+ assert_series_equal(s, expected)
def test_where_inplace(self):
s = Series(np.random.randn(5))
@@ -1221,14 +1236,14 @@ def test_setitem_boolean(self):
# similiar indexed series
result = self.series.copy()
- result[mask] = self.series*2
- expected = self.series*2
+ result[mask] = self.series * 2
+ expected = self.series * 2
assert_series_equal(result[mask], expected[mask])
# needs alignment
result = self.series.copy()
- result[mask] = (self.series*2)[0:5]
- expected = (self.series*2)[0:5].reindex_like(self.series)
+ result[mask] = (self.series * 2)[0:5]
+ expected = (self.series * 2)[0:5].reindex_like(self.series)
expected[-mask] = self.series[mask]
assert_series_equal(result[mask], expected[mask])
@@ -1391,8 +1406,7 @@ def test_timeseries_periodindex(self):
prng = period_range('1/1/2011', '1/1/2012', freq='M')
ts = Series(np.random.randn(len(prng)), prng)
new_ts = pickle.loads(pickle.dumps(ts))
- self.assertEqual(new_ts.index.freq,'M')
-
+ self.assertEqual(new_ts.index.freq, 'M')
def test_iter(self):
for i, val in enumerate(self.series):
@@ -1501,19 +1515,19 @@ def test_argsort(self):
self.assert_(issubclass(argsorted.dtype.type, np.integer))
# GH 2967 (introduced bug in 0.11-dev I think)
- s = Series([Timestamp('201301%02d'% (i+1)) for i in range(5)])
+ s = Series([Timestamp('201301%02d' % (i + 1)) for i in range(5)])
self.assert_(s.dtype == 'datetime64[ns]')
shifted = s.shift(-1)
self.assert_(shifted.dtype == 'datetime64[ns]')
self.assert_(isnull(shifted[4]) == True)
result = s.argsort()
- expected = Series(lrange(5),dtype='int64')
- assert_series_equal(result,expected)
+ expected = Series(lrange(5), dtype='int64')
+ assert_series_equal(result, expected)
result = shifted.argsort()
- expected = Series(lrange(4) + [-1],dtype='int64')
- assert_series_equal(result,expected)
+ expected = Series(lrange(4) + [-1], dtype='int64')
+ assert_series_equal(result, expected)
def test_argsort_stable(self):
s = Series(np.random.randint(0, 100, size=10000))
@@ -1567,7 +1581,6 @@ def testit():
# add some NaNs
self.series[5:15] = np.NaN
-
# idxmax, idxmin, min, and max are valid for dates
if not ('max' in name or 'min' in name):
ds = Series(date_range('1/1/2001', periods=10))
@@ -1591,7 +1604,7 @@ def testit():
# 2888
l = [0]
- l.extend(lrange(2**40,2**40+1000))
+ l.extend(lrange(2 ** 40, 2 ** 40+1000))
s = Series(l, dtype='int64')
assert_almost_equal(float(f(s)), float(alternate(s.values)))
@@ -1748,50 +1761,52 @@ def test_invert(self):
def test_modulo(self):
# GH3590, modulo as ints
- p = DataFrame({ 'first' : [3,4,5,8], 'second' : [0,0,0,3] })
+ p = DataFrame({'first': [3, 4, 5, 8], 'second': [0, 0, 0, 3]})
result = p['first'] % p['second']
- expected = Series(p['first'].values % p['second'].values,dtype='float64')
+ expected = Series(p['first'].values %
+ p['second'].values, dtype='float64')
expected.iloc[0:3] = np.nan
- assert_series_equal(result,expected)
+ assert_series_equal(result, expected)
result = p['first'] % 0
- expected = Series(np.nan,index=p.index)
- assert_series_equal(result,expected)
+ expected = Series(np.nan, index=p.index)
+ assert_series_equal(result, expected)
p = p.astype('float64')
result = p['first'] % p['second']
expected = Series(p['first'].values % p['second'].values)
- assert_series_equal(result,expected)
+ assert_series_equal(result, expected)
p = p.astype('float64')
result = p['first'] % p['second']
result2 = p['second'] % p['first']
- self.assertFalse(np.array_equal(result,result2))
+ self.assertFalse(np.array_equal(result, result2))
def test_div(self):
# integer div, but deal with the 0's
- p = DataFrame({ 'first' : [3,4,5,8], 'second' : [0,0,0,3] })
+ p = DataFrame({'first': [3, 4, 5, 8], 'second': [0, 0, 0, 3]})
result = p['first'] / p['second']
- expected = Series(p['first'].values / p['second'].values,dtype='float64')
+ expected = Series(
+ p['first'].values / p['second'].values, dtype='float64')
expected.iloc[0:3] = np.inf
- assert_series_equal(result,expected)
+ assert_series_equal(result, expected)
result = p['first'] / 0
- expected = Series(np.inf,index=p.index)
- assert_series_equal(result,expected)
+ expected = Series(np.inf, index=p.index)
+ assert_series_equal(result, expected)
p = p.astype('float64')
result = p['first'] / p['second']
expected = Series(p['first'].values / p['second'].values)
- assert_series_equal(result,expected)
+ assert_series_equal(result, expected)
- p = DataFrame({ 'first' : [3,4,5,8], 'second' : [1,1,1,1] })
+ p = DataFrame({'first': [3, 4, 5, 8], 'second': [1, 1, 1, 1]})
result = p['first'] / p['second']
if compat.PY3:
- assert_series_equal(result,p['first'].astype('float64'))
+ assert_series_equal(result, p['first'].astype('float64'))
else:
- assert_series_equal(result,p['first'])
+ assert_series_equal(result, p['first'])
self.assertFalse(np.array_equal(result, p['second'] / p['first']))
def test_operators(self):
@@ -1845,146 +1860,325 @@ def test_operators_empty_int_corner(self):
def test_constructor_dtype_timedelta64(self):
- td = Series([ timedelta(days=i) for i in range(3) ])
- self.assert_(td.dtype=='timedelta64[ns]')
+ td = Series([timedelta(days=i) for i in range(3)])
+ 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]' )
- self.assert_(td.dtype=='timedelta64[ns]')
+ td = Series([timedelta(days=i)
+ for i in range(3)] + [tslib.NaT ], dtype='m8[ns]' )
+ self.assert_(td.dtype == 'timedelta64[ns]')
- td = Series([ timedelta(days=i) for i in range(3) ] + [ tslib.iNaT ], dtype='m8[ns]' )
- self.assert_(td.dtype=='timedelta64[ns]')
+ td = Series([timedelta(days=i)
+ for i in range(3)] + [tslib.iNaT ], dtype='m8[ns]' )
+ self.assert_(td.dtype == 'timedelta64[ns]')
- td = Series([ timedelta(days=i) for i in range(3) ] + [ np.nan ], dtype='m8[ns]' )
- self.assert_(td.dtype=='timedelta64[ns]')
+ td = Series([timedelta(days=i)
+ for i in range(3)] + [np.nan ], dtype='m8[ns]' )
+ self.assert_(td.dtype == 'timedelta64[ns]')
# invalid astypes
- for t in ['s','D','us','ms']:
+ for t in ['s', 'D', 'us', 'ms']:
self.assertRaises(TypeError, td.astype, 'm8[%s]' % t)
# 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]' )
+ self.assertRaises(Exception, Series, [timedelta(days=i)
+ for i in range(3)] + ['foo' ], dtype='m8[ns]' )
self.assertRaises(TypeError, td.astype, 'int32')
# leave as object here
- td = Series([ timedelta(days=i) for i in range(3) ] + [ 'foo' ])
- self.assert_(td.dtype=='object')
+ td = Series([timedelta(days=i) for i in range(3)] + ['foo'])
+ self.assert_(td.dtype == 'object')
def test_operators_timedelta64(self):
# invalid ops
self.assertRaises(Exception, self.objSeries.__add__, 1)
- self.assertRaises(Exception, self.objSeries.__add__, np.array(1,dtype=np.int64))
+ self.assertRaises(
+ Exception, self.objSeries.__add__, np.array(1, dtype=np.int64))
self.assertRaises(Exception, self.objSeries.__sub__, 1)
- self.assertRaises(Exception, self.objSeries.__sub__, np.array(1,dtype=np.int64))
+ self.assertRaises(
+ Exception, self.objSeries.__sub__, np.array(1, dtype=np.int64))
# seriese ops
v1 = date_range('2012-1-1', periods=3, freq='D')
v2 = date_range('2012-1-2', periods=3, freq='D')
rs = Series(v2) - Series(v1)
- xp = Series(1e9 * 3600 * 24, rs.index).astype('int64').astype('timedelta64[ns]')
+ xp = Series(1e9 * 3600 * 24, rs.index).astype(
+ 'int64').astype('timedelta64[ns]')
assert_series_equal(rs, xp)
- self.assert_(rs.dtype=='timedelta64[ns]')
+ self.assert_(rs.dtype == 'timedelta64[ns]')
- df = DataFrame(dict(A = v1))
- td = Series([ timedelta(days=i) for i in range(3) ])
- self.assert_(td.dtype=='timedelta64[ns]')
+ df = DataFrame(dict(A=v1))
+ td = Series([timedelta(days=i) for i in range(3)])
+ self.assert_(td.dtype == 'timedelta64[ns]')
# series on the rhs
result = df['A'] - df['A'].shift()
- self.assert_(result.dtype=='timedelta64[ns]')
+ self.assert_(result.dtype == 'timedelta64[ns]')
result = df['A'] + td
- self.assert_(result.dtype=='M8[ns]')
+ self.assert_(result.dtype == 'M8[ns]')
# scalar Timestamp on rhs
maxa = df['A'].max()
- tm.assert_isinstance(maxa,Timestamp)
+ tm.assert_isinstance(maxa, Timestamp)
- resultb = df['A']- df['A'].max()
- self.assert_(resultb.dtype=='timedelta64[ns]')
+ resultb = df['A'] - df['A'].max()
+ self.assert_(resultb.dtype == 'timedelta64[ns]')
# timestamp on lhs
result = resultb + df['A']
- expected = Series([Timestamp('20111230'),Timestamp('20120101'),Timestamp('20120103')])
- assert_series_equal(result,expected)
+ expected = Series(
+ [Timestamp('20111230'), Timestamp('20120101'), Timestamp('20120103')])
+ assert_series_equal(result, expected)
# datetimes on rhs
- result = df['A'] - datetime(2001,1,1)
- expected = Series([timedelta(days=4017+i) for i in range(3)])
- assert_series_equal(result,expected)
- self.assert_(result.dtype=='m8[ns]')
+ result = df['A'] - datetime(2001, 1, 1)
+ expected = Series([timedelta(days=4017 + i) for i in range(3)])
+ assert_series_equal(result, expected)
+ self.assert_(result.dtype == 'm8[ns]')
- d = datetime(2001,1,1,3,4)
+ d = datetime(2001, 1, 1, 3, 4)
resulta = df['A'] - d
- self.assert_(resulta.dtype=='m8[ns]')
+ self.assert_(resulta.dtype == 'm8[ns]')
# roundtrip
resultb = resulta + d
- assert_series_equal(df['A'],resultb)
+ assert_series_equal(df['A'], resultb)
# timedeltas on rhs
td = timedelta(days=1)
resulta = df['A'] + td
resultb = resulta - td
- assert_series_equal(resultb,df['A'])
- self.assert_(resultb.dtype=='M8[ns]')
+ assert_series_equal(resultb, df['A'])
+ self.assert_(resultb.dtype == 'M8[ns]')
# roundtrip
- td = timedelta(minutes=5,seconds=3)
+ td = timedelta(minutes=5, seconds=3)
resulta = df['A'] + td
resultb = resulta - td
- assert_series_equal(df['A'],resultb)
- self.assert_(resultb.dtype=='M8[ns]')
+ assert_series_equal(df['A'], resultb)
+ self.assert_(resultb.dtype == 'M8[ns]')
+
+ # inplace
+ value = rs[2] + np.timedelta64(timedelta(minutes=5,seconds=1))
+ rs[2] += np.timedelta64(timedelta(minutes=5,seconds=1))
+ self.assert_(rs[2] == value)
+
+ def test_timedeltas_with_DateOffset(self):
+
+ # GH 4532
+ # operate with pd.offsets
+ s = Series([Timestamp('20130101 9:01'), Timestamp('20130101 9:02')])
+
+ result = s + pd.offsets.Second(5)
+ expected = Series(
+ [Timestamp('20130101 9:01:05'), Timestamp('20130101 9:02:05')])
+
+ result = s + pd.offsets.Milli(5)
+ expected = Series(
+ [Timestamp('20130101 9:01:00.005'), Timestamp('20130101 9:02:00.005')])
+ assert_series_equal(result, expected)
+
+ result = s + pd.offsets.Minute(5) + pd.offsets.Milli(5)
+ expected = Series(
+ [Timestamp('20130101 9:06:00.005'), Timestamp('20130101 9:07:00.005')])
+ assert_series_equal(result, expected)
+
+ if not com._np_version_under1p7:
+
+ # operate with np.timedelta64 correctly
+ result = s + np.timedelta64(1, 's')
+ expected = Series(
+ [Timestamp('20130101 9:01:01'), Timestamp('20130101 9:02:01')])
+ assert_series_equal(result, expected)
+
+ result = s + np.timedelta64(5, 'ms')
+ expected = Series(
+ [Timestamp('20130101 9:01:00.005'), Timestamp('20130101 9:02:00.005')])
+ assert_series_equal(result, expected)
+
+ # valid DateOffsets
+ for do in [ 'Hour', 'Minute', 'Second', 'Day', 'Micro',
+ 'Milli', 'Nano' ]:
+ op = getattr(pd.offsets,do)
+ s + op(5)
+
+ # invalid DateOffsets
+ for do in [ 'Week', 'BDay', 'BQuarterEnd', 'BMonthEnd', 'BYearEnd',
+ 'BYearBegin','BQuarterBegin', 'BMonthBegin',
+ 'MonthEnd','YearBegin', 'YearEnd',
+ 'MonthBegin', 'QuarterBegin' ]:
+ op = getattr(pd.offsets,do)
+ self.assertRaises(TypeError, s.__add__, op(5))
+
+ def test_timedelta64_operations_with_timedeltas(self):
# td operate with td
- td1 = Series([timedelta(minutes=5,seconds=3)]*3)
- td2 = timedelta(minutes=5,seconds=4)
- result = td1-td2
- expected = Series([timedelta(seconds=0)]*3)-Series([timedelta(seconds=1)]*3)
- self.assert_(result.dtype=='m8[ns]')
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
+ td2 = timedelta(minutes=5, seconds=4)
+ result = td1 - td2
+ expected = Series([timedelta(seconds=0)] * 3) -Series(
+ [timedelta(seconds=1)] * 3)
+ self.assert_(result.dtype == 'm8[ns]')
+ assert_series_equal(result, expected)
+
+ # roundtrip
+ assert_series_equal(result + td2,td1)
+
+ def test_timedelta64_operations_with_integers(self):
+
+ # GH 4521
+ # divide/multiply by integers
+ startdate = Series(date_range('2013-01-01', '2013-01-03'))
+ enddate = Series(date_range('2013-03-01', '2013-03-03'))
+
+ s1 = enddate - startdate
+ s1[2] = np.nan
+ s2 = Series([2, 3, 4])
+ expected = Series(s1.values.astype(np.int64) / s2, dtype='m8[ns]')
+ expected[2] = np.nan
+ result = s1 / s2
+ assert_series_equal(result,expected)
+
+ s2 = Series([20, 30, 40])
+ expected = Series(s1.values.astype(np.int64) / s2, dtype='m8[ns]')
+ expected[2] = np.nan
+ result = s1 / s2
+ assert_series_equal(result,expected)
+
+ result = s1 / 2
+ expected = Series(s1.values.astype(np.int64) / 2, dtype='m8[ns]')
+ expected[2] = np.nan
+ assert_series_equal(result,expected)
+
+ s2 = Series([20, 30, 40])
+ expected = Series(s1.values.astype(np.int64) * s2, dtype='m8[ns]')
+ expected[2] = np.nan
+ result = s1 * s2
+ assert_series_equal(result,expected)
+
+ for dtype in ['int32','int16','uint32','uint64','uint32','uint16','uint8']:
+ s2 = Series([20, 30, 40],dtype=dtype)
+ expected = Series(s1.values.astype(np.int64) * s2.astype(np.int64), dtype='m8[ns]')
+ expected[2] = np.nan
+ result = s1 * s2
+ assert_series_equal(result,expected)
+
+ result = s1 * 2
+ expected = Series(s1.values.astype(np.int64) * 2, dtype='m8[ns]')
+ expected[2] = np.nan
assert_series_equal(result,expected)
+ result = s1 * -1
+ expected = Series(s1.values.astype(np.int64) * -1, dtype='m8[ns]')
+ expected[2] = np.nan
+ assert_series_equal(result,expected)
+
+ # invalid ops
+ for op in ['__true_div__','__div__','__mul__']:
+ sop = getattr(s1,op,None)
+ if sop is not None:
+ self.assertRaises(TypeError, sop, s2.astype(float))
+ self.assertRaises(TypeError, sop, 2.)
+
+ for op in ['__add__','__sub__']:
+ sop = getattr(s1,op,None)
+ if sop is not None:
+ self.assertRaises(TypeError, sop, 1)
+ self.assertRaises(TypeError, sop, s2.values)
+
+ def test_timedelta64_conversions(self):
+ if com._np_version_under1p7:
+ raise nose.SkipTest("cannot use 2 argument form of timedelta64 conversions with numpy < 1.7")
+
+ startdate = Series(date_range('2013-01-01', '2013-01-03'))
+ enddate = Series(date_range('2013-03-01', '2013-03-03'))
+
+ s1 = enddate - startdate
+ s1[2] = np.nan
+
+ for m in [1, 3, 10]:
+ for unit in ['D','h','m','s','ms','us','ns']:
+ expected = s1.apply(lambda x: x / np.timedelta64(m,unit))
+ result = s1 / np.timedelta64(m,unit)
+ assert_series_equal(result, expected)
+
+ def test_timedelta64_equal_timedelta_supported_ops(self):
+ ser = Series([Timestamp('20130301'), Timestamp('20130228 23:00:00'),
+ Timestamp('20130228 22:00:00'),
+ Timestamp('20130228 21:00:00')])
+
+ intervals = 'D', 'h', 'm', 's', 'us'
+ npy16_mappings = {'D': 24 * 60 * 60 * 1000000, 'h': 60 * 60 * 1000000,
+ 'm': 60 * 1000000, 's': 1000000, 'us': 1}
+
+ def timedelta64(*args):
+ if com._np_version_under1p7:
+ coeffs = np.array(args)
+ terms = np.array([npy16_mappings[interval]
+ for interval in intervals])
+ return np.timedelta64(coeffs.dot(terms))
+ return sum(starmap(np.timedelta64, zip(args, intervals)))
+
+ for op, d, h, m, s, us in product([operator.add, operator.sub],
+ *([range(2)] * 5)):
+ nptd = timedelta64(d, h, m, s, us)
+ pytd = timedelta(days=d, hours=h, minutes=m, seconds=s,
+ microseconds=us)
+ lhs = op(ser, nptd)
+ rhs = op(ser, pytd)
+
+ try:
+ assert_series_equal(lhs, rhs)
+ except:
+ raise AssertionError(
+ "invalid comparsion [op->{0},d->{1},h->{2},m->{3},s->{4},us->{5}]\n{6}\n{7}\n".format(op, d, h, m, s, us, lhs, rhs))
+
def test_operators_datetimelike(self):
- ### timedelta64 ###
- td1 = Series([timedelta(minutes=5,seconds=3)]*3)
- td2 = timedelta(minutes=5,seconds=4)
- for op in ['__mul__','__floordiv__','__truediv__','__div__','__pow__']:
- op = getattr(td1,op,None)
+ # timedelta64 ###
+ td1 = Series([timedelta(minutes=5, seconds=3)] * 3)
+ td2 = timedelta(minutes=5, seconds=4)
+ for op in ['__mul__', '__floordiv__', '__pow__']:
+ op = getattr(td1, op, None)
if op is not None:
self.assertRaises(TypeError, op, td2)
td1 + td2
td1 - td2
-
- ### datetime64 ###
- dt1 = Series([Timestamp('20111230'),Timestamp('20120101'),Timestamp('20120103')])
- dt2 = Series([Timestamp('20111231'),Timestamp('20120102'),Timestamp('20120104')])
- for op in ['__add__','__mul__','__floordiv__','__truediv__','__div__','__pow__']:
- op = getattr(dt1,op,None)
- if op is not None:
- self.assertRaises(TypeError, op, dt2)
+ td1 / td2
+
+ # datetime64 ###
+ dt1 = Series(
+ [Timestamp('20111230'), Timestamp('20120101'), Timestamp('20120103')])
+ dt2 = Series(
+ [Timestamp('20111231'), Timestamp('20120102'), Timestamp('20120104')])
+ for op in ['__add__', '__mul__', '__floordiv__', '__truediv__', '__div__', '__pow__']:
+ sop = getattr(dt1, op, None)
+ if sop is not None:
+ self.assertRaises(TypeError, sop, dt2)
dt1 - dt2
- ### datetime64 with timetimedelta ###
- for op in ['__mul__','__floordiv__','__truediv__','__div__','__pow__']:
- op = getattr(dt1,op,None)
- if op is not None:
- self.assertRaises(TypeError, op, td1)
+ # datetime64 with timetimedelta ###
+ for op in ['__mul__', '__floordiv__', '__truediv__', '__div__', '__pow__']:
+ sop = getattr(dt1, op, None)
+ if sop is not None:
+ self.assertRaises(TypeError, sop, td1)
dt1 + td1
dt1 - td1
- ### timetimedelta with datetime64 ###
- for op in ['__mul__','__floordiv__','__truediv__','__div__','__pow__']:
- op = getattr(td1,op,None)
- if op is not None:
- self.assertRaises(TypeError, op, dt1)
+ # timetimedelta with datetime64 ###
+ for op in ['__sub__', '__mul__', '__floordiv__', '__truediv__', '__div__', '__pow__']:
+ sop = getattr(td1, op, None)
+ if sop is not None:
+ self.assertRaises(TypeError, sop, dt1)
+
+ # timedelta + datetime ok
td1 + dt1
- td1 - dt1
def test_timedelta64_functions(self):
@@ -1992,7 +2186,8 @@ def test_timedelta64_functions(self):
from pandas import date_range
# index min/max
- td = Series(date_range('2012-1-1', periods=3, freq='D'))-Timestamp('20120101')
+ td = Series(date_range('2012-1-1', periods=3, freq='D')) - \
+ Timestamp('20120101')
result = td.idxmin()
self.assert_(result == 0)
@@ -2011,31 +2206,30 @@ def test_timedelta64_functions(self):
self.assert_(result == 2)
# abs
- s1 = Series(date_range('20120101',periods=3))
- s2 = Series(date_range('20120102',periods=3))
- expected = Series(s2-s1)
+ s1 = Series(date_range('20120101', periods=3))
+ s2 = Series(date_range('20120102', periods=3))
+ expected = Series(s2 - s1)
# this fails as numpy returns timedelta64[us]
#result = np.abs(s1-s2)
- #assert_frame_equal(result,expected)
+ # assert_frame_equal(result,expected)
- result = (s1-s2).abs()
- assert_series_equal(result,expected)
+ result = (s1 - s2).abs()
+ assert_series_equal(result, expected)
# max/min
result = td.max()
- expected = Series([timedelta(2)],dtype='timedelta64[ns]')
- assert_series_equal(result,expected)
+ expected = Series([timedelta(2)], dtype='timedelta64[ns]')
+ assert_series_equal(result, expected)
result = td.min()
- expected = Series([timedelta(1)],dtype='timedelta64[ns]')
- assert_series_equal(result,expected)
-
+ expected = Series([timedelta(1)], dtype='timedelta64[ns]')
+ assert_series_equal(result, expected)
def test_sub_of_datetime_from_TimeSeries(self):
from pandas.core import common as com
from datetime import datetime
- a = Timestamp(datetime(1993,0o1,0o7,13,30,00))
+ a = Timestamp(datetime(1993, 0o1, 0o7, 13, 30, 00))
b = datetime(1993, 6, 22, 13, 30)
a = Series([a])
result = com._possibly_cast_to_timedelta(np.abs(a - b))
@@ -2044,7 +2238,7 @@ def test_sub_of_datetime_from_TimeSeries(self):
def test_timedelta64_nan(self):
from pandas import tslib
- td = Series([ timedelta(days=i) for i in range(10) ])
+ td = Series([timedelta(days=i) for i in range(10)])
# nan ops on timedeltas
td1 = td.copy()
@@ -2066,8 +2260,8 @@ def test_timedelta64_nan(self):
td1[2] = td[2]
self.assert_(isnull(td1[2]) == False)
- #### boolean setting
- #### this doesn't work, not sure numpy even supports it
+ # boolean setting
+ # this doesn't work, not sure numpy even supports it
#result = td[(td>np.timedelta64(timedelta(days=3))) & (td<np.timedelta64(timedelta(days=7)))] = np.nan
#self.assert_(isnull(result).sum() == 7)
@@ -2262,7 +2456,7 @@ def test_idxmin(self):
# datetime64[ns]
from pandas import date_range
- s = Series(date_range('20130102',periods=6))
+ s = Series(date_range('20130102', periods=6))
result = s.idxmin()
self.assert_(result == 0)
@@ -2292,7 +2486,7 @@ def test_idxmax(self):
self.assert_(isnull(allna.idxmax()))
from pandas import date_range
- s = Series(date_range('20130102',periods=6))
+ s = Series(date_range('20130102', periods=6))
result = s.idxmax()
self.assert_(result == 5)
@@ -2464,7 +2658,7 @@ def test_update(self):
df['c'] = np.nan
# this will fail as long as series is a sub-class of ndarray
- ##### df['c'].update(Series(['foo'],index=[0])) #####
+ # df['c'].update(Series(['foo'],index=[0])) #####
def test_corr(self):
_skip_if_no_scipy()
@@ -2579,7 +2773,7 @@ def test_dot(self):
index=['1', '2', '3'])
assert_series_equal(result, expected)
- #Check index alignment
+ # Check index alignment
b2 = b.reindex(index=reversed(b.index))
result = a.dot(b)
assert_series_equal(result, expected)
@@ -2589,7 +2783,7 @@ def test_dot(self):
self.assertTrue(np.all(result == expected.values))
assert_almost_equal(a.dot(b['2'].values), expected['2'])
- #Check series argument
+ # Check series argument
assert_almost_equal(a.dot(b['1']), expected['1'])
assert_almost_equal(a.dot(b2['1']), expected['1'])
@@ -2622,20 +2816,22 @@ def test_value_counts_nunique(self):
# GH 3002, datetime64[ns]
import pandas as pd
- f = StringIO("xxyyzz20100101PIE\nxxyyzz20100101GUM\nxxyyww20090101EGG\nfoofoo20080909PIE")
- df = pd.read_fwf(f, widths=[6,8,3], names=["person_id", "dt", "food"], parse_dates=["dt"])
+ f = StringIO(
+ "xxyyzz20100101PIE\nxxyyzz20100101GUM\nxxyyww20090101EGG\nfoofoo20080909PIE")
+ df = pd.read_fwf(f, widths=[6, 8, 3], names=[
+ "person_id", "dt", "food"], parse_dates=["dt"])
s = df.dt.copy()
result = s.value_counts()
self.assert_(result.index.dtype == 'datetime64[ns]')
# with NaT
- s = s.append(Series({ 4 : pd.NaT }))
+ s = s.append(Series({4: pd.NaT}))
result = s.value_counts()
self.assert_(result.index.dtype == 'datetime64[ns]')
# timedelta64[ns]
from datetime import timedelta
- td = df.dt-df.dt+timedelta(1)
+ td = df.dt - df.dt + timedelta(1)
result = td.value_counts()
#self.assert_(result.index.dtype == 'timedelta64[ns]')
self.assert_(result.index.dtype == 'int64')
@@ -3210,7 +3406,7 @@ def test_getitem_setitem_datetime_tz(self):
assert_series_equal(result, ts)
def test_getitem_setitem_periodindex(self):
- from pandas import period_range, Period
+ from pandas import period_range
N = 50
rng = period_range('1/1/1990', periods=N, freq='H')
ts = Series(np.random.randn(N), index=rng)
@@ -3319,9 +3515,9 @@ def test_cast_on_putmask(self):
# GH 2746
# need to upcast
- s = Series([1,2],index=[1,2],dtype='int64')
- s[[True, False]] = Series([0],index=[1],dtype='int64')
- expected = Series([0,2],index=[1,2],dtype='int64')
+ s = Series([1, 2], index=[1, 2], dtype='int64')
+ s[[True, False]] = Series([0], index=[1], dtype='int64')
+ expected = Series([0, 2], index=[1, 2], dtype='int64')
assert_series_equal(s, expected)
@@ -3441,7 +3637,7 @@ def test_apply(self):
tm.assert_series_equal(s, rs)
# index but no data
- s = Series(index=[1,2,3])
+ s = Series(index=[1, 2, 3])
rs = s.apply(lambda x: x)
tm.assert_series_equal(s, rs)
@@ -3467,66 +3663,78 @@ def test_apply_dont_convert_dtype(self):
def test_convert_objects(self):
- s = Series([1., 2, 3],index=['a','b','c'])
- result = s.convert_objects(convert_dates=False,convert_numeric=True)
+ s = Series([1., 2, 3], index=['a', 'b', 'c'])
+ result = s.convert_objects(convert_dates=False, convert_numeric=True)
assert_series_equal(result, s)
# force numeric conversion
r = s.copy().astype('O')
r['a'] = '1'
- result = r.convert_objects(convert_dates=False,convert_numeric=True)
+ result = r.convert_objects(convert_dates=False, convert_numeric=True)
assert_series_equal(result, s)
r = s.copy().astype('O')
r['a'] = '1.'
- result = r.convert_objects(convert_dates=False,convert_numeric=True)
+ result = r.convert_objects(convert_dates=False, convert_numeric=True)
assert_series_equal(result, s)
r = s.copy().astype('O')
r['a'] = 'garbled'
expected = s.copy()
expected['a'] = np.nan
- result = r.convert_objects(convert_dates=False,convert_numeric=True)
+ result = r.convert_objects(convert_dates=False, convert_numeric=True)
assert_series_equal(result, expected)
# GH 4119, not converting a mixed type (e.g.floats and object)
- s = Series([1, 'na', 3 ,4])
+ s = Series([1, 'na', 3, 4])
result = s.convert_objects(convert_numeric=True)
- expected = Series([1,np.nan,3,4])
+ expected = Series([1, np.nan, 3, 4])
assert_series_equal(result, expected)
- s = Series([1, '', 3 ,4])
+ s = Series([1, '', 3, 4])
result = s.convert_objects(convert_numeric=True)
- expected = Series([1,np.nan,3,4])
+ expected = Series([1, np.nan, 3, 4])
assert_series_equal(result, expected)
# dates
- s = Series([datetime(2001,1,1,0,0), datetime(2001,1,2,0,0), datetime(2001,1,3,0,0) ])
- s2 = Series([datetime(2001,1,1,0,0), datetime(2001,1,2,0,0), datetime(2001,1,3,0,0), 'foo', 1.0, 1, Timestamp('20010104'), '20010105'],dtype='O')
-
- result = s.convert_objects(convert_dates=True,convert_numeric=False)
- expected = Series([Timestamp('20010101'),Timestamp('20010102'),Timestamp('20010103')],dtype='M8[ns]')
+ s = Series(
+ [datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime(2001, 1, 3, 0, 0)])
+ s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0), datetime(
+ 2001, 1, 3, 0, 0), 'foo', 1.0, 1, Timestamp('20010104'), '20010105'], dtype='O')
+
+ result = s.convert_objects(convert_dates=True, convert_numeric=False)
+ expected = Series(
+ [Timestamp('20010101'), Timestamp('20010102'), Timestamp('20010103')], dtype='M8[ns]')
assert_series_equal(result, expected)
- result = s.convert_objects(convert_dates='coerce',convert_numeric=False)
- result = s.convert_objects(convert_dates='coerce',convert_numeric=True)
+ result = s.convert_objects(
+ convert_dates='coerce', convert_numeric=False)
+ result = s.convert_objects(
+ convert_dates='coerce', convert_numeric=True)
assert_series_equal(result, expected)
- expected = Series([Timestamp('20010101'),Timestamp('20010102'),Timestamp('20010103'),lib.NaT,lib.NaT,lib.NaT,Timestamp('20010104'),Timestamp('20010105')],dtype='M8[ns]')
- result = s2.convert_objects(convert_dates='coerce',convert_numeric=False)
+ expected = Series(
+ [Timestamp(
+ '20010101'), Timestamp('20010102'), Timestamp('20010103'),
+ lib.NaT, lib.NaT, lib.NaT, Timestamp('20010104'), Timestamp('20010105')], dtype='M8[ns]')
+ result = s2.convert_objects(
+ convert_dates='coerce', convert_numeric=False)
assert_series_equal(result, expected)
- result = s2.convert_objects(convert_dates='coerce',convert_numeric=True)
+ result = s2.convert_objects(
+ convert_dates='coerce', convert_numeric=True)
assert_series_equal(result, expected)
# preserver all-nans (if convert_dates='coerce')
- s = Series(['foo','bar',1,1.0],dtype='O')
- result = s.convert_objects(convert_dates='coerce',convert_numeric=False)
- assert_series_equal(result,s)
+ s = Series(['foo', 'bar', 1, 1.0], dtype='O')
+ result = s.convert_objects(
+ convert_dates='coerce', convert_numeric=False)
+ assert_series_equal(result, s)
# preserver if non-object
- s = Series([1],dtype='float32')
- result = s.convert_objects(convert_dates='coerce',convert_numeric=False)
- assert_series_equal(result,s)
+ s = Series([1], dtype='float32')
+ result = s.convert_objects(
+ convert_dates='coerce', convert_numeric=False)
+ assert_series_equal(result, s)
#r = s.copy()
#r[0] = np.nan
@@ -3535,12 +3743,12 @@ def test_convert_objects(self):
# dateutil parses some single letters into today's value as a date
for x in 'abcdefghijklmnopqrstuvwxyz':
- s = Series([x])
- result = s.convert_objects(convert_dates='coerce')
- assert_series_equal(result,s)
- s = Series([x.upper()])
- result = s.convert_objects(convert_dates='coerce')
- assert_series_equal(result,s)
+ s = Series([x])
+ result = s.convert_objects(convert_dates='coerce')
+ assert_series_equal(result, s)
+ s = Series([x.upper()])
+ result = s.convert_objects(convert_dates='coerce')
+ assert_series_equal(result, s)
def test_apply_args(self):
s = Series(['foo,bar'])
@@ -3824,7 +4032,8 @@ def test_rename(self):
self.assert_(np.array_equal(renamed.index, ['a', 'foo', 'c', 'bar']))
# index with name
- renamer = Series(np.arange(4), index=Index(['a', 'b', 'c', 'd'], name='name'))
+ renamer = Series(
+ np.arange(4), index=Index(['a', 'b', 'c', 'd'], name='name'))
renamed = renamer.rename({})
self.assertEqual(renamed.index.name, renamer.index.name)
@@ -3971,7 +4180,6 @@ def cummin(x):
def cummax(x):
return np.maximum.accumulate(x)
- from itertools import product
a = pd.Series([False, False, False, True, True, False, False])
b = ~a
c = pd.Series([False] * len(b))
@@ -3996,7 +4204,6 @@ def cummax(x):
res = getattr(e, method)()
assert_series_equal(res, expecteds[method])
-
def test_replace(self):
N = 100
ser = Series(np.random.randn(N))
@@ -4136,7 +4343,8 @@ def test_interpolate_index_values(self):
expected = s.copy()
bad = isnull(expected.values)
good = -bad
- expected = Series(np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad])
+ expected = Series(
+ np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad])
assert_series_equal(result[bad], expected)
@@ -4167,13 +4375,13 @@ def test_diff(self):
assert_series_equal(rs, xp)
# datetime diff (GH3100)
- s = Series(date_range('20130102',periods=5))
- rs = s-s.shift(1)
+ s = Series(date_range('20130102', periods=5))
+ rs = s - s.shift(1)
xp = s.diff()
assert_series_equal(rs, xp)
# timedelta diff
- nrs = rs-rs.shift(1)
+ nrs = rs - rs.shift(1)
nxp = xp.diff()
assert_series_equal(nrs, nxp)
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 17d357370c078..285ff312bbf5a 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -6,7 +6,8 @@
import numpy as np
-from pandas.core.common import isnull, _NS_DTYPE, _INT64_DTYPE
+from pandas.core.common import (isnull, _NS_DTYPE, _INT64_DTYPE,
+ is_list_like,_possibly_cast_to_timedelta)
from pandas.core.index import Index, Int64Index
import pandas.compat as compat
from pandas.compat import u
@@ -541,7 +542,7 @@ def __add__(self, other):
elif isinstance(other, (DateOffset, timedelta)):
return self._add_delta(other)
elif isinstance(other, np.timedelta64):
- raise NotImplementedError
+ return self._add_delta(other)
elif com.is_integer(other):
return self.shift(other)
else: # pragma: no cover
@@ -553,7 +554,7 @@ def __sub__(self, other):
elif isinstance(other, (DateOffset, timedelta)):
return self._add_delta(-other)
elif isinstance(other, np.timedelta64):
- raise NotImplementedError
+ return self._add_delta(-other)
elif com.is_integer(other):
return self.shift(-other)
else: # pragma: no cover
@@ -568,6 +569,9 @@ def _add_delta(self, delta):
utc = _utc()
if self.tz is not None and self.tz is not utc:
result = result.tz_convert(self.tz)
+ elif isinstance(delta, np.timedelta64):
+ new_values = self.to_series() + delta
+ result = DatetimeIndex(new_values, tz=self.tz, freq='infer')
else:
new_values = self.astype('O') + delta
result = DatetimeIndex(new_values, tz=self.tz, freq='infer')
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index e0413531d05b4..46402ad859b05 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -2296,6 +2296,16 @@ def test_timedelta(self):
expected = index + timedelta(-1)
self.assert_(result.equals(expected))
+ # GH4134, buggy with timedeltas
+ rng = date_range('2013', '2014')
+ s = Series(rng)
+ result1 = rng - pd.offsets.Hour(1)
+ result2 = DatetimeIndex(s - np.timedelta64(100000000))
+ result3 = rng - np.timedelta64(100000000)
+ result4 = DatetimeIndex(s - pd.offsets.Hour(1))
+ self.assert_(result1.equals(result4))
+ self.assert_(result2.equals(result3))
+
def test_shift(self):
ts = Series(np.random.randn(5),
index=date_range('1/1/2000', periods=5, freq='H'))
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 1c12b627f0690..bb3512e532b0e 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -45,6 +45,8 @@ PyDateTime_IMPORT
cdef int64_t NPY_NAT = util.get_nat()
+# < numpy 1.7 compat for NaT
+compat_NaT = np.array([NPY_NAT]).astype('m8[ns]').item()
try:
basestring
| closes #4532
closes #4134
closes #4135
closes #4521
Timedeltas can be converted to other ‘frequencies’ by dividing by another timedelta.
```
In [210]: td = Series(date_range('20130101',periods=4))-Series(date_range('20121201',periods=4))
In [211]: td[2] += np.timedelta64(timedelta(minutes=5,seconds=3))
In [212]: td[3] = np.nan
In [213]: td
0 31 days, 00:00:00
1 31 days, 00:00:00
2 31 days, 00:05:03
3 NaT
dtype: timedelta64[ns]
```
to days
```
In [214]: td / np.timedelta64(1,'D')
0 31.000000
1 31.000000
2 31.003507
3 NaN
dtype: float64
```
to seconds
```
In [215]: td / np.timedelta64(1,'s')
0 2678400
1 2678400
2 2678703
3 NaN
dtype: float64
```
Dividing or multiplying a timedelta64[ns] Series by an integer or integer Series yields a float64 dtyped Series.
```
In [216]: td * -1
0 -31 days, 00:00:00
1 -31 days, 00:00:00
2 -31 days, 00:05:03
3 NaT
dtype: timedelta64[ns]
In [217]: td * Series([1,2,3,4])
0 31 days, 00:00:00
1 62 days, 00:00:00
2 93 days, 00:15:09
3 NaT
dtype: timedelta64[ns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4534 | 2013-08-10T14:40:02Z | 2013-08-13T22:19:43Z | 2013-08-13T22:19:43Z | 2014-06-16T17:04:14Z |
DOC/BLD: Update version support in docs and setup.py. | diff --git a/doc/source/install.rst b/doc/source/install.rst
index 4d9864b272c2a..4472d844c1871 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -16,11 +16,10 @@ compiler (MinGW or Visual Studio) installed. `How-to install MinGW on Windows
Python version support
~~~~~~~~~~~~~~~~~~~~~~
-Officially Python 2.6 to 2.7 and Python 3.1+, although Python 3 support is less
-well tested. Python 2.4 support is being phased out since the userbase has
-shrunk significantly. Continuing Python 2.4 support will require either monetary
-development support or someone contributing to the project to maintain
-compatibility.
+Officially Python 2.6 to 2.7 and Python 3.2+. Python 2.4 and Python 2.5 are no
+longer supported since the userbase has shrunk significantly. Continuing Python
+2.4 and 2.5 support will require either monetary development support or someone
+contributing to the project to restore compatibility.
Binary installers
diff --git a/setup.py b/setup.py
index a99ba88322796..58513c9d4077d 100755
--- a/setup.py
+++ b/setup.py
@@ -180,6 +180,10 @@ def build_extensions(self):
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 2.6',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
'Programming Language :: Cython',
'Topic :: Scientific/Engineering',
]
| Fixes #4412.
Changes install.rst to explicitly reference that pandas supports 2.6,
2.7, and 3.2+. (and removes line that Python 3 support is less
well-tested). Also adds 2.6, 2.7, 3.2, and 3.3 in classifiers in
setup.py
| https://api.github.com/repos/pandas-dev/pandas/pulls/4530 | 2013-08-10T02:06:38Z | 2013-08-10T12:07:18Z | 2013-08-10T12:07:18Z | 2014-07-16T08:22:55Z |
BUG: GH4516 Fixed issue with sorting a duplicate multi-index that has multiple dtypes | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 95ce03a858570..769b47b18db08 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -135,6 +135,7 @@ pandas 0.13
- Raise on set indexing with a Panel and a Panel as a value which needs alignment (:issue:`3777`)
- frozenset objects now raise in the ``Series`` constructor (:issue:`4482`,
:issue:`4480`)
+ - Fixed issue with sorting a duplicate multi-index that has multiple dtypes (:issue:`4516`)
pandas 0.12
===========
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 902a6c736b569..0f3bcb32f7287 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3304,10 +3304,13 @@ def sortlevel(self, level=0, axis=0, ascending=True, inplace=False):
new_axis, indexer = the_axis.sortlevel(level, ascending=ascending)
if self._is_mixed_type and not inplace:
- if axis == 0:
- return self.reindex(index=new_axis)
+ ax = 'index' if axis == 0 else 'columns'
+
+ if new_axis.is_unique:
+ d = { ax : new_axis }
else:
- return self.reindex(columns=new_axis)
+ d = { ax : indexer, 'takeable' : True }
+ return self.reindex(**d)
if inplace:
if axis == 1:
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 5175e01d116c0..33ea4d25bc7dc 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2165,8 +2165,17 @@ def reindex(self, target, method=None, level=None, limit=None,
if self.equals(target):
indexer = None
else:
- indexer = self.get_indexer(target, method=method,
- limit=limit)
+ if self.is_unique:
+ indexer = self.get_indexer(target, method=method,
+ limit=limit)
+ else:
+ if takeable:
+ if method is not None or limit is not None:
+ raise ValueError("cannot do a takeable reindex with "
+ "with a method or limit")
+ return self[target], target
+
+ raise Exception("cannot handle a non-takeable non-unique multi-index!")
if not isinstance(target, MultiIndex):
if indexer is None:
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index d54fc32b6efa6..7379bf5d148dc 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -1828,6 +1828,18 @@ def test_duplicate_groupby_issues(self):
result = s.groupby(s.index).first()
self.assertEquals(len(result), 3)
+ def test_duplicate_mi(self):
+ # GH 4516
+ df = DataFrame([['foo','bar',1.0,1],['foo','bar',2.0,2],['bah','bam',3.0,3],
+ ['bah','bam',4.0,4],['foo','bar',5.0,5],['bah','bam',6.0,6]],
+ columns=list('ABCD'))
+ df = df.set_index(['A','B'])
+ df = df.sortlevel(0)
+ result = df.loc[('foo','bar')]
+ expected = DataFrame([['foo','bar',1.0,1],['foo','bar',2.0,2],['foo','bar',5.0,5]],
+ columns=list('ABCD')).set_index(['A','B'])
+ assert_frame_equal(result,expected)
+
def test_multiindex_set_index(self):
# segfault in #3308
d = {'t1': [2, 2.5, 3], 't2': [4, 5, 6]}
| closes #4516
| https://api.github.com/repos/pandas-dev/pandas/pulls/4522 | 2013-08-09T13:42:27Z | 2013-08-09T14:36:39Z | 2013-08-09T14:36:39Z | 2020-11-06T03:13:44Z |
DOC: added google finance as a data source to the DataReader doc | diff --git a/pandas/io/data.py b/pandas/io/data.py
index e6d19aee4a9d6..cb9f096a1d07a 100644
--- a/pandas/io/data.py
+++ b/pandas/io/data.py
@@ -36,15 +36,15 @@ def DataReader(name, data_source=None, start=None, end=None,
"""
Imports data from a number of online sources.
- Currently supports Yahoo! finance, St. Louis FED (FRED), and Kenneth
- French's data library.
+ Currently supports Yahoo! Finance, Google Finance, St. Louis FED (FRED)
+ and Kenneth French's data library.
Parameters
----------
name : str
the name of the dataset
data_source: str
- the data source ("yahoo", "fred", or "ff")
+ the data source ("yahoo", "google", "fred", or "ff")
start : {datetime, None}
left boundary for range (defaults to 1/1/2010)
end : {datetime, None}
@@ -53,9 +53,12 @@ def DataReader(name, data_source=None, start=None, end=None,
Examples
----------
- # Data from Yahoo!
+ # Data from Yahoo! Finance
gs = DataReader("GS", "yahoo")
+ # Data from Google Finance
+ aapl = DataReader("AAPL", "google")
+
# Data from FRED
vix = DataReader("VIXCLS", "fred")
| Google Finance is already a supported data source in the source code of DataReader, but it is not reflected in the docstring.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4518 | 2013-08-09T04:12:37Z | 2013-08-09T14:26:17Z | 2013-08-09T14:26:17Z | 2014-07-02T21:24:28Z |
ENH/API: GH2578, allow ix and friends to partially set when the key is not contained in the object | diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 902a51ab03022..e3a069960ab6b 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -412,6 +412,41 @@ Pandas will detect this and raise ``IndexError``, rather than return an empty st
>>> df.iloc[:,3:6]
IndexError: out-of-bounds on slice (end)
+.. _indexing.basics.partial_setting:
+
+Setting With Enlargement
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. versionadded:: 0.13
+
+The ``.loc/.ix/[]`` operations can perform enlargement when setting a non-existant key for that axis.
+
+In the ``Series`` case this is effectively an appending operation
+
+.. ipython:: python
+
+ se = Series([1,2,3])
+ se
+ se[5] = 5.
+ se
+
+A ``DataFrame`` can be enlarged on either axis via ``.loc``
+
+.. ipython:: python
+
+ dfi = DataFrame(np.arange(6).reshape(3,2),
+ columns=['A','B'])
+ dfi
+ dfi.loc[:,'C'] = dfi.loc[:,'A']
+ dfi
+
+This is like an ``append`` operation on the ``DataFrame``.
+
+.. ipython:: python
+
+ dfi.loc[3] = 5
+ dfi
+
.. _indexing.basics.get_value:
Fast scalar value getting and setting
@@ -431,15 +466,20 @@ Similary to ``loc``, ``at`` provides **label** based scalar lookups, while, ``ia
df.at[dates[5], 'A']
df.iat[3, 0]
-You can also set using these same indexers. These have the additional
-capability of enlarging an object. This method *always* returns a reference to
-the object it modified, which in the case of enlargement, will be a **new object**:
+You can also set using these same indexers.
.. ipython:: python
df.at[dates[5], 'E'] = 7
df.iat[3, 0] = 7
+``at`` may enlarge the object in-place as above if the indexer is missing.
+
+.. ipython:: python
+
+ df.at[6, 0] = 7
+ df
+
Boolean indexing
~~~~~~~~~~~~~~~~
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 69647939ab0d0..557c4b293a84e 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -92,6 +92,9 @@ pandas 0.13
an alias of iteritems used to get around ``2to3``'s changes).
(:issue:`4384`, :issue:`4375`, :issue:`4372`)
- ``Series.get`` with negative indexers now returns the same as ``[]`` (:issue:`4390`)
+ - allow ``ix/loc`` for Series/DataFrame/Panel to set on any axis even when the single-key is not currently contained in
+ the index for that axis (:issue:`2578`)
+ - ``at`` now will enlarge the object inplace (and return the same) (:issue:`2578`)
- ``HDFStore``
@@ -296,7 +299,7 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- ``tslib.get_period_field()`` and ``tslib.get_period_field_arr()`` now raise
if code argument out of range (:issue:`4519`, :issue:`4520`)
- Fix boolean indexing on an empty series loses index names (:issue:`4235`),
- infer_dtype works with empty arrays.
+ infer_dtype works with empty arrays.
- Fix reindexing with multiple axes; if an axes match was not replacing the current axes, leading
to a possible lazay frequency inference issue (:issue:`3317`)
- Fixed issue where ``DataFrame.apply`` was reraising exceptions incorrectly
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 74cdb1ce35441..d1decc164484d 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -134,6 +134,54 @@ API changes
df1 and df2
s1 and s2
+Indexing API Changes
+~~~~~~~~~~~~~~~~~~~~
+
+ Prior to 0.13, it was impossible to use an indexer (``.loc/.iloc/.ix``) to set a value that
+ was not contained in the index of a particular axis. (:issue:`2578`). See more at :ref:`here<indexing.basics.partial_setting>`
+
+ In the ``Series`` case this is effectively an appending operation
+
+ .. ipython:: python
+
+ s = Series([1,2,3])
+ s
+ s[5] = 5.
+ s
+
+ .. ipython:: python
+
+ dfi = DataFrame(np.arange(6).reshape(3,2),
+ columns=['A','B'])
+ dfi
+
+ This would previously ``KeyError``
+
+ .. ipython:: python
+
+ dfi.loc[:,'C'] = dfi.loc[:,'A']
+ dfi
+
+ This is like an ``append`` operation.
+
+ .. ipython:: python
+
+ dfi.loc[3] = 5
+ dfi
+
+ A Panel setting operation on an arbitrary axis aligns the input to the Panel
+
+ .. ipython:: python
+
+ p = pd.Panel(np.arange(16).reshape(2,4,2),
+ items=['Item1','Item2'],
+ major_axis=pd.date_range('2001/1/12',periods=4),
+ minor_axis=['A','B'],dtype='float64')
+ p
+ p.loc[:,:,'C'] = Series([30,32],index=p.items)
+ p
+ p.loc[:,:,'C']
+
Enhancements
~~~~~~~~~~~~
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4e9f28122b43d..d184120185955 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1731,18 +1731,12 @@ def set_value(self, index, col, value):
engine.set_value(series.values, index, value)
return self
except KeyError:
- new_index, new_columns = self._expand_axes((index, col))
- result = self.reindex(index=new_index, columns=new_columns,
- copy=False)
- likely_dtype, value = _infer_dtype_from_scalar(value)
- made_bigger = not np.array_equal(new_columns, self.columns)
+ # set using a non-recursive method & reset the cache
+ self.loc[index,col] = value
+ self._item_cache.pop(col,None)
- # how to make this logic simpler?
- if made_bigger:
- com._possibly_cast_item(result, col, likely_dtype)
-
- return result.set_value(index, col, value)
+ return self
def irow(self, i, copy=False):
return self._ixs(i, axis=0)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 64760cdba60ff..856e97ad163f2 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1,7 +1,7 @@
# pylint: disable=W0223
from datetime import datetime
-from pandas.core.common import _asarray_tuplesafe
+from pandas.core.common import _asarray_tuplesafe, is_list_like
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.compat import range, zip
import pandas.compat as compat
@@ -86,28 +86,120 @@ def __setitem__(self, key, value):
if len(key) > self.ndim:
raise IndexingError('only tuples of length <= %d supported',
self.ndim)
- indexer = self._convert_tuple(key)
+ indexer = self._convert_tuple(key, is_setter=True)
else:
- indexer = self._convert_to_indexer(key)
+ indexer = self._convert_to_indexer(key, is_setter=True)
self._setitem_with_indexer(indexer, value)
def _has_valid_tuple(self, key):
pass
- def _convert_tuple(self, key):
+ def _convert_tuple(self, key, is_setter=False):
keyidx = []
for i, k in enumerate(key):
- idx = self._convert_to_indexer(k, axis=i)
+ idx = self._convert_to_indexer(k, axis=i, is_setter=is_setter)
keyidx.append(idx)
return tuple(keyidx)
+ def _has_valid_setitem_indexer(self, indexer):
+ return True
+
+ def _has_valid_positional_setitem_indexer(self, indexer):
+ """ validate that an positional indexer cannot enlarge its target
+ will raise if needed, does not modify the indexer externally """
+ if isinstance(indexer, dict):
+ raise IndexError("{0} cannot enlarge its target object".format(self.name))
+ else:
+ if not isinstance(indexer, tuple):
+ indexer = self._tuplify(indexer)
+ for ax, i in zip(self.obj.axes,indexer):
+ if isinstance(i, slice):
+ # should check the stop slice?
+ pass
+ elif is_list_like(i):
+ # should check the elements?
+ pass
+ elif com.is_integer(i):
+ if i >= len(ax):
+ raise IndexError("{0} cannot enlarge its target object".format(self.name))
+ elif isinstance(i, dict):
+ raise IndexError("{0} cannot enlarge its target object".format(self.name))
+
+ return True
+
def _setitem_with_indexer(self, indexer, value):
+ self._has_valid_setitem_indexer(indexer)
+
# also has the side effect of consolidating in-place
- # mmm, spaghetti
+ from pandas import Panel, DataFrame, Series
+
+ # maybe partial set
+ take_split_path = self.obj._is_mixed_type
+ if isinstance(indexer,tuple):
+ nindexer = []
+ for i, idx in enumerate(indexer):
+ if isinstance(idx, dict):
+
+ # reindex the axis to the new value
+ # and set inplace
+ key,_ = _convert_missing_indexer(idx)
+
+ # if this is the items axes, then take the main missing path
+ # first; this correctly sets the dtype and avoids cache issues
+ # essentially this separates out the block that is needed to possibly
+ # be modified
+ if self.ndim > 1 and i == self.obj._info_axis_number:
+
+ # add the new item, and set the value
+ new_indexer = _convert_from_missing_indexer_tuple(indexer)
+ self.obj[key] = np.nan
+ self.obj.loc[new_indexer] = value
+ return self.obj
+
+ # reindex the axis
+ index = self.obj._get_axis(i)
+ labels = _safe_append_to_index(index, key)
+ self.obj._data = self.obj.reindex_axis(labels,i)._data
+
+ nindexer.append(labels.get_loc(key))
- if self.obj._is_mixed_type:
+ else:
+ nindexer.append(idx)
+
+ indexer = tuple(nindexer)
+ else:
+
+ indexer, missing = _convert_missing_indexer(indexer)
+
+ if missing:
+
+ # reindex the axis to the new value
+ # and set inplace
+ if self.ndim == 1:
+ index = self.obj.index
+ if len(index) == 0:
+ new_index = Index([indexer])
+ else:
+ new_index = _safe_append_to_index(index, indexer)
+
+ new_values = np.concatenate([self.obj.values, [value]])
+ self.obj._data = self.obj._constructor(new_values, index=new_index, name=self.obj.name)
+ return self.obj
+
+ elif self.ndim == 2:
+ index = self.obj._get_axis(0)
+ labels = _safe_append_to_index(index, indexer)
+ self.obj._data = self.obj.reindex_axis(labels,0)._data
+ return getattr(self.obj,self.name).__setitem__(indexer,value)
+
+ # set using setitem (Panel and > dims)
+ elif self.ndim >= 3:
+ return self.obj.__setitem__(indexer,value)
+
+ # align and set the values
+ if take_split_path:
if not isinstance(indexer, tuple):
indexer = self._tuplify(indexer)
@@ -192,14 +284,73 @@ def setter(item, v):
def _align_series(self, indexer, ser):
# indexer to assign Series can be tuple or scalar
if isinstance(indexer, tuple):
+
+ aligners = [ not _is_null_slice(idx) for idx in indexer ]
+ single_aligner = sum(aligners) == 1
+ is_frame = self.obj.ndim == 2
+ is_panel = self.obj.ndim >= 3
+
+ # are we a single alignable value on a non-primary
+ # dim (e.g. panel: 1,2, or frame: 0) ?
+ # hence need to align to a single axis dimension
+ # rather that find all valid dims
+
+ # frame
+ if is_frame:
+ single_aligner = single_aligner and aligners[0]
+
+ # panel
+ elif is_panel:
+ single_aligner = single_aligner and (aligners[1] or aligners[2])
+
+ obj = self.obj
for i, idx in enumerate(indexer):
- ax = self.obj.axes[i]
+ ax = obj.axes[i]
+
+ # multiple aligners (or null slices)
if com._is_sequence(idx) or isinstance(idx, slice):
+ if single_aligner and _is_null_slice(idx):
+ continue
new_ix = ax[idx]
+ if not is_list_like(new_ix):
+ new_ix = Index([new_ix])
if ser.index.equals(new_ix):
return ser.values.copy()
return ser.reindex(new_ix).values
+ # 2 dims
+ elif single_aligner and is_frame:
+
+ # reindex along index
+ ax = self.obj.axes[1]
+ if ser.index.equals(ax):
+ return ser.values.copy()
+ return ser.reindex(ax).values
+
+ # >2 dims
+ elif single_aligner:
+
+ broadcast = []
+ for n, labels in enumerate(self.obj._get_plane_axes(i)):
+
+ # reindex along the matching dimensions
+ if len(labels & ser.index):
+ ser = ser.reindex(labels)
+ else:
+ broadcast.append((n,len(labels)))
+
+ # broadcast along other dims
+ ser = ser.values.copy()
+ for (axis,l) in broadcast:
+ shape = [ -1 ] * (len(broadcast)+1)
+ shape[axis] = l
+ ser = np.tile(ser,l).reshape(shape)
+
+ if self.obj.ndim == 3:
+ ser = ser.T
+
+ return ser
+
elif np.isscalar(indexer):
ax = self.obj._get_axis(1)
@@ -521,7 +672,7 @@ def _reindex(keys, level=None):
return result
- def _convert_to_indexer(self, obj, axis=0):
+ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
"""
Convert indexing key into something we can use to do actual fancy
indexing on an ndarray
@@ -634,12 +785,23 @@ def _convert_to_indexer(self, obj, axis=0):
mask = check == -1
if mask.any():
+
+ # mi here
+ if isinstance(obj, tuple) and is_setter:
+ return { 'key' : obj }
raise KeyError('%s not in index' % objarr[mask])
return indexer
else:
- return labels.get_loc(obj)
+ try:
+ return labels.get_loc(obj)
+ except (KeyError):
+
+ # allow a not found key only if we are a setter
+ if not is_list_like(obj) and is_setter:
+ return { 'key' : obj }
+ raise
def _tuplify(self, loc):
tup = [slice(None, None) for _ in range(self.ndim)]
@@ -828,6 +990,9 @@ def _has_valid_type(self, key, axis):
return isinstance(key, slice) or com.is_integer(key) or _is_list_like(key)
+ def _has_valid_setitem_indexer(self, indexer):
+ self._has_valid_positional_setitem_indexer(indexer)
+
def _getitem_tuple(self, tup):
self._has_valid_tuple(tup)
@@ -860,7 +1025,6 @@ def _get_slice_axis(self, slice_obj, axis=0):
return self.obj.take(slice_obj, axis=axis)
def _getitem_axis(self, key, axis=0):
-
if isinstance(key, slice):
self._has_valid_type(key,axis)
return self._get_slice_axis(key, axis=axis)
@@ -877,7 +1041,7 @@ def _getitem_axis(self, key, axis=0):
return self._get_loc(key,axis=axis)
- def _convert_to_indexer(self, obj, axis=0):
+ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
""" much simpler as we only have to deal with our valid types """
if self._has_valid_type(obj,axis):
return obj
@@ -900,14 +1064,12 @@ def __getitem__(self, key):
else:
raise ValueError('Invalid call for scalar access (getting)!')
- if len(key) != self.obj.ndim:
- raise ValueError('Not enough indexers for scalar access (getting)!')
key = self._convert_key(key)
return self.obj.get_value(*key)
def __setitem__(self, key, value):
if not isinstance(key, tuple):
- raise ValueError('Invalid call for scalar access (setting)!')
+ key = self._tuplify(key)
if len(key) != self.obj.ndim:
raise ValueError('Not enough indexers for scalar access (setting)!')
key = self._convert_key(key)
@@ -921,6 +1083,9 @@ class _AtIndexer(_ScalarAccessIndexer):
class _iAtIndexer(_ScalarAccessIndexer):
""" integer based scalar accessor """
+ def _has_valid_setitem_indexer(self, indexer):
+ self._has_valid_positional_setitem_indexer(indexer)
+
def _convert_key(self, key):
""" require integer args (and convert to label arguments) """
ckey = []
@@ -1028,6 +1193,12 @@ def _slice(self, indexer, axis=0):
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):
@@ -1053,6 +1224,34 @@ def _check_bool_indexer(ax, key):
return result
+def _convert_missing_indexer(indexer):
+ """ reverse convert a missing indexer, which is a dict
+ return the scalar indexer and a boolean indicating if we converted """
+
+ if isinstance(indexer, dict):
+
+ # a missing key (but not a tuple indexer)
+ indexer = indexer['key']
+
+ if isinstance(indexer, bool):
+ raise KeyError("cannot use a single bool to index into setitem")
+ return indexer, True
+
+ return indexer, False
+
+def _convert_from_missing_indexer_tuple(indexer):
+ """ create a filtered indexer that doesn't have any missing indexers """
+ def get_indexer(_idx):
+ return _idx['key'] if isinstance(_idx,dict) else _idx
+ return tuple([ get_indexer(_idx) for _i, _idx in enumerate(indexer) ])
+
+def _safe_append_to_index(index, key):
+ """ a safe append to an index, if incorrect type, then catch and recreate """
+ try:
+ return index.insert(len(index), key)
+ except:
+ return Index(np.concatenate([index.asobject.values,np.array([key])]))
+
def _maybe_convert_indices(indices, n):
""" if we have negative indicies, translate to postive here
if have indicies that are out-of-bounds, raise an IndexError """
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index c6af7e27070a9..d025c7a7fcf6d 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -9,7 +9,7 @@
from pandas.core.common import (_possibly_downcast_to_dtype, isnull, notnull,
_NS_DTYPE, _TD_DTYPE, ABCSeries, ABCSparseSeries,
- is_list_like)
+ is_list_like, _infer_dtype_from_scalar)
from pandas.core.index import (Index, MultiIndex, _ensure_index,
_handle_legacy_indexes)
from pandas.core.indexing import _check_slice_bounds, _maybe_convert_indices
@@ -460,6 +460,24 @@ def _try_cast_result(self, result, dtype=None):
if self.is_integer or self.is_bool or self.is_datetime:
pass
elif self.is_float and result.dtype == self.dtype:
+
+ # protect against a bool/object showing up here
+ if isinstance(dtype,compat.string_types) and dtype == 'infer':
+ return result
+ if not isinstance(dtype,type):
+ dtype = dtype.type
+ if issubclass(dtype,(np.bool_,np.object_)):
+ if issubclass(dtype,np.bool_):
+ if isnull(result).all():
+ return result.astype(np.bool_)
+ else:
+ result = result.astype(np.object_)
+ result[result==1] = True
+ result[result==0] = False
+ return result
+ else:
+ return result.astype(np.object_)
+
return result
# may need to change the dtype here
@@ -536,8 +554,12 @@ def setitem(self, indexer, value):
values[indexer] = value
# coerce and try to infer the dtypes of the result
+ if np.isscalar(value):
+ dtype,_ = _infer_dtype_from_scalar(value)
+ else:
+ dtype = 'infer'
values = self._try_coerce_result(values)
- values = self._try_cast_result(values, 'infer')
+ values = self._try_cast_result(values, dtype)
return [make_block(transf(values), self.items, self.ref_items, ndim=self.ndim, fastpath=True)]
except:
pass
@@ -902,7 +924,7 @@ def _can_hold_element(self, element):
if is_list_like(element):
element = np.array(element)
return issubclass(element.dtype.type, (np.floating, np.integer))
- return isinstance(element, (float, int))
+ return isinstance(element, (float, int, np.float_, np.int_)) and not isinstance(bool,np.bool_)
def _try_cast(self, element):
try:
@@ -2647,7 +2669,7 @@ def reindex_axis(self, new_axis, indexer=None, method=None, axis=0, fill_value=N
if method is not None or limit is not None:
return self.reindex_axis0_with_method(new_axis, indexer=indexer,
method=method, fill_value=fill_value, limit=limit, copy=copy)
- return self.reindex_items(new_axis, copy=copy, fill_value=fill_value)
+ return self.reindex_items(new_axis, indexer=indexer, copy=copy, fill_value=fill_value)
new_axis, indexer = cur_axis.reindex(
new_axis, method, copy_if_needed=True)
@@ -2709,7 +2731,7 @@ def _reindex_indexer_items(self, new_items, indexer, fill_value):
return self.__class__(new_blocks, new_axes)
- def reindex_items(self, new_items, copy=True, fill_value=None):
+ def reindex_items(self, new_items, indexer=None, copy=True, fill_value=None):
"""
"""
@@ -2719,8 +2741,8 @@ def reindex_items(self, new_items, copy=True, fill_value=None):
data = data.consolidate()
return data.reindex_items(new_items, copy=copy, fill_value=fill_value)
- # TODO: this part could be faster (!)
- new_items, indexer = self.items.reindex(new_items, copy_if_needed=True)
+ if indexer is None:
+ new_items, indexer = self.items.reindex(new_items, copy_if_needed=True)
new_axes = [new_items] + self.axes[1:]
# could have so me pathological (MultiIndex) issues here
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 3a8c0ec5e1a0f..8396de9c5997b 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1204,13 +1204,10 @@ def set_value(self, label, value):
self.index._engine.set_value(self.values, label, value)
return self
except KeyError:
- if len(self.index) == 0:
- new_index = Index([label])
- else:
- new_index = self.index.insert(len(self), label)
- new_values = np.concatenate([self.values, [value]])
- return self._constructor(new_values, index=new_index, name=self.name)
+ # set using a non-recursive method
+ self.loc[label] = value
+ return self
def reset_index(self, level=None, drop=False, name=None, inplace=False):
"""
diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py
index ba002415c1112..91f2fe319957b 100644
--- a/pandas/sparse/tests/test_sparse.py
+++ b/pandas/sparse/tests/test_sparse.py
@@ -1075,6 +1075,7 @@ def test_icol(self):
type(iframe.icol(0).sp_index))
def test_set_value(self):
+
res = self.frame.set_value('foobar', 'B', 1.5)
self.assert_(res is not self.frame)
self.assert_(res.index[-1] == 'foobar')
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index d72c379919e93..118672a85d3fb 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -866,9 +866,11 @@ def test_fancy_index_int_labels_exceptions(self):
self.assertRaises(KeyError,
self.frame.ix.__setitem__,
(slice(None, None), ['E']), 1)
- self.assertRaises(KeyError,
- self.frame.ix.__setitem__,
- (slice(None, None), 'E'), 1)
+
+ # partial setting now allows this GH2578
+ #self.assertRaises(KeyError,
+ # self.frame.ix.__setitem__,
+ # (slice(None, None), 'E'), 1)
def test_setitem_fancy_mixed_2d(self):
self.mixed_frame.ix[:5, ['C', 'B', 'A']] = 5
@@ -1481,33 +1483,54 @@ def test_set_value(self):
assert_almost_equal(self.frame[col][idx], 1)
def test_set_value_resize(self):
+
res = self.frame.set_value('foobar', 'B', 0)
- self.assert_(res is not self.frame)
+ self.assert_(res is self.frame)
self.assert_(res.index[-1] == 'foobar')
self.assertEqual(res.get_value('foobar', 'B'), 0)
- res2 = res.set_value('foobar', 'qux', 0)
- self.assert_(res2 is not res)
- self.assert_(np.array_equal(res2.columns,
- list(self.frame.columns) + ['qux']))
- self.assertEqual(res2.get_value('foobar', 'qux'), 0)
+ self.frame.loc['foobar','qux'] = 0
+ self.assertEqual(self.frame.get_value('foobar', 'qux'), 0)
+ res = self.frame.copy()
res3 = res.set_value('foobar', 'baz', 'sam')
self.assert_(res3['baz'].dtype == np.object_)
+ res = self.frame.copy()
res3 = res.set_value('foobar', 'baz', True)
self.assert_(res3['baz'].dtype == np.object_)
+ res = self.frame.copy()
res3 = res.set_value('foobar', 'baz', 5)
self.assert_(com.is_float_dtype(res3['baz']))
self.assert_(isnull(res3['baz'].drop(['foobar'])).values.all())
self.assertRaises(ValueError, res3.set_value, 'foobar', 'baz', 'sam')
def test_set_value_with_index_dtype_change(self):
- df = DataFrame(randn(3, 3), index=lrange(3), columns=list('ABC'))
- res = df.set_value('C', 2, 1.0)
- self.assert_(list(res.index) == list(df.index) + ['C'])
- self.assert_(list(res.columns) == list(df.columns) + [2])
+ df_orig = DataFrame(randn(3, 3), index=lrange(3), columns=list('ABC'))
+
+ # this is actually ambiguous as the 2 is interpreted as a positional
+ # so column is not created
+ df = df_orig.copy()
+ df.set_value('C', 2, 1.0)
+ self.assert_(list(df.index) == list(df_orig.index) + ['C'])
+ #self.assert_(list(df.columns) == list(df_orig.columns) + [2])
+
+ df = df_orig.copy()
+ df.loc['C', 2] = 1.0
+ self.assert_(list(df.index) == list(df_orig.index) + ['C'])
+ #self.assert_(list(df.columns) == list(df_orig.columns) + [2])
+
+ # create both new
+ df = df_orig.copy()
+ df.set_value('C', 'D', 1.0)
+ self.assert_(list(df.index) == list(df_orig.index) + ['C'])
+ self.assert_(list(df.columns) == list(df_orig.columns) + ['D'])
+
+ df = df_orig.copy()
+ df.loc['C', 'D'] = 1.0
+ self.assert_(list(df.index) == list(df_orig.index) + ['C'])
+ self.assert_(list(df.columns) == list(df_orig.columns) + ['D'])
def test_get_set_value_no_partial_indexing(self):
# partial w/ MultiIndex raise exception
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index da4e1e98e6b7a..66193248ffb7d 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1229,6 +1229,118 @@ def test_dups_loc(self):
result = df.loc[1]
assert_series_equal(result,expected)
+ def test_partial_setting(self):
+
+ # GH2578, allow ix and friends to partially set
+
+ ### series ###
+ s_orig = Series([1,2,3])
+
+ s = s_orig.copy()
+ s[5] = 5
+ expected = Series([1,2,3,5],index=[0,1,2,5])
+ assert_series_equal(s,expected)
+
+ s = s_orig.copy()
+ s.loc[5] = 5
+ expected = Series([1,2,3,5],index=[0,1,2,5])
+ assert_series_equal(s,expected)
+
+ s = s_orig.copy()
+ s[5] = 5.
+ expected = Series([1,2,3,5.],index=[0,1,2,5])
+ assert_series_equal(s,expected)
+
+ s = s_orig.copy()
+ s.loc[5] = 5.
+ expected = Series([1,2,3,5.],index=[0,1,2,5])
+ assert_series_equal(s,expected)
+
+ # iloc/iat raise
+ s = s_orig.copy()
+ def f():
+ s.iloc[3] = 5.
+ self.assertRaises(IndexError, f)
+ def f():
+ s.iat[3] = 5.
+ self.assertRaises(IndexError, f)
+
+ ### frame ###
+
+ df_orig = DataFrame(np.arange(6).reshape(3,2),columns=['A','B'])
+
+ # iloc/iat raise
+ df = df_orig.copy()
+ def f():
+ df.iloc[4,2] = 5.
+ self.assertRaises(IndexError, f)
+ def f():
+ df.iat[4,2] = 5.
+ self.assertRaises(IndexError, f)
+
+ # row setting where it exists
+ expected = DataFrame(dict({ 'A' : [0,4,4], 'B' : [1,5,5] }))
+ df = df_orig.copy()
+ df.iloc[1] = df.iloc[2]
+ assert_frame_equal(df,expected)
+
+ expected = DataFrame(dict({ 'A' : [0,4,4], 'B' : [1,5,5] }))
+ df = df_orig.copy()
+ df.loc[1] = df.loc[2]
+ assert_frame_equal(df,expected)
+
+ expected = DataFrame(dict({ 'A' : [0,2,4,4], 'B' : [1,3,5,5] }),dtype='float64')
+ df = df_orig.copy()
+ df.loc[3] = df.loc[2]
+ assert_frame_equal(df,expected)
+
+ # single dtype frame, overwrite
+ expected = DataFrame(dict({ 'A' : [0,2,4], 'B' : [0,2,4] }))
+ df = df_orig.copy()
+ df.ix[:,'B'] = df.ix[:,'A']
+ assert_frame_equal(df,expected)
+
+ # mixed dtype frame, overwrite
+ expected = DataFrame(dict({ 'A' : [0,2,4], 'B' : Series([0.,2.,4.]) }))
+ df = df_orig.copy()
+ df['B'] = df['B'].astype(np.float64)
+ df.ix[:,'B'] = df.ix[:,'A']
+ assert_frame_equal(df,expected)
+
+ # single dtype frame, partial setting
+ expected = df_orig.copy()
+ expected['C'] = df['A'].astype(np.float64)
+ df = df_orig.copy()
+ df.ix[:,'C'] = df.ix[:,'A']
+ assert_frame_equal(df,expected)
+
+ # mixed frame, partial setting
+ expected = df_orig.copy()
+ expected['C'] = df['A'].astype(np.float64)
+ df = df_orig.copy()
+ df.ix[:,'C'] = df.ix[:,'A']
+ assert_frame_equal(df,expected)
+
+ ### panel ###
+ p_orig = Panel(np.arange(16).reshape(2,4,2),items=['Item1','Item2'],major_axis=pd.date_range('2001/1/12',periods=4),minor_axis=['A','B'],dtype='float64')
+
+ # panel setting via item
+ p_orig = Panel(np.arange(16).reshape(2,4,2),items=['Item1','Item2'],major_axis=pd.date_range('2001/1/12',periods=4),minor_axis=['A','B'],dtype='float64')
+ expected = p_orig.copy()
+ expected['Item3'] = expected['Item1']
+ p = p_orig.copy()
+ p.loc['Item3'] = p['Item1']
+ assert_panel_equal(p,expected)
+
+ # panel with aligned series
+ expected = p_orig.copy()
+ expected = expected.transpose(2,1,0)
+ expected['C'] = DataFrame({ 'Item1' : [30,30,30,30], 'Item2' : [32,32,32,32] },index=p_orig.major_axis)
+ expected = expected.transpose(2,1,0)
+ p = p_orig.copy()
+ p.loc[:,:,'C'] = Series([30,32],index=p_orig.items)
+ assert_panel_equal(p,expected)
+
if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index c903af1860421..50d94ada7b9df 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -1400,8 +1400,10 @@ def test_getitem_lowerdim_corner(self):
self.assertRaises(KeyError, self.frame.ix.__getitem__,
(('bar', 'three'), 'B'))
- self.assertRaises(KeyError, self.frame.ix.__setitem__,
- (('bar', 'three'), 'B'), 0)
+
+ # in theory should be inserting in a sorted space????
+ self.frame.ix[('bar','three'),'B'] = 0
+ self.assert_(self.frame.sortlevel().ix[('bar','three'),'B'] == 0)
#----------------------------------------------------------------------
# AMBIGUOUS CASES!
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index b2849aeb2fbe8..282dad5c0d6be 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -851,8 +851,17 @@ def test_getitem_dups_with_missing(self):
def test_setitem_ambiguous_keyerror(self):
s = Series(lrange(10), index=lrange(0, 20, 2))
- self.assertRaises(KeyError, s.__setitem__, 1, 5)
- self.assertRaises(KeyError, s.ix.__setitem__, 1, 5)
+
+ # equivalent of an append
+ s2 = s.copy()
+ s2[1] = 5
+ expected = s.append(Series([5],index=[1]))
+ assert_series_equal(s2,expected)
+
+ s2 = s.copy()
+ s2.ix[1] = 5
+ expected = s.append(Series([5],index=[1]))
+ assert_series_equal(s2,expected)
def test_setitem_float_labels(self):
# note labels are floats
@@ -954,8 +963,10 @@ def test_setitem(self):
self.assert_((series[::2] == 0).all())
# set item that's not contained
- self.assertRaises(Exception, self.series.__setitem__,
- 'foobar', 1)
+ s = self.series.copy()
+ s['foobar'] = 1
+ expected = self.series.append(Series([1],index=['foobar']))
+ assert_series_equal(s,expected)
def test_setitem_dtypes(self):
@@ -989,11 +1000,18 @@ def test_set_value(self):
self.assert_(res is self.ts)
self.assertEqual(self.ts[idx], 0)
- res = self.series.set_value('foobar', 0)
- self.assert_(res is not self.series)
+ # equiv
+ s = self.series.copy()
+ res = s.set_value('foobar', 0)
+ self.assert_(res is s)
self.assert_(res.index[-1] == 'foobar')
self.assertEqual(res['foobar'], 0)
+ s = self.series.copy()
+ s.loc['foobar'] = 0
+ self.assert_(s.index[-1] == 'foobar')
+ self.assertEqual(s['foobar'], 0)
+
def test_setslice(self):
sl = self.ts[5:20]
self.assertEqual(len(sl), len(sl.index))
@@ -4719,33 +4737,26 @@ def test_basic_indexing(self):
self.assertRaises(IndexError, s.__setitem__, 5, 0)
self.assertRaises(KeyError, s.__getitem__, 'c')
- self.assertRaises(KeyError, s.__setitem__, 'c', 0)
s = s.sort_index()
self.assertRaises(IndexError, s.__getitem__, 5)
self.assertRaises(IndexError, s.__setitem__, 5, 0)
- self.assertRaises(KeyError, s.__getitem__, 'c')
- self.assertRaises(KeyError, s.__setitem__, 'c', 0)
def test_int_indexing(self):
s = Series(np.random.randn(6), index=[0, 0, 1, 1, 2, 2])
self.assertRaises(KeyError, s.__getitem__, 5)
- self.assertRaises(KeyError, s.__setitem__, 5, 0)
self.assertRaises(KeyError, s.__getitem__, 'c')
- self.assertRaises(KeyError, s.__setitem__, 'c', 0)
# not monotonic
s = Series(np.random.randn(6), index=[2, 2, 0, 0, 1, 1])
self.assertRaises(KeyError, s.__getitem__, 5)
- self.assertRaises(KeyError, s.__setitem__, 5, 0)
self.assertRaises(KeyError, s.__getitem__, 'c')
- self.assertRaises(KeyError, s.__setitem__, 'c', 0)
def test_datetime_indexing(self):
from pandas import date_range
@@ -4757,13 +4768,16 @@ def test_datetime_indexing(self):
stamp = Timestamp('1/8/2000')
self.assertRaises(KeyError, s.__getitem__, stamp)
- self.assertRaises(KeyError, s.__setitem__, stamp, 0)
+ s[stamp] = 0
+ self.assert_(s[stamp] == 0)
# not monotonic
+ s = Series(len(index), index=index)
s = s[::-1]
self.assertRaises(KeyError, s.__getitem__, stamp)
- self.assertRaises(KeyError, s.__setitem__, stamp, 0)
+ s[stamp] = 0
+ self.assert_(s[stamp] == 0)
def test_reset_index(self):
df = tm.makeDataFrame()[:5]
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 01f573279fe5c..5bed7777cf439 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -109,7 +109,10 @@ def test_duplicate_dates_indexing(self):
assert_series_equal(cp, expected)
self.assertRaises(KeyError, ts.__getitem__, datetime(2000, 1, 6))
- self.assertRaises(KeyError, ts.__setitem__, datetime(2000, 1, 6), 0)
+
+ # new index
+ ts[datetime(2000,1,6)] = 0
+ self.assert_(ts[datetime(2000,1,6)] == 0)
def test_range_slice(self):
idx = DatetimeIndex(['1/1/2000', '1/2/2000', '1/2/2000', '1/3/2000',
| closes #2578
On a series, this is kind of like an inplace append operation (note the dtype change - on purpose)
```
In [6]: s = Series([1,2,3])
In [7]: s[4] = 5.
In [3]: s
Out[3]:
0 1
1 2
2 3
4 5
dtype: float64
```
This is now allowed: (previously would `KeyError`), you first have to create the column `C`, then set it
```
In [1]: df = DataFrame(np.arange(6).reshape(3,2),columns=['A','B'])
In [3]: df
Out[3]:
A B
0 0 1
1 2 3
2 4 5
In [4]: df.ix[:,'C'] = df.ix[:,'A']
In [5]: df
Out[5]:
A B C
0 0 1 0
1 2 3 2
2 4 5 4
```
This would previously raise an `IndexError`
```
In [4]: df.loc[3] = 5
In [5]: df
Out[5]:
A B C
0 0 1 0
1 2 3 2
2 4 5 4
3 5 5 5
```
and on Panel:
```
In [6]: p = Panel(np.arange(16).reshape(2,4,2),
items=['Item1','Item2'],
major_axis=pd.date_range('2001/1/12',periods=4),
minor_axis=['A','B'],dtype='float64')
In [7]: p
Out[7]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 2 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
Minor_axis axis: A to B
In [10]: p.loc[:,:,'C'] = Series([30,32],index=p_orig.items)
In [11]: p
Out[11]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
Minor_axis axis: A to C
In [13]: p.loc[:,:,'C']
Out[13]:
Item1 Item2
2001-01-12 30 32
2001-01-13 30 32
2001-01-14 30 32
2001-01-15 30 32
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4515 | 2013-08-08T18:52:15Z | 2013-09-05T17:23:51Z | 2013-09-05T17:23:51Z | 2014-06-12T09:17:05Z |
BUG: read_hdf was not respecting a passed mode (GH4504) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 95ce03a858570..01d27cc113e51 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -87,8 +87,11 @@ pandas 0.13
**Bug Fixes**
- - ``HDFStore`` raising an invalid ``TypeError`` rather than ``ValueError`` when appending
- with a different block ordering (:issue:`4096`)
+ - ``HDFStore``
+
+ - raising an invalid ``TypeError`` rather than ``ValueError`` when appending
+ with a different block ordering (:issue:`4096`)
+ - ``read_hdf`` was not respecting as passed ``mode`` (:issue:`4504`)
- The ``by`` argument now works correctly with the ``layout`` argument
(:issue:`4102`, :issue:`4014`) in ``*.hist`` plotting methods
- Fixed bug in ``PeriodIndex.map`` where using ``str`` would return the str
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 4295139965f81..9990da148f8a3 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -167,8 +167,7 @@ def h5_open(path, mode):
@contextmanager
-def get_store(path, mode='a', complevel=None, complib=None,
- fletcher32=False):
+def get_store(path, **kwargs):
"""
Creates an HDFStore instance. This function can be used in a with statement
@@ -184,8 +183,7 @@ def get_store(path, mode='a', complevel=None, complib=None,
"""
store = None
try:
- store = HDFStore(path, mode=mode, complevel=complevel,
- complib=complib, fletcher32=False)
+ store = HDFStore(path, **kwargs)
yield store
finally:
if store is not None:
@@ -215,7 +213,7 @@ def read_hdf(path_or_buf, key, **kwargs):
# can't auto open/close if we are using an iterator
# so delegate to the iterator
- store = HDFStore(path_or_buf)
+ store = HDFStore(path_or_buf,**kwargs)
try:
return f(store, True)
except:
@@ -274,7 +272,7 @@ class HDFStore(StringMixin):
"""
def __init__(self, path, mode=None, complevel=None, complib=None,
- fletcher32=False):
+ fletcher32=False, **kwargs):
try:
import tables as _
except ImportError: # pragma: no cover
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 9575d99229dc4..9c09fe965a20f 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -234,6 +234,56 @@ def test_versioning(self):
store.get_node('df2')._v_attrs.pandas_version = None
self.assertRaises(Exception, store.select, 'df2')
+ def test_mode(self):
+
+ df = tm.makeTimeDataFrame()
+
+ def check(mode):
+
+ with tm.ensure_clean(self.path) as path:
+
+ # constructor
+ if mode in ['r','r+']:
+ self.assertRaises(IOError, HDFStore, path, mode=mode)
+
+ else:
+ store = HDFStore(path,mode=mode)
+ self.assert_(store._handle.mode == mode)
+ store.close()
+
+ with tm.ensure_clean(self.path) as path:
+
+ # context
+ if mode in ['r','r+']:
+ def f():
+ with get_store(path,mode=mode) as store:
+ pass
+ self.assertRaises(IOError, f)
+ else:
+ with get_store(path,mode=mode) as store:
+ self.assert_(store._handle.mode == mode)
+
+ with tm.ensure_clean(self.path) as path:
+
+ # conv write
+ if mode in ['r','r+']:
+ self.assertRaises(IOError, df.to_hdf, path, 'df', mode=mode)
+ df.to_hdf(path,'df',mode='w')
+ else:
+ df.to_hdf(path,'df',mode=mode)
+
+ # conv read
+ if mode in ['w']:
+ self.assertRaises(KeyError, read_hdf, path, 'df', mode=mode)
+ else:
+ result = read_hdf(path,'df',mode=mode)
+ assert_frame_equal(result,df)
+
+ check('r')
+ check('r+')
+ check('a')
+ check('w')
+
def test_reopen_handle(self):
with tm.ensure_clean(self.path) as path:
| closes #4504
| https://api.github.com/repos/pandas-dev/pandas/pulls/4513 | 2013-08-08T12:02:53Z | 2013-08-12T13:23:49Z | 2013-08-12T13:23:49Z | 2014-07-14T08:39:02Z |
TST: tests for GH4502, consistency in ix assignments, but ok in master | diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 385e762af424f..101cbd9d6baf8 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -2,6 +2,7 @@
import unittest
import nose
import itertools
+import warnings
from pandas.compat import range, lrange, StringIO, lmap, map
from numpy import random, nan
@@ -954,6 +955,24 @@ def test_ix_assign_column_mixed(self):
df.ix[df.x % 2 == 0, 'y'] = df.ix[df.x % 2 == 0, 'y'] * 100
assert_frame_equal(df,expected)
+ # GH 4508, making sure consistency of assignments
+ df = DataFrame({'a':[1,2,3],'b':[0,1,2]})
+ df.ix[[0,2,],'b'] = [100,-100]
+ expected = DataFrame({'a' : [1,2,3], 'b' : [100,1,-100] })
+ assert_frame_equal(df,expected)
+
+ df = pd.DataFrame({'a': lrange(4) })
+ df['b'] = np.nan
+ df.ix[[1,3],'b'] = [100,-100]
+ expected = DataFrame({'a' : [0,1,2,3], 'b' : [np.nan,100,np.nan,-100] })
+ assert_frame_equal(df,expected)
+
+ # ok, but chained assignments are dangerous
+ df = pd.DataFrame({'a': lrange(4) })
+ df['b'] = np.nan
+ df['b'].ix[[1,3]] = [100,-100]
+ assert_frame_equal(df,expected)
+
def test_iloc_mask(self):
# GH 3631, iloc with a mask (of a series) should raise
@@ -985,7 +1004,6 @@ def test_iloc_mask(self):
('locs','.iloc') : 'iLocation based boolean indexing on an integer type is not available',
}
- import warnings
warnings.filterwarnings(action='ignore', category=UserWarning)
result = dict()
for idx in [None, 'index', 'locs']:
| closes #4508 (is ok in master though), this are just tests
| https://api.github.com/repos/pandas-dev/pandas/pulls/4509 | 2013-08-07T23:20:07Z | 2013-08-07T23:35:30Z | 2013-08-07T23:35:29Z | 2014-07-16T08:22:35Z |
BUG/ER: various panel indexing fixes | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9af04a8d703cf..00309b7a3dc0d 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -129,6 +129,10 @@ pandas 0.13
(:issue:`4486`)
- Fixed an issue where cumsum and cumprod didn't work with bool dtypes
(:issue:`4170`, :issue:`4440`)
+ - Fixed Panel slicing issued in ``xs`` that was returning an incorrect dimmed object
+ (:issue:`4016`)
+ - Fixed Panel assignment with a transposed frame (:issue:`3830`)
+ - Raise on set indexing with a Panel and a Panel as a value which needs alignment (:issue:`3777`)
pandas 0.12
===========
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 4d64b058a15d7..a4d2cffc3dd23 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -100,7 +100,7 @@ def _convert_tuple(self, key):
return tuple(keyidx)
def _setitem_with_indexer(self, indexer, value):
- from pandas.core.frame import DataFrame, Series
+ from pandas import Panel, DataFrame, Series
# also has the side effect of consolidating in-place
@@ -181,6 +181,9 @@ def setter(item, v):
if isinstance(value, DataFrame):
value = self._align_frame(indexer, value)
+ if isinstance(value, Panel):
+ value = self._align_panel(indexer, value)
+
# 2096
values = self.obj.values
if np.prod(values.shape):
@@ -208,12 +211,11 @@ def _align_series(self, indexer, ser):
raise ValueError('Incompatible indexer with Series')
def _align_frame(self, indexer, df):
- from pandas import DataFrame
- is_frame = isinstance(self.obj, DataFrame)
- if not is_frame:
- df = df.T
+ is_frame = self.obj.ndim == 2
+ is_panel = self.obj.ndim >= 3
if isinstance(indexer, tuple):
idx, cols = None, None
+ sindexers = []
for i, ix in enumerate(indexer):
ax = self.obj.axes[i]
if com._is_sequence(ix) or isinstance(ix, slice):
@@ -223,6 +225,16 @@ def _align_frame(self, indexer, df):
cols = ax[ix].ravel()
else:
break
+ else:
+ sindexers.append(i)
+
+ # panel
+ if is_panel:
+ if len(sindexers) == 1 and idx is None and cols is None:
+ if sindexers[0] == 0:
+ df = df.T
+ return self.obj.conform(df,axis=sindexers[0])
+ df = df.T
if idx is not None and cols is not None:
if df.index.equals(idx) and df.columns.equals(cols):
@@ -244,12 +256,27 @@ def _align_frame(self, indexer, df):
idx = self.obj.axes[1]
cols = self.obj.axes[2]
+ # by definition we are indexing on the 0th axis
+ if is_panel:
+ df = df.T
+
if idx.equals(df.index) and cols.equals(df.columns):
return df.copy().values
+
+ # a passed in dataframe which is actually a transpose
+ # of what is needed
+ elif idx.equals(df.columns) and cols.equals(df.index):
+ return df.T.copy().values
+
return df.reindex(idx, columns=cols).values
raise ValueError('Incompatible indexer with DataFrame')
+ def _align_panel(self, indexer, df):
+ is_frame = self.obj.ndim == 2
+ is_panel = self.obj.ndim >= 3
+ raise NotImplementedError("cannot set using an indexer with a Panel yet!")
+
def _getitem_tuple(self, tup):
try:
return self._getitem_lowerdim(tup)
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index 75990e76c2b8f..d89121b1309b4 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -1048,7 +1048,7 @@ def xs(self, key, axis=1, copy=True):
self._consolidate_inplace()
axis_number = self._get_axis_number(axis)
new_data = self._data.xs(key, axis=axis_number, copy=copy)
- return self._constructor_sliced(new_data)
+ return self._construct_return_type(new_data)
_xs = xs
@@ -1263,24 +1263,33 @@ def _reduce(self, op, axis=0, skipna=True):
if result.ndim == 2 and axis_name != self._info_axis:
result = result.T
- return self._constructor_sliced(result,
+ return self._construct_return_type(result, axes)
+
+ def _construct_return_type(self, result, axes=None, **kwargs):
+ """ return the type for the ndim of the result """
+ ndim = result.ndim
+ if self.ndim == ndim:
+ """ return the construction dictionary for these axes """
+ if axes is None:
+ return self._constructor(result)
+ return self._constructor(result, **self._construct_axes_dict())
+
+ elif self.ndim == ndim + 1:
+ if axes is None:
+ return self._constructor_sliced(result)
+ return self._constructor_sliced(result,
**self._extract_axes_for_slice(self, axes))
+ raise PandasError("invalid _construct_return_type [self->%s] [result->%s]" %
+ (self.ndim, result.ndim))
+
def _wrap_result(self, result, axis):
axis = self._get_axis_name(axis)
axes = self._get_plane_axes(axis)
if result.ndim == 2 and axis != self._info_axis:
result = result.T
- # do we have reduced dimensionalility?
- if self.ndim == result.ndim:
- return self._constructor(result, **self._construct_axes_dict())
- elif self.ndim == result.ndim + 1:
- return self._constructor_sliced(result,
- **self._extract_axes_for_slice(self, axes))
-
- raise PandasError("invalid _wrap_result [self->%s] [result->%s]" %
- (self.ndim, result.ndim))
+ return self._construct_return_type(result, axes)
def count(self, axis='major'):
"""
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index f6a6bd1587a04..385e762af424f 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -873,6 +873,31 @@ def test_iloc_panel_issue(self):
self.assert_(p.iloc[1, :3, 1].shape == (3,))
self.assert_(p.iloc[:3, 1, 1].shape == (3,))
+ def test_panel_getitem(self):
+ # GH4016, date selection returns a frame when a partial string selection
+ ind = date_range(start="2000", freq="D", periods=1000)
+ df = DataFrame(np.random.randn(len(ind), 5), index=ind, columns=list('ABCDE'))
+ panel = Panel(dict([ ('frame_'+c,df) for c in list('ABC') ]))
+
+ test2 = panel.ix[:, "2002":"2002-12-31"]
+ test1 = panel.ix[:, "2002"]
+ tm.assert_panel_equal(test1,test2)
+
+ def test_panel_assignment(self):
+
+ # GH3777
+ wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D'])
+ wp2 = Panel(randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D'])
+ expected = wp.loc[['Item1', 'Item2'], :, ['A', 'B']]
+
+ def f():
+ wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']]
+ self.assertRaises(NotImplementedError, f)
+
+ #wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']]
+ #result = wp.loc[['Item1', 'Item2'], :, ['A', 'B']]
+ #tm.assert_panel_equal(result,expected)
+
def test_multi_assign(self):
# GH 3626, an assignement of a sub-df to a df
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 94afac7d9328f..3d2a5f2e58ded 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -655,6 +655,31 @@ def test_ix_frame_align(self):
out = p.ix[0, [0, 1, 3, 5], -2:]
assert_frame_equal(out, df.T.reindex([0, 1, 3, 5], p.minor_axis[-2:]))
+ # GH3830, panel assignent by values/frame
+ for dtype in ['float64','int64']:
+
+ panel = Panel(np.arange(40).reshape((2,4,5)), items=['a1','a2'], dtype=dtype)
+ df1 = panel.iloc[0]
+ df2 = panel.iloc[1]
+
+ tm.assert_frame_equal(panel.loc['a1'], df1)
+ tm.assert_frame_equal(panel.loc['a2'], df2)
+
+ # Assignment by Value Passes for 'a2'
+ panel.loc['a2'] = df1.values
+ tm.assert_frame_equal(panel.loc['a1'], df1)
+ tm.assert_frame_equal(panel.loc['a2'], df1)
+
+ # Assignment by DataFrame Ok w/o loc 'a2'
+ panel['a2'] = df2
+ tm.assert_frame_equal(panel.loc['a1'], df1)
+ tm.assert_frame_equal(panel.loc['a2'], df2)
+
+ # Assignment by DataFrame Fails for 'a2'
+ panel.loc['a2'] = df2
+ tm.assert_frame_equal(panel.loc['a1'], df1)
+ tm.assert_frame_equal(panel.loc['a2'], df2)
+
def _check_view(self, indexer, comp):
cp = self.panel.copy()
obj = cp.ix[indexer]
| - ER: #3777, raise a `NotImplementedError` for `Panel` -> `Panel` setting with alignment (issue will still be open though)
- BUG: closes #3830, panel assignment using loc with a transpose frame did not work
- BUG: closes #4016 fix panel slicing issue that was returning an object that should not have be a reduction in ndim
| https://api.github.com/repos/pandas-dev/pandas/pulls/4507 | 2013-08-07T19:18:42Z | 2013-08-07T20:20:41Z | 2013-08-07T20:20:41Z | 2014-06-25T04:37:54Z |
ENH add bins argument to value_counts | diff --git a/doc/source/release.rst b/doc/source/release.rst
index b301dcb80445a..dc8b05a97b75a 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -41,6 +41,8 @@ pandas 0.13
- ``read_excel`` now supports an integer in its ``sheetname`` argument giving
the index of the sheet to read in (:issue:`4301`).
- Added a test for ``read_clipboard()`` and ``to_clipboard()`` (:issue:`4282`)
+ - Added bins argument to ``value_counts`` (:issue:`3945`), also sort and
+ ascending, now available in Series method as well as top-level function.
- Text parser now treats anything that reads like inf ("inf", "Inf", "-Inf",
"iNf", etc.) to infinity. (:issue:`4220`, :issue:`4219`), affecting
``read_table``, ``read_csv``, etc.
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index f1d78dc34957b..f6b1131120aa6 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -148,7 +148,7 @@ def factorize(values, sort=False, order=None, na_sentinel=-1):
return labels, uniques
-def value_counts(values, sort=True, ascending=False, normalize=False):
+def value_counts(values, sort=True, ascending=False, normalize=False, bins=None):
"""
Compute a histogram of the counts of non-null values
@@ -161,26 +161,39 @@ def value_counts(values, sort=True, ascending=False, normalize=False):
Sort in ascending order
normalize: boolean, default False
If True then compute a relative histogram
+ bins : integer, optional
+ Rather than count values, group them into half-open bins,
+ convenience for pd.cut, only works with numeric data
Returns
-------
value_counts : Series
+
"""
from pandas.core.series import Series
+ from pandas.tools.tile import cut
+
+ values = Series(values).values
- values = np.asarray(values)
+ if bins is not None:
+ try:
+ cat, bins = cut(values, bins, retbins=True)
+ except TypeError:
+ raise TypeError("bins argument only works with numeric data.")
+ values = cat.labels
if com.is_integer_dtype(values.dtype):
values = com._ensure_int64(values)
keys, counts = htable.value_count_int64(values)
- elif issubclass(values.dtype.type, (np.datetime64,np.timedelta64)):
+ elif issubclass(values.dtype.type, (np.datetime64,np.timedelta64)):
dtype = values.dtype
values = values.view(np.int64)
keys, counts = htable.value_count_int64(values)
# convert the keys back to the dtype we came in
- keys = Series(keys,dtype=dtype)
+ keys = Series(keys, dtype=dtype)
+
else:
mask = com.isnull(values)
values = com._ensure_object(values)
@@ -188,6 +201,11 @@ def value_counts(values, sort=True, ascending=False, normalize=False):
result = Series(counts, index=com._values_from_object(keys))
+ if bins is not None:
+ # TODO: This next line should be more efficient
+ result = result.reindex(np.arange(len(cat.levels)), fill_value=0)
+ result.index = bins[:-1]
+
if sort:
result.sort()
if not ascending:
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index b25a027adedd9..b085738018950 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -6,7 +6,6 @@
from pandas.core.base import PandasObject
from pandas.core.index import Index
import pandas.core.common as com
-from pandas.core.frame import DataFrame
def _cat_compare_op(op):
@@ -182,6 +181,7 @@ def describe(self):
Returns a dataframe with frequency and counts by level.
"""
#Hack?
+ from pandas.core.frame import DataFrame
grouped = DataFrame(self.labels).groupby(0)
counts = grouped.count().values.squeeze()
freqs = counts/float(counts.sum())
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 050a9de2b23dc..ad4295d05fca7 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -27,6 +27,7 @@
_is_index_slice, _maybe_convert_indices)
from pandas.core import generic
from pandas.core.internals import SingleBlockManager
+from pandas.core.categorical import Categorical
import pandas.core.expressions as expressions
from pandas.tseries.index import DatetimeIndex
from pandas.tseries.period import PeriodIndex, Period
@@ -579,6 +580,10 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
index = data.index
else:
data = data.reindex(index, copy=copy)
+ elif isinstance(data, Categorical):
+ if name is None:
+ name = data.name
+ data = np.asarray(data)
elif isinstance(data, types.GeneratorType):
data = list(data)
elif isinstance(data, (set, frozenset)):
@@ -1525,7 +1530,7 @@ def count(self, level=None):
return notnull(_values_from_object(self)).sum()
- def value_counts(self, normalize=False):
+ def value_counts(self, normalize=False, sort=True, ascending=False, bins=None):
"""
Returns Series containing counts of unique values. The resulting Series
will be in descending order so that the first element is the most
@@ -1536,14 +1541,21 @@ def value_counts(self, normalize=False):
normalize: boolean, default False
If True then the Series returned will contain the relative
frequencies of the unique values.
+ sort : boolean, default True
+ Sort by values
+ ascending : boolean, default False
+ Sort in ascending order
+ bins : integer, optional
+ Rather than count values, group them into half-open bins,
+ a convenience for pd.cut, only works with numeric data
Returns
-------
counts : Series
"""
from pandas.core.algorithms import value_counts
- return value_counts(self.values, sort=True, ascending=False,
- normalize=normalize)
+ return value_counts(self.values, sort=sort, ascending=ascending,
+ normalize=normalize, bins=bins)
def unique(self):
"""
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index d0a050984a07f..6458d7c31d689 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -3,7 +3,7 @@
import numpy as np
-from pandas.core.api import Series
+from pandas.core.api import Series, Categorical
import pandas as pd
import pandas.core.algorithms as algos
@@ -63,6 +63,44 @@ def test_on_index_object(self):
tm.assert_almost_equal(result, expected)
+class TestValueCounts(unittest.TestCase):
+ _multiprocess_can_split_ = True
+
+ def test_value_counts(self):
+ from pandas.tools.tile import cut
+
+ arr = np.random.randn(4)
+ factor = cut(arr, 4)
+
+ tm.assert_isinstance(factor, Categorical)
+
+ result = algos.value_counts(factor)
+ expected = algos.value_counts(np.asarray(factor))
+ tm.assert_series_equal(result, expected)
+
+ def test_value_counts_bins(self):
+ s = [1, 2, 3, 4]
+ result = algos.value_counts(s, bins=1)
+ self.assertEqual(result.tolist(), [4])
+ self.assertEqual(result.index[0], 0.997)
+
+ result = algos.value_counts(s, bins=2, sort=False)
+ self.assertEqual(result.tolist(), [2, 2])
+ self.assertEqual(result.index[0], 0.997)
+ self.assertEqual(result.index[1], 2.5)
+
+ def test_value_counts_dtypes(self):
+ result = algos.value_counts([1, 1.])
+ self.assertEqual(len(result), 1)
+
+ result = algos.value_counts([1, 1.], bins=1)
+ self.assertEqual(len(result), 1)
+
+ result = algos.value_counts(Series([1, 1., '1'])) # object
+ self.assertEqual(len(result), 2)
+
+ self.assertRaises(TypeError, lambda s: algos.value_counts(s, bins=1), ['1', 1])
+
def test_quantile():
s = Series(np.random.randn(100))
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 29d104e9c465c..71e9f36c26e70 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -7,7 +7,6 @@
import numpy as np
-from pandas.core.api import value_counts
from pandas.core.categorical import Categorical
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.frame import DataFrame
@@ -89,18 +88,6 @@ def test_comparisons(self):
expected = np.repeat(False, len(self.factor))
self.assert_(np.array_equal(result, expected))
- def test_value_counts(self):
- from pandas.tools.tile import cut
-
- arr = np.random.randn(4)
- factor = cut(arr, 4)
-
- tm.assert_isinstance(factor, Categorical)
-
- result = value_counts(factor)
- expected = value_counts(np.asarray(factor))
- tm.assert_series_equal(result, expected)
-
def test_na_flags_int_levels(self):
# #1457
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index e0780e8674600..3599d3a9a9ac0 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -371,6 +371,16 @@ def test_constructor_generator(self):
exp.index = lrange(10, 20)
assert_series_equal(result, exp)
+ def test_constructor_categorical(self):
+ cat = pd.Categorical([0, 1, 2, 0, 1, 2], ['a', 'b', 'c'])
+ res = Series(cat)
+ exp = Series({0: 'a', 1: 'b', 2: 'c', 3: 'a', 4: 'b', 5: 'c'})
+ assert_series_equal(res, exp)
+
+ cat.name = 'foo'
+ res = Series(cat)
+ self.assertEqual(res.name, cat.name)
+
def test_constructor_maskedarray(self):
data = ma.masked_all((3,), dtype=float)
result = Series(data)
@@ -2966,6 +2976,18 @@ def test_value_counts_nunique(self):
expected = Series([4, 3, 2, 1], index=['b', 'a', 'd', 'c'])
assert_series_equal(hist, expected)
+ # don't sort, have to sort after the fact as not sorting is platform-dep
+ hist = s.value_counts(sort=False)
+ hist.sort()
+ expected = Series([3, 1, 4, 2], index=list('acbd'))
+ expected.sort()
+ assert_series_equal(hist, expected)
+
+ # sort ascending
+ hist = s.value_counts(ascending=True)
+ expected = Series([1, 2, 3, 4], index=list('cdab'))
+ assert_series_equal(hist, expected)
+
# relative histogram.
hist = s.value_counts(normalize=True)
expected = Series([.4, .3, .2, .1], index=['b', 'a', 'd', 'c'])
@@ -2973,6 +2995,24 @@ def test_value_counts_nunique(self):
self.assertEquals(s.nunique(), 4)
+ # bins
+ self.assertRaises(TypeError, lambda bins: s.value_counts(bins=bins), 1)
+
+ s1 = Series([1, 1, 2, 3])
+ res1 = s1.value_counts(bins=1)
+ exp1 = Series({0.998: 4})
+ assert_series_equal(res1, exp1)
+ res1n = s1.value_counts(bins=1, normalize=True)
+ exp1n = Series({0.998: 1.0})
+ assert_series_equal(res1n, exp1n)
+
+ res4 = s1.value_counts(bins=4)
+ exp4 = Series({0.998: 2, 1.5: 1, 2.0: 0, 2.5: 1}, index=[0.998, 2.5, 1.5, 2.0])
+ assert_series_equal(res4, exp4)
+ res4n = s1.value_counts(bins=4, normalize=True)
+ exp4n = Series({0.998: 0.5, 1.5: 0.25, 2.0: 0.0, 2.5: 0.25}, index=[0.998, 2.5, 1.5, 2.0])
+ assert_series_equal(res4n, exp4n)
+
# handle NA's properly
s[5:7] = np.nan
hist = s.value_counts()
| fixes #3945
Also, adds arguments present in top-level function to the Series
method (sort and ascending).
Note: this only works with numeric data (it raises a TypeError if there was a TypeError problem in cut, however perhaps cut should raise a more descirptive error...)
```
In [1]: s = pd.Series(np.random.randn(100))
In [2]: s.value_counts(bins=4)
Out[2]:
0.017354 44
-1.154431 35
1.189140 14
-2.330904 7
dtype: int64
In [3]: s.value_counts(bins=4, normalize=True) # also works with sort and ascending arguments.
Out[3]:
0.017354 0.44
-1.154431 0.35
1.189140 0.14
-2.330904 0.07
dtype: float64
In [11]: s = pd.Series(list('abc'))
In [12]: s.value_counts(bins=1)
TypeError: bins argument only works with numeric data.
```
_Note: Have a test failing on python3 (topically) a sorting one_.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4502 | 2013-08-07T15:34:27Z | 2013-08-27T00:07:49Z | 2013-08-27T00:07:49Z | 2014-07-07T06:28:32Z |
DOC: fix conflicting ewma documentation | diff --git a/doc/source/computation.rst b/doc/source/computation.rst
index eca5bf902aa39..207e2796c468d 100644
--- a/doc/source/computation.rst
+++ b/doc/source/computation.rst
@@ -450,7 +450,7 @@ average as
.. math::
- y_t = \alpha y_{t-1} + (1 - \alpha) x_t
+ y_t = (1 - \alpha) y_{t-1} + \alpha x_t
One must have :math:`0 < \alpha \leq 1`, but rather than pass :math:`\alpha`
directly, it's easier to think about either the **span** or **center of mass
@@ -461,9 +461,19 @@ directly, it's easier to think about either the **span** or **center of mass
\alpha =
\begin{cases}
\frac{2}{s + 1}, s = \text{span}\\
- \frac{1}{c + 1}, c = \text{center of mass}
+ \frac{1}{1 + c}, c = \text{center of mass}
\end{cases}
+.. note::
+
+ the equation above is sometimes written in the form
+
+ .. math::
+
+ y_t = \alpha' y_{t-1} + (1 - \alpha') x_t
+
+ where :math:`\alpha' = 1 - \alpha`.
+
You can pass one or the other to these functions but not both. **Span**
corresponds to what is commonly called a "20-day EW moving average" for
example. **Center of mass** has a more physical interpretation. For example,
diff --git a/pandas/stats/moments.py b/pandas/stats/moments.py
index c3f4c8b3cd604..fd81bd119fe09 100644
--- a/pandas/stats/moments.py
+++ b/pandas/stats/moments.py
@@ -56,9 +56,9 @@
----------
%s
com : float. optional
- Center of mass: \alpha = com / (1 + com),
+ Center of mass: :math:`\alpha = 1 / (1 + com)`,
span : float, optional
- Specify decay in terms of span, \alpha = 2 / (span + 1)
+ Specify decay in terms of span, :math:`\alpha = 2 / (span + 1)`
min_periods : int, default 0
Number of observations in sample to require (only affects
beginning)
@@ -75,8 +75,8 @@
Either center of mass or span must be specified
EWMA is sometimes specified using a "span" parameter s, we have have that the
-decay parameter \alpha is related to the span as
-:math:`\alpha = 1 - 2 / (s + 1) = c / (1 + c)`
+decay parameter :math:`\alpha` is related to the span as
+:math:`\alpha = 2 / (s + 1) = 1 / (1 + c)`
where c is the center of mass. Given a span, the associated center of mass is
:math:`c = (s - 1) / 2`
| The information in the docs, in the parameter description and in the body of the docstring is conflicting. This should hopefully make them consistent amongst themselves (and with the code).
| https://api.github.com/repos/pandas-dev/pandas/pulls/4499 | 2013-08-07T13:10:33Z | 2013-08-22T10:16:05Z | 2013-08-22T10:16:05Z | 2014-07-02T21:24:28Z |
JSON native support for datetime encoding | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 4cee1f7d9510b..ba68943f1324a 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1034,11 +1034,12 @@ with optional parameters:
``columns``; dict like {column -> {index -> value}}
``values``; just the values array
-- ``date_format`` : type of date conversion (epoch = epoch milliseconds, iso = ISO8601), default is epoch
+- ``date_format`` : string, type of date conversion, 'epoch' for timestamp, 'iso' for ISO8601.
- ``double_precision`` : The number of decimal places to use when encoding floating point values, default 10.
- ``force_ascii`` : force encoded string to be ASCII, default True.
+- ``date_unit`` : The time unit to encode to, governs timestamp and ISO8601 precision. One of 's', 'ms', 'us' or 'ns' for seconds, milliseconds, microseconds and nanoseconds respectively. Default 'ms'.
-Note NaN's and None will be converted to null and datetime objects will be converted based on the date_format parameter
+Note NaN's, NaT's and None will be converted to null and datetime objects will be converted based on the date_format and date_unit parameters.
.. ipython:: python
@@ -1055,6 +1056,20 @@ Writing in iso date format
json = dfd.to_json(date_format='iso')
json
+Writing in iso date format, with microseconds
+
+.. ipython:: python
+
+ json = dfd.to_json(date_format='iso', date_unit='us')
+ json
+
+Actually I prefer epoch timestamps, in seconds
+
+.. ipython:: python
+
+ json = dfd.to_json(date_format='epoch', date_unit='s')
+ json
+
Writing to a file, with a date index and a date column
.. ipython:: python
@@ -1063,7 +1078,7 @@ Writing to a file, with a date index and a date column
dfj2['date'] = Timestamp('20130101')
dfj2['ints'] = list(range(5))
dfj2['bools'] = True
- dfj2.index = date_range('20130101',periods=5)
+ dfj2.index = date_range('20130101', periods=5)
dfj2.to_json('test.json')
open('test.json').read()
@@ -1107,16 +1122,22 @@ is ``None``. To explicity force ``Series`` parsing, pass ``typ=series``
- ``keep_default_dates`` : boolean, default True. If parsing dates, then parse the default datelike columns
- ``numpy`` : direct decoding to numpy arrays. default is False;
Note that the JSON ordering **MUST** be the same for each term if ``numpy=True``
-- ``precise_float`` : boolean, default ``False``. Set to enable usage of higher precision (strtod) function
- when decoding string to double values. Default (``False``) is to use fast but less precise builtin functionality
+- ``precise_float`` : boolean, default ``False``. Set to enable usage of higher precision (strtod) function when decoding string to double values. Default (``False``) is to use fast but less precise builtin functionality
+- ``date_unit`` : string, the timestamp unit to detect if converting dates. Default
+ None. By default the timestamp precision will be detected, if this is not desired
+ then pass one of 's', 'ms', 'us' or 'ns' to force timestamp precision to
+ seconds, milliseconds, microseconds or nanoseconds respectively.
-The parser will raise one of ``ValueError/TypeError/AssertionError`` if the JSON is
-not parsable.
+The parser will raise one of ``ValueError/TypeError/AssertionError`` if the JSON is not parsable.
The default of ``convert_axes=True``, ``dtype=True``, and ``convert_dates=True`` will try to parse the axes, and all of the data
into appropriate types, including dates. If you need to override specific dtypes, pass a dict to ``dtype``. ``convert_axes`` should only
be set to ``False`` if you need to preserve string-like numbers (e.g. '1', '2') in an axes.
+.. note::
+
+ Large integer values may be converted to dates if ``convert_dates=True`` and the data and / or column labels appear 'date-like'. The exact threshold depends on the ``date_unit`` specified.
+
.. warning::
When reading JSON data, automatic coercing into dtypes has some quirks:
@@ -1143,13 +1164,13 @@ Don't convert any data (but still convert axes and dates)
.. ipython:: python
- pd.read_json('test.json',dtype=object).dtypes
+ pd.read_json('test.json', dtype=object).dtypes
Specify how I want to convert data
.. ipython:: python
- pd.read_json('test.json',dtype={'A' : 'float32', 'bools' : 'int8'}).dtypes
+ pd.read_json('test.json', dtype={'A' : 'float32', 'bools' : 'int8'}).dtypes
I like my string indicies
@@ -1163,11 +1184,30 @@ I like my string indicies
si.columns
json = si.to_json()
- sij = pd.read_json(json,convert_axes=False)
+ sij = pd.read_json(json, convert_axes=False)
sij
sij.index
sij.columns
+My dates have been written in nanoseconds, so they need to be read back in
+nanoseconds
+
+.. ipython:: python
+
+ json = dfj2.to_json(date_unit='ns')
+
+ # Try to parse timestamps as millseconds -> Won't Work
+ dfju = pd.read_json(json, date_unit='ms')
+ dfju
+
+ # Let Pandas detect the correct precision
+ dfju = pd.read_json(json)
+ dfju
+
+ # Or specify that all timestamps are in nanoseconds
+ dfju = pd.read_json(json, date_unit='ns')
+ dfju
+
.. ipython:: python
:suppress:
diff --git a/doc/source/release.rst b/doc/source/release.rst
index e0532b6be136f..b1dfff6988cc3 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -47,6 +47,7 @@ pandas 0.13
- Added a more informative error message when plot arguments contain
overlapping color and style arguments (:issue:`4402`)
- Significant table writing performance improvements in ``HDFStore``
+ - JSON date serialisation now performed in low-level C code.
- ``Index.copy()`` and ``MultiIndex.copy()`` now accept keyword arguments to
change attributes (i.e., ``names``, ``levels``, ``labels``)
(:issue:`4039`)
@@ -94,6 +95,10 @@ pandas 0.13
- removed the ``warn`` argument from ``open``. Instead a ``PossibleDataLossError`` exception will
be raised if you try to use ``mode='w'`` with an OPEN file handle (:issue:`4367`)
- allow a passed locations array or mask as a ``where`` condition (:issue:`4467`)
+ - ``JSON``
+
+ - added ``date_unit`` parameter to specify resolution of timestamps. Options
+ are seconds, milliseconds, microseconds and nanoseconds. (:issue:`4362`, :issue:`4498`).
- ``Index`` and ``MultiIndex`` changes (:issue:`4039`):
@@ -134,6 +139,9 @@ pandas 0.13
local variable was undefined (:issue:`4381`)
- In ``to_json``, raise if a passed ``orient`` would cause loss of data because
of a duplicate index (:issue:`4359`)
+ - In ``to_json``, fix date handling so milliseconds are the default timestamp
+ as the docstring says (:issue:`4362`).
+ - JSON NaT handling fixed, NaTs are now serialised to `null` (:issue:`4498`)
- Fixed passing ``keep_default_na=False`` when ``na_values=None`` (:issue:`4318`)
- Fixed bug with ``values`` raising an error on a DataFrame with duplicate columns and mixed
dtypes, surfaced in (:issue:`4377`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 2ee7f791c671f..ece7d460c0d33 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -535,7 +535,7 @@ def to_clipboard(self):
clipboard.to_clipboard(self)
def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
- double_precision=10, force_ascii=True):
+ double_precision=10, force_ascii=True, date_unit='ms'):
"""
Convert the object to a JSON string.
@@ -566,11 +566,15 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
- columns : dict like {column -> {index -> value}}
- values : just the values array
- date_format : type of date conversion (epoch = epoch milliseconds, iso = ISO8601)
- default is epoch
+ date_format : string, default 'epoch'
+ type of date conversion, 'epoch' for timestamp, 'iso' for ISO8601
double_precision : The number of decimal places to use when encoding
floating point values, default 10.
force_ascii : force encoded string to be ASCII, default True.
+ date_unit : string, default 'ms' (milliseconds)
+ The time unit to encode to, governs timestamp and ISO8601
+ precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,
+ microsecond, and nanosecond respectively.
Returns
-------
@@ -580,8 +584,13 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
"""
from pandas.io import json
- return json.to_json(path_or_buf=path_or_buf, obj=self, orient=orient, date_format=date_format,
- double_precision=double_precision, force_ascii=force_ascii)
+ return json.to_json(
+ path_or_buf=path_or_buf,
+ obj=self, orient=orient,
+ date_format=date_format,
+ double_precision=double_precision,
+ force_ascii=force_ascii,
+ date_unit=date_unit)
# install the indexerse
for _name, _indexer in indexing.get_indexers_list():
diff --git a/pandas/io/json.py b/pandas/io/json.py
index 78d1bc83d6107..0c4f193ad253b 100644
--- a/pandas/io/json.py
+++ b/pandas/io/json.py
@@ -1,43 +1,51 @@
-
# pylint: disable-msg=E1101,W0613,W0603
-from pandas.compat import StringIO, long
-from pandas import compat
import os
+import numpy as np
+
+import pandas.json as _json
+from pandas.tslib import iNaT
+from pandas.compat import long
+from pandas import compat, isnull
from pandas import Series, DataFrame, to_datetime
from pandas.io.common import get_filepath_or_buffer
-import pandas.json as _json
+
loads = _json.loads
dumps = _json.dumps
-import numpy as np
-from pandas.tslib import iNaT
-import pandas.lib as lib
### interface to/from ###
-def to_json(path_or_buf, obj, orient=None, date_format='epoch', double_precision=10, force_ascii=True):
+
+def to_json(path_or_buf, obj, orient=None, date_format='epoch',
+ double_precision=10, force_ascii=True, date_unit='ms'):
if isinstance(obj, Series):
- s = SeriesWriter(obj, orient=orient, date_format=date_format, double_precision=double_precision,
- ensure_ascii=force_ascii).write()
+ s = SeriesWriter(
+ obj, orient=orient, date_format=date_format,
+ double_precision=double_precision, ensure_ascii=force_ascii,
+ date_unit=date_unit).write()
elif isinstance(obj, DataFrame):
- s = FrameWriter(obj, orient=orient, date_format=date_format, double_precision=double_precision,
- ensure_ascii=force_ascii).write()
+ s = FrameWriter(
+ obj, orient=orient, date_format=date_format,
+ double_precision=double_precision, ensure_ascii=force_ascii,
+ date_unit=date_unit).write()
else:
raise NotImplementedError
if isinstance(path_or_buf, compat.string_types):
- with open(path_or_buf,'w') as fh:
+ with open(path_or_buf, 'w') as fh:
fh.write(s)
elif path_or_buf is None:
return s
else:
path_or_buf.write(s)
+
class Writer(object):
- def __init__(self, obj, orient, date_format, double_precision, ensure_ascii):
+ def __init__(self, obj, orient, date_format, double_precision,
+ ensure_ascii, date_unit):
self.obj = obj
if orient is None:
@@ -47,38 +55,23 @@ def __init__(self, obj, orient, date_format, double_precision, ensure_ascii):
self.date_format = date_format
self.double_precision = double_precision
self.ensure_ascii = ensure_ascii
+ self.date_unit = date_unit
self.is_copy = False
self._format_axes()
- self._format_dates()
-
- def _needs_to_date(self, obj):
- return obj.dtype == 'datetime64[ns]'
-
- def _format_dates(self):
- raise NotImplementedError
def _format_axes(self):
raise NotImplementedError
- def _format_to_date(self, data):
-
- # iso
- if self.date_format == 'iso':
- return data.apply(lambda x: x.isoformat())
-
- # int64
- else:
- return data.astype(np.int64)
-
- def copy_if_needed(self):
- """ copy myself if necessary """
- if not self.is_copy:
- self.obj = self.obj.copy()
- self.is_copy = True
-
def write(self):
- return dumps(self.obj, orient=self.orient, double_precision=self.double_precision, ensure_ascii=self.ensure_ascii)
+ return dumps(
+ self.obj,
+ orient=self.orient,
+ double_precision=self.double_precision,
+ ensure_ascii=self.ensure_ascii,
+ date_unit=self.date_unit,
+ iso_dates=self.date_format == 'iso')
+
class SeriesWriter(Writer):
_default_orient = 'index'
@@ -87,17 +80,7 @@ def _format_axes(self):
if not self.obj.index.is_unique and self.orient == 'index':
raise ValueError("Series index must be unique for orient="
"'%s'" % self.orient)
- if self._needs_to_date(self.obj.index):
- self.copy_if_needed()
- self.obj.index = self._format_to_date(self.obj.index.to_series())
- def _format_dates(self):
- if self.obj.dtype == 'datetime64[ns]':
- self.obj = self._format_to_date(self.obj)
-
- def _format_bools(self):
- if self._needs_to_bool(self.obj):
- self.obj = self._format_to_bool(self.obj)
class FrameWriter(Writer):
_default_orient = 'columns'
@@ -113,48 +96,19 @@ def _format_axes(self):
raise ValueError("DataFrame columns must be unique for orient="
"'%s'." % self.orient)
- if self.orient == 'columns':
- axis = 'index'
- elif self.orient == 'index':
- axis = 'columns'
- else:
- return
-
- a = getattr(self.obj,axis)
- if self._needs_to_date(a):
- self.copy_if_needed()
- setattr(self.obj,axis,self._format_to_date(a.to_series()))
-
- def _format_dates(self):
- dtypes = self.obj.dtypes
- if len(dtypes[dtypes == 'datetime64[ns]']):
-
- # need to create a new object
- d = {}
-
- for i, (col, c) in enumerate(self.obj.iteritems()):
-
- if c.dtype == 'datetime64[ns]':
- c = self._format_to_date(c)
-
- d[i] = c
-
- d = DataFrame(d,index=self.obj.index)
- d.columns = self.obj.columns
- self.obj = d
def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
convert_axes=True, convert_dates=True, keep_default_dates=True,
- numpy=False, precise_float=False):
+ numpy=False, precise_float=False, date_unit=None):
"""
Convert JSON string to pandas object
Parameters
----------
- filepath_or_buffer : a VALID JSON string or file handle / StringIO. 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
+ filepath_or_buffer : a VALID JSON string or file handle / StringIO. The
+ string could be a URL. Valid URL schemes include http, ftp, s3, and
+ file. For file URLs, a host is expected. For instance, a local file
+ could be file ://localhost/path/to/table.json
orient :
Series :
default is 'index'
@@ -169,35 +123,46 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
and 'records'.
The format of the JSON string
- split : dict like {index -> [index], columns -> [columns], data -> [values]}
+ split : dict like
+ {index -> [index], columns -> [columns], data -> [values]}
records : list like [{column -> value}, ... , {column -> value}]
index : dict like {index -> {column -> value}}
columns : dict like {column -> {index -> value}}
values : just the values array
typ : type of object to recover (series or frame), default 'frame'
- dtype : if True, infer dtypes, if a dict of column to dtype, then use those,
- if False, then don't infer dtypes at all, default is True,
- apply only to the data
- convert_axes : boolean, try to convert the axes to the proper dtypes, default is True
- convert_dates : a list of columns to parse for dates; If True, then try to parse datelike columns
- default is True
- keep_default_dates : boolean, default True. If parsing dates,
- then parse the default datelike columns
- numpy : direct decoding to numpy arrays. default is False.Note that the JSON ordering MUST be the same
- for each term if numpy=True.
- precise_float : boolean, default False. Set to enable usage of higher precision (strtod) function
- when decoding string to double values. Default (False) is to use fast but less precise builtin functionality
+ dtype : boolean or dict, default True
+ If True, infer dtypes, if a dict of column to dtype, then use those,
+ if False, then don't infer dtypes at all, applies only to the data.
+ convert_axes : boolean, default True
+ Try to convert the axes to the proper dtypes.
+ convert_dates : boolean, default True
+ List of columns to parse for dates; If True, then try to parse
+ datelike columns default is True
+ keep_default_dates : boolean, default True.
+ If parsing dates, then parse the default datelike columns
+ numpy : boolean, default False
+ Direct decoding to numpy arrays. Note that the JSON ordering MUST be
+ the same for each term if numpy=True.
+ precise_float : boolean, default False.
+ Set to enable usage of higher precision (strtod) function when
+ decoding string to double values. Default (False) is to use fast but
+ less precise builtin functionality
+ date_unit : string, default None
+ The timestamp unit to detect if converting dates. The default behaviour
+ is to try and detect the correct precision, but if this is not desired
+ then pass one of 's', 'ms', 'us' or 'ns' to force parsing only seconds,
+ milliseconds, microseconds or nanoseconds respectively.
Returns
-------
result : Series or DataFrame
"""
- filepath_or_buffer,_ = get_filepath_or_buffer(path_or_buf)
+ 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):
- with open(filepath_or_buffer,'r') as fh:
+ with open(filepath_or_buffer, 'r') as fh:
json = fh.read()
else:
json = filepath_or_buffer
@@ -208,20 +173,32 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
obj = None
if typ == 'frame':
- obj = FrameParser(json, orient, dtype, convert_axes, convert_dates, keep_default_dates, numpy).parse()
+ obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
+ keep_default_dates, numpy, precise_float,
+ date_unit).parse()
if typ == 'series' or obj is None:
- if not isinstance(dtype,bool):
- dtype = dict(data = dtype)
- obj = SeriesParser(json, orient, dtype, convert_axes, convert_dates, keep_default_dates, numpy).parse()
+ if not isinstance(dtype, bool):
+ dtype = dict(data=dtype)
+ obj = SeriesParser(json, orient, dtype, convert_axes, convert_dates,
+ keep_default_dates, numpy, precise_float,
+ date_unit).parse()
return obj
+
class Parser(object):
+ _STAMP_UNITS = ('s', 'ms', 'us', 'ns')
+ _MIN_STAMPS = {
+ 's': long(31536000),
+ 'ms': long(31536000000),
+ 'us': long(31536000000000),
+ 'ns': long(31536000000000000)}
+
def __init__(self, json, orient, dtype=True, convert_axes=True,
convert_dates=True, keep_default_dates=False, numpy=False,
- precise_float=False):
+ precise_float=False, date_unit=None):
self.json = json
if orient is None:
@@ -233,10 +210,20 @@ def __init__(self, json, orient, dtype=True, convert_axes=True,
if orient == "split":
numpy = False
+ if date_unit is not None:
+ date_unit = date_unit.lower()
+ if date_unit not in self._STAMP_UNITS:
+ raise ValueError('date_unit must be one of %s' %
+ (self._STAMP_UNITS,))
+ self.min_stamp = self._MIN_STAMPS[date_unit]
+ else:
+ self.min_stamp = self._MIN_STAMPS['s']
+
self.numpy = numpy
self.precise_float = precise_float
- self.convert_axes = convert_axes
+ self.convert_axes = convert_axes
self.convert_dates = convert_dates
+ self.date_unit = date_unit
self.keep_default_dates = keep_default_dates
self.obj = None
@@ -250,7 +237,8 @@ def parse(self):
else:
self._parse_no_numpy()
- if self.obj is None: return None
+ if self.obj is None:
+ return None
if self.convert_axes:
self._convert_axes()
self._try_convert_types()
@@ -259,14 +247,17 @@ def parse(self):
def _convert_axes(self):
""" try to convert axes """
for axis in self.obj._AXIS_NUMBERS.keys():
- new_axis, result = self._try_convert_data(axis, self.obj._get_axis(axis), use_dtypes=False, convert_dates=True)
+ new_axis, result = self._try_convert_data(
+ axis, self.obj._get_axis(axis), use_dtypes=False,
+ convert_dates=True)
if result:
- setattr(self.obj,axis,new_axis)
+ setattr(self.obj, axis, new_axis)
def _try_convert_types(self):
raise NotImplementedError
- def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True):
+ def _try_convert_data(self, name, data, use_dtypes=True,
+ convert_dates=True):
""" try to parse a ndarray like into a column by inferring dtype """
# don't try to coerce, unless a force conversion
@@ -279,7 +270,8 @@ def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True):
else:
# dtype to force
- dtype = self.dtype.get(name) if isinstance(self.dtype,dict) else self.dtype
+ dtype = (self.dtype.get(name)
+ if isinstance(self.dtype, dict) else self.dtype)
if dtype is not None:
try:
dtype = np.dtype(dtype)
@@ -345,7 +337,8 @@ def _try_convert_to_date(self, data):
was successful """
# no conversion on empty
- if not len(data): return data, False
+ if not len(data):
+ return data, False
new_data = data
if new_data.dtype == 'object':
@@ -354,27 +347,29 @@ def _try_convert_to_date(self, data):
except:
pass
-
# ignore numbers that are out of range
- if issubclass(new_data.dtype.type,np.number):
- if not ((new_data == iNaT) | (new_data > long(31536000000000000))).all():
+ if issubclass(new_data.dtype.type, np.number):
+ in_range = (isnull(new_data.values) | (new_data > self.min_stamp) |
+ (new_data.values == iNaT))
+ if not in_range.all():
return data, False
- try:
- new_data = to_datetime(new_data)
- except:
+ date_units = (self.date_unit,) if self.date_unit else self._STAMP_UNITS
+ for date_unit in date_units:
try:
- new_data = to_datetime(new_data.astype('int64'))
+ new_data = to_datetime(new_data, errors='raise',
+ unit=date_unit)
+ except OverflowError:
+ continue
except:
-
- # return old, noting more we can do
- return data, False
-
- return new_data, True
+ break
+ return new_data, True
+ return data, False
def _try_convert_dates(self):
raise NotImplementedError
+
class SeriesParser(Parser):
_default_orient = 'index'
@@ -410,11 +405,14 @@ def _parse_numpy(self):
precise_float=self.precise_float))
def _try_convert_types(self):
- if self.obj is None: return
- obj, result = self._try_convert_data('data', self.obj, convert_dates=self.convert_dates)
+ if self.obj is None:
+ return
+ obj, result = self._try_convert_data(
+ 'data', self.obj, convert_dates=self.convert_dates)
if result:
self.obj = obj
+
class FrameParser(Parser):
_default_orient = 'columns'
@@ -438,7 +436,8 @@ def _parse_numpy(self):
self.obj = DataFrame(loads(json, dtype=None, numpy=True,
precise_float=self.precise_float))
else:
- self.obj = DataFrame(*loads(json, dtype=None, numpy=True, labelled=True,
+ self.obj = DataFrame(*loads(json, dtype=None, numpy=True,
+ labelled=True,
precise_float=self.precise_float))
def _parse_no_numpy(self):
@@ -481,19 +480,22 @@ def _process_converter(self, f, filt=None):
if needs_new_obj:
# possibly handle dup columns
- new_obj = DataFrame(new_obj,index=self.obj.index)
+ new_obj = DataFrame(new_obj, index=self.obj.index)
new_obj.columns = self.obj.columns
self.obj = new_obj
def _try_convert_types(self):
- if self.obj is None: return
+ if self.obj is None:
+ return
if self.convert_dates:
self._try_convert_dates()
- self._process_converter(lambda col, c: self._try_convert_data(col, c, convert_dates=False))
+ self._process_converter(
+ lambda col, c: self._try_convert_data(col, c, convert_dates=False))
def _try_convert_dates(self):
- if self.obj is None: return
+ if self.obj is None:
+ return
# our columns to parse
convert_dates = self.convert_dates
@@ -503,16 +505,18 @@ def _try_convert_dates(self):
def is_ok(col):
""" return if this col is ok to try for a date parse """
- if not isinstance(col, compat.string_types): return False
+ if not isinstance(col, compat.string_types):
+ return False
if (col.endswith('_at') or
- col.endswith('_time') or
- col.lower() == 'modified' or
- col.lower() == 'date' or
- col.lower() == 'datetime'):
- return True
+ col.endswith('_time') or
+ col.lower() == 'modified' or
+ col.lower() == 'date' or
+ col.lower() == 'datetime'):
+ return True
return False
- self._process_converter(lambda col, c: self._try_convert_to_date(c),
- lambda col, c: (self.keep_default_dates and is_ok(col)) or col in convert_dates)
-
+ self._process_converter(
+ lambda col, c: self._try_convert_to_date(c),
+ lambda col, c: ((self.keep_default_dates and is_ok(col))
+ or col in convert_dates))
diff --git a/pandas/io/tests/test_json/data/tsframe_iso_v012.json b/pandas/io/tests/test_json/data/tsframe_iso_v012.json
new file mode 100644
index 0000000000000..bd9ff885ad23a
--- /dev/null
+++ b/pandas/io/tests/test_json/data/tsframe_iso_v012.json
@@ -0,0 +1 @@
+{"A":{"2000-01-03T00:00:00":1.56808523,"2000-01-04T00:00:00":-0.2550111,"2000-01-05T00:00:00":1.51493992,"2000-01-06T00:00:00":-0.02765498,"2000-01-07T00:00:00":0.05951614},"B":{"2000-01-03T00:00:00":0.65727391,"2000-01-04T00:00:00":-0.08072427,"2000-01-05T00:00:00":0.11805825,"2000-01-06T00:00:00":0.44679743,"2000-01-07T00:00:00":-2.69652057},"C":{"2000-01-03T00:00:00":1.81021139,"2000-01-04T00:00:00":-0.03202878,"2000-01-05T00:00:00":1.629455,"2000-01-06T00:00:00":0.33192641,"2000-01-07T00:00:00":1.28163262},"D":{"2000-01-03T00:00:00":-0.17251653,"2000-01-04T00:00:00":-0.17581665,"2000-01-05T00:00:00":-1.31506612,"2000-01-06T00:00:00":-0.27885413,"2000-01-07T00:00:00":0.34703478},"date":{"2000-01-03T00:00:00":"1992-01-06T18:21:32.120000","2000-01-04T00:00:00":"1992-01-06T18:21:32.120000","2000-01-05T00:00:00":"1992-01-06T18:21:32.120000","2000-01-06T00:00:00":"2013-01-01T00:00:00","2000-01-07T00:00:00":"1992-01-06T18:21:32.120000"}}
\ No newline at end of file
diff --git a/pandas/io/tests/test_json/data/tsframe_v012.json b/pandas/io/tests/test_json/data/tsframe_v012.json
new file mode 100644
index 0000000000000..d4474c767855c
--- /dev/null
+++ b/pandas/io/tests/test_json/data/tsframe_v012.json
@@ -0,0 +1 @@
+{"A":{"946857600000000000":1.56808523,"946944000000000000":-0.2550111,"947030400000000000":1.51493992,"947116800000000000":-0.02765498,"947203200000000000":0.05951614},"B":{"946857600000000000":0.65727391,"946944000000000000":-0.08072427,"947030400000000000":0.11805825,"947116800000000000":0.44679743,"947203200000000000":-2.69652057},"C":{"946857600000000000":1.81021139,"946944000000000000":-0.03202878,"947030400000000000":1.629455,"947116800000000000":0.33192641,"947203200000000000":1.28163262},"D":{"946857600000000000":-0.17251653,"946944000000000000":-0.17581665,"947030400000000000":-1.31506612,"947116800000000000":-0.27885413,"947203200000000000":0.34703478},"date":{"946857600000000000":694722092120000000,"946944000000000000":694722092120000000,"947030400000000000":694722092120000000,"947116800000000000":1356998400000000000,"947203200000000000":694722092120000000},"modified":{"946857600000000000":694722092120000000,"946944000000000000":null,"947030400000000000":694722092120000000,"947116800000000000":1356998400000000000,"947203200000000000":694722092120000000}}
\ No newline at end of file
diff --git a/pandas/io/tests/test_json/test_pandas.py b/pandas/io/tests/test_json/test_pandas.py
index cd0e56db84256..1f79f5670cc75 100644
--- a/pandas/io/tests/test_json/test_pandas.py
+++ b/pandas/io/tests/test_json/test_pandas.py
@@ -1,11 +1,7 @@
-
# pylint: disable-msg=W0612,E1101
-from copy import deepcopy
-from datetime import datetime, timedelta
-from pandas.compat import range, lrange, StringIO, cPickle as pickle
+from pandas.compat import range, lrange, StringIO
from pandas import compat
from pandas.io.common import URLError
-import operator
import os
import unittest
@@ -37,6 +33,8 @@
class TestPandasContainer(unittest.TestCase):
def setUp(self):
+ self.dirpath = tm.get_data_path()
+
self.ts = tm.makeTimeSeries()
self.ts.name = 'ts'
@@ -119,7 +117,8 @@ def _check_orient(df, orient, dtype=None, numpy=False, convert_axes=True, check_
check_dtype=False
if not convert_axes and df.index.dtype.type == np.datetime64:
- unser.index = DatetimeIndex(unser.index.values.astype('i8'))
+ unser.index = DatetimeIndex(
+ unser.index.values.astype('i8') * 1e6)
if orient == "records":
# index is not captured in this orientation
assert_almost_equal(df.values, unser.values)
@@ -280,6 +279,30 @@ def test_frame_to_json_except(self):
df = DataFrame([1, 2, 3])
self.assertRaises(ValueError, df.to_json, orient="garbage")
+ def test_v12_compat(self):
+ df = DataFrame(
+ [[1.56808523, 0.65727391, 1.81021139, -0.17251653],
+ [-0.2550111, -0.08072427, -0.03202878, -0.17581665],
+ [1.51493992, 0.11805825, 1.629455, -1.31506612],
+ [-0.02765498, 0.44679743, 0.33192641, -0.27885413],
+ [0.05951614, -2.69652057, 1.28163262, 0.34703478]],
+ columns=['A', 'B', 'C', 'D'],
+ index=pd.date_range('2000-01-03', '2000-01-07'))
+ df['date'] = pd.Timestamp('19920106 18:21:32.12')
+ df.ix[3, 'date'] = pd.Timestamp('20130101')
+ df['modified'] = df['date']
+ df.ix[1, 'modified'] = pd.NaT
+
+ v12_json = os.path.join(self.dirpath, 'tsframe_v012.json')
+ df_unser = pd.read_json(v12_json)
+ df_unser = pd.read_json(v12_json)
+ assert_frame_equal(df, df_unser)
+
+ df_iso = df.drop(['modified'], axis=1)
+ v12_iso_json = os.path.join(self.dirpath, 'tsframe_iso_v012.json')
+ df_unser_iso = pd.read_json(v12_iso_json)
+ assert_frame_equal(df_iso, df_unser_iso)
+
def test_series_non_unique_index(self):
s = Series(['a', 'b'], index=[1, 1])
@@ -295,11 +318,10 @@ 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), typ='series',
- orient=orient, numpy=numpy, dtype=dtype)
+ unser = read_json(series.to_json(orient=orient),
+ typ='series', orient=orient, numpy=numpy,
+ dtype=dtype)
unser = unser.sort_index()
- #if series.index.dtype.type == np.datetime64:
- # unser.index = DatetimeIndex(unser.index.values.astype('i8'))
if orient == "records" or orient == "values":
assert_almost_equal(series.values, unser.values)
else:
@@ -380,12 +402,12 @@ def test_axis_dates(self):
# frame
json = self.tsframe.to_json()
result = read_json(json)
- assert_frame_equal(result,self.tsframe)
+ assert_frame_equal(result, self.tsframe)
# series
json = self.ts.to_json()
- result = read_json(json,typ='series')
- assert_series_equal(result,self.ts)
+ result = read_json(json, typ='series')
+ assert_series_equal(result, self.ts)
def test_convert_dates(self):
@@ -395,39 +417,84 @@ def test_convert_dates(self):
json = df.to_json()
result = read_json(json)
- assert_frame_equal(result,df)
+ assert_frame_equal(result, df)
df['foo'] = 1.
- json = df.to_json()
- result = read_json(json,convert_dates=False)
+ json = df.to_json(date_unit='ns')
+ result = read_json(json, convert_dates=False)
expected = df.copy()
expected['date'] = expected['date'].values.view('i8')
expected['foo'] = expected['foo'].astype('int64')
- assert_frame_equal(result,expected)
+ assert_frame_equal(result, expected)
# series
- ts = Series(Timestamp('20130101'),index=self.ts.index)
+ ts = Series(Timestamp('20130101'), index=self.ts.index)
json = ts.to_json()
- result = read_json(json,typ='series')
- assert_series_equal(result,ts)
+ result = read_json(json, typ='series')
+ assert_series_equal(result, ts)
+
+ def test_date_format_frame(self):
+ df = self.tsframe.copy()
+
+ def test_w_date(date, date_unit=None):
+ df['date'] = Timestamp(date)
+ df.ix[1, 'date'] = pd.NaT
+ df.ix[5, 'date'] = pd.NaT
+ if date_unit:
+ json = df.to_json(date_format='iso', date_unit=date_unit)
+ else:
+ json = df.to_json(date_format='iso')
+ result = read_json(json)
+ assert_frame_equal(result, df)
+
+ test_w_date('20130101 20:43:42.123')
+ test_w_date('20130101 20:43:42', date_unit='s')
+ test_w_date('20130101 20:43:42.123', date_unit='ms')
+ test_w_date('20130101 20:43:42.123456', date_unit='us')
+ test_w_date('20130101 20:43:42.123456789', date_unit='ns')
+
+ self.assertRaises(ValueError, df.to_json, date_format='iso',
+ date_unit='foo')
+
+ def test_date_format_series(self):
+ def test_w_date(date, date_unit=None):
+ ts = Series(Timestamp(date), index=self.ts.index)
+ ts.ix[1] = pd.NaT
+ ts.ix[5] = pd.NaT
+ if date_unit:
+ 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')
+ assert_series_equal(result, ts)
+
+ test_w_date('20130101 20:43:42.123')
+ test_w_date('20130101 20:43:42', date_unit='s')
+ test_w_date('20130101 20:43:42.123', date_unit='ms')
+ test_w_date('20130101 20:43:42.123456', date_unit='us')
+ test_w_date('20130101 20:43:42.123456789', date_unit='ns')
- def test_date_format(self):
+ ts = Series(Timestamp('20130101 20:43:42.123'), index=self.ts.index)
+ self.assertRaises(ValueError, ts.to_json, date_format='iso',
+ date_unit='foo')
+ def test_date_unit(self):
df = self.tsframe.copy()
- df['date'] = Timestamp('20130101')
- df_orig = df.copy()
+ df['date'] = Timestamp('20130101 20:43:42')
+ df.ix[1, 'date'] = Timestamp('19710101 20:43:42')
+ df.ix[2, 'date'] = Timestamp('21460101 20:43:42')
+ df.ix[4, 'date'] = pd.NaT
- json = df.to_json(date_format='iso')
- result = read_json(json)
- assert_frame_equal(result,df_orig)
+ for unit in ('s', 'ms', 'us', 'ns'):
+ json = df.to_json(date_format='epoch', date_unit=unit)
- # make sure that we did in fact copy
- assert_frame_equal(df,df_orig)
+ # force date unit
+ result = read_json(json, date_unit=unit)
+ assert_frame_equal(result, df)
- ts = Series(Timestamp('20130101'),index=self.ts.index)
- json = ts.to_json(date_format='iso')
- result = read_json(json,typ='series')
- assert_series_equal(result,ts)
+ # detect date unit
+ result = read_json(json, date_unit=None)
+ assert_frame_equal(result, df)
def test_weird_nested_json(self):
diff --git a/pandas/io/tests/test_json/test_ujson.py b/pandas/io/tests/test_json/test_ujson.py
index ff684e30b206d..831a426ee8307 100644
--- a/pandas/io/tests/test_json/test_ujson.py
+++ b/pandas/io/tests/test_json/test_ujson.py
@@ -1,5 +1,4 @@
-import unittest
-from unittest import TestCase
+from unittest import TestCase
try:
import json
@@ -13,20 +12,17 @@
import datetime
import calendar
import re
-import random
import decimal
from functools import partial
from pandas.compat import range, zip, StringIO, u
-from pandas import compat
import pandas.json as ujson
import pandas.compat as compat
import numpy as np
-from pandas.util.testing import assert_almost_equal
from numpy.testing import (assert_array_equal,
assert_array_almost_equal_nulp,
assert_approx_equal)
-from pandas import DataFrame, Series, Index
+from pandas import DataFrame, Series, Index, NaT, DatetimeIndex
import pandas.util.testing as tm
@@ -327,38 +323,58 @@ def test_encodeFalseConversion(self):
self.assertEquals(input, json.loads(output))
self.assertEquals(output, json.dumps(input))
self.assertEquals(input, ujson.decode(output))
- pass
- # def test_encodeDatetimeConversion(self):
- # ts = time.time()
- # input = datetime.datetime.fromtimestamp(ts)
- # output = ujson.encode(input)
- # expected = calendar.timegm(input.utctimetuple())
- # self.assertEquals(int(expected), json.loads(output))
- # self.assertEquals(int(expected), ujson.decode(output))
- # pass
+ def test_encodeDatetimeConversion(self):
+ ts = time.time()
+ input = datetime.datetime.fromtimestamp(ts)
+ output = ujson.encode(input, date_unit='s')
+ expected = calendar.timegm(input.utctimetuple())
+ self.assertEquals(int(expected), json.loads(output))
+ self.assertEquals(int(expected), ujson.decode(output))
+
+ def test_encodeDateConversion(self):
+ ts = time.time()
+ input = datetime.date.fromtimestamp(ts)
+
+ output = ujson.encode(input, date_unit='s')
+ tup = (input.year, input.month, input.day, 0, 0, 0)
- # def test_encodeDateConversion(self):
- # ts = time.time()
- # input = datetime.date.fromtimestamp(ts)
+ expected = calendar.timegm(tup)
+ self.assertEquals(int(expected), json.loads(output))
+ self.assertEquals(int(expected), ujson.decode(output))
+
+ def test_nat(self):
+ input = NaT
+ assert ujson.encode(input) == 'null', "Expected null"
- # output = ujson.encode(input)
- # tup = ( input.year, input.month, input.day, 0, 0, 0 )
+ def test_npy_nat(self):
+ from distutils.version import LooseVersion
+ if LooseVersion(np.__version__) < '1.7.0':
+ raise nose.SkipTest
- # expected = calendar.timegm(tup)
- # self.assertEquals(int(expected), json.loads(output))
- # self.assertEquals(int(expected), ujson.decode(output))
+ input = np.datetime64('NaT')
+ assert ujson.encode(input) == 'null', "Expected null"
- def test_datetime_nanosecond_unit(self):
- from datetime import datetime
+ def test_datetime_units(self):
from pandas.lib import Timestamp
- val = datetime.now()
+ val = datetime.datetime.now()
stamp = Timestamp(val)
- roundtrip = ujson.decode(ujson.encode(val))
+ roundtrip = ujson.decode(ujson.encode(val, date_unit='s'))
+ self.assert_(roundtrip == stamp.value // 1e9)
+
+ roundtrip = ujson.decode(ujson.encode(val, date_unit='ms'))
+ self.assert_(roundtrip == stamp.value // 1e6)
+
+ roundtrip = ujson.decode(ujson.encode(val, date_unit='us'))
+ self.assert_(roundtrip == stamp.value / 1e3)
+
+ roundtrip = ujson.decode(ujson.encode(val, date_unit='ns'))
self.assert_(roundtrip == stamp.value)
+ self.assertRaises(ValueError, ujson.encode, val, date_unit='foo')
+
def test_encodeToUTF8(self):
_skip_if_python_ver(2, 5)
input = "\xe6\x97\xa5\xd1\x88"
@@ -1267,17 +1283,17 @@ def testIndex(self):
self.assert_(i.equals(outp))
def test_datetimeindex(self):
- from pandas.tseries.index import date_range, DatetimeIndex
+ from pandas.tseries.index import date_range
rng = date_range('1/1/2000', periods=20)
- encoded = ujson.encode(rng)
+ encoded = ujson.encode(rng, date_unit='ns')
decoded = DatetimeIndex(np.array(ujson.decode(encoded)))
self.assert_(rng.equals(decoded))
ts = Series(np.random.randn(len(rng)), index=rng)
- decoded = Series(ujson.decode(ujson.encode(ts)))
+ decoded = Series(ujson.decode(ujson.encode(ts, date_unit='ns')))
idx_values = decoded.index.values.astype(np.int64)
decoded.index = DatetimeIndex(idx_values)
tm.assert_series_equal(ts, decoded)
diff --git a/pandas/src/ujson/python/objToJSON.c b/pandas/src/ujson/python/objToJSON.c
index bebaf89de341d..f28ed137383c6 100644
--- a/pandas/src/ujson/python/objToJSON.c
+++ b/pandas/src/ujson/python/objToJSON.c
@@ -38,20 +38,24 @@ Numeric decoder derived from from TCL library
#include "py_defines.h"
#include <numpy/arrayobject.h>
-#include <numpy/npy_math.h>
+#include <numpy/arrayscalars.h>
#include <np_datetime.h>
+#include <np_datetime_strings.h>
+#include <numpy_helper.h>
+#include <numpy/npy_math.h>
+#include <math.h>
#include <stdio.h>
#include <datetime.h>
#include <ultrajson.h>
-#define EPOCH_ORD 719163
static PyObject* type_decimal;
#define NPY_JSON_BUFSIZE 32768
-static PyObject* cls_dataframe;
-static PyObject* cls_series;
-static PyObject* cls_index;
+static PyTypeObject* cls_dataframe;
+static PyTypeObject* cls_series;
+static PyTypeObject* cls_index;
+static PyTypeObject* cls_nat;
typedef void *(*PFN_PyTypeToJSON)(JSOBJ obj, JSONTypeContext *ti, void *outValue, size_t *_outLen);
@@ -63,7 +67,6 @@ typedef struct __NpyArrContext
{
PyObject *array;
char* dataptr;
- int was_datetime64;
int curdim; // current dimension in array's order
int stridedim; // dimension we are striding over
int inc; // stride dimension increment (+/- 1)
@@ -71,7 +74,6 @@ typedef struct __NpyArrContext
npy_intp stride;
npy_intp ndim;
npy_intp index[NPY_MAXDIMS];
- PyArray_GetItemFunc* getitem;
char** rowLabels;
char** columnLabels;
@@ -96,7 +98,7 @@ typedef struct __TypeContext
JSINT64 longValue;
- char *citemName;
+ char *cStr;
NpyArrContext *npyarr;
int transpose;
char** rowLabels;
@@ -112,6 +114,9 @@ typedef struct __PyObjectEncoder
// pass through the NpyArrContext when encoding multi-dimensional arrays
NpyArrContext* npyCtxtPassthru;
+ int datetimeIso;
+ PANDAS_DATETIMEUNIT datetimeUnit;
+
// output format style for pandas data types
int outputFormat;
int originalOutputFormat;
@@ -144,7 +149,8 @@ void initObjToJSON(void)
int initObjToJSON(void)
#endif
{
- PyObject *mod_frame;
+ PyObject *mod_pandas;
+ PyObject *mod_tslib;
PyObject* mod_decimal = PyImport_ImportModule("decimal");
type_decimal = PyObject_GetAttrString(mod_decimal, "Decimal");
Py_INCREF(type_decimal);
@@ -152,13 +158,20 @@ int initObjToJSON(void)
PyDateTime_IMPORT;
- mod_frame = PyImport_ImportModule("pandas.core.frame");
- if (mod_frame)
+ mod_pandas = PyImport_ImportModule("pandas");
+ if (mod_pandas)
{
- cls_dataframe = PyObject_GetAttrString(mod_frame, "DataFrame");
- cls_index = PyObject_GetAttrString(mod_frame, "Index");
- cls_series = PyObject_GetAttrString(mod_frame, "Series");
- Py_DECREF(mod_frame);
+ cls_dataframe = (PyTypeObject*) PyObject_GetAttrString(mod_pandas, "DataFrame");
+ cls_index = (PyTypeObject*) PyObject_GetAttrString(mod_pandas, "Index");
+ cls_series = (PyTypeObject*) PyObject_GetAttrString(mod_pandas, "Series");
+ Py_DECREF(mod_pandas);
+ }
+
+ mod_tslib = PyImport_ImportModule("pandas.tslib");
+ if (mod_tslib)
+ {
+ cls_nat = (PyTypeObject*) PyObject_GetAttrString(mod_tslib, "NaTType");
+ Py_DECREF(mod_tslib);
}
/* Initialise numpy API */
@@ -187,9 +200,9 @@ static void *PyLongToINT64(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size
static void *NpyFloatToDOUBLE(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
{
- PyObject *obj = (PyObject *) _obj;
- PyArray_CastScalarToCtype(obj, outValue, PyArray_DescrFromType(NPY_DOUBLE));
- return NULL;
+ PyObject *obj = (PyObject *) _obj;
+ PyArray_CastScalarToCtype(obj, outValue, PyArray_DescrFromType(NPY_DOUBLE));
+ return NULL;
}
static void *PyFloatToDOUBLE(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
@@ -217,41 +230,83 @@ static void *PyUnicodeToUTF8(JSOBJ _obj, JSONTypeContext *tc, void *outValue, si
return PyString_AS_STRING(newObj);
}
-static void *NpyDateTimeToINT64(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
+static void *PandasDateTimeStructToJSON(pandas_datetimestruct *dts, JSONTypeContext *tc, void *outValue, size_t *_outLen)
{
- PyObject *obj = (PyObject *) _obj;
- PyArray_CastScalarToCtype(obj, outValue, PyArray_DescrFromType(NPY_DATETIME));
+ int base = ((PyObjectEncoder*) tc->encoder)->datetimeUnit;
+
+ if (((PyObjectEncoder*) tc->encoder)->datetimeIso)
+ {
+ PRINTMARK();
+ *_outLen = (size_t) get_datetime_iso_8601_strlen(0, base);
+ GET_TC(tc)->cStr = PyObject_Malloc(sizeof(char) * (*_outLen));
+ if (!GET_TC(tc)->cStr)
+ {
+ PyErr_NoMemory();
+ ((JSONObjectEncoder*) tc->encoder)->errorMsg = "";
+ return NULL;
+ }
+
+ if (!make_iso_8601_datetime(dts, GET_TC(tc)->cStr, *_outLen, 0, base, -1, NPY_UNSAFE_CASTING))
+ {
+ PRINTMARK();
+ *_outLen = strlen(GET_TC(tc)->cStr);
+ return GET_TC(tc)->cStr;
+ }
+ else
+ {
+ PRINTMARK();
+ PyErr_SetString(PyExc_ValueError, "Could not convert datetime value to string");
+ PyObject_Free(GET_TC(tc)->cStr);
+ return NULL;
+ }
+ }
+ else
+ {
+ PRINTMARK();
+ *((JSINT64*)outValue) = pandas_datetimestruct_to_datetime(base, dts);
return NULL;
+ }
+}
+
+static void *NpyDateTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
+{
+ PRINTMARK();
+ pandas_datetimestruct dts;
+ PyDatetimeScalarObject *obj = (PyDatetimeScalarObject *) _obj;
+
+ pandas_datetime_to_datetimestruct(obj->obval, obj->obmeta.base, &dts);
+ return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen);
}
-static void *PyDateTimeToINT64(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
+static void *PyDateTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
{
pandas_datetimestruct dts;
PyObject *obj = (PyObject *) _obj;
- dts.year = PyDateTime_GET_YEAR(obj);
- dts.month = PyDateTime_GET_MONTH(obj);
- dts.day = PyDateTime_GET_DAY(obj);
- dts.hour = PyDateTime_DATE_GET_HOUR(obj);
- dts.min = PyDateTime_DATE_GET_MINUTE(obj);
- dts.sec = PyDateTime_DATE_GET_SECOND(obj);
- dts.us = PyDateTime_DATE_GET_MICROSECOND(obj);
- dts.ps = dts.as = 0;
- *((JSINT64*)outValue) = (JSINT64) pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts);
- return NULL;
+
+ if (!convert_pydatetime_to_datetimestruct(obj, &dts, NULL, 1))
+ {
+ PRINTMARK();
+ return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen);
+ }
+ else
+ {
+ if (!PyErr_Occurred())
+ {
+ PyErr_SetString(PyExc_ValueError, "Could not convert datetime value to string");
+ }
+ ((JSONObjectEncoder*) tc->encoder)->errorMsg = "";
+ return NULL;
+ }
}
-static void *PyDateToINT64(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
+static void *NpyDatetime64ToJSON(JSOBJ _obj, JSONTypeContext *tc, void *outValue, size_t *_outLen)
{
pandas_datetimestruct dts;
PyObject *obj = (PyObject *) _obj;
- dts.year = PyDateTime_GET_YEAR(obj);
- dts.month = PyDateTime_GET_MONTH(obj);
- dts.day = PyDateTime_GET_DAY(obj);
- dts.hour = dts.min = dts.sec = dts.ps = dts.as = 0;
- *((JSINT64*)outValue) = (JSINT64) pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts);
- return NULL;
+ pandas_datetime_to_datetimestruct(PyLong_AsLongLong(obj), PANDAS_FR_ns, &dts);
+ return PandasDateTimeStructToJSON(&dts, tc, outValue, _outLen);
}
//=============================================================================
@@ -265,7 +320,6 @@ int NpyArr_iterNextNone(JSOBJ _obj, JSONTypeContext *tc)
void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc)
{
PyArrayObject *obj;
- PyArray_Descr *dtype;
NpyArrContext *npyarr;
if (GET_TC(tc)->newObj)
@@ -290,17 +344,7 @@ void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc)
return;
}
- // uber hack to support datetime64[ns] arrays
- if (PyArray_DESCR(obj)->type_num == NPY_DATETIME) {
- npyarr->was_datetime64 = 1;
- dtype = PyArray_DescrFromType(NPY_INT64);
- obj = (PyArrayObject *) PyArray_CastToType(obj, dtype, 0);
- } else {
- npyarr->was_datetime64 = 0;
- }
-
npyarr->array = (PyObject*) obj;
- npyarr->getitem = (PyArray_GetItemFunc*) PyArray_DESCR(obj)->f->getitem;
npyarr->dataptr = PyArray_DATA(obj);
npyarr->ndim = PyArray_NDIM(obj) - 1;
npyarr->curdim = 0;
@@ -338,10 +382,6 @@ void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc)
if (npyarr)
{
- if (npyarr->was_datetime64) {
- Py_XDECREF(npyarr->array);
- }
-
if (GET_TC(tc)->itemValue != npyarr->array)
{
Py_XDECREF(GET_TC(tc)->itemValue);
@@ -384,6 +424,11 @@ int NpyArr_iterNextItem(JSOBJ _obj, JSONTypeContext *tc)
PRINTMARK();
npyarr = GET_TC(tc)->npyarr;
+ if (PyErr_Occurred())
+ {
+ return 0;
+ }
+
if (GET_TC(tc)->itemValue != npyarr->array)
{
Py_XDECREF(GET_TC(tc)->itemValue);
@@ -395,7 +440,7 @@ int NpyArr_iterNextItem(JSOBJ _obj, JSONTypeContext *tc)
return 0;
}
- GET_TC(tc)->itemValue = npyarr->getitem(npyarr->dataptr, npyarr->array);
+ GET_TC(tc)->itemValue = PyArray_ToScalar(npyarr->dataptr, npyarr->array);
npyarr->dataptr += npyarr->stride;
npyarr->index[npyarr->stridedim]++;
@@ -408,6 +453,12 @@ int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc)
PRINTMARK();
npyarr = GET_TC(tc)->npyarr;
+ if (PyErr_Occurred())
+ {
+ PRINTMARK();
+ return 0;
+ }
+
if (npyarr->curdim >= npyarr->ndim || npyarr->index[npyarr->stridedim] >= npyarr->dim)
{
// innermost dimension, start retrieving item values
@@ -720,8 +771,8 @@ char *List_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
void Index_iterBegin(JSOBJ obj, JSONTypeContext *tc)
{
GET_TC(tc)->index = 0;
- GET_TC(tc)->citemName = PyObject_Malloc(20 * sizeof(char));
- if (!GET_TC(tc)->citemName)
+ GET_TC(tc)->cStr = PyObject_Malloc(20 * sizeof(char));
+ if (!GET_TC(tc)->cStr)
{
PyErr_NoMemory();
}
@@ -731,7 +782,7 @@ void Index_iterBegin(JSOBJ obj, JSONTypeContext *tc)
int Index_iterNext(JSOBJ obj, JSONTypeContext *tc)
{
Py_ssize_t index;
- if (!GET_TC(tc)->citemName)
+ if (!GET_TC(tc)->cStr)
{
return 0;
}
@@ -740,13 +791,13 @@ int Index_iterNext(JSOBJ obj, JSONTypeContext *tc)
Py_XDECREF(GET_TC(tc)->itemValue);
if (index == 0)
{
- memcpy(GET_TC(tc)->citemName, "name", sizeof(char)*5);
+ memcpy(GET_TC(tc)->cStr, "name", sizeof(char)*5);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "name");
}
else
if (index == 1)
{
- memcpy(GET_TC(tc)->citemName, "data", sizeof(char)*5);
+ memcpy(GET_TC(tc)->cStr, "data", sizeof(char)*5);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "values");
}
else
@@ -762,10 +813,6 @@ int Index_iterNext(JSOBJ obj, JSONTypeContext *tc)
void Index_iterEnd(JSOBJ obj, JSONTypeContext *tc)
{
- if (GET_TC(tc)->citemName)
- {
- PyObject_Free(GET_TC(tc)->citemName);
- }
PRINTMARK();
}
@@ -776,8 +823,8 @@ JSOBJ Index_iterGetValue(JSOBJ obj, JSONTypeContext *tc)
char *Index_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
- *outLen = strlen(GET_TC(tc)->citemName);
- return GET_TC(tc)->citemName;
+ *outLen = strlen(GET_TC(tc)->cStr);
+ return GET_TC(tc)->cStr;
}
//=============================================================================
@@ -787,9 +834,9 @@ void Series_iterBegin(JSOBJ obj, JSONTypeContext *tc)
{
PyObjectEncoder* enc = (PyObjectEncoder*) tc->encoder;
GET_TC(tc)->index = 0;
- GET_TC(tc)->citemName = PyObject_Malloc(20 * sizeof(char));
+ GET_TC(tc)->cStr = PyObject_Malloc(20 * sizeof(char));
enc->outputFormat = VALUES; // for contained series
- if (!GET_TC(tc)->citemName)
+ if (!GET_TC(tc)->cStr)
{
PyErr_NoMemory();
}
@@ -799,7 +846,7 @@ void Series_iterBegin(JSOBJ obj, JSONTypeContext *tc)
int Series_iterNext(JSOBJ obj, JSONTypeContext *tc)
{
Py_ssize_t index;
- if (!GET_TC(tc)->citemName)
+ if (!GET_TC(tc)->cStr)
{
return 0;
}
@@ -808,19 +855,19 @@ int Series_iterNext(JSOBJ obj, JSONTypeContext *tc)
Py_XDECREF(GET_TC(tc)->itemValue);
if (index == 0)
{
- memcpy(GET_TC(tc)->citemName, "name", sizeof(char)*5);
+ memcpy(GET_TC(tc)->cStr, "name", sizeof(char)*5);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "name");
}
else
if (index == 1)
{
- memcpy(GET_TC(tc)->citemName, "index", sizeof(char)*6);
+ memcpy(GET_TC(tc)->cStr, "index", sizeof(char)*6);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "index");
}
else
if (index == 2)
{
- memcpy(GET_TC(tc)->citemName, "data", sizeof(char)*5);
+ memcpy(GET_TC(tc)->cStr, "data", sizeof(char)*5);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "values");
}
else
@@ -838,10 +885,6 @@ void Series_iterEnd(JSOBJ obj, JSONTypeContext *tc)
{
PyObjectEncoder* enc = (PyObjectEncoder*) tc->encoder;
enc->outputFormat = enc->originalOutputFormat;
- if (GET_TC(tc)->citemName)
- {
- PyObject_Free(GET_TC(tc)->citemName);
- }
PRINTMARK();
}
@@ -852,8 +895,8 @@ JSOBJ Series_iterGetValue(JSOBJ obj, JSONTypeContext *tc)
char *Series_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
- *outLen = strlen(GET_TC(tc)->citemName);
- return GET_TC(tc)->citemName;
+ *outLen = strlen(GET_TC(tc)->cStr);
+ return GET_TC(tc)->cStr;
}
//=============================================================================
@@ -863,9 +906,9 @@ void DataFrame_iterBegin(JSOBJ obj, JSONTypeContext *tc)
{
PyObjectEncoder* enc = (PyObjectEncoder*) tc->encoder;
GET_TC(tc)->index = 0;
- GET_TC(tc)->citemName = PyObject_Malloc(20 * sizeof(char));
+ GET_TC(tc)->cStr = PyObject_Malloc(20 * sizeof(char));
enc->outputFormat = VALUES; // for contained series & index
- if (!GET_TC(tc)->citemName)
+ if (!GET_TC(tc)->cStr)
{
PyErr_NoMemory();
}
@@ -875,7 +918,7 @@ void DataFrame_iterBegin(JSOBJ obj, JSONTypeContext *tc)
int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc)
{
Py_ssize_t index;
- if (!GET_TC(tc)->citemName)
+ if (!GET_TC(tc)->cStr)
{
return 0;
}
@@ -884,19 +927,19 @@ int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc)
Py_XDECREF(GET_TC(tc)->itemValue);
if (index == 0)
{
- memcpy(GET_TC(tc)->citemName, "columns", sizeof(char)*8);
+ memcpy(GET_TC(tc)->cStr, "columns", sizeof(char)*8);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "columns");
}
else
if (index == 1)
{
- memcpy(GET_TC(tc)->citemName, "index", sizeof(char)*6);
+ memcpy(GET_TC(tc)->cStr, "index", sizeof(char)*6);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "index");
}
else
if (index == 2)
{
- memcpy(GET_TC(tc)->citemName, "data", sizeof(char)*5);
+ memcpy(GET_TC(tc)->cStr, "data", sizeof(char)*5);
GET_TC(tc)->itemValue = PyObject_GetAttrString(obj, "values");
}
else
@@ -914,10 +957,6 @@ void DataFrame_iterEnd(JSOBJ obj, JSONTypeContext *tc)
{
PyObjectEncoder* enc = (PyObjectEncoder*) tc->encoder;
enc->outputFormat = enc->originalOutputFormat;
- if (GET_TC(tc)->citemName)
- {
- PyObject_Free(GET_TC(tc)->citemName);
- }
PRINTMARK();
}
@@ -928,8 +967,8 @@ JSOBJ DataFrame_iterGetValue(JSOBJ obj, JSONTypeContext *tc)
char *DataFrame_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
{
- *outLen = strlen(GET_TC(tc)->citemName);
- return GET_TC(tc)->citemName;
+ *outLen = strlen(GET_TC(tc)->cStr);
+ return GET_TC(tc)->cStr;
}
//=============================================================================
@@ -1023,15 +1062,12 @@ void NpyArr_freeLabels(char** labels, npy_intp len)
char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_intp num)
{
// NOTE this function steals a reference to labels.
- PyArray_Descr *dtype = NULL;
PyArrayObject* labelsTmp = NULL;
PyObject* item = NULL;
npy_intp i, stride, len;
- // npy_intp bufsize = 32768;
char** ret;
char *dataptr, *cLabel, *origend, *origst, *origoffset;
char labelBuffer[NPY_JSON_BUFSIZE];
- PyArray_GetItemFunc* getitem;
PRINTMARK();
if (PyArray_SIZE(labels) < num)
@@ -1058,20 +1094,12 @@ char** NpyArr_encodeLabels(PyArrayObject* labels, JSONObjectEncoder* enc, npy_in
origend = enc->end;
origoffset = enc->offset;
- if (PyArray_DESCR(labels)->type_num == NPY_DATETIME) {
- dtype = PyArray_DescrFromType(NPY_INT64);
- labelsTmp = labels;
- labels = (PyArrayObject *) PyArray_CastToType(labels, dtype, 0);
- Py_DECREF(labelsTmp);
- }
-
stride = PyArray_STRIDE(labels, 0);
dataptr = PyArray_DATA(labels);
- getitem = PyArray_DESCR(labels)->f->getitem;
for (i = 0; i < num; i++)
{
- item = getitem(dataptr, labels);
+ item = PyArray_ToScalar(dataptr, labels);
if (!item)
{
NpyArr_freeLabels(ret, num);
@@ -1150,7 +1178,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
pc->index = 0;
pc->size = 0;
pc->longValue = 0;
- pc->citemName = NULL;
+ pc->cStr = NULL;
pc->npyarr = NULL;
pc->rowLabels = NULL;
pc->columnLabels = NULL;
@@ -1158,6 +1186,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
pc->rowLabelsLen = 0;
pc->columnLabelsLen = 0;
+
if (PyIter_Check(obj))
{
PRINTMARK();
@@ -1194,9 +1223,32 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
+ if (PyArray_IsScalar(obj, Datetime))
+ {
+ PRINTMARK();
+ if (((PyDatetimeScalarObject*) obj)->obval == get_nat()) {
+ PRINTMARK();
+ tc->type = JT_NULL;
+ return;
+ }
+
+ PRINTMARK();
+ pc->PyTypeToJSON = NpyDateTimeToJSON;
+ if (enc->datetimeIso)
+ {
+ tc->type = JT_UTF8;
+ }
+ else
+ {
+ tc->type = JT_LONG;
+ }
+ return;
+ }
+ else
if (PyInt_Check(obj))
{
PRINTMARK();
+
#ifdef _LP64
pc->PyTypeToJSON = PyIntToINT64; tc->type = JT_LONG;
#else
@@ -1205,6 +1257,14 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
+ if (PyArray_IsScalar(obj, Bool))
+ {
+ PRINTMARK();
+ PyArray_CastScalarToCtype(obj, &(GET_TC(tc)->longValue), PyArray_DescrFromType(NPY_BOOL));
+ tc->type = (GET_TC(tc)->longValue) ? JT_TRUE : JT_FALSE;
+ return;
+ }
+ else
if (PyArray_IsScalar(obj, Integer))
{
PRINTMARK();
@@ -1266,24 +1326,27 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
- if (PyArray_IsScalar(obj, Datetime))
- {
- PRINTMARK();
- pc->PyTypeToJSON = NpyDateTimeToINT64; tc->type = JT_LONG;
- return;
- }
- else
- if (PyDateTime_Check(obj))
- {
- PRINTMARK();
- pc->PyTypeToJSON = PyDateTimeToINT64; tc->type = JT_LONG;
- return;
- }
- else
- if (PyDate_Check(obj))
+ if (PyDateTime_Check(obj) || PyDate_Check(obj))
{
+ if (PyObject_TypeCheck(obj, cls_nat))
+ {
+ PRINTMARK();
+ tc->type = JT_NULL;
+ return;
+ }
+
PRINTMARK();
- pc->PyTypeToJSON = PyDateToINT64; tc->type = JT_LONG;
+ pc->PyTypeToJSON = PyDateTimeToJSON;
+ if (enc->datetimeIso)
+ {
+ PRINTMARK();
+ tc->type = JT_UTF8;
+ }
+ else
+ {
+ PRINTMARK();
+ tc->type = JT_LONG;
+ }
return;
}
else
@@ -1348,7 +1411,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
- if (PyObject_TypeCheck(obj, (PyTypeObject*) cls_index))
+ if (PyObject_TypeCheck(obj, cls_index))
{
if (enc->outputFormat == SPLIT)
{
@@ -1373,7 +1436,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
- if (PyObject_TypeCheck(obj, (PyTypeObject*) cls_series))
+ if (PyObject_TypeCheck(obj, cls_series))
{
if (enc->outputFormat == SPLIT)
{
@@ -1392,7 +1455,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
PRINTMARK();
tc->type = JT_OBJECT;
pc->columnLabelsLen = PyArray_SIZE(obj);
- pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "index"), (JSONObjectEncoder*) enc, pc->columnLabelsLen);
+ pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "index"), "values"), (JSONObjectEncoder*) enc, pc->columnLabelsLen);
if (!pc->columnLabels)
{
goto INVALID;
@@ -1438,7 +1501,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
return;
}
else
- if (PyObject_TypeCheck(obj, (PyTypeObject*) cls_dataframe))
+ if (PyObject_TypeCheck(obj, cls_dataframe))
{
if (enc->outputFormat == SPLIT)
{
@@ -1482,7 +1545,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
PRINTMARK();
tc->type = JT_OBJECT;
pc->rowLabelsLen = PyArray_DIM(pc->newObj, 0);
- pc->rowLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "index"), (JSONObjectEncoder*) enc, pc->rowLabelsLen);
+ pc->rowLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "index"), "values"), (JSONObjectEncoder*) enc, pc->rowLabelsLen);
if (!pc->rowLabels)
{
goto INVALID;
@@ -1507,7 +1570,7 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
goto INVALID;
}
pc->columnLabelsLen = PyArray_DIM(pc->newObj, 0);
- pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(obj, "index"), (JSONObjectEncoder*) enc, pc->columnLabelsLen);
+ pc->columnLabels = NpyArr_encodeLabels((PyArrayObject*) PyObject_GetAttrString(PyObject_GetAttrString(obj, "index"), "values"), (JSONObjectEncoder*) enc, pc->columnLabelsLen);
if (!pc->columnLabels)
{
NpyArr_freeLabels(pc->rowLabels, pc->rowLabelsLen);
@@ -1573,12 +1636,14 @@ void Object_beginTypeContext (JSOBJ _obj, JSONTypeContext *tc)
void Object_endTypeContext(JSOBJ obj, JSONTypeContext *tc)
{
- Py_XDECREF(GET_TC(tc)->newObj);
- NpyArr_freeLabels(GET_TC(tc)->rowLabels, GET_TC(tc)->rowLabelsLen);
- NpyArr_freeLabels(GET_TC(tc)->columnLabels, GET_TC(tc)->columnLabelsLen);
+ PRINTMARK();
+ Py_XDECREF(GET_TC(tc)->newObj);
+ NpyArr_freeLabels(GET_TC(tc)->rowLabels, GET_TC(tc)->rowLabelsLen);
+ NpyArr_freeLabels(GET_TC(tc)->columnLabels, GET_TC(tc)->columnLabelsLen);
- PyObject_Free(tc->prv);
- tc->prv = NULL;
+ PyObject_Free(GET_TC(tc)->cStr);
+ PyObject_Free(tc->prv);
+ tc->prv = NULL;
}
const char *Object_getStringValue(JSOBJ obj, JSONTypeContext *tc, size_t *_outLen)
@@ -1639,7 +1704,7 @@ char *Object_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen)
PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
{
- static char *kwlist[] = { "obj", "ensure_ascii", "double_precision", "encode_html_chars", "orient", NULL};
+ static char *kwlist[] = { "obj", "ensure_ascii", "double_precision", "encode_html_chars", "orient", "date_unit", "iso_dates", NULL};
char buffer[65536];
char *ret;
@@ -1649,6 +1714,8 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
int idoublePrecision = 10; // default double precision setting
PyObject *oencodeHTMLChars = NULL;
char *sOrient = NULL;
+ char *sdateFormat = NULL;
+ PyObject *oisoDates = 0;
PyObjectEncoder pyEncoder =
{
@@ -1677,11 +1744,13 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
JSONObjectEncoder* encoder = (JSONObjectEncoder*) &pyEncoder;
pyEncoder.npyCtxtPassthru = NULL;
+ pyEncoder.datetimeIso = 0;
+ pyEncoder.datetimeUnit = PANDAS_FR_ms;
pyEncoder.outputFormat = COLUMNS;
PRINTMARK();
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OiOs", kwlist, &oinput, &oensureAscii, &idoublePrecision, &oencodeHTMLChars, &sOrient))
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OiOssO", kwlist, &oinput, &oensureAscii, &idoublePrecision, &oencodeHTMLChars, &sOrient, &sdateFormat, &oisoDates))
{
return NULL;
}
@@ -1736,6 +1805,40 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
}
}
+ if (sdateFormat != NULL)
+ {
+ if (strcmp(sdateFormat, "s") == 0)
+ {
+ pyEncoder.datetimeUnit = PANDAS_FR_s;
+ }
+ else
+ if (strcmp(sdateFormat, "ms") == 0)
+ {
+ pyEncoder.datetimeUnit = PANDAS_FR_ms;
+ }
+ else
+ if (strcmp(sdateFormat, "us") == 0)
+ {
+ pyEncoder.datetimeUnit = PANDAS_FR_us;
+ }
+ else
+ if (strcmp(sdateFormat, "ns") == 0)
+ {
+ pyEncoder.datetimeUnit = PANDAS_FR_ns;
+ }
+ else
+ {
+ PyErr_Format (PyExc_ValueError, "Invalid value '%s' for option 'date_unit'", sdateFormat);
+ return NULL;
+ }
+ }
+
+ if (oisoDates != NULL && PyObject_IsTrue(oisoDates))
+ {
+ pyEncoder.datetimeIso = 1;
+ }
+
+
pyEncoder.originalOutputFormat = pyEncoder.outputFormat;
PRINTMARK();
ret = JSON_EncodeObject (oinput, encoder, buffer, sizeof (buffer));
@@ -1743,11 +1846,13 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
if (PyErr_Occurred())
{
+ PRINTMARK();
return NULL;
}
if (encoder->errorMsg)
{
+ PRINTMARK();
if (ret != buffer)
{
encoder->free (ret);
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index bb3512e532b0e..698d9a81af387 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1276,7 +1276,7 @@ cdef inline _get_datetime64_nanos(object val):
else:
return ival
-cdef inline int64_t cast_from_unit(object unit, object ts):
+cdef inline int64_t cast_from_unit(object unit, object ts) except -1:
""" return a casting of the unit represented to nanoseconds
round the fractional part of a float to our precision, p """
if unit == 'D':
diff --git a/setup.py b/setup.py
index 58513c9d4077d..956b9b13db2ce 100755
--- a/setup.py
+++ b/setup.py
@@ -475,7 +475,8 @@ def pxd(name):
ext.sources[0] = root + suffix
ujson_ext = Extension('pandas.json',
- depends=['pandas/src/ujson/lib/ultrajson.h'],
+ depends=['pandas/src/ujson/lib/ultrajson.h',
+ 'pandas/src/numpy_helper.h'],
sources=['pandas/src/ujson/python/ujson.c',
'pandas/src/ujson/python/objToJSON.c',
'pandas/src/ujson/python/JSONtoObj.c',
@@ -531,7 +532,8 @@ def pxd(name):
'tests/data/*.xls',
'tests/data/*.xlsx',
'tests/data/*.table',
- 'tests/data/*.html'],
+ 'tests/data/*.html',
+ 'tests/test_json/data/*.json'],
'pandas.tools': ['tests/*.csv'],
'pandas.tests': ['data/*.pickle',
'data/*.csv'],
| This adds support at the C level for encoding datetime values in JSON. I added a new parameter `date_unit` which controls the precision of the encoding, options are seconds, milliseconds, microseconds and nanoseconds. It defaults to milliseconds which should fix #4362.
I also added support for NaTs and tried to detect when numpy arrays of datetime64 longs are passed.
Note that datetime decoding is still handled at the Python level but I added a date_unit param here too so timestamps can be converted correctly.
valgrind looks happy with the changes and all tests pass ok for me on Python 2.7 & 3.3
| https://api.github.com/repos/pandas-dev/pandas/pulls/4498 | 2013-08-07T12:43:08Z | 2013-08-15T01:14:12Z | 2013-08-15T01:14:12Z | 2014-06-14T10:38:30Z |
Fix issue #4496: tslib.tz_convert(vals, tz1, tz2) may raise an IndexErro... | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 578e235b0f88b..e679fa320e1db 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -197,6 +197,8 @@ See :ref:`Internal Refactoring<whatsnew_0130.refactoring>`
- raising an invalid ``TypeError`` rather than ``ValueError`` when appending
with a different block ordering (:issue:`4096`)
- ``read_hdf`` was not respecting as passed ``mode`` (:issue:`4504`)
+ - Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while
+ trying to access trans[pos + 1] (:issue:`4496`)
- The ``by`` argument now works correctly with the ``layout`` argument
(:issue:`4102`, :issue:`4014`) in ``*.hist`` plotting methods
- Fixed bug in ``PeriodIndex.map`` where using ``str`` would return the str
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index c8f87a19a5f34..517c984fa0e64 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -10587,6 +10587,25 @@ def test_consolidate_datetime64(self):
assert_array_equal(df.starting.values, ser_starting.index.values)
assert_array_equal(df.ending.values, ser_ending.index.values)
+ def test_tslib_tz_convert_trans_pos_plus_1__bug(self):
+ """
+ Regression test for tslib.tz_convert(vals, tz1, tz2).
+ See https://github.com/pydata/pandas/issues/4496 for details.
+ """
+ idx = pd.date_range(datetime(2011, 3, 26, 23), datetime(2011, 3, 27, 1), freq='1min')
+ idx = idx.tz_localize('UTC')
+ idx = idx.tz_convert('Europe/Moscow')
+
+ test_vector = pd.Series([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 5], dtype=int)
+
+ hours = idx.hour
+
+ np.testing.assert_equal(hours, test_vector.values)
+
def _check_bool_op(self, name, alternative, frame=None, has_skipna=True,
has_bool_only=False):
if frame is None:
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 18917fdd82d1b..983d3385e8f85 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1432,9 +1432,11 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
pos -= 1
offset = deltas[pos]
+ cdef Py_ssize_t trans_len = len(trans)
+
for i in range(n):
v = utc_dates[i]
- if v >= trans[pos + 1]:
+ if (pos + 1) < trans_len and v >= trans[pos + 1]:
pos += 1
offset = deltas[pos]
result[i] = v + offset
| Bug-fix for Issue #4496 Bug: tslib.tz_convert(vals, tz1, tz2) may raise an IndexError exception.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4497 | 2013-08-07T11:32:59Z | 2013-08-23T13:26:18Z | 2013-08-23T13:26:18Z | 2014-07-16T08:22:12Z |
BLD/TST: correct pytz version for tox | diff --git a/tox.ini b/tox.ini
index 2a9c454a29435..51480832284b9 100644
--- a/tox.ini
+++ b/tox.ini
@@ -11,7 +11,7 @@ deps =
cython
numpy >= 1.6.1
nose
- pytz
+ pytz >= 2011k
six
# cd to anything but the default {toxinidir} which
| Tox fails to build pandas without a specific version of pytz.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4495 | 2013-08-07T03:11:53Z | 2013-08-07T14:51:16Z | 2013-08-07T14:51:16Z | 2014-07-16T08:22:10Z |
FIX: resample to single group with custom function | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 97150cbeb53a2..a0e04156bbb64 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -380,6 +380,7 @@ Bug Fixes
(:issue:`4170`, :issue:`4440`)
- Fixed Panel slicing issued in ``xs`` that was returning an incorrect dimmed object
(:issue:`4016`)
+ - Fix resampling bug where custom reduce function not used if only one group (:issue:`3849`, :issue:`4494`)
- Fixed Panel assignment with a transposed frame (:issue:`3830`)
- Raise on set indexing with a Panel and a Panel as a value which needs alignment (:issue:`3777`)
- frozenset objects now raise in the ``Series`` constructor (:issue:`4482`,
diff --git a/pandas/src/reduce.pyx b/pandas/src/reduce.pyx
index d59c28a30796a..cd010151f1ef7 100644
--- a/pandas/src/reduce.pyx
+++ b/pandas/src/reduce.pyx
@@ -206,7 +206,7 @@ cdef class SeriesBinGrouper:
counts = np.zeros(self.ngroups, dtype=np.int64)
- if self.ngroups > 1:
+ if self.ngroups > 0:
counts[0] = self.bins[0]
for i in range(1, self.ngroups):
if i == self.ngroups - 1:
diff --git a/pandas/tseries/tests/test_resample.py b/pandas/tseries/tests/test_resample.py
index 6ad69a466ba03..620310e32ffcc 100644
--- a/pandas/tseries/tests/test_resample.py
+++ b/pandas/tseries/tests/test_resample.py
@@ -438,6 +438,26 @@ def test_resample_anchored_ticks(self):
expected = ts.resample(freq, closed='left', label='left')
assert_series_equal(result, expected)
+ def test_resample_single_group(self):
+ mysum = lambda x: x.sum()
+
+ rng = date_range('2000-1-1', '2000-2-10', freq='D')
+ ts = Series(np.random.randn(len(rng)), index=rng)
+ assert_series_equal(ts.resample('M', how='sum'),
+ ts.resample('M', how=mysum))
+
+ rng = date_range('2000-1-1', '2000-1-10', freq='D')
+ ts = Series(np.random.randn(len(rng)), index=rng)
+ assert_series_equal(ts.resample('M', how='sum'),
+ ts.resample('M', how=mysum))
+
+ # GH 3849
+ s = Series([30.1, 31.6], index=[Timestamp('20070915 15:30:00'),
+ Timestamp('20070915 15:40:00')])
+ expected = Series([0.75], index=[Timestamp('20070915')])
+ result = s.resample('D', how=lambda x: np.std(x))
+ assert_series_equal(result, expected)
+
def test_resample_base(self):
rng = date_range('1/1/2000 00:00:00', '1/1/2000 02:00', freq='s')
ts = Series(np.random.randn(len(rng)), index=rng)
| Using master code, when re-sampling to a frequency that would result in a single group the use of custom aggregation functions do not work as expected. The included changes fix this, and should fix #3849 too.
``` python
In [17]: import pandas as pd
In [18]: import numpy as np
In [19]: mysum = lambda x: x.sum()
In [20]: rng = pd.date_range('2000-1-1', '2000-1-10', freq='D')
In [21]: ts = pd.Series(np.random.randn(len(rng)), index=rng)
In [22]: ts.resample('M', how='sum')
Out[22]:
2000-01-31 0.985236
Freq: M, dtype: float64
In [23]: ts.resample('M', how=mysum)
Out[23]:
2000-01-31 0
Freq: M, dtype: float64
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/4494 | 2013-08-07T02:46:53Z | 2013-09-25T12:31:36Z | 2013-09-25T12:31:36Z | 2014-06-13T23:41:52Z |
BUG: fix plotting of dup indexed objects | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 35f422ccad9dc..92822e3038545 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -125,6 +125,8 @@ pandas 0.13
(:issue:`4455`)
- Fixed Panel attribute naming conflict if item is named 'a'
(:issue:`3440`)
+ - Fixed an issue where duplicate indexes were raising when plotting
+ (:issue:`4486`)
pandas 0.12
===========
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 10b03ccd3a310..4899c53ad64b5 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -602,7 +602,6 @@ def _ixs(self, i, axis=0):
else:
return _index.get_value_at(self, i)
-
@property
def _is_mixed_type(self):
return False
@@ -2646,8 +2645,10 @@ def reindex(self, index=None, method=None, level=None, fill_value=pa.NA,
level=level, limit=limit,
takeable=takeable)
- # GH4246 (dispatch to a common method with frame to handle possibly duplicate index)
- return self._reindex_with_indexers(new_index, indexer, copy=copy, fill_value=fill_value)
+ # GH4246 (dispatch to a common method with frame to handle possibly
+ # duplicate index)
+ return self._reindex_with_indexers(new_index, indexer, copy=copy,
+ fill_value=fill_value)
def _reindex_with_indexers(self, index, indexer, copy, fill_value):
new_values = com.take_1d(self.values, indexer, fill_value=fill_value)
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index faaac1cbb5419..3e74b71441410 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -3,7 +3,7 @@
import string
import unittest
-from datetime import datetime, date
+from datetime import datetime, date, timedelta
from pandas import Series, DataFrame, MultiIndex, PeriodIndex, date_range
from pandas.compat import range, lrange, StringIO, lmap, lzip, u, zip
@@ -309,6 +309,16 @@ def test_invalid_kind(self):
s = Series([1, 2])
self.assertRaises(ValueError, s.plot, kind='aasdf')
+ @slow
+ def test_dup_datetime_index_plot(self):
+ dr1 = date_range('1/1/2009', periods=4)
+ dr2 = date_range('1/2/2009', periods=4)
+ index = dr1.append(dr2)
+ values = randn(index.size)
+ s = Series(values, index=index)
+ _check_plot_works(s.plot)
+
+
class TestDataFramePlots(unittest.TestCase):
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 5deff90244135..9ae88c071eb27 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -1041,7 +1041,7 @@ def _get_xticks(self, convert_period=False):
"""
x = index._mpl_repr()
elif is_datetype:
- self.data = self.data.reindex(index=index.order())
+ self.data = self.data.sort_index()
x = self.data.index._mpl_repr()
else:
self._need_to_set_index = True
| closes #4486.
| https://api.github.com/repos/pandas-dev/pandas/pulls/4492 | 2013-08-07T02:12:03Z | 2013-08-07T17:22:27Z | 2013-08-07T17:22:27Z | 2014-06-23T05:29:07Z |
TST: reverse hdf_fix | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 9034007be2f6e..4295139965f81 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -332,11 +332,12 @@ def __len__(self):
def __unicode__(self):
output = '%s\nFile path: %s\n' % (type(self), pprint_thing(self._path))
if self.is_open:
- if len(list(self.keys())):
+ lkeys = list(self.keys())
+ if len(lkeys):
keys = []
values = []
- for k in self.keys():
+ for k in lkeys:
try:
s = self.get_storer(k)
if s is not None:
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 4ccbbb7e18cb2..43b77ec7bdd82 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -11,7 +11,7 @@
import pandas
from pandas import (Series, DataFrame, Panel, MultiIndex, bdate_range,
- date_range, Index, DatetimeIndex)
+ date_range, Index, DatetimeIndex, isnull)
from pandas.io.pytables import (HDFStore, get_store, Term, read_hdf,
IncompatibilityWarning, PerformanceWarning,
AttributeConflictWarning, DuplicateWarning,
@@ -2404,14 +2404,11 @@ def test_frame_select(self):
def test_string_select(self):
# GH 2973
-
- df = tm.makeTimeDataFrame()
-
with ensure_clean(self.path) as store:
+ df = tm.makeTimeDataFrame()
# test string ==/!=
-
df['x'] = 'none'
df.ix[2:7,'x'] = ''
@@ -2421,25 +2418,18 @@ def test_string_select(self):
expected = df[df.x == 'none']
assert_frame_equal(result,expected)
- print("bogus test")
- print(df)
- print(store)
result = store.select('df',Term('x!=none'))
- print(result)
expected = df[df.x != 'none']
- print(expected)
assert_frame_equal(result,expected)
df2 = df.copy()
- df2.x[df2.x==''] = np.nan
+ df2.loc[df2.x=='','x'] = np.nan
- from pandas import isnull
store.append('df2',df2,data_columns=['x'])
result = store.select('df2',Term('x!=none'))
expected = df2[isnull(df2.x)]
assert_frame_equal(result,expected)
-
# int ==/!=
df['int'] = 1
df.ix[2:7,'int'] = 2
| https://api.github.com/repos/pandas-dev/pandas/pulls/4490 | 2013-08-07T01:04:42Z | 2013-08-07T01:17:10Z | 2013-08-07T01:17:10Z | 2014-07-16T08:22:05Z | |
TST: test for breaking test in pytables on travis | diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index ec2dce753c6b5..4ccbbb7e18cb2 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -2421,8 +2421,13 @@ def test_string_select(self):
expected = df[df.x == 'none']
assert_frame_equal(result,expected)
+ print("bogus test")
+ print(df)
+ print(store)
result = store.select('df',Term('x!=none'))
+ print(result)
expected = df[df.x != 'none']
+ print(expected)
assert_frame_equal(result,expected)
df2 = df.copy()
| https://api.github.com/repos/pandas-dev/pandas/pulls/4489 | 2013-08-07T00:42:40Z | 2013-08-07T00:42:51Z | 2013-08-07T00:42:51Z | 2014-06-18T10:03:26Z | |
Backport PR #42057 on branch 1.3.x (PERF: contiguity, less gil in join algos) | diff --git a/pandas/_libs/algos_take_helper.pxi.in b/pandas/_libs/algos_take_helper.pxi.in
index 11679fc432edc..96605fd2009fb 100644
--- a/pandas/_libs/algos_take_helper.pxi.in
+++ b/pandas/_libs/algos_take_helper.pxi.in
@@ -9,31 +9,6 @@ WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in
# ----------------------------------------------------------------------
-@cython.wraparound(False)
-@cython.boundscheck(False)
-def take_1d_intp_intp(
- const intp_t[:] values,
- const intp_t[:] indexer,
- intp_t[::1] out,
- intp_t fill_value=-1,
-):
- cdef:
- Py_ssize_t i, n, idx
- intp_t fv
-
- n = indexer.shape[0]
-
- fv = fill_value
-
- with nogil:
- for i in range(n):
- idx = indexer[i]
- if idx == -1:
- out[i] = fv
- else:
- out[i] = values[idx]
-
-
{{py:
# c_type_in, c_type_out
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx
index b69b89c0de019..eefa16d23f576 100644
--- a/pandas/_libs/join.pyx
+++ b/pandas/_libs/join.pyx
@@ -20,27 +20,22 @@ from numpy cimport (
cnp.import_array()
-from pandas._libs.algos import (
- groupsort_indexer,
- take_1d_int64_int64,
- take_1d_intp_intp,
-)
+from pandas._libs.algos import groupsort_indexer
+@cython.wraparound(False)
@cython.boundscheck(False)
def inner_join(const intp_t[:] left, const intp_t[:] right,
Py_ssize_t max_groups):
cdef:
Py_ssize_t i, j, k, count = 0
- ndarray[intp_t] left_sorter, right_sorter
- ndarray[intp_t] left_count, right_count
- ndarray[intp_t] left_indexer, right_indexer
+ intp_t[::1] left_sorter, right_sorter
+ intp_t[::1] left_count, right_count
+ intp_t[::1] left_indexer, right_indexer
intp_t lc, rc
- Py_ssize_t loc, left_pos = 0, right_pos = 0, position = 0
+ Py_ssize_t left_pos = 0, right_pos = 0, position = 0
Py_ssize_t offset
- # NA group in location 0
-
left_sorter, left_count = groupsort_indexer(left, max_groups)
right_sorter, right_count = groupsort_indexer(right, max_groups)
@@ -53,14 +48,13 @@ def inner_join(const intp_t[:] left, const intp_t[:] right,
if rc > 0 and lc > 0:
count += lc * rc
- # exclude the NA group
- left_pos = left_count[0]
- right_pos = right_count[0]
-
left_indexer = np.empty(count, dtype=np.intp)
right_indexer = np.empty(count, dtype=np.intp)
with nogil:
+ # exclude the NA group
+ left_pos = left_count[0]
+ right_pos = right_count[0]
for i in range(1, max_groups + 1):
lc = left_count[i]
rc = right_count[i]
@@ -75,24 +69,27 @@ def inner_join(const intp_t[:] left, const intp_t[:] right,
left_pos += lc
right_pos += rc
- return (_get_result_indexer(left_sorter, left_indexer),
- _get_result_indexer(right_sorter, right_indexer))
+ # Will overwrite left/right indexer with the result
+ _get_result_indexer(left_sorter, left_indexer)
+ _get_result_indexer(right_sorter, right_indexer)
+
+ return np.asarray(left_indexer), np.asarray(right_indexer)
+@cython.wraparound(False)
@cython.boundscheck(False)
def left_outer_join(const intp_t[:] left, const intp_t[:] right,
Py_ssize_t max_groups, bint sort=True):
cdef:
Py_ssize_t i, j, k, count = 0
- ndarray[intp_t] left_count, right_count
- ndarray[intp_t] rev, left_sorter, right_sorter
- ndarray[intp_t] left_indexer, right_indexer
+ ndarray[intp_t] rev
+ intp_t[::1] left_count, right_count
+ intp_t[::1] left_sorter, right_sorter
+ intp_t[::1] left_indexer, right_indexer
intp_t lc, rc
- Py_ssize_t loc, left_pos = 0, right_pos = 0, position = 0
+ Py_ssize_t left_pos = 0, right_pos = 0, position = 0
Py_ssize_t offset
- # NA group in location 0
-
left_sorter, left_count = groupsort_indexer(left, max_groups)
right_sorter, right_count = groupsort_indexer(right, max_groups)
@@ -104,14 +101,13 @@ def left_outer_join(const intp_t[:] left, const intp_t[:] right,
else:
count += left_count[i]
- # exclude the NA group
- left_pos = left_count[0]
- right_pos = right_count[0]
-
left_indexer = np.empty(count, dtype=np.intp)
right_indexer = np.empty(count, dtype=np.intp)
with nogil:
+ # exclude the NA group
+ left_pos = left_count[0]
+ right_pos = right_count[0]
for i in range(1, max_groups + 1):
lc = left_count[i]
rc = right_count[i]
@@ -131,40 +127,38 @@ def left_outer_join(const intp_t[:] left, const intp_t[:] right,
left_pos += lc
right_pos += rc
- left_indexer = _get_result_indexer(left_sorter, left_indexer)
- right_indexer = _get_result_indexer(right_sorter, right_indexer)
+ # Will overwrite left/right indexer with the result
+ _get_result_indexer(left_sorter, left_indexer)
+ _get_result_indexer(right_sorter, right_indexer)
if not sort: # if not asked to sort, revert to original order
- # cast to avoid build warning GH#26757
- if <Py_ssize_t>len(left) == len(left_indexer):
+ if len(left) == len(left_indexer):
# no multiple matches for any row on the left
# this is a short-cut to avoid groupsort_indexer
# otherwise, the `else` path also works in this case
rev = np.empty(len(left), dtype=np.intp)
- rev.put(left_sorter, np.arange(len(left)))
+ rev.put(np.asarray(left_sorter), np.arange(len(left)))
else:
rev, _ = groupsort_indexer(left_indexer, len(left))
- right_indexer = right_indexer.take(rev)
- left_indexer = left_indexer.take(rev)
-
- return left_indexer, right_indexer
+ return np.asarray(left_indexer).take(rev), np.asarray(right_indexer).take(rev)
+ else:
+ return np.asarray(left_indexer), np.asarray(right_indexer)
+@cython.wraparound(False)
@cython.boundscheck(False)
def full_outer_join(const intp_t[:] left, const intp_t[:] right,
Py_ssize_t max_groups):
cdef:
Py_ssize_t i, j, k, count = 0
- ndarray[intp_t] left_sorter, right_sorter
- ndarray[intp_t] left_count, right_count
- ndarray[intp_t] left_indexer, right_indexer
+ intp_t[::1] left_sorter, right_sorter
+ intp_t[::1] left_count, right_count
+ intp_t[::1] left_indexer, right_indexer
intp_t lc, rc
intp_t left_pos = 0, right_pos = 0
Py_ssize_t offset, position = 0
- # NA group in location 0
-
left_sorter, left_count = groupsort_indexer(left, max_groups)
right_sorter, right_count = groupsort_indexer(right, max_groups)
@@ -179,14 +173,13 @@ def full_outer_join(const intp_t[:] left, const intp_t[:] right,
else:
count += lc + rc
- # exclude the NA group
- left_pos = left_count[0]
- right_pos = right_count[0]
-
left_indexer = np.empty(count, dtype=np.intp)
right_indexer = np.empty(count, dtype=np.intp)
with nogil:
+ # exclude the NA group
+ left_pos = left_count[0]
+ right_pos = right_count[0]
for i in range(1, max_groups + 1):
lc = left_count[i]
rc = right_count[i]
@@ -211,24 +204,33 @@ def full_outer_join(const intp_t[:] left, const intp_t[:] right,
left_pos += lc
right_pos += rc
- return (_get_result_indexer(left_sorter, left_indexer),
- _get_result_indexer(right_sorter, right_indexer))
+ # Will overwrite left/right indexer with the result
+ _get_result_indexer(left_sorter, left_indexer)
+ _get_result_indexer(right_sorter, right_indexer)
+
+ return np.asarray(left_indexer), np.asarray(right_indexer)
-cdef ndarray[intp_t] _get_result_indexer(
- ndarray[intp_t] sorter, ndarray[intp_t] indexer
-):
+@cython.wraparound(False)
+@cython.boundscheck(False)
+cdef void _get_result_indexer(intp_t[::1] sorter, intp_t[::1] indexer) nogil:
+ """NOTE: overwrites indexer with the result to avoid allocating another array"""
+ cdef:
+ Py_ssize_t i, n, idx
+
if len(sorter) > 0:
# cython-only equivalent to
# `res = algos.take_nd(sorter, indexer, fill_value=-1)`
- res = np.empty(len(indexer), dtype=np.intp)
- take_1d_intp_intp(sorter, indexer, res, -1)
+ n = indexer.shape[0]
+ for i in range(n):
+ idx = indexer[i]
+ if idx == -1:
+ indexer[i] = -1
+ else:
+ indexer[i] = sorter[idx]
else:
# length-0 case
- res = np.empty(len(indexer), dtype=np.intp)
- res[:] = -1
-
- return res
+ indexer[:] = -1
def ffill_indexer(const intp_t[:] indexer) -> np.ndarray:
| Backport PR #42057: PERF: contiguity, less gil in join algos | https://api.github.com/repos/pandas-dev/pandas/pulls/42075 | 2021-06-17T13:26:32Z | 2021-06-17T14:56:35Z | 2021-06-17T14:56:35Z | 2021-06-17T14:56:35Z |
Backport PR #41897 on branch 1.3.x (BUG: to_hdf append string column to incompatible column) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 7159f422e3fd6..6c2fef3808566 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1080,6 +1080,7 @@ I/O
- Bug in the conversion from PyArrow to pandas (e.g. for reading Parquet) with nullable dtypes and a PyArrow array whose data buffer size is not a multiple of the dtype size (:issue:`40896`)
- Bug in :func:`read_excel` would raise an error when pandas could not determine the file type even though the user specified the ``engine`` argument (:issue:`41225`)
- Bug in :func:`read_clipboard` copying from an excel file shifts values into the wrong column if there are null values in first column (:issue:`41108`)
+- Bug in :meth:`DataFrame.to_hdf` and :meth:`Series.to_hdf` raising a ``TypeError`` when trying to append a string column to an incompatible column (:issue:`41897`)
Period
^^^^^^
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 208b8a008ffe6..1b4bd62ee7db7 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -5000,7 +5000,7 @@ def _maybe_convert_for_string_atom(
# check for column in the values conflicts
if existing_col is not None:
eci = existing_col.validate_col(itemsize)
- if eci > itemsize:
+ if eci is not None and eci > itemsize:
itemsize = eci
data_converted = data_converted.astype(f"|S{itemsize}", copy=False)
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index 719b54a57a6c7..b5f9e6e74ece9 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -778,6 +778,22 @@ def test_append_raise(setup_path):
with pytest.raises(ValueError, match=msg):
store.append("df", df)
+ # incompatible type (GH 41897)
+ _maybe_remove(store, "df")
+ df["foo"] = Timestamp("20130101")
+ store.append("df", df)
+ df["foo"] = "bar"
+ msg = re.escape(
+ "invalid combination of [values_axes] on appending data "
+ "[name->values_block_1,cname->values_block_1,"
+ "dtype->bytes24,kind->string,shape->(1, 30)] "
+ "vs current table "
+ "[name->values_block_1,cname->values_block_1,"
+ "dtype->datetime64,kind->datetime64,shape->None]"
+ )
+ with pytest.raises(ValueError, match=msg):
+ store.append("df", df)
+
def test_append_with_timedelta(setup_path):
# GH 3577
| Backport PR #41897: BUG: to_hdf append string column to incompatible column | https://api.github.com/repos/pandas-dev/pandas/pulls/42074 | 2021-06-17T13:16:14Z | 2021-06-17T14:56:57Z | 2021-06-17T14:56:57Z | 2021-06-17T14:56:57Z |
CI: pin psycopg2 in Linux_py37_cov on 1.2.x | diff --git a/ci/deps/actions-37-cov.yaml b/ci/deps/actions-37-cov.yaml
index fd4c05802ccd3..5d9ba70e37307 100644
--- a/ci/deps/actions-37-cov.yaml
+++ b/ci/deps/actions-37-cov.yaml
@@ -30,7 +30,7 @@ dependencies:
- openpyxl
- pandas-gbq
- google-cloud-bigquery>=1.27.2 # GH 36436
- - psycopg2
+ - psycopg2=2.8.6
- pyarrow>=0.15.0
- pymysql<0.10.0 # temporary pin, GH 36465
- pytables
| https://api.github.com/repos/pandas-dev/pandas/pulls/42073 | 2021-06-17T13:15:24Z | 2021-06-17T14:03:28Z | 2021-06-17T14:03:28Z | 2021-06-17T14:03:32Z | |
ENH: `Styler.set_sticky` for maintaining index and column headers in HTML frame | diff --git a/doc/source/reference/style.rst b/doc/source/reference/style.rst
index ae3647185f93d..aad56aa0c37e8 100644
--- a/doc/source/reference/style.rst
+++ b/doc/source/reference/style.rst
@@ -40,6 +40,7 @@ Style application
Styler.set_table_attributes
Styler.set_tooltips
Styler.set_caption
+ Styler.set_sticky
Styler.set_properties
Styler.set_uuid
Styler.clear
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb
index 677e4b10b846b..6e10e6ec74b48 100644
--- a/doc/source/user_guide/style.ipynb
+++ b/doc/source/user_guide/style.ipynb
@@ -1405,7 +1405,26 @@
"source": [
"### Sticky Headers\n",
"\n",
- "If you display a large matrix or DataFrame in a notebook, but you want to always see the column and row headers you can use the following CSS to make them stick. We might make this into an API function later."
+ "If you display a large matrix or DataFrame in a notebook, but you want to always see the column and row headers you can use the [.set_sticky][sticky] method which manipulates the table styles CSS.\n",
+ "\n",
+ "[sticky]: ../reference/api/pandas.io.formats.style.Styler.set_sticky.rst"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "bigdf = pd.DataFrame(np.random.randn(16, 100))\n",
+ "bigdf.style.set_sticky(axis=\"index\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is also possible to stick MultiIndexes and even only specific levels."
]
},
{
@@ -1414,11 +1433,8 @@
"metadata": {},
"outputs": [],
"source": [
- "bigdf = pd.DataFrame(np.random.randn(15, 100))\n",
- "bigdf.style.set_table_styles([\n",
- " {'selector': 'thead th', 'props': 'position: sticky; top:0; background-color:salmon;'},\n",
- " {'selector': 'tbody th', 'props': 'position: sticky; left:0; background-color:lightgreen;'} \n",
- "])"
+ "bigdf.index = pd.MultiIndex.from_product([[\"A\",\"B\"],[0,1],[0,1,2,3]])\n",
+ "bigdf.style.set_sticky(axis=\"index\", pixel_size=18, levels=[1,2])"
]
},
{
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 7159f422e3fd6..3c0d48c7ca840 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -138,6 +138,7 @@ which has been revised and improved (:issue:`39720`, :issue:`39317`, :issue:`404
- Added the option ``styler.render.max_elements`` to avoid browser overload when styling large DataFrames (:issue:`40712`)
- Added the method :meth:`.Styler.to_latex` (:issue:`21673`), which also allows some limited CSS conversion (:issue:`40731`)
- Added the method :meth:`.Styler.to_html` (:issue:`13379`)
+ - Added the method :meth:`.Styler.set_sticky` to make index and column headers permanently visible in scrolling HTML frames (:issue:`29072`)
.. _whatsnew_130.enhancements.dataframe_honors_copy_with_dict:
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 39e05d1dde061..c03275b565fd4 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -1414,6 +1414,71 @@ def set_caption(self, caption: str | tuple) -> Styler:
self.caption = caption
return self
+ def set_sticky(
+ self,
+ axis: Axis = 0,
+ pixel_size: int | None = None,
+ levels: list[int] | None = None,
+ ) -> Styler:
+ """
+ Add CSS to permanently display the index or column headers in a scrolling frame.
+
+ Parameters
+ ----------
+ axis : {0 or 'index', 1 or 'columns', None}, default 0
+ Whether to make the index or column headers sticky.
+ pixel_size : int, optional
+ Required to configure the width of index cells or the height of column
+ header cells when sticking a MultiIndex. Defaults to 75 and 25 respectively.
+ levels : list of int
+ If ``axis`` is a MultiIndex the specific levels to stick. If ``None`` will
+ stick all levels.
+
+ Returns
+ -------
+ self : Styler
+ """
+ if axis in [0, "index"]:
+ axis, obj, tag, pos = 0, self.data.index, "tbody", "left"
+ pixel_size = 75 if not pixel_size else pixel_size
+ elif axis in [1, "columns"]:
+ axis, obj, tag, pos = 1, self.data.columns, "thead", "top"
+ pixel_size = 25 if not pixel_size else pixel_size
+ else:
+ raise ValueError("`axis` must be one of {0, 1, 'index', 'columns'}")
+
+ if not isinstance(obj, pd.MultiIndex):
+ return self.set_table_styles(
+ [
+ {
+ "selector": f"{tag} th",
+ "props": f"position:sticky; {pos}:0px; background-color:white;",
+ }
+ ],
+ overwrite=False,
+ )
+ else:
+ range_idx = list(range(obj.nlevels))
+
+ levels = sorted(levels) if levels else range_idx
+ for i, level in enumerate(levels):
+ self.set_table_styles(
+ [
+ {
+ "selector": f"{tag} th.level{level}",
+ "props": f"position: sticky; "
+ f"{pos}: {i * pixel_size}px; "
+ f"{f'height: {pixel_size}px; ' if axis == 1 else ''}"
+ f"{f'min-width: {pixel_size}px; ' if axis == 0 else ''}"
+ f"{f'max-width: {pixel_size}px; ' if axis == 0 else ''}"
+ f"background-color: white;",
+ }
+ ],
+ overwrite=False,
+ )
+
+ return self
+
def set_table_styles(
self,
table_styles: dict[Any, CSSStyles] | CSSStyles,
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index 74b4c7ea3977c..1ef5fc3adc50e 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -1,8 +1,12 @@
from textwrap import dedent
+import numpy as np
import pytest
-from pandas import DataFrame
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
jinja2 = pytest.importorskip("jinja2")
from pandas.io.formats.style import Styler
@@ -16,6 +20,12 @@ def styler():
return Styler(DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"]))
+@pytest.fixture
+def styler_mi():
+ midx = MultiIndex.from_product([["a", "b"], ["c", "d"]])
+ return Styler(DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx))
+
+
@pytest.fixture
def tpl_style():
return env.get_template("html_style.tpl")
@@ -236,3 +246,146 @@ def test_from_custom_template(tmpdir):
def test_caption_as_sequence(styler):
styler.set_caption(("full cap", "short cap"))
assert "<caption>full cap</caption>" in styler.render()
+
+
+@pytest.mark.parametrize("index", [False, True])
+@pytest.mark.parametrize("columns", [False, True])
+def test_sticky_basic(styler, index, columns):
+ if index:
+ styler.set_sticky(axis=0)
+ if columns:
+ styler.set_sticky(axis=1)
+
+ res = styler.set_uuid("").to_html()
+ cs1 = "tbody th {\n position: sticky;\n left: 0px;\n background-color: white;\n}"
+ assert (cs1 in res) is index
+ cs2 = "thead th {\n position: sticky;\n top: 0px;\n background-color: white;\n}"
+ assert (cs2 in res) is columns
+
+
+@pytest.mark.parametrize("index", [False, True])
+@pytest.mark.parametrize("columns", [False, True])
+def test_sticky_mi(styler_mi, index, columns):
+ if index:
+ styler_mi.set_sticky(axis=0)
+ if columns:
+ styler_mi.set_sticky(axis=1)
+
+ res = styler_mi.set_uuid("").to_html()
+ assert (
+ (
+ dedent(
+ """\
+ #T_ tbody th.level0 {
+ position: sticky;
+ left: 0px;
+ min-width: 75px;
+ max-width: 75px;
+ background-color: white;
+ }
+ """
+ )
+ in res
+ )
+ is index
+ )
+ assert (
+ (
+ dedent(
+ """\
+ #T_ tbody th.level1 {
+ position: sticky;
+ left: 75px;
+ min-width: 75px;
+ max-width: 75px;
+ background-color: white;
+ }
+ """
+ )
+ in res
+ )
+ is index
+ )
+ assert (
+ (
+ dedent(
+ """\
+ #T_ thead th.level0 {
+ position: sticky;
+ top: 0px;
+ height: 25px;
+ background-color: white;
+ }
+ """
+ )
+ in res
+ )
+ is columns
+ )
+ assert (
+ (
+ dedent(
+ """\
+ #T_ thead th.level1 {
+ position: sticky;
+ top: 25px;
+ height: 25px;
+ background-color: white;
+ }
+ """
+ )
+ in res
+ )
+ is columns
+ )
+
+
+@pytest.mark.parametrize("index", [False, True])
+@pytest.mark.parametrize("columns", [False, True])
+def test_sticky_levels(styler_mi, index, columns):
+ if index:
+ styler_mi.set_sticky(axis=0, levels=[1])
+ if columns:
+ styler_mi.set_sticky(axis=1, levels=[1])
+
+ res = styler_mi.set_uuid("").to_html()
+ assert "#T_ tbody th.level0 {" not in res
+ assert "#T_ thead th.level0 {" not in res
+ assert (
+ (
+ dedent(
+ """\
+ #T_ tbody th.level1 {
+ position: sticky;
+ left: 0px;
+ min-width: 75px;
+ max-width: 75px;
+ background-color: white;
+ }
+ """
+ )
+ in res
+ )
+ is index
+ )
+ assert (
+ (
+ dedent(
+ """\
+ #T_ thead th.level1 {
+ position: sticky;
+ top: 0px;
+ height: 25px;
+ background-color: white;
+ }
+ """
+ )
+ in res
+ )
+ is columns
+ )
+
+
+def test_sticky_raises(styler):
+ with pytest.raises(ValueError, match="`axis` must be"):
+ styler.set_sticky(axis="bad")
| - [x] closes #29072
This allows you to quickly make the index and/or column headers stick in place when scrolling in HTML.
Additional args allow the control of subselecting specific multiindex levels and controlling the width /or height of the sticking elements.
https://user-images.githubusercontent.com/24256554/122395757-99017700-cf77-11eb-93f0-f3c401afca4e.mov
| https://api.github.com/repos/pandas-dev/pandas/pulls/42072 | 2021-06-17T12:32:05Z | 2021-06-17T23:59:40Z | 2021-06-17T23:59:40Z | 2021-06-18T05:09:13Z |
Backport PR #41987: TST: Un-xfail tests on numpy-dev | diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py
index 0b710d7ebf7d7..e83882be9c680 100644
--- a/pandas/tests/frame/methods/test_to_records.py
+++ b/pandas/tests/frame/methods/test_to_records.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-from pandas.compat.numpy import is_numpy_dev
-
from pandas import (
CategoricalDtype,
DataFrame,
@@ -164,28 +162,20 @@ def test_to_records_with_categorical(self):
),
),
# Pass in a type instance.
- pytest.param(
+ (
{"column_dtypes": str},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")],
),
- marks=pytest.mark.xfail(
- is_numpy_dev,
- reason="https://github.com/numpy/numpy/issues/19078",
- ),
),
# Pass in a dtype instance.
- pytest.param(
+ (
{"column_dtypes": np.dtype("unicode")},
np.rec.array(
[("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")],
),
- marks=pytest.mark.xfail(
- is_numpy_dev,
- reason="https://github.com/numpy/numpy/issues/19078",
- ),
),
# Pass in a dictionary (name-only).
(
| Backport PR #41987 | https://api.github.com/repos/pandas-dev/pandas/pulls/42069 | 2021-06-17T11:35:29Z | 2021-06-17T13:13:22Z | 2021-06-17T13:13:22Z | 2021-06-17T13:13:27Z |
BUG: pd.to_datetime(infer_datetime_format=True) drops timezone | diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py
index 4cbaa184791b8..769889dfbe75d 100644
--- a/asv_bench/benchmarks/inference.py
+++ b/asv_bench/benchmarks/inference.py
@@ -173,6 +173,7 @@ def setup(self):
self.strings_tz_space = [
x.strftime("%Y-%m-%d %H:%M:%S") + " -0800" for x in rng
]
+ self.strings_zero_tz = [x.strftime("%Y-%m-%d %H:%M:%S") + "Z" for x in rng]
def time_iso8601(self):
to_datetime(self.strings)
@@ -189,6 +190,10 @@ def time_iso8601_format_no_sep(self):
def time_iso8601_tz_spaceformat(self):
to_datetime(self.strings_tz_space)
+ def time_iso8601_infer_zero_tz_fromat(self):
+ # GH 41047
+ to_datetime(self.strings_zero_tz, infer_datetime_format=True)
+
class ToDatetimeNONISO8601:
def setup(self):
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 8755ae851d474..8a78d63eab5c8 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -334,6 +334,7 @@ Timedelta
Timezones
^^^^^^^^^
+- Bug in :func:`to_datetime` with ``infer_datetime_format=True`` failing to parse zero UTC offset (``Z``) correctly (:issue:`41047`)
- Bug in :meth:`Series.dt.tz_convert` resetting index in a :class:`Series` with :class:`CategoricalIndex` (:issue:`43080`)
-
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index cfa16df367bce..afbb63ecbd2d7 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -845,15 +845,17 @@ def format_is_iso(f: str) -> bint:
Generally of form YYYY-MM-DDTHH:MM:SS - date separator can be different
but must be consistent. Leading 0s in dates and times are optional.
"""
- iso_template = '%Y{date_sep}%m{date_sep}%d{time_sep}%H:%M:%S.%f'.format
+ iso_template = '%Y{date_sep}%m{date_sep}%d{time_sep}%H:%M:%S{micro_or_tz}'.format
excluded_formats = ['%Y%m%d', '%Y%m', '%Y']
for date_sep in [' ', '/', '\\', '-', '.', '']:
for time_sep in [' ', 'T']:
- if (iso_template(date_sep=date_sep,
- time_sep=time_sep
- ).startswith(f) and f not in excluded_formats):
- return True
+ for micro_or_tz in ['', '%z', '%Z', '.%f', '.%f%z', '.%f%Z']:
+ if (iso_template(date_sep=date_sep,
+ time_sep=time_sep,
+ micro_or_tz=micro_or_tz,
+ ).startswith(f) and f not in excluded_formats):
+ return True
return False
@@ -907,6 +909,7 @@ def guess_datetime_format(
(('second',), '%S', 2),
(('microsecond',), '%f', 6),
(('second', 'microsecond'), '%S.%f', 0),
+ (('tzinfo',), '%z', 0),
(('tzinfo',), '%Z', 0),
]
@@ -927,6 +930,33 @@ def guess_datetime_format(
# that any user-provided function will not either.
tokens = dt_str_split(dt_str)
+ # Normalize offset part of tokens.
+ # There are multiple formats for the timezone offset.
+ # To pass the comparison condition between the output of `strftime` and
+ # joined tokens, which is carried out at the final step of the function,
+ # the offset part of the tokens must match the '%z' format like '+0900'
+ # instead of ‘+09:00’.
+ if parsed_datetime.tzinfo is not None:
+ offset_index = None
+ if len(tokens) > 0 and tokens[-1] == 'Z':
+ # the last 'Z' means zero offset
+ offset_index = -1
+ elif len(tokens) > 1 and tokens[-2] in ('+', '-'):
+ # ex. [..., '+', '0900']
+ offset_index = -2
+ elif len(tokens) > 3 and tokens[-4] in ('+', '-'):
+ # ex. [..., '+', '09', ':', '00']
+ offset_index = -4
+
+ if offset_index is not None:
+ # If the input string has a timezone offset like '+0900',
+ # the offset is separated into two tokens, ex. ['+', '0900’].
+ # This separation will prevent subsequent processing
+ # from correctly parsing the time zone format.
+ # So in addition to the format nomalization, we rejoin them here.
+ tokens[offset_index] = parsed_datetime.strftime("%z")
+ tokens = tokens[:offset_index + 1 or None]
+
format_guess = [None] * len(tokens)
found_attrs = set()
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 469a5caf7d694..a38affbc7f723 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -2032,6 +2032,23 @@ def test_infer_datetime_format_tz_name(self, tz_name, offset):
)
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "ts,zero_tz,is_utc",
+ [
+ ("2019-02-02 08:07:13", "Z", True),
+ ("2019-02-02 08:07:13", "", False),
+ ("2019-02-02 08:07:13.012345", "Z", True),
+ ("2019-02-02 08:07:13.012345", "", False),
+ ],
+ )
+ def test_infer_datetime_format_zero_tz(self, ts, zero_tz, is_utc):
+ # GH 41047
+ s = Series([ts + zero_tz])
+ result = to_datetime(s, infer_datetime_format=True)
+ tz = pytz.utc if is_utc else None
+ expected = Series([Timestamp(ts, tz=tz)])
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.parametrize("cache", [True, False])
def test_to_datetime_iso8601_noleading_0s(self, cache):
# GH 11871
diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py
index e580b9112f3ec..3992457c9c361 100644
--- a/pandas/tests/tslibs/test_parsing.py
+++ b/pandas/tests/tslibs/test_parsing.py
@@ -144,6 +144,28 @@ def test_parsers_month_freq(date_str, expected):
("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-30T00:00:00UTC", "%Y-%m-%dT%H:%M:%S%Z"),
+ ("2011-12-30T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+9", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+09", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+090", None),
+ ("2011-12-30T00:00:00+0900", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00-0900", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+09:00", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+09:000", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+9:0", "%Y-%m-%dT%H:%M:%S%z"),
+ ("2011-12-30T00:00:00+09:", None),
+ ("2011-12-30T00:00:00.000000UTC", "%Y-%m-%dT%H:%M:%S.%f%Z"),
+ ("2011-12-30T00:00:00.000000Z", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+9", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+09", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+090", None),
+ ("2011-12-30T00:00:00.000000+0900", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000-0900", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+09:00", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+09:000", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+9:0", "%Y-%m-%dT%H:%M:%S.%f%z"),
+ ("2011-12-30T00:00:00.000000+09:", None),
("2011-12-30 00:00:00.000000", "%Y-%m-%d %H:%M:%S.%f"),
],
)
@@ -226,3 +248,31 @@ def test_parse_time_string_check_instance_type_raise_exception():
result = parse_time_string("2019")
expected = (datetime(2019, 1, 1), "year")
assert result == expected
+
+
+@pytest.mark.parametrize(
+ "fmt,expected",
+ [
+ ("%Y %m %d %H:%M:%S", True),
+ ("%Y/%m/%d %H:%M:%S", True),
+ (r"%Y\%m\%d %H:%M:%S", True),
+ ("%Y-%m-%d %H:%M:%S", True),
+ ("%Y.%m.%d %H:%M:%S", True),
+ ("%Y%m%d %H:%M:%S", True),
+ ("%Y-%m-%dT%H:%M:%S", True),
+ ("%Y-%m-%dT%H:%M:%S%z", True),
+ ("%Y-%m-%dT%H:%M:%S%Z", True),
+ ("%Y-%m-%dT%H:%M:%S.%f", True),
+ ("%Y-%m-%dT%H:%M:%S.%f%z", True),
+ ("%Y-%m-%dT%H:%M:%S.%f%Z", True),
+ ("%Y%m%d", False),
+ ("%Y%m", False),
+ ("%Y", False),
+ ("%Y-%m-%d", True),
+ ("%Y-%m", True),
+ ],
+)
+def test_is_iso_format(fmt, expected):
+ # see gh-41047
+ result = parsing.format_is_iso(fmt)
+ assert result == expected
| - [x] closes #41047
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
In this PR, I try to fix issue #41047.
I would appreciate it if you could review this PR.
## About the issue
In the UTC format, "Z" is used as a special timezone "+00:00".
But current `pd.to_datetime` function can not recognize the last "Z" when the `infer_datetime_format` is `True`.
Note that `pd.to_datetime` can properly interpret "Z" as "+00:00" when the `infer_datetime_format` is unspecified.
The problem happens in the following codes of datetimes.py:
```py
if infer_datetime_format and format is None:
format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst)
if format is not 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 = format_is_iso(format)
if format_is_iso8601:
require_iso8601 = not infer_datetime_format
format = None
if format is not None:
res = _to_datetime_with_format(
arg, orig_arg, name, tz, format, exact, errors, infer_datetime_format
)
if res is not None:
return res
```
Here, the `_guess_datetime_format_for_array` returns a format string like '%Y-%m-%d %H:%M:%SZ' depending on the input strings.
The resulting format is estimated by `format_is_iso` function.
This result is used to judge whether the function specialized for iso format is used or not.
But current `format_is_iso` can not recognize the last "Z" in a format string, so it returns `False` if the format has "Z" regardless the format is valid iso8601 format or not.
Because of this misjudgment, the wrong function (`_to_datetime_with_format`) is used for the iso string, and the timestamp that does not have timezone information is returned.
## About the fix
I fixed the format_is_iso function to recognize the last "Z" in the format string to solve this problem. | https://api.github.com/repos/pandas-dev/pandas/pulls/42068 | 2021-06-17T11:07:52Z | 2021-09-14T12:35:18Z | 2021-09-14T12:35:17Z | 2021-09-14T12:35:25Z |
Backport PR #42023: CI: pin fsspec | diff --git a/ci/deps/actions-37-cov.yaml b/ci/deps/actions-37-cov.yaml
index 6bdbfa769f772..fd4c05802ccd3 100644
--- a/ci/deps/actions-37-cov.yaml
+++ b/ci/deps/actions-37-cov.yaml
@@ -16,7 +16,7 @@ dependencies:
- botocore>=1.11
- dask
- fastparquet>=0.4.0, <=0.5.0
- - fsspec>=0.7.4
+ - fsspec>=0.7.4, <2021.6.0
- gcsfs>=0.6.0
- geopandas
- html5lib
diff --git a/ci/deps/azure-37.yaml b/ci/deps/azure-37.yaml
index 1f9e2db71baf5..13b46b4d28828 100644
--- a/ci/deps/azure-37.yaml
+++ b/ci/deps/azure-37.yaml
@@ -14,7 +14,7 @@ dependencies:
# pandas dependencies
- botocore>=1.11
- - fsspec>=0.7.4
+ - fsspec>=0.7.4, <2021.6.0
- numpy=1.19
- python-dateutil
- nomkl
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml
index e7ac4c783b855..dd67d9a9c1177 100644
--- a/ci/deps/azure-windows-37.yaml
+++ b/ci/deps/azure-windows-37.yaml
@@ -15,7 +15,7 @@ dependencies:
# pandas dependencies
- beautifulsoup4
- bottleneck
- - fsspec>=0.8.0
+ - fsspec>=0.8.0, <2021.6.0
- gcsfs>=0.6.0
- html5lib
- jinja2
diff --git a/environment.yml b/environment.yml
index 5c47d9c5fa484..ec3c31a15ee02 100644
--- a/environment.yml
+++ b/environment.yml
@@ -104,7 +104,7 @@ dependencies:
- pyqt>=5.9.2 # pandas.read_clipboard
- pytables>=3.5.1 # pandas.read_hdf, DataFrame.to_hdf
- s3fs>=0.4.0 # file IO when using 's3://...' path
- - fsspec>=0.7.4 # for generic remote file operations
+ - fsspec>=0.7.4, <2021.6.0 # for generic remote file operations
- gcsfs>=0.6.0 # file IO when using 'gcs://...' path
- sqlalchemy # pandas.read_sql, DataFrame.to_sql
- xarray # DataFrame.to_xarray
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 33073cf953729..78aca0913b006 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -68,7 +68,7 @@ python-snappy
pyqt5>=5.9.2
tables>=3.5.1
s3fs>=0.4.0
-fsspec>=0.7.4
+fsspec>=0.7.4, <2021.6.0
gcsfs>=0.6.0
sqlalchemy
xarray
| Backport PR #42023 | https://api.github.com/repos/pandas-dev/pandas/pulls/42067 | 2021-06-17T10:37:20Z | 2021-06-17T11:29:51Z | 2021-06-17T11:29:51Z | 2021-06-17T11:29:55Z |
BUG: avoid unnecessary casting in CategoricalIndex.reindex | diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 6500a9c8eef61..760b69c4e88a5 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -399,9 +399,9 @@ def reindex(
indexer = None
missing = np.array([], dtype=np.intp)
else:
- indexer, missing = self.get_indexer_non_unique(np.array(target))
+ indexer, missing = self.get_indexer_non_unique(target)
- if len(self.codes) and indexer is not None:
+ if len(self) and indexer is not None:
new_target = self.take(indexer)
else:
new_target = target
@@ -410,10 +410,8 @@ def reindex(
if len(missing):
cats = self.categories.get_indexer(target)
- if not isinstance(cats, CategoricalIndex) or (cats == -1).any():
- # coerce to a regular index here!
- result = Index(np.array(self), name=self.name)
- new_target, indexer, _ = result._reindex_non_unique(target)
+ if not isinstance(target, CategoricalIndex) or (cats == -1).any():
+ new_target, indexer, _ = super()._reindex_non_unique(target)
else:
codes = new_target.codes.copy()
@@ -426,11 +424,12 @@ def reindex(
# coerce based on the actual values, only on the dtype)
# unless we had an initial Categorical to begin with
# in which case we are going to conform to the passed Categorical
- new_target = np.asarray(new_target)
if is_categorical_dtype(target):
cat = Categorical(new_target, dtype=target.dtype)
new_target = type(self)._simple_new(cat, name=self.name)
else:
+ # e.g. test_reindex_with_categoricalindex, test_reindex_duplicate_target
+ new_target = np.asarray(new_target)
new_target = Index(new_target, name=self.name)
return new_target, indexer
| Doesn't appear to be anything user-facing. The only unequivocally wrong bit is on L420 where the current condition is always truthy. | https://api.github.com/repos/pandas-dev/pandas/pulls/42063 | 2021-06-17T01:10:38Z | 2021-07-12T01:34:38Z | 2021-07-12T01:34:38Z | 2021-07-12T02:12:31Z |
Backport PR #41875 on branch 1.3.x (BUG: unstack with object dtype of tzaware timestamps) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index cadc5615cd654..7159f422e3fd6 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1161,6 +1161,7 @@ Reshaping
- Bug in :func:`to_datetime` raising an error when the input sequence contained unhashable items (:issue:`39756`)
- Bug in :meth:`Series.explode` preserving the index when ``ignore_index`` was ``True`` and values were scalars (:issue:`40487`)
- Bug in :func:`to_datetime` raising a ``ValueError`` when :class:`Series` contains ``None`` and ``NaT`` and has more than 50 elements (:issue:`39882`)
+- Bug in :meth:`Series.unstack` and :meth:`DataFrame.unstack` with object-dtype values containing timezone-aware datetime objects incorrectly raising ``TypeError`` (:issue:`41875`)
- Bug in :meth:`DataFrame.melt` raising ``InvalidIndexError`` when :class:`DataFrame` has duplicate columns used as ``value_vars`` (:issue:`41951`)
Sparse
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 93859eb11dd44..2f45cae46b32e 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -25,11 +25,13 @@
is_object_dtype,
needs_i8_conversion,
)
+from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.missing import notna
import pandas.core.algorithms as algos
from pandas.core.arrays import SparseArray
from pandas.core.arrays.categorical import factorize_from_iterable
+from pandas.core.construction import ensure_wrapped_if_datetimelike
from pandas.core.frame import DataFrame
from pandas.core.indexes.api import (
Index,
@@ -233,15 +235,22 @@ def get_new_values(self, values, fill_value=None):
if mask_all:
dtype = values.dtype
new_values = np.empty(result_shape, dtype=dtype)
+ name = np.dtype(dtype).name
else:
dtype, fill_value = maybe_promote(values.dtype, fill_value)
- new_values = np.empty(result_shape, dtype=dtype)
- new_values.fill(fill_value)
+ if isinstance(dtype, ExtensionDtype):
+ # GH#41875
+ cls = dtype.construct_array_type()
+ new_values = cls._empty(result_shape, dtype=dtype)
+ new_values[:] = fill_value
+ name = dtype.name
+ else:
+ new_values = np.empty(result_shape, dtype=dtype)
+ new_values.fill(fill_value)
+ name = np.dtype(dtype).name
new_mask = np.zeros(result_shape, dtype=bool)
- name = np.dtype(dtype).name
-
# we need to convert to a basic dtype
# and possibly coerce an input to our output dtype
# e.g. ints -> floats
@@ -267,6 +276,10 @@ def get_new_values(self, values, fill_value=None):
# reconstruct dtype if needed
if needs_i8_conversion(values.dtype):
+ # view as datetime64 so we can wrap in DatetimeArray and use
+ # DTA's view method
+ new_values = new_values.view("M8[ns]")
+ new_values = ensure_wrapped_if_datetimelike(new_values)
new_values = new_values.view(values.dtype)
return new_values, new_mask
diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py
index 3e6b1cbfb311c..8f241679d5108 100644
--- a/pandas/tests/extension/base/reshaping.py
+++ b/pandas/tests/extension/base/reshaping.py
@@ -4,6 +4,7 @@
import pytest
from pandas.core.dtypes.common import (
+ is_datetime64tz_dtype,
is_interval_dtype,
is_period_dtype,
)
@@ -328,6 +329,9 @@ def test_unstack(self, data, index, obj):
)
if obj == "series":
# TODO: special cases belong in dtype-specific tests
+ if is_datetime64tz_dtype(data.dtype):
+ assert expected.dtypes.apply(is_datetime64tz_dtype).all()
+ expected = expected.astype(object)
if is_period_dtype(data.dtype):
assert expected.dtypes.apply(is_period_dtype).all()
expected = expected.astype(object)
diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py
index bb8347f0a0122..54e31e05e8b0e 100644
--- a/pandas/tests/extension/test_datetime.py
+++ b/pandas/tests/extension/test_datetime.py
@@ -193,40 +193,6 @@ def test_concat_mixed_dtypes(self, data):
# drops the tz.
super().test_concat_mixed_dtypes(data)
- @pytest.mark.parametrize("obj", ["series", "frame"])
- def test_unstack(self, obj):
- # GH-13287: can't use base test, since building the expected fails.
- dtype = DatetimeTZDtype(tz="US/Central")
- data = DatetimeArray._from_sequence(
- ["2000", "2001", "2002", "2003"],
- dtype=dtype,
- )
- index = pd.MultiIndex.from_product(([["A", "B"], ["a", "b"]]), names=["a", "b"])
-
- if obj == "series":
- ser = pd.Series(data, index=index)
- expected = pd.DataFrame(
- {"A": data.take([0, 1]), "B": data.take([2, 3])},
- index=pd.Index(["a", "b"], name="b"),
- )
- expected.columns.name = "a"
-
- else:
- ser = pd.DataFrame({"A": data, "B": data}, index=index)
- expected = pd.DataFrame(
- {
- ("A", "A"): data.take([0, 1]),
- ("A", "B"): data.take([2, 3]),
- ("B", "A"): data.take([0, 1]),
- ("B", "B"): data.take([2, 3]),
- },
- index=pd.Index(["a", "b"], name="b"),
- )
- expected.columns.names = [None, "a"]
-
- result = ser.unstack(0)
- self.assert_equal(result, expected)
-
class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
pass
| Backport PR #41875: BUG: unstack with object dtype of tzaware timestamps | https://api.github.com/repos/pandas-dev/pandas/pulls/42062 | 2021-06-17T00:31:29Z | 2021-06-17T10:48:16Z | 2021-06-17T10:48:16Z | 2021-06-17T10:48:17Z |
Backport PR #41844 on branch 1.3.x (DOC: Add .to_xyz to io docs) | diff --git a/doc/source/reference/io.rst b/doc/source/reference/io.rst
index 442631de50c7a..82d4ec4950ef1 100644
--- a/doc/source/reference/io.rst
+++ b/doc/source/reference/io.rst
@@ -13,6 +13,7 @@ Pickling
:toctree: api/
read_pickle
+ DataFrame.to_pickle
Flat file
~~~~~~~~~
@@ -21,6 +22,7 @@ Flat file
read_table
read_csv
+ DataFrame.to_csv
read_fwf
Clipboard
@@ -29,6 +31,7 @@ Clipboard
:toctree: api/
read_clipboard
+ DataFrame.to_clipboard
Excel
~~~~~
@@ -36,23 +39,33 @@ Excel
:toctree: api/
read_excel
+ DataFrame.to_excel
ExcelFile.parse
+.. currentmodule:: pandas.io.formats.style
+
+.. autosummary::
+ :toctree: api/
+
+ Styler.to_excel
+
+.. currentmodule:: pandas
+
.. autosummary::
:toctree: api/
:template: autosummary/class_without_autosummary.rst
ExcelWriter
+.. currentmodule:: pandas.io.json
+
JSON
~~~~
.. autosummary::
:toctree: api/
read_json
- json_normalize
-
-.. currentmodule:: pandas.io.json
+ to_json
.. autosummary::
:toctree: api/
@@ -67,6 +80,16 @@ HTML
:toctree: api/
read_html
+ DataFrame.to_html
+
+.. currentmodule:: pandas.io.formats.style
+
+.. autosummary::
+ :toctree: api/
+
+ Styler.to_html
+
+.. currentmodule:: pandas
XML
~~~~
@@ -74,6 +97,23 @@ XML
:toctree: api/
read_xml
+ DataFrame.to_xml
+
+Latex
+~~~~~
+.. autosummary::
+ :toctree: api/
+
+ DataFrame.to_latex
+
+.. currentmodule:: pandas.io.formats.style
+
+.. autosummary::
+ :toctree: api/
+
+ Styler.to_latex
+
+.. currentmodule:: pandas
HDFStore: PyTables (HDF5)
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -101,6 +141,7 @@ Feather
:toctree: api/
read_feather
+ DataFrame.to_feather
Parquet
~~~~~~~
@@ -108,6 +149,7 @@ Parquet
:toctree: api/
read_parquet
+ DataFrame.to_parquet
ORC
~~~
@@ -138,6 +180,7 @@ SQL
read_sql_table
read_sql_query
read_sql
+ DataFrame.to_sql
Google BigQuery
~~~~~~~~~~~~~~~
@@ -152,6 +195,7 @@ STATA
:toctree: api/
read_stata
+ DataFrame.to_stata
.. currentmodule:: pandas.io.stata
| Backport PR #41844: DOC: Add .to_xyz to io docs | https://api.github.com/repos/pandas-dev/pandas/pulls/42060 | 2021-06-16T23:07:53Z | 2021-06-17T00:30:49Z | 2021-06-17T00:30:49Z | 2021-06-17T00:30:49Z |
Backport PR #42052 on branch 1.3.x (DOC: update styler user guide for ref to hiding cols and index and link to to_LaTeX) | diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb
index 7d8d8e90dfbda..677e4b10b846b 100644
--- a/doc/source/user_guide/style.ipynb
+++ b/doc/source/user_guide/style.ipynb
@@ -152,7 +152,7 @@
"\n",
"Before adding styles it is useful to show that the [Styler][styler] can distinguish the *display* value from the *actual* value. To control the display value, the text is printed in each cell, and we can use the [.format()][formatfunc] method to manipulate this according to a [format spec string][format] or a callable that takes a single value and returns a string. It is possible to define this for the whole table or for individual columns. \n",
"\n",
- "Additionally, the format function has a **precision** argument to specifically help formatting floats, an **na_rep** argument to display missing data, and an **escape** argument to help displaying safe-HTML. The default formatter is configured to adopt pandas' regular `display.precision` option, controllable using `with pd.option_context('display.precision', 2):`\n",
+ "Additionally, the format function has a **precision** argument to specifically help formatting floats, as well as **decimal** and **thousands** separators to support other locales, an **na_rep** argument to display missing data, and an **escape** argument to help displaying safe-HTML or safe-LaTeX. The default formatter is configured to adopt pandas' regular `display.precision` option, controllable using `with pd.option_context('display.precision', 2):`\n",
"\n",
"Here is an example of using the multiple options to control the formatting generally and with specific column formatters.\n",
"\n",
@@ -167,9 +167,9 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.format(precision=0, na_rep='MISSING', \n",
+ "df.style.format(precision=0, na_rep='MISSING', thousands=\" \",\n",
" formatter={('Decision Tree', 'Tumour'): \"{:.2f}\",\n",
- " ('Regression', 'Non-Tumour'): lambda x: \"$ {:,.1f}\".format(x*-1e3)\n",
+ " ('Regression', 'Non-Tumour'): lambda x: \"$ {:,.1f}\".format(x*-1e6)\n",
" })"
]
},
@@ -179,9 +179,11 @@
"source": [
"### Hiding Data\n",
"\n",
- "The index can be hidden from rendering by calling [.hide_index()][hideidx], which might be useful if your index is integer based.\n",
+ "The index and column headers can be completely hidden, as well subselecting rows or columns that one wishes to exclude. Both these options are performed using the same methods.\n",
"\n",
- "Columns can be hidden from rendering by calling [.hide_columns()][hidecols] and passing in the name of a column, or a slice of columns.\n",
+ "The index can be hidden from rendering by calling [.hide_index()][hideidx] without any arguments, which might be useful if your index is integer based. Similarly column headers can be hidden by calling [.hide_columns()][hidecols] without any arguments.\n",
+ "\n",
+ "Specific rows or columns can be hidden from rendering by calling the same [.hide_index()][hideidx] or [.hide_columns()][hidecols] methods and passing in a row/column label, a list-like or a slice of row/column labels to for the ``subset`` argument.\n",
"\n",
"Hiding does not change the integer arrangement of CSS classes, e.g. hiding the first two columns of a DataFrame means the column class indexing will start at `col2`, since `col0` and `col1` are simply ignored.\n",
"\n",
@@ -1419,24 +1421,6 @@
"])"
]
},
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Hiding Headers\n",
- "\n",
- "We don't yet have any API to hide headers so a quick fix is:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "df3.style.set_table_styles([{'selector': 'thead tr', 'props': 'display: none;'}]) # or 'thead th'"
- ]
- },
{
"cell_type": "markdown",
"metadata": {},
@@ -1524,6 +1508,17 @@
"\n"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Export to LaTeX\n",
+ "\n",
+ "There is support (*since version 1.3.0*) to export `Styler` to LaTeX. The documentation for the [.to_latex][latex] method gives further detail and numerous examples.\n",
+ "\n",
+ "[latex]: ../reference/api/pandas.io.formats.style.Styler.to_latex.rst"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
| Backport PR #42052: DOC: update styler user guide for ref to hiding cols and index and link to to_LaTeX | https://api.github.com/repos/pandas-dev/pandas/pulls/42059 | 2021-06-16T22:16:11Z | 2021-06-16T23:06:24Z | 2021-06-16T23:06:24Z | 2021-06-16T23:06:24Z |
Backport PR #41952 on branch 1.3.x (BUG: take nans correctly into consideration in complex and tuple) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1a5a9980e5e96..cadc5615cd654 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1033,6 +1033,7 @@ Missing
- Bug in :meth:`DataFrame.fillna` not accepting a dictionary for the ``downcast`` keyword (:issue:`40809`)
- Bug in :func:`isna` not returning a copy of the mask for nullable types, causing any subsequent mask modification to change the original array (:issue:`40935`)
- Bug in :class:`DataFrame` construction with float data containing ``NaN`` and an integer ``dtype`` casting instead of retaining the ``NaN`` (:issue:`26919`)
+- Bug in :meth:`Series.isin` and :meth:`MultiIndex.isin` didn't treat all nans as equivalent if they were in tuples (:issue:`41836`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/_libs/src/klib/khash_python.h b/pandas/_libs/src/klib/khash_python.h
index aee018262e3a6..87c6283c19a2f 100644
--- a/pandas/_libs/src/klib/khash_python.h
+++ b/pandas/_libs/src/klib/khash_python.h
@@ -163,18 +163,90 @@ KHASH_MAP_INIT_COMPLEX128(complex128, size_t)
#define kh_exist_complex128(h, k) (kh_exist(h, k))
+// NaN-floats should be in the same equivalency class, see GH 22119
+int PANDAS_INLINE floatobject_cmp(PyFloatObject* a, PyFloatObject* b){
+ return (
+ Py_IS_NAN(PyFloat_AS_DOUBLE(a)) &&
+ Py_IS_NAN(PyFloat_AS_DOUBLE(b))
+ )
+ ||
+ ( PyFloat_AS_DOUBLE(a) == PyFloat_AS_DOUBLE(b) );
+}
+
+
+// NaNs should be in the same equivalency class, see GH 41836
+// PyObject_RichCompareBool for complexobjects has a different behavior
+// needs to be replaced
+int PANDAS_INLINE complexobject_cmp(PyComplexObject* a, PyComplexObject* b){
+ return (
+ Py_IS_NAN(a->cval.real) &&
+ Py_IS_NAN(b->cval.real) &&
+ Py_IS_NAN(a->cval.imag) &&
+ Py_IS_NAN(b->cval.imag)
+ )
+ ||
+ (
+ Py_IS_NAN(a->cval.real) &&
+ Py_IS_NAN(b->cval.real) &&
+ a->cval.imag == b->cval.imag
+ )
+ ||
+ (
+ a->cval.real == b->cval.real &&
+ Py_IS_NAN(a->cval.imag) &&
+ Py_IS_NAN(b->cval.imag)
+ )
+ ||
+ (
+ a->cval.real == b->cval.real &&
+ a->cval.imag == b->cval.imag
+ );
+}
+
+int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b);
+
+
+// replacing PyObject_RichCompareBool (NaN!=NaN) with pyobject_cmp (NaN==NaN),
+// which treats NaNs as equivalent
+// see GH 41836
+int PANDAS_INLINE tupleobject_cmp(PyTupleObject* a, PyTupleObject* b){
+ Py_ssize_t i;
+
+ if (Py_SIZE(a) != Py_SIZE(b)) {
+ return 0;
+ }
+
+ for (i = 0; i < Py_SIZE(a); ++i) {
+ if (!pyobject_cmp(PyTuple_GET_ITEM(a, i), PyTuple_GET_ITEM(b, i))) {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+
int PANDAS_INLINE pyobject_cmp(PyObject* a, PyObject* b) {
+ if (Py_TYPE(a) == Py_TYPE(b)) {
+ // special handling for some built-in types which could have NaNs
+ // as we would like to have them equivalent, but the usual
+ // PyObject_RichCompareBool would return False
+ if (PyFloat_CheckExact(a)) {
+ return floatobject_cmp((PyFloatObject*)a, (PyFloatObject*)b);
+ }
+ if (PyComplex_CheckExact(a)) {
+ return complexobject_cmp((PyComplexObject*)a, (PyComplexObject*)b);
+ }
+ if (PyTuple_CheckExact(a)) {
+ return tupleobject_cmp((PyTupleObject*)a, (PyTupleObject*)b);
+ }
+ // frozenset isn't yet supported
+ }
+
int result = PyObject_RichCompareBool(a, b, Py_EQ);
if (result < 0) {
PyErr_Clear();
return 0;
}
- if (result == 0) { // still could be two NaNs
- return PyFloat_CheckExact(a) &&
- PyFloat_CheckExact(b) &&
- Py_IS_NAN(PyFloat_AS_DOUBLE(a)) &&
- Py_IS_NAN(PyFloat_AS_DOUBLE(b));
- }
return result;
}
diff --git a/pandas/tests/indexes/multi/test_isin.py b/pandas/tests/indexes/multi/test_isin.py
index 97eb34e28764b..695458273d16e 100644
--- a/pandas/tests/indexes/multi/test_isin.py
+++ b/pandas/tests/indexes/multi/test_isin.py
@@ -1,14 +1,11 @@
import numpy as np
import pytest
-from pandas.compat import PYPY
-
from pandas import MultiIndex
import pandas._testing as tm
-@pytest.mark.skipif(not PYPY, reason="tuples cmp recursively on PyPy")
-def test_isin_nan_pypy():
+def test_isin_nan():
idx = MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]])
tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, True]))
tm.assert_numpy_array_equal(
@@ -31,15 +28,6 @@ def test_isin():
assert result.dtype == np.bool_
-@pytest.mark.skipif(PYPY, reason="tuples cmp recursively on PyPy")
-def test_isin_nan_not_pypy():
- idx = MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]])
- tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, False]))
- tm.assert_numpy_array_equal(
- idx.isin([("bar", float("nan"))]), np.array([False, False])
- )
-
-
def test_isin_level_kwarg():
idx = MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)])
diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index aeff591e3f0dc..0edcebdc069f4 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -8,6 +8,7 @@
import pandas as pd
import pandas._testing as tm
+from pandas.core.algorithms import isin
@contextmanager
@@ -178,6 +179,67 @@ def test_no_reallocation(self, table_type, dtype):
assert n_buckets_start == clean_table.get_state()["n_buckets"]
+class TestPyObjectHashTableWithNans:
+ def test_nan_float(self):
+ nan1 = float("nan")
+ nan2 = float("nan")
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_complex_both(self):
+ nan1 = complex(float("nan"), float("nan"))
+ nan2 = complex(float("nan"), float("nan"))
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_complex_real(self):
+ nan1 = complex(float("nan"), 1)
+ nan2 = complex(float("nan"), 1)
+ other = complex(float("nan"), 2)
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+ def test_nan_complex_imag(self):
+ nan1 = complex(1, float("nan"))
+ nan2 = complex(1, float("nan"))
+ other = complex(2, float("nan"))
+ assert nan1 is not nan2
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+ def test_nan_in_tuple(self):
+ nan1 = (float("nan"),)
+ nan2 = (float("nan"),)
+ assert nan1[0] is not nan2[0]
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+
+ def test_nan_in_nested_tuple(self):
+ nan1 = (1, (2, (float("nan"),)))
+ nan2 = (1, (2, (float("nan"),)))
+ other = (1, 2)
+ table = ht.PyObjectHashTable()
+ table.set_item(nan1, 42)
+ assert table.get_item(nan2) == 42
+ with pytest.raises(KeyError, match=None) as error:
+ table.get_item(other)
+ assert str(error.value) == str(other)
+
+
def test_get_labels_groupby_for_Int64(writable):
table = ht.Int64HashTable()
vals = np.array([1, 2, -1, 2, 1, -1], dtype=np.int64)
@@ -426,3 +488,12 @@ def test_mode(self, dtype, type_suffix):
values = np.array([42, np.nan, np.nan, np.nan], dtype=dtype)
assert mode(values, True) == 42
assert np.isnan(mode(values, False))
+
+
+def test_ismember_tuple_with_nans():
+ # GH-41836
+ values = [("a", float("nan")), ("b", 1)]
+ comps = [("a", float("nan"))]
+ result = isin(values, comps)
+ expected = np.array([True, False], dtype=np.bool_)
+ tm.assert_numpy_array_equal(result, expected)
| Backport PR #41952: BUG: take nans correctly into consideration in complex and tuple | https://api.github.com/repos/pandas-dev/pandas/pulls/42058 | 2021-06-16T22:15:46Z | 2021-06-16T23:06:33Z | 2021-06-16T23:06:33Z | 2021-06-16T23:06:33Z |
PERF: contiguity, less gil in join algos | diff --git a/pandas/_libs/algos_take_helper.pxi.in b/pandas/_libs/algos_take_helper.pxi.in
index 11679fc432edc..96605fd2009fb 100644
--- a/pandas/_libs/algos_take_helper.pxi.in
+++ b/pandas/_libs/algos_take_helper.pxi.in
@@ -9,31 +9,6 @@ WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in
# ----------------------------------------------------------------------
-@cython.wraparound(False)
-@cython.boundscheck(False)
-def take_1d_intp_intp(
- const intp_t[:] values,
- const intp_t[:] indexer,
- intp_t[::1] out,
- intp_t fill_value=-1,
-):
- cdef:
- Py_ssize_t i, n, idx
- intp_t fv
-
- n = indexer.shape[0]
-
- fv = fill_value
-
- with nogil:
- for i in range(n):
- idx = indexer[i]
- if idx == -1:
- out[i] = fv
- else:
- out[i] = values[idx]
-
-
{{py:
# c_type_in, c_type_out
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx
index b69b89c0de019..eefa16d23f576 100644
--- a/pandas/_libs/join.pyx
+++ b/pandas/_libs/join.pyx
@@ -20,27 +20,22 @@ from numpy cimport (
cnp.import_array()
-from pandas._libs.algos import (
- groupsort_indexer,
- take_1d_int64_int64,
- take_1d_intp_intp,
-)
+from pandas._libs.algos import groupsort_indexer
+@cython.wraparound(False)
@cython.boundscheck(False)
def inner_join(const intp_t[:] left, const intp_t[:] right,
Py_ssize_t max_groups):
cdef:
Py_ssize_t i, j, k, count = 0
- ndarray[intp_t] left_sorter, right_sorter
- ndarray[intp_t] left_count, right_count
- ndarray[intp_t] left_indexer, right_indexer
+ intp_t[::1] left_sorter, right_sorter
+ intp_t[::1] left_count, right_count
+ intp_t[::1] left_indexer, right_indexer
intp_t lc, rc
- Py_ssize_t loc, left_pos = 0, right_pos = 0, position = 0
+ Py_ssize_t left_pos = 0, right_pos = 0, position = 0
Py_ssize_t offset
- # NA group in location 0
-
left_sorter, left_count = groupsort_indexer(left, max_groups)
right_sorter, right_count = groupsort_indexer(right, max_groups)
@@ -53,14 +48,13 @@ def inner_join(const intp_t[:] left, const intp_t[:] right,
if rc > 0 and lc > 0:
count += lc * rc
- # exclude the NA group
- left_pos = left_count[0]
- right_pos = right_count[0]
-
left_indexer = np.empty(count, dtype=np.intp)
right_indexer = np.empty(count, dtype=np.intp)
with nogil:
+ # exclude the NA group
+ left_pos = left_count[0]
+ right_pos = right_count[0]
for i in range(1, max_groups + 1):
lc = left_count[i]
rc = right_count[i]
@@ -75,24 +69,27 @@ def inner_join(const intp_t[:] left, const intp_t[:] right,
left_pos += lc
right_pos += rc
- return (_get_result_indexer(left_sorter, left_indexer),
- _get_result_indexer(right_sorter, right_indexer))
+ # Will overwrite left/right indexer with the result
+ _get_result_indexer(left_sorter, left_indexer)
+ _get_result_indexer(right_sorter, right_indexer)
+
+ return np.asarray(left_indexer), np.asarray(right_indexer)
+@cython.wraparound(False)
@cython.boundscheck(False)
def left_outer_join(const intp_t[:] left, const intp_t[:] right,
Py_ssize_t max_groups, bint sort=True):
cdef:
Py_ssize_t i, j, k, count = 0
- ndarray[intp_t] left_count, right_count
- ndarray[intp_t] rev, left_sorter, right_sorter
- ndarray[intp_t] left_indexer, right_indexer
+ ndarray[intp_t] rev
+ intp_t[::1] left_count, right_count
+ intp_t[::1] left_sorter, right_sorter
+ intp_t[::1] left_indexer, right_indexer
intp_t lc, rc
- Py_ssize_t loc, left_pos = 0, right_pos = 0, position = 0
+ Py_ssize_t left_pos = 0, right_pos = 0, position = 0
Py_ssize_t offset
- # NA group in location 0
-
left_sorter, left_count = groupsort_indexer(left, max_groups)
right_sorter, right_count = groupsort_indexer(right, max_groups)
@@ -104,14 +101,13 @@ def left_outer_join(const intp_t[:] left, const intp_t[:] right,
else:
count += left_count[i]
- # exclude the NA group
- left_pos = left_count[0]
- right_pos = right_count[0]
-
left_indexer = np.empty(count, dtype=np.intp)
right_indexer = np.empty(count, dtype=np.intp)
with nogil:
+ # exclude the NA group
+ left_pos = left_count[0]
+ right_pos = right_count[0]
for i in range(1, max_groups + 1):
lc = left_count[i]
rc = right_count[i]
@@ -131,40 +127,38 @@ def left_outer_join(const intp_t[:] left, const intp_t[:] right,
left_pos += lc
right_pos += rc
- left_indexer = _get_result_indexer(left_sorter, left_indexer)
- right_indexer = _get_result_indexer(right_sorter, right_indexer)
+ # Will overwrite left/right indexer with the result
+ _get_result_indexer(left_sorter, left_indexer)
+ _get_result_indexer(right_sorter, right_indexer)
if not sort: # if not asked to sort, revert to original order
- # cast to avoid build warning GH#26757
- if <Py_ssize_t>len(left) == len(left_indexer):
+ if len(left) == len(left_indexer):
# no multiple matches for any row on the left
# this is a short-cut to avoid groupsort_indexer
# otherwise, the `else` path also works in this case
rev = np.empty(len(left), dtype=np.intp)
- rev.put(left_sorter, np.arange(len(left)))
+ rev.put(np.asarray(left_sorter), np.arange(len(left)))
else:
rev, _ = groupsort_indexer(left_indexer, len(left))
- right_indexer = right_indexer.take(rev)
- left_indexer = left_indexer.take(rev)
-
- return left_indexer, right_indexer
+ return np.asarray(left_indexer).take(rev), np.asarray(right_indexer).take(rev)
+ else:
+ return np.asarray(left_indexer), np.asarray(right_indexer)
+@cython.wraparound(False)
@cython.boundscheck(False)
def full_outer_join(const intp_t[:] left, const intp_t[:] right,
Py_ssize_t max_groups):
cdef:
Py_ssize_t i, j, k, count = 0
- ndarray[intp_t] left_sorter, right_sorter
- ndarray[intp_t] left_count, right_count
- ndarray[intp_t] left_indexer, right_indexer
+ intp_t[::1] left_sorter, right_sorter
+ intp_t[::1] left_count, right_count
+ intp_t[::1] left_indexer, right_indexer
intp_t lc, rc
intp_t left_pos = 0, right_pos = 0
Py_ssize_t offset, position = 0
- # NA group in location 0
-
left_sorter, left_count = groupsort_indexer(left, max_groups)
right_sorter, right_count = groupsort_indexer(right, max_groups)
@@ -179,14 +173,13 @@ def full_outer_join(const intp_t[:] left, const intp_t[:] right,
else:
count += lc + rc
- # exclude the NA group
- left_pos = left_count[0]
- right_pos = right_count[0]
-
left_indexer = np.empty(count, dtype=np.intp)
right_indexer = np.empty(count, dtype=np.intp)
with nogil:
+ # exclude the NA group
+ left_pos = left_count[0]
+ right_pos = right_count[0]
for i in range(1, max_groups + 1):
lc = left_count[i]
rc = right_count[i]
@@ -211,24 +204,33 @@ def full_outer_join(const intp_t[:] left, const intp_t[:] right,
left_pos += lc
right_pos += rc
- return (_get_result_indexer(left_sorter, left_indexer),
- _get_result_indexer(right_sorter, right_indexer))
+ # Will overwrite left/right indexer with the result
+ _get_result_indexer(left_sorter, left_indexer)
+ _get_result_indexer(right_sorter, right_indexer)
+
+ return np.asarray(left_indexer), np.asarray(right_indexer)
-cdef ndarray[intp_t] _get_result_indexer(
- ndarray[intp_t] sorter, ndarray[intp_t] indexer
-):
+@cython.wraparound(False)
+@cython.boundscheck(False)
+cdef void _get_result_indexer(intp_t[::1] sorter, intp_t[::1] indexer) nogil:
+ """NOTE: overwrites indexer with the result to avoid allocating another array"""
+ cdef:
+ Py_ssize_t i, n, idx
+
if len(sorter) > 0:
# cython-only equivalent to
# `res = algos.take_nd(sorter, indexer, fill_value=-1)`
- res = np.empty(len(indexer), dtype=np.intp)
- take_1d_intp_intp(sorter, indexer, res, -1)
+ n = indexer.shape[0]
+ for i in range(n):
+ idx = indexer[i]
+ if idx == -1:
+ indexer[i] = -1
+ else:
+ indexer[i] = sorter[idx]
else:
# length-0 case
- res = np.empty(len(indexer), dtype=np.intp)
- res[:] = -1
-
- return res
+ indexer[:] = -1
def ffill_indexer(const intp_t[:] indexer) -> np.ndarray:
| Broken off a branch working towards #13745
This doesn't have noticeable user-facing impact on its own since this is a smaller part of the merge operation. Some timings:
```
import numpy as np
import pandas._libs.join as libjoin
np.random.seed(0)
arr1 = np.random.randint(0, 100, 100000)
arr2 = np.random.randint(0, 100, 100000)
```
Master:
```
In [2]: %timeit libjoin.inner_join(arr1, arr2, 100)
1.19 s ± 17.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [3]: %timeit libjoin.left_outer_join(arr1, arr2, 100)
1.22 s ± 16.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [4]: %timeit libjoin.full_outer_join(arr1, arr2, 100)
1.26 s ± 33.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
This pr:
```
In [2]: %timeit libjoin.inner_join(arr1, arr2, 100)
729 ms ± 17.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [3]: %timeit libjoin.left_outer_join(arr1, arr2, 100)
714 ms ± 11 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [4]: %timeit libjoin.full_outer_join(arr1, arr2, 100)
715 ms ± 6.99 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/42057 | 2021-06-16T21:42:31Z | 2021-06-17T13:26:23Z | 2021-06-17T13:26:23Z | 2021-06-17T17:07:44Z |
DOC: update styler user guide for ref to hiding cols and index and link to to_LaTeX | diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb
index 7d8d8e90dfbda..677e4b10b846b 100644
--- a/doc/source/user_guide/style.ipynb
+++ b/doc/source/user_guide/style.ipynb
@@ -152,7 +152,7 @@
"\n",
"Before adding styles it is useful to show that the [Styler][styler] can distinguish the *display* value from the *actual* value. To control the display value, the text is printed in each cell, and we can use the [.format()][formatfunc] method to manipulate this according to a [format spec string][format] or a callable that takes a single value and returns a string. It is possible to define this for the whole table or for individual columns. \n",
"\n",
- "Additionally, the format function has a **precision** argument to specifically help formatting floats, an **na_rep** argument to display missing data, and an **escape** argument to help displaying safe-HTML. The default formatter is configured to adopt pandas' regular `display.precision` option, controllable using `with pd.option_context('display.precision', 2):`\n",
+ "Additionally, the format function has a **precision** argument to specifically help formatting floats, as well as **decimal** and **thousands** separators to support other locales, an **na_rep** argument to display missing data, and an **escape** argument to help displaying safe-HTML or safe-LaTeX. The default formatter is configured to adopt pandas' regular `display.precision` option, controllable using `with pd.option_context('display.precision', 2):`\n",
"\n",
"Here is an example of using the multiple options to control the formatting generally and with specific column formatters.\n",
"\n",
@@ -167,9 +167,9 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.format(precision=0, na_rep='MISSING', \n",
+ "df.style.format(precision=0, na_rep='MISSING', thousands=\" \",\n",
" formatter={('Decision Tree', 'Tumour'): \"{:.2f}\",\n",
- " ('Regression', 'Non-Tumour'): lambda x: \"$ {:,.1f}\".format(x*-1e3)\n",
+ " ('Regression', 'Non-Tumour'): lambda x: \"$ {:,.1f}\".format(x*-1e6)\n",
" })"
]
},
@@ -179,9 +179,11 @@
"source": [
"### Hiding Data\n",
"\n",
- "The index can be hidden from rendering by calling [.hide_index()][hideidx], which might be useful if your index is integer based.\n",
+ "The index and column headers can be completely hidden, as well subselecting rows or columns that one wishes to exclude. Both these options are performed using the same methods.\n",
"\n",
- "Columns can be hidden from rendering by calling [.hide_columns()][hidecols] and passing in the name of a column, or a slice of columns.\n",
+ "The index can be hidden from rendering by calling [.hide_index()][hideidx] without any arguments, which might be useful if your index is integer based. Similarly column headers can be hidden by calling [.hide_columns()][hidecols] without any arguments.\n",
+ "\n",
+ "Specific rows or columns can be hidden from rendering by calling the same [.hide_index()][hideidx] or [.hide_columns()][hidecols] methods and passing in a row/column label, a list-like or a slice of row/column labels to for the ``subset`` argument.\n",
"\n",
"Hiding does not change the integer arrangement of CSS classes, e.g. hiding the first two columns of a DataFrame means the column class indexing will start at `col2`, since `col0` and `col1` are simply ignored.\n",
"\n",
@@ -1419,24 +1421,6 @@
"])"
]
},
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Hiding Headers\n",
- "\n",
- "We don't yet have any API to hide headers so a quick fix is:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "df3.style.set_table_styles([{'selector': 'thead tr', 'props': 'display: none;'}]) # or 'thead th'"
- ]
- },
{
"cell_type": "markdown",
"metadata": {},
@@ -1524,6 +1508,17 @@
"\n"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Export to LaTeX\n",
+ "\n",
+ "There is support (*since version 1.3.0*) to export `Styler` to LaTeX. The documentation for the [.to_latex][latex] method gives further detail and numerous examples.\n",
+ "\n",
+ "[latex]: ../reference/api/pandas.io.formats.style.Styler.to_latex.rst"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
| should be backported to 1.3.0 as it references the features add there.
| https://api.github.com/repos/pandas-dev/pandas/pulls/42052 | 2021-06-16T11:12:37Z | 2021-06-16T22:16:02Z | 2021-06-16T22:16:02Z | 2021-06-17T06:22:02Z |
Backport PR #42046 on branch 1.3.x (BUG: Don't supply name to Series when using 'size' with agg/apply) | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 388c1881afed7..9e787555f2b1f 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -842,7 +842,7 @@ def apply_str(self) -> FrameOrSeriesUnion:
# Special-cased because DataFrame.size returns a single scalar
obj = self.obj
value = obj.shape[self.axis]
- return obj._constructor_sliced(value, index=self.agg_axis, name="size")
+ return obj._constructor_sliced(value, index=self.agg_axis)
return super().apply_str()
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index 2511f6fc2563c..14266a2c29a7f 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -1279,9 +1279,9 @@ def test_size_as_str(how, axis):
# on the columns
result = getattr(df, how)("size", axis=axis)
if axis == 0 or axis == "index":
- expected = Series(df.shape[0], index=df.columns, name="size")
+ expected = Series(df.shape[0], index=df.columns)
else:
- expected = Series(df.shape[1], index=df.index, name="size")
+ expected = Series(df.shape[1], index=df.index)
tm.assert_series_equal(result, expected)
| Backport PR #42046: BUG: Don't supply name to Series when using 'size' with agg/apply | https://api.github.com/repos/pandas-dev/pandas/pulls/42051 | 2021-06-16T11:09:17Z | 2021-06-16T12:33:54Z | 2021-06-16T12:33:54Z | 2021-06-16T12:33:54Z |
Backport PR #42048 on branch 1.3.x (CI/TST: fix typo in #41982) | diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index de75f1dffde56..9747167296be7 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -536,7 +536,7 @@ def test_constructor(self, dtype):
tm.assert_index_equal(res, idx)
@pytest.mark.xfail(
- not (is_platform_arm and is_platform_mac()),
+ not (is_platform_arm() and is_platform_mac()),
reason="https://github.com/numpy/numpy/issues/19146",
)
def test_constructor_does_not_cast_to_float(self):
| Backport PR #42048: CI/TST: fix typo in #41982 | https://api.github.com/repos/pandas-dev/pandas/pulls/42050 | 2021-06-16T08:14:08Z | 2021-06-16T09:25:25Z | 2021-06-16T09:25:25Z | 2021-06-16T09:25:25Z |
BUG: hash_pandas_object ignores optional arguments when the input is a DataFrame. | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 438313f3e58e2..7269a184358b7 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -1205,6 +1205,7 @@ Other
- Bug in :class:`Series` backed by :class:`DatetimeArray` or :class:`TimedeltaArray` sometimes failing to set the array's ``freq`` to ``None`` (:issue:`41425`)
- Bug in creating a :class:`Series` from a ``range`` object that does not fit in the bounds of ``int64`` dtype (:issue:`30173`)
- Bug in creating a :class:`Series` from a ``dict`` with all-tuple keys and an :class:`Index` that requires reindexing (:issue:`41707`)
+- Bug in :func:`pandas.util.hash_pandas_object` not recognizing ``hash_key``, ``encoding`` and ``categorize`` when the input object type is a :class:`DataFrame` (:issue:`41404`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index 962728b2f38c4..09213b9e37aa2 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -139,7 +139,10 @@ def hash_pandas_object(
ser = Series(h, index=obj.index, dtype="uint64", copy=False)
elif isinstance(obj, ABCDataFrame):
- hashes = (hash_array(series._values) for _, series in obj.items())
+ hashes = (
+ hash_array(series._values, encoding, hash_key, categorize)
+ for _, series in obj.items()
+ )
num_items = len(obj.columns)
if index:
index_hash_generator = (
diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py
index 8ce24dc963dc5..e4a46de11ceb7 100644
--- a/pandas/tests/util/test_hashing.py
+++ b/pandas/tests/util/test_hashing.py
@@ -255,6 +255,32 @@ def test_hash_keys():
assert (a != b).all()
+def test_df_hash_keys():
+ # DataFrame version of the test_hash_keys.
+ # https://github.com/pandas-dev/pandas/issues/41404
+ obj = DataFrame({"x": np.arange(3), "y": list("abc")})
+
+ a = hash_pandas_object(obj, hash_key="9876543210123456")
+ b = hash_pandas_object(obj, hash_key="9876543210123465")
+
+ assert (a != b).all()
+
+
+def test_df_encoding():
+ # Check that DataFrame recognizes optional encoding.
+ # https://github.com/pandas-dev/pandas/issues/41404
+ # https://github.com/pandas-dev/pandas/pull/42049
+ obj = DataFrame({"x": np.arange(3), "y": list("a+c")})
+
+ a = hash_pandas_object(obj, encoding="utf8")
+ b = hash_pandas_object(obj, encoding="utf7")
+
+ # Note that the "+" is encoded as "+-" in utf-7.
+ assert a[0] == b[0]
+ assert a[1] != b[1]
+ assert a[2] == b[2]
+
+
def test_invalid_key():
# This only matters for object dtypes.
msg = "key should be a 16-byte string encoded"
| - [x] closes #41404
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
In this PR, I will try to solve issue #41404.
I would appreciate it if you could review this.
## About the issue
In the current `pandas.util.hash_pandas_object` function implementation, the hash_key argument is ignored when the input object type is a DataFrame.
This is a reproducible example.
```py
df = pd.DataFrame({"x": list("abc")})
new_hash_key = "a"*16
print("Series")
print(pd.util.hash_pandas_object(df["x"]).values)
print(pd.util.hash_pandas_object(df["x"], hash_key=new_hash_key).values)
print("DataFrame")
print(pd.util.hash_pandas_object(df).values)
print(pd.util.hash_pandas_object(df, hash_key=new_hash_key).values)
```
The output is here.
```
Series
[ 4578374827886788867 17338122309987883691 5473791562133574857]
[14372590553486244284 12017144478307119910 34790805896362026]
DataFrame
[ 4578374827886788867 17338122309987883691 5473791562133574857]
[ 4578374827886788867 17338122309987883691 5473791562133574857]
```
The last output should be
```
[14372590553486244284 12017144478307119910 34790805896362026]
```
## About the fix
When the input object is a DataFrame, the hash values are calculated by applying `hash_array` function for each Series.
However, optional arguments, including `hash_key`, are not passed to the hash_array function in the current implementation.
To fix this, I passed the optional arguments to the hash_array function. | https://api.github.com/repos/pandas-dev/pandas/pulls/42049 | 2021-06-16T04:36:31Z | 2021-06-18T15:43:42Z | 2021-06-18T15:43:41Z | 2021-06-18T15:44:18Z |
CI/TST: fix typo in #41982 | diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py
index de75f1dffde56..9747167296be7 100644
--- a/pandas/tests/indexes/numeric/test_numeric.py
+++ b/pandas/tests/indexes/numeric/test_numeric.py
@@ -536,7 +536,7 @@ def test_constructor(self, dtype):
tm.assert_index_equal(res, idx)
@pytest.mark.xfail(
- not (is_platform_arm and is_platform_mac()),
+ not (is_platform_arm() and is_platform_mac()),
reason="https://github.com/numpy/numpy/issues/19146",
)
def test_constructor_does_not_cast_to_float(self):
| fix a typo in #41982, which is causing CI failure. | https://api.github.com/repos/pandas-dev/pandas/pulls/42048 | 2021-06-16T04:10:32Z | 2021-06-16T08:13:43Z | 2021-06-16T08:13:43Z | 2021-06-18T02:21:01Z |
Backport PR #38587 on branch 1.3.x (ENH: Raise ParserWarning when length of names does not match length of data) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 414794dd6a56e..1b5f9dd41eaeb 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -246,6 +246,7 @@ Other enhancements
- Improved error message when ``usecols`` and ``names`` do not match for :func:`read_csv` and ``engine="c"`` (:issue:`29042`)
- Improved consistency of error messages when passing an invalid ``win_type`` argument in :ref:`Window methods <api.window>` (:issue:`15969`)
- :func:`read_sql_query` now accepts a ``dtype`` argument to cast the columnar data from the SQL database based on user input (:issue:`10285`)
+- :func:`read_csv` now raising ``ParserWarning`` if length of header or given names does not match length of data when ``usecols`` is not specified (:issue:`21768`)
- Improved integer type mapping from pandas to SQLAlchemy when using :meth:`DataFrame.to_sql` (:issue:`35076`)
- :func:`to_numeric` now supports downcasting of nullable ``ExtensionDtype`` objects (:issue:`33013`)
- Added support for dict-like names in :class:`MultiIndex.set_names` and :class:`MultiIndex.rename` (:issue:`20421`)
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 2a86ff13a2edc..f914e0601fb89 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -23,6 +23,7 @@
from pandas._libs.parsers import STR_NA_VALUES
from pandas._libs.tslibs import parsing
from pandas._typing import (
+ ArrayLike,
DtypeArg,
FilePathOrBuffer,
final,
@@ -803,6 +804,29 @@ def _do_date_conversions(self, names, data):
return names, data
+ def _check_data_length(self, columns: list[str], data: list[ArrayLike]) -> None:
+ """Checks if length of data is equal to length of column names.
+
+ One set of trailing commas is allowed. self.index_col not False
+ results in a ParserError previously when lengths do not match.
+
+ Parameters
+ ----------
+ columns: list of column names
+ data: list of array-likes containing the data column-wise.
+ """
+ if not self.index_col and len(columns) != len(data) and columns:
+ if len(columns) == len(data) - 1 and np.all(
+ (is_object_dtype(data[-1]) and data[-1] == "") | isna(data[-1])
+ ):
+ return
+ warnings.warn(
+ "Length of header or names does not match length of data. This leads "
+ "to a loss of data with index_col=False.",
+ ParserWarning,
+ stacklevel=6,
+ )
+
def _evaluate_usecols(self, usecols, names):
"""
Check whether or not the 'usecols' parameter
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index 5c1f8f94a72da..110211125514e 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -300,6 +300,8 @@ def read(self, nrows=None):
# columns as list
alldata = [x[1] for x in data_tups]
+ if self.usecols is None:
+ self._check_data_length(names, alldata)
data = {k: v for k, (i, v) in zip(names, data_tups)}
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 670868c6f4261..0d41d2972e799 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -292,6 +292,8 @@ def _exclude_implicit_index(self, alldata):
offset = len(self.index_col) # type: ignore[has-type]
len_alldata = len(alldata)
+ self._check_data_length(names, alldata)
+
return {
name: alldata[i + offset] for i, name in enumerate(names) if i < len_alldata
}, names
diff --git a/pandas/tests/io/parser/common/__init__.py b/pandas/tests/io/parser/common/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py
index ceb770ce72b78..5b7df02603b74 100644
--- a/pandas/tests/io/parser/common/test_chunksize.py
+++ b/pandas/tests/io/parser/common/test_chunksize.py
@@ -143,10 +143,7 @@ def test_read_chunksize_jagged_names(all_parsers):
parser = all_parsers
data = "\n".join(["0"] * 7 + [",".join(["0"] * 10)])
- # error: List item 0 has incompatible type "float"; expected "int"
- expected = DataFrame(
- [[0] + [np.nan] * 9] * 7 + [[0] * 10] # type: ignore[list-item]
- )
+ expected = DataFrame([[0] + [np.nan] * 9] * 7 + [[0] * 10])
with parser.read_csv(StringIO(data), names=range(10), chunksize=4) as reader:
result = concat(reader)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py
index 8fa2d7f7b8d65..a1c76e2740dbe 100644
--- a/pandas/tests/io/parser/common/test_common_basic.py
+++ b/pandas/tests/io/parser/common/test_common_basic.py
@@ -15,6 +15,7 @@
from pandas.errors import (
EmptyDataError,
ParserError,
+ ParserWarning,
)
from pandas import (
@@ -685,7 +686,8 @@ def test_no_header_two_extra_columns(all_parsers):
ref = DataFrame([["foo", "bar", "baz"]], columns=column_names)
stream = StringIO("foo,bar,baz,bam,blah")
parser = all_parsers
- df = parser.read_csv(stream, header=None, names=column_names, index_col=False)
+ with tm.assert_produces_warning(ParserWarning):
+ df = parser.read_csv(stream, header=None, names=column_names, index_col=False)
tm.assert_frame_equal(df, ref)
diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py
index b86dc5ef85fc6..16649be5b8a58 100644
--- a/pandas/tests/io/parser/usecols/test_usecols_basic.py
+++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py
@@ -383,7 +383,9 @@ def test_usecols_indices_out_of_bounds(all_parsers, names):
a,b
1,2
"""
- with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ with tm.assert_produces_warning(
+ FutureWarning, check_stacklevel=False, raise_on_extra_warnings=False
+ ):
result = parser.read_csv(StringIO(data), usecols=[0, 2], names=names, header=0)
expected = DataFrame({"a": [1], "b": [None]})
if names is None and parser.engine == "python":
| Backport PR #38587: ENH: Raise ParserWarning when length of names does not match length of data | https://api.github.com/repos/pandas-dev/pandas/pulls/42047 | 2021-06-16T02:14:33Z | 2021-06-16T08:03:28Z | 2021-06-16T08:03:28Z | 2021-06-16T08:03:29Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.