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 |
|---|---|---|---|---|---|---|---|
BLD: Handle git describe failure more cleanly in setup.py GH5495 | diff --git a/setup.py b/setup.py
index fe921b1ff6029..5a09a27f36eee 100755
--- a/setup.py
+++ b/setup.py
@@ -197,26 +197,30 @@ def build_extensions(self):
FULLVERSION = VERSION
if not ISRELEASED:
+ import subprocess
FULLVERSION += '.dev'
- try:
- import subprocess
+
+ for cmd in ['git','git.cmd']:
try:
- pipe = subprocess.Popen(["git", "describe", "--always"],
- stdout=subprocess.PIPE).stdout
- except OSError:
- # msysgit compatibility
- pipe = subprocess.Popen(
- ["git.cmd", "describe", "--always"],
- stdout=subprocess.PIPE).stdout
- rev = pipe.read().strip()
- # makes distutils blow up on Python 2.7
- if sys.version_info[0] >= 3:
- rev = rev.decode('ascii')
-
- FULLVERSION = rev.lstrip('v')
-
- except:
- warnings.warn("WARNING: Couldn't get git revision")
+ pipe = subprocess.Popen([cmd, "describe", "--always"],
+ stdout=subprocess.PIPE)
+ (so,serr) = pipe.communicate()
+ if pipe.returncode == 0:
+ break
+ except:
+ pass
+
+ if pipe.returncode != 0:
+ warnings.warn("WARNING: Couldn't get git revision, using generic version string")
+ else:
+ rev = so.strip()
+ # makes distutils blow up on Python 2.7
+ if sys.version_info[0] >= 3:
+ rev = rev.decode('ascii')
+
+ # use result og git describe as version string
+ FULLVERSION = rev.lstrip('v')
+
else:
FULLVERSION += QUALIFIER
| closes #5495
| https://api.github.com/repos/pandas-dev/pandas/pulls/5739 | 2013-12-19T04:58:11Z | 2013-12-30T20:55:38Z | 2013-12-30T20:55:38Z | 2014-06-25T08:29:42Z |
BLD: ci/print_versions.py learned to output json | diff --git a/ci/print_versions.py b/ci/print_versions.py
index 560695532e67c..f9123fc28f6fe 100755
--- a/ci/print_versions.py
+++ b/ci/print_versions.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python
-def show_versions():
+
+def show_versions(as_json=False):
import imp
import os
fn = __file__
@@ -9,8 +10,15 @@ def show_versions():
pandas_dir = os.path.abspath(os.path.join(this_dir,".."))
sv_path = os.path.join(pandas_dir, 'pandas','util')
mod = imp.load_module('pvmod', *imp.find_module('print_versions', [sv_path]))
- return mod.show_versions()
+ return mod.show_versions(as_json)
if __name__ == '__main__':
- show_versions()
+ # optparse is 2.6-safe
+ from optparse import OptionParser
+ parser = OptionParser()
+ parser.add_option("-j", "--json", action="store_true", help="Format output as JSON")
+
+ (options, args) = parser.parse_args()
+
+ show_versions(as_json=options.json)
diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py
index c40366ec2d804..ca94448f7294c 100644
--- a/pandas/util/print_versions.py
+++ b/pandas/util/print_versions.py
@@ -1,167 +1,96 @@
import os
import platform
import sys
+import struct
+def get_sys_info():
+ "Returns system information as a dict"
-def show_versions():
- print("\nINSTALLED VERSIONS")
- print("------------------")
- print("Python: %d.%d.%d.%s.%s" % sys.version_info[:])
-
+ # list of tuples over dict because OrderedDict not in 2.6, least
+ # resistance.
+ blob = []
try:
sysname, nodename, release, version, machine, processor = platform.uname()
- print("OS: %s" % (sysname))
- print("Release: %s" % (release))
- #print("Version: %s" % (version))
- #print("Machine: %s" % (machine))
- print("Processor: %s" % (processor))
- print("byteorder: %s" % sys.byteorder)
- print("LC_ALL: %s" % os.environ.get('LC_ALL', "None"))
- print("LANG: %s" % os.environ.get('LANG', "None"))
+ blob = [
+ ("python", "%d.%d.%d.%s.%s" % sys.version_info[:]),
+ ("python-bits", struct.calcsize("P") * 8),
+ ("OS","%s" % (sysname)),
+ ("OS-release", "%s" % (release)),
+ # ("Version", "%s" % (version)),
+ # ("Machine", "%s" % (machine)),
+ ("processor", "%s" % (processor)),
+ ("byteorder", "%s" % sys.byteorder),
+ ("LC_ALL", "%s" % os.environ.get('LC_ALL', "None")),
+ ("LANG", "%s" % os.environ.get('LANG', "None")),
+
+ ]
except:
pass
- print("")
-
- try:
- import pandas
- print("pandas: %s" % pandas.__version__)
- except:
- print("pandas: Not installed")
-
- 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 xlsxwriter
- print("xlsxwriter: %s" % xlsxwriter.__version__)
- except:
- print("xlsxwriter: 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")
-
- try:
- import bq
- print("bigquery: %s" % bq._VersionNumber())
- except:
- print("bigquery: Not installed")
-
- try:
- import apiclient
- print("apiclient: %s" % apiclient.__version__)
- except:
- print("apiclient: Not installed")
-
+ return blob
+
+
+def show_versions(as_json=False):
+ import imp
+ sys_info = get_sys_info()
+
+ deps = [
+ # (MODULE_NAME, f(mod) -> mod version)
+ ("pandas", lambda mod: mod.__version__),
+ ("Cython", lambda mod: mod.__version__),
+ ("numpy", lambda mod: mod.version.version),
+ ("scipy", lambda mod: mod.version.version),
+ ("statsmodels", lambda mod: mod.__version__),
+ ("patsy", lambda mod: mod.__version__),
+ ("scikits.timeseries", lambda mod: mod.__version__),
+ ("dateutil", lambda mod: mod.__version__),
+ ("pytz", lambda mod: mod.VERSION),
+ ("bottleneck", lambda mod: mod.__version__),
+ ("tables", lambda mod: mod.__version__),
+ ("numexpr", lambda mod: mod.__version__),
+ ("matplotlib", lambda mod: mod.__version__),
+ ("openpyxl", lambda mod: mod.__version__),
+ ("xlrd", lambda mod: mod.__VERSION__),
+ ("xlwt", lambda mod: mod.__VERSION__),
+ ("xlsxwriter", lambda mod: mod.__version__),
+ ("sqlalchemy", lambda mod: mod.__version__),
+ ("lxml", lambda mod: mod.etree.__version__),
+ ("bs4", lambda mod: mod.__version__),
+ ("html5lib", lambda mod: mod.__version__),
+ ("bq", lambda mod: mod._VersionNumber()),
+ ("apiclient", lambda mod: mod.__version__),
+ ]
+
+ deps_blob = list()
+ for (modname, ver_f) in deps:
+ try:
+ mod = imp.load_module(modname, *imp.find_module(modname))
+ ver = ver_f(mod)
+ deps_blob.append((modname, ver))
+ except:
+ deps_blob.append((modname, None))
+
+ if (as_json):
+ # 2.6-safe
+ try:
+ import json
+ except:
+ import simplejson as json
+
+ print(json.dumps(dict(system=dict(sys_info), dependencies=dict(deps_blob)), indent=2))
+
+ else:
+
+ print("\nINSTALLED VERSIONS")
+ print("------------------")
+
+ for k, stat in sys_info:
+ print("%s: %s" % (k, stat))
+
+ print("")
+ for k, stat in deps_blob:
+ print("%s: %s" % (k, stat))
if __name__ == "__main__":
- show_versions()
+ show_versions(as_json=False)
| Putting some pieces in place.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5738 | 2013-12-19T04:31:31Z | 2013-12-31T01:24:12Z | 2013-12-31T01:24:12Z | 2014-06-18T11:08:50Z |
BUG: raise KeyError if missing value in py3 on multi-index (GH5725), revisted | diff --git a/pandas/core/index.py b/pandas/core/index.py
index 30f93564db318..5c77c1e5e9516 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2306,8 +2306,11 @@ def _try_mi(k):
compat.PY3 and isinstance(key, compat.string_types)):
try:
return _try_mi(key)
+ except (KeyError):
+ raise
except:
pass
+
try:
return _try_mi(Timestamp(key))
except:
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index e601755ba8aaf..3107b1c679cc7 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -844,15 +844,36 @@ def test_getitem_multiindex(self):
# GH 5725
# the 'A' happens to be a valid Timestamp so the doesn't raise the appropriate
# error, only in PY3 of course!
- index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
+ index = MultiIndex(levels=[['D', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
names=['tag', 'day'])
arr = np.random.randn(len(index),1)
df = DataFrame(arr,index=index,columns=['val'])
+ result = df.val['D']
+ expected = Series(arr.ravel()[0:3],name='val',index=Index([26,37,57],name='day'))
+ assert_series_equal(result,expected)
+
+ def f():
+ df.val['A']
+ self.assertRaises(KeyError, f)
+
+ def f():
+ df.val['X']
+ self.assertRaises(KeyError, f)
+
+ # A is treated as a special Timestamp
+ index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
+ labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
+ names=['tag', 'day'])
+ df = DataFrame(arr,index=index,columns=['val'])
result = df.val['A']
expected = Series(arr.ravel()[0:3],name='val',index=Index([26,37,57],name='day'))
assert_series_equal(result,expected)
+ def f():
+ df.val['X']
+ self.assertRaises(KeyError, f)
+
def test_setitem_dtype_upcast(self):
# GH3216
| #5725
raise KeyError appropriately under py3 on mi series
| https://api.github.com/repos/pandas-dev/pandas/pulls/5737 | 2013-12-19T01:04:09Z | 2013-12-19T01:24:38Z | 2013-12-19T01:24:38Z | 2014-06-19T17:03:00Z |
TST: Cleanup temp files in Excel test. | diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index eeeb914a3754e..edcb80ae74f6f 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -1070,12 +1070,15 @@ def test_ExcelWriter_dispatch(self):
except ImportError:
_skip_if_no_openpyxl()
writer_klass = _OpenpyxlWriter
- writer = ExcelWriter('apple.xlsx')
- tm.assert_isinstance(writer, writer_klass)
+
+ with ensure_clean('.xlsx') as path:
+ writer = ExcelWriter(path)
+ tm.assert_isinstance(writer, writer_klass)
_skip_if_no_xlwt()
- writer = ExcelWriter('apple.xls')
- tm.assert_isinstance(writer, _XlwtWriter)
+ with ensure_clean('.xls') as path:
+ writer = ExcelWriter(path)
+ tm.assert_isinstance(writer, _XlwtWriter)
def test_register_writer(self):
# some awkward mocking to test out dispatch and such actually works
| Fix for issue #5735
| https://api.github.com/repos/pandas-dev/pandas/pulls/5736 | 2013-12-19T00:30:15Z | 2013-12-19T00:31:32Z | 2013-12-19T00:31:32Z | 2014-06-30T06:58:37Z |
Fix prefix argument for read_csv/read_table | diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index bd0649a7a85f3..7004bcaf0cb74 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -972,7 +972,7 @@ def __init__(self, src, **kwds):
if self.names is None:
if self.prefix:
- self.names = ['X%d' % i
+ self.names = ['%s%d' % (self.prefix, i)
for i in range(self._reader.table_width)]
else:
self.names = lrange(self._reader.table_width)
@@ -1563,7 +1563,7 @@ def _infer_columns(self):
num_original_columns = ncols
if not names:
if self.prefix:
- columns = [['X%d' % i for i in range(ncols)]]
+ columns = [['%s%d' % (self.prefix,i) for i in range(ncols)]]
else:
columns = [lrange(ncols)]
columns = self._handle_usecols(columns, columns[0])
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index 93a26b70a019e..4fe95647bae28 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -968,6 +968,22 @@ def test_no_header(self):
self.assert_(np.array_equal(df2.columns, names))
+ def test_no_header_prefix(self):
+ data = """1,2,3,4,5
+6,7,8,9,10
+11,12,13,14,15
+"""
+ df_pref = self.read_table(StringIO(data), sep=',', prefix='Field',
+ header=None)
+
+ expected = [[1, 2, 3, 4, 5.],
+ [6, 7, 8, 9, 10],
+ [11, 12, 13, 14, 15]]
+ tm.assert_almost_equal(df_pref.values, expected)
+
+ self.assert_(np.array_equal(df_pref.columns,
+ ['Field0', 'Field1', 'Field2', 'Field3', 'Field4']))
+
def test_header_with_index_col(self):
data = """foo,1,2,3
bar,4,5,6
| Closes #5732
| https://api.github.com/repos/pandas-dev/pandas/pulls/5733 | 2013-12-18T15:29:56Z | 2014-01-03T01:09:56Z | 2014-01-03T01:09:56Z | 2014-06-14T13:17:44Z |
DOC: add demo of factorize | diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst
index f50586f12d2dd..288cd48b10aca 100644
--- a/doc/source/reshaping.rst
+++ b/doc/source/reshaping.rst
@@ -417,3 +417,25 @@ This function is often used along with discretization functions like ``cut``:
get_dummies(cut(values, bins))
+
+Factorizing values
+------------------
+
+To encode 1-d values as an enumerated type use ``factorize``:
+
+.. ipython:: python
+
+ x = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf])
+ x
+ labels, uniques = pd.factorize(x)
+ labels
+ uniques
+
+Note that ``factorize`` is similar to ``numpy.unique``, but differs in its
+handling of NaN:
+
+.. ipython:: python
+
+ pd.factorize(x, sort=True)
+ np.unique(x, return_inverse=True)[::-1]
+
| Here is some documentation of `factorize`, per [this request](http://stackoverflow.com/questions/20619851/pandas-equivalent-of-statas-encode/20619971?noredirect=1#comment30860849_20619971).
| https://api.github.com/repos/pandas-dev/pandas/pulls/5731 | 2013-12-18T14:57:56Z | 2013-12-18T15:15:45Z | 2013-12-18T15:15:45Z | 2014-07-16T08:43:44Z |
CLN/BUG: indexing fixes (GH5725, GH5727) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index dc82550be6500..3a22de3cb43f3 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -826,6 +826,7 @@ Bug Fixes
- Bug in repeated indexing of object with resultant non-unique index (:issue:`5678`)
- Bug in fillna with Series and a passed series/dict (:issue:`5703`)
- Bug in groupby transform with a datetime-like grouper (:issue:`5712`)
+ - Bug in multi-index selection in PY3 when using certain keys (:issue:`5725`)
pandas 0.12.0
-------------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index b77ea2b22f4fa..e07655b0539a5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -721,13 +721,13 @@ def __setstate__(self, state):
# to avoid definitional recursion
# e.g. say fill_value needing _data to be
# defined
- for k in self._internal_names:
+ for k in self._internal_names_set:
if k in state:
v = state[k]
object.__setattr__(self, k, v)
for k, v in state.items():
- if k not in self._internal_names:
+ if k not in self._internal_names_set:
object.__setattr__(self, k, v)
else:
@@ -938,15 +938,22 @@ def to_clipboard(self, excel=None, sep=None, **kwargs):
@classmethod
def _create_indexer(cls, name, indexer):
""" create an indexer like _name in the class """
- iname = '_%s' % name
- setattr(cls, iname, None)
- def _indexer(self):
- if getattr(self, iname, None) is None:
- setattr(self, iname, indexer(self, name))
- return getattr(self, iname)
+ if getattr(cls, name, None) is None:
+ iname = '_%s' % name
+ setattr(cls, iname, None)
- setattr(cls, name, property(_indexer))
+ def _indexer(self):
+ i = getattr(self, iname)
+ if i is None:
+ i = indexer(self, name)
+ setattr(self, iname, i)
+ return i
+
+ setattr(cls, name, property(_indexer))
+
+ # add to our internal names set
+ cls._internal_names_set.add(iname)
def get(self, key, default=None):
"""
@@ -1831,9 +1838,9 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
value : scalar, dict, or Series
- Value to use to fill holes (e.g. 0), alternately a dict/Series of
- values specifying which value to use for each index (for a Series) or
- column (for a DataFrame). (values not in the dict/Series will not be
+ Value to use to fill holes (e.g. 0), alternately a dict/Series of
+ values specifying which value to use for each index (for a Series) or
+ column (for a DataFrame). (values not in the dict/Series will not be
filled). This value cannot be a list.
axis : {0, 1}, default 0
0: fill column-by-column
@@ -1845,8 +1852,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,
- or the string 'infer' which will try to downcast to an appropriate
+ a dict of item->dtype of what to 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
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 7ae273d08fa87..30f93564db318 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2300,8 +2300,14 @@ def _try_mi(k):
# a Timestamp will raise a TypeError in a multi-index
# rather than a KeyError, try it here
+ # note that a string that 'looks' like a Timestamp will raise
+ # a KeyError! (GH5725)
if isinstance(key, (datetime.datetime, np.datetime64)) or (
compat.PY3 and isinstance(key, compat.string_types)):
+ try:
+ return _try_mi(key)
+ except:
+ pass
try:
return _try_mi(Timestamp(key))
except:
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 4954decd5195b..e601755ba8aaf 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -3,7 +3,7 @@
import itertools
import warnings
-from pandas.compat import range, lrange, StringIO, lmap, map
+from pandas.compat import range, lrange, lzip, StringIO, lmap, map
from numpy import random, nan
from numpy.random import randn
import numpy as np
@@ -249,6 +249,15 @@ def _print(result, error = None):
k2 = key2
_eq(t, o, a, obj, key1, k2)
+ def test_indexer_caching(self):
+ # GH5727
+ # make sure that indexers are in the _internal_names_set
+ n = 1000001
+ arrays = [lrange(n), lrange(n)]
+ index = MultiIndex.from_tuples(lzip(*arrays))
+ s = Series(np.zeros(n), index=index)
+ str(s)
+
def test_at_and_iat_get(self):
def _check(f, func, values = False):
@@ -830,6 +839,20 @@ def test_xs_multiindex(self):
expected.columns = expected.columns.droplevel('lvl1')
assert_frame_equal(result, expected)
+ def test_getitem_multiindex(self):
+
+ # GH 5725
+ # the 'A' happens to be a valid Timestamp so the doesn't raise the appropriate
+ # error, only in PY3 of course!
+ index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
+ labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
+ names=['tag', 'day'])
+ arr = np.random.randn(len(index),1)
+ df = DataFrame(arr,index=index,columns=['val'])
+ result = df.val['A']
+ expected = Series(arr.ravel()[0:3],name='val',index=Index([26,37,57],name='day'))
+ assert_series_equal(result,expected)
+
def test_setitem_dtype_upcast(self):
# GH3216
| closes #5727
closes #5725
| https://api.github.com/repos/pandas-dev/pandas/pulls/5730 | 2013-12-18T14:52:16Z | 2013-12-18T20:30:27Z | 2013-12-18T20:30:27Z | 2014-06-20T00:36:45Z |
DOC: small doc build warning: Note -> Notes | diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 12f21df9e7c0e..3b1b220d3fac7 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -332,8 +332,8 @@ def str_match(arr, pat, case=True, flags=0, na=np.nan, as_indexer=False):
matches : boolean array (if as_indexer=True)
matches : array of tuples (if as_indexer=False, default but deprecated)
- Note
- ----
+ Notes
+ -----
To extract matched groups, which is the deprecated behavior of match, use
str.extract.
"""
| https://api.github.com/repos/pandas-dev/pandas/pulls/5726 | 2013-12-18T08:52:58Z | 2013-12-18T14:57:35Z | 2013-12-18T14:57:35Z | 2014-07-16T08:43:40Z | |
BUG: don't use partial setting with scalars (GH5720) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 5ce9ccd25a7fc..79079cc52a148 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -246,7 +246,7 @@ API Changes
(: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`, :issue:`5226`, :issue:`5632`)
+ (:issue:`2578`, :issue:`5226`, :issue:`5632`, :issue:`5720`)
- Default export for ``to_clipboard`` is now csv with a sep of `\t` for
compat (:issue:`3368`)
- ``at`` now will enlarge the object inplace (and return the same)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 90641a833f2a7..2f299488bd321 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1904,16 +1904,17 @@ def _ensure_valid_index(self, value):
if not len(self.index):
# GH5632, make sure that we are a Series convertible
- try:
- value = Series(value)
- except:
- pass
+ if is_list_like(value):
+ try:
+ value = Series(value)
+ except:
+ pass
- if not isinstance(value, Series):
- raise ValueError('Cannot set a frame with no defined index '
- 'and a value that cannot be converted to a '
- 'Series')
- self._data.set_axis(1, value.index.copy(), check_axis=False)
+ if not isinstance(value, Series):
+ raise ValueError('Cannot set a frame with no defined index '
+ 'and a value that cannot be converted to a '
+ 'Series')
+ self._data.set_axis(1, value.index.copy(), check_axis=False)
def _set_item(self, key, value):
"""
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index e396bee3f4ad9..4954decd5195b 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1730,6 +1730,14 @@ def f():
str(df)
assert_frame_equal(df,expected)
+ # GH5720
+ # don't create rows when empty
+ df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
+ y = df[df.A > 5]
+ y['New'] = np.nan
+ expected = DataFrame(columns=['A','B','New'])
+ assert_frame_equal(y, expected)
+
def test_cache_updating(self):
# GH 4939, make sure to update the cache on setitem
| closes #5720
| https://api.github.com/repos/pandas-dev/pandas/pulls/5723 | 2013-12-17T20:36:18Z | 2013-12-17T21:32:24Z | 2013-12-17T21:32:24Z | 2014-06-21T16:51:31Z |
DOC: DatetimeIndex accepts name param | diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index fd9fac58a973c..23b949c1fedfb 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -119,6 +119,8 @@ class DatetimeIndex(Int64Index):
closed : string or None, default None
Make the interval closed with respect to the given frequency to
the 'left', 'right', or both sides (None)
+ name : object
+ Name to be stored in the index
"""
_join_precedence = 10
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index f2f137e18a15c..f4dcdb7a44a3e 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -1966,6 +1966,11 @@ def test_constructor_coverage(self):
end='2011-01-01', freq='B')
self.assertRaises(ValueError, DatetimeIndex, periods=10, freq='D')
+ def test_constructor_name(self):
+ idx = DatetimeIndex(start='2000-01-01', periods=1, freq='A',
+ name='TEST')
+ self.assertEquals(idx.name, 'TEST')
+
def test_comparisons_coverage(self):
rng = date_range('1/1/2000', periods=10)
| Just a docstring change to reflect `DatetimeIndex` taking a name parameter. I added a test since it wasn't explicitly tested anywhere.
``` python
In [1]: from pandas import DatetimeIndex
In [2]: idx = DatetimeIndex(start='2000-01-01', periods=1, freq='A', name='TEST')
In [3]: idx.name
Out[3]: 'TEST'
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5722 | 2013-12-17T16:26:49Z | 2013-12-17T17:36:22Z | 2013-12-17T17:36:22Z | 2016-11-03T12:37:39Z |
DOC: trim CONTRIBUTING.MD | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2966aed5f57ee..1c1423678fffb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -4,41 +4,39 @@ All contributions, bug reports, bug fixes, documentation improvements,
enhancements and ideas are welcome.
The [GitHub "issues" tab](https://github.com/pydata/pandas/issues)
-contains some issues labeled "Good as first PR"; these are
-tasks which do not require deep knowledge of the package. Look those up if you're
+contains some issues labeled "Good as first PR"; Look those up if you're
looking for a quick way to help out.
-Please try and follow these guidelines, as this makes it easier for us to accept
-your contribution or address the issue you're having.
-
#### Bug Reports
- Please include a short, self-contained Python snippet reproducing the problem.
You can have the code formatted nicely by using [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/) :
```python
-
+
print("I ♥ pandas!")
```
- - A [test case](https://github.com/pydata/pandas/tree/master/pandas/tests) may be more helpful.
- - Specify the pandas (and NumPy) version used. (check `pandas.__version__`
- and `numpy.__version__`)
- - Explain what the expected behavior was, and what you saw instead.
- - If the issue seems to involve some of [pandas' dependencies](https://github.com/pydata/pandas#dependencies)
- such as
- [NumPy](http://numpy.org),
- [matplotlib](http://matplotlib.org/), and
- [PyTables](http://www.pytables.org/)
- you should include (the relevant parts of) the output of
+ - Specify the pandas version used and those of it's dependencies. You can simply include the output of
[`ci/print_versions.py`](https://github.com/pydata/pandas/blob/master/ci/print_versions.py).
+ - Explain what the expected behavior was, and what you saw instead.
#### Pull Requests
- - **Make sure the test suite passes** for both python2 and python3.
- You can use `test_fast.sh`, **tox** locally, and/or enable **Travis-CI** on your fork.
- See "Getting Travis-CI going" below.
+ - **Make sure the test suite passes** on your box, Use the provided `test_*.sh` scripts or tox.
+ - Enable [Travis-Ci](http://travis-ci.org/pydata/pandas). See "Getting Travis-CI going" below.
+ - Use [proper commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html):
+ - a subject line with `< 80` chars.
+ - One blank line.
+ - Optionally, a commit message body.
+ - Please reference relevant Github issues in your commit message using `GH1234`
+ or `#1234`. Either style is fine but the '#' style generates nose when your rebase your PR.
+ - `doc/source/release.rst` and `doc/source/vx.y.z.txt` contain an ongoing
+ changelog for each release. Add entries to these files
+ as needed in a separate commit in your PR: document the fix, enhancement,
+ or (unavoidable) breaking change.
+ - Keep style fixes to a separate commit to make your PR more readable.
- An informal commit message format is in effect for the project. Please try
and adhere to it. Check `git log` for examples. Here are some common prefixes
along with general guidelines for when to use them:
@@ -49,69 +47,25 @@ your contribution or address the issue you're having.
- **BLD**: Updates to the build process/scripts
- **PERF**: Performance improvement
- **CLN**: Code cleanup
- - Commit messages should have:
- - a subject line with `< 80` chars
- - one blank line
- - a commit message body, if there's a need for one
- - If you are changing any code, you should enable Travis-CI on your fork
- to make it easier for the team to see that the PR does indeed pass all the tests.
- - **Backward-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.
- - If there is a need, explain it in the PR.
- - Changes to method signatures should be made in a way which doesn't break existing
- code. For example, you should beware of changes to ordering and naming of keyword
- arguments.
+ - Maintain backward-compatibility. Pandas has lots of users with lots of existing code. Don't break it.
+ - If you think breakage is required clearly state why as part of the PR.
+ - Be careful when changing method signatures.
- Add deprecation warnings where needed.
- - Performance matters. You can use the included `test_perf.sh`
- script to make sure your PR does not introduce any new performance regressions
- in the library.
+ - Performance matters. Make sure your PR hasn't introduced perf regressions by using `test_perf.sh`.
- Docstrings follow the [numpydoc](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) format.
+ - When writing tests, use 2.6 compatible `self.assertFoo` methods. Some polyfills such as `assertRaises`
+ can be found in `pandas.util.testing`.
+ - Generally, pandas source files should not contain attributions. You can include a "thanks to..."
+ in the release changelog. The rest is `git blame`/`git log`.
+ - For extra brownie points, you can squash and reorder the commits in your PR using `git rebase -i`.
+ Use your own judgment to decide what history needs to be preserved. If git frightens you, that's OK too.
+ - Use `raise AssertionError` over `assert` unless you want the assertion stripped by `python -o`.
- **Don't** merge upstream into a branch you're going to submit as a PR.
This can create all sorts of problems. Use `git rebase` instead. This ensures
no merge conflicts occur when your code is merged by the core team.
- - Please reference the GH issue number in your commit message using `GH1234`
- or `#1234`. Either style is fine.
- - Use `raise AssertionError` rather then plain `assert` in library code (`assert` is fine
- for test code). `python -o` strips assertions. Better safe than sorry.
- - When writing tests, don't use "new" assertion methods added to the `unittest` module
- in 2.7 since pandas currently supports 2.6. The most common pitfall is:
-
- with self.assertRaises(ValueError):
- foo
-
-
- which fails with 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 ongoing
- changelog for each release. Add entries to these files
- as needed in a separate commit in your PR: document the fix, enhancement,
- or (unavoidable) breaking change.
- - For extra brownie points, use `git rebase -i` to squash and reorder
- commits in your PR so that the history makes the most sense. Use your own
- judgment to decide what history needs to be preserved.
- - Pandas source code should not -- with some exceptions, such as 3rd party licensed code --
- generally speaking, include an "Authors" list or attribution to individuals in source code.
- `RELEASE.rst` details changes and enhancements to the code over time.
- A "thanks goes to @JohnSmith." as part of the appropriate entry is a suitable way to acknowledge
- contributions. The rest is `git blame`/`git log`.
- Feel free to ask the commiter who merges your code to include such an entry
- or include it directly yourself as part of the PR if you'd like to.
- **We're always glad to have new contributors join us from the ever-growing pandas community.**
- You may also be interested in the copyright policy as detailed in the pandas [LICENSE](https://github.com/pydata/pandas/blob/master/LICENSE).
+ - The pandas copyright policy is detailed in the pandas [LICENSE](https://github.com/pydata/pandas/blob/master/LICENSE).
- On the subject of [PEP8](http://www.python.org/dev/peps/pep-0008/): yes.
- - On the subject of massive PEP8 fix PRs touching everything, please consider the following:
- - They create noisy merge conflicts for people working in their own fork.
- - They make `git blame` less effective.
- - Different tools / people achieve PEP8 in different styles. This can create
- "style wars" and churn that produces little real benefit.
- - If your code changes are intermixed with style fixes, they are harder to review
- before merging. Keep style fixes in separate commits.
- - It's fine to clean-up a little around an area you just worked on.
- - Generally it's a BAD idea to PEP8 on documentation.
-
- Having said that, if you still feel a PEP8 storm is in order, go for it.
+ - On the subject of a massive PEP8-storm touching everything: not too often (once per release works).
### Notes on plotting function conventions
@@ -137,11 +91,7 @@ Here's a few high-level notes:
See the Green "Good to merge!" banner? that's it.
-This is especially important for new contributors, as members of the pandas dev team
-like to know that the test suite passes before considering it for merging.
-Even regular contributors who test religiously on their local box (using tox
-for example) often rely on a PR+travis=green to make double sure everything
-works ok on another system, as occasionally, it doesn't.
+It's important to get travis working as PRs won't generally get merged until travis is green.
#### Steps to enable Travis-CI
| Still working on the 140 char version. maybe we should just use the sha1 instead. hmm.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5721 | 2013-12-17T15:55:04Z | 2013-12-17T15:55:09Z | 2013-12-17T15:55:09Z | 2014-07-12T15:00:06Z |
CLN: add diff to series/dataframe groupby dispatch whitelist | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 46711e4917e4c..e8a9d6e49a066 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -68,7 +68,7 @@
'shift', 'tshift',
'ffill', 'bfill',
'pct_change', 'skew',
- 'corr', 'cov',
+ 'corr', 'cov', 'diff',
]) | _plotting_methods
_series_apply_whitelist = \
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index fef6a18acd7ff..942efdfc23740 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -3270,6 +3270,7 @@ def test_groupby_whitelist(self):
'plot', 'boxplot', 'hist',
'median', 'dtypes',
'corrwith', 'corr', 'cov',
+ 'diff',
])
s_whitelist = frozenset([
'last', 'first',
@@ -3290,6 +3291,7 @@ def test_groupby_whitelist(self):
'median', 'dtype',
'corr', 'cov',
'value_counts',
+ 'diff',
])
for obj, whitelist in zip((df, s),
@@ -3411,7 +3413,7 @@ def test_tab_completion(self):
'resample', 'cummin', 'fillna', 'cumsum', 'cumcount',
'all', 'shift', 'skew', 'bfill', 'irow', 'ffill',
'take', 'tshift', 'pct_change', 'any', 'mad', 'corr', 'corrwith',
- 'cov', 'dtypes',
+ 'cov', 'dtypes', 'diff',
])
self.assertEqual(results, expected)
| Building on #5480, this PR adds `diff` to the groupby dispatch whitelist.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5719 | 2013-12-17T04:33:21Z | 2013-12-17T15:45:32Z | 2013-12-17T15:45:32Z | 2014-07-06T04:39:17Z |
BUG: In a HDFStore, correctly handle data_columns with a Panel (GH5717) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index d5163b9dbc60b..5ce9ccd25a7fc 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -550,6 +550,7 @@ Bug Fixes
(:issue:`4708`)
- Fixed decoding perf issue on pyt3 (:issue:`5441`)
- Validate levels in a multi-index before storing (:issue:`5527`)
+ - Correctly handle ``data_columns`` with a Panel (:issue:`5717`)
- 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/pandas/io/pytables.py b/pandas/io/pytables.py
index 09618b77a2968..bc99417c67310 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3446,6 +3446,8 @@ def read(self, where=None, columns=None, **kwargs):
# the data need to be sorted
sorted_values = c.take_data().take(sorter, axis=0)
+ if sorted_values.ndim == 1:
+ sorted_values = sorted_values.reshape(sorted_values.shape[0],1)
take_labels = [l.take(sorter) for l in labels]
items = Index(c.values)
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index e9c04932aba40..c9955b1ae2fb2 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -1350,6 +1350,29 @@ def check_col(key,name,size):
expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == 'foo')]
tm.assert_frame_equal(result,expected)
+ with ensure_clean_store(self.path) as store:
+ # panel
+ # GH5717 not handling data_columns
+ np.random.seed(1234)
+ p = tm.makePanel()
+
+ store.append('p1',p)
+ tm.assert_panel_equal(store.select('p1'),p)
+
+ store.append('p2',p,data_columns=True)
+ tm.assert_panel_equal(store.select('p2'),p)
+
+ result = store.select('p2',where='ItemA>0')
+ expected = p.to_frame()
+ expected = expected[expected['ItemA']>0]
+ tm.assert_frame_equal(result.to_frame(),expected)
+
+ result = store.select('p2',where='ItemA>0 & minor_axis=["A","B"]')
+ expected = p.to_frame()
+ expected = expected[expected['ItemA']>0]
+ expected = expected[expected.reset_index(level=['major']).index.isin(['A','B'])]
+ tm.assert_frame_equal(result.to_frame(),expected)
+
def test_create_table_index(self):
with ensure_clean_store(self.path) as store:
| closes #5717
| https://api.github.com/repos/pandas-dev/pandas/pulls/5718 | 2013-12-17T02:19:01Z | 2013-12-17T02:35:54Z | 2013-12-17T02:35:54Z | 2014-06-19T11:37:31Z |
TST/DOC: close win32 tests issues (GH5711) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 5e79d05146de3..b77ea2b22f4fa 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1830,23 +1830,24 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
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
- value : scalar or dict
- Value to use to fill holes (e.g. 0), alternately a dict of values
- specifying which value to use for each column (columns not in the
- dict will not be filled). This value cannot be a list.
+ value : scalar, dict, or Series
+ Value to use to fill holes (e.g. 0), alternately a dict/Series of
+ values specifying which value to use for each index (for a Series) or
+ column (for a DataFrame). (values not in the dict/Series will not be
+ filled). This value cannot be a list.
axis : {0, 1}, default 0
0: fill column-by-column
1: fill row-by-row
inplace : boolean, default False
If True, fill in place. Note: this will modify any
other views on this object, (e.g. a no-copy slice for a column in a
- DataFrame). Still returns the object.
+ DataFrame).
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, or the string 'infer' which will try to
- downcast to an appropriate equal type (e.g. float64 to int64 if
- possible)
+ downcast : dict, default is None
+ a dict of item->dtype of what to 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
--------
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index bfd2b784490ca..e396bee3f4ad9 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1382,7 +1382,7 @@ def test_astype_assignment(self):
df_orig = DataFrame([['1','2','3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
df = df_orig.copy()
- df.iloc[:,0:2] = df.iloc[:,0:2].astype(int)
+ df.iloc[:,0:2] = df.iloc[:,0:2].astype(np.int64)
expected = DataFrame([[1,2,'3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
assert_frame_equal(df,expected)
@@ -1393,12 +1393,12 @@ def test_astype_assignment(self):
# GH5702 (loc)
df = df_orig.copy()
- df.loc[:,'A'] = df.loc[:,'A'].astype(int)
+ df.loc[:,'A'] = df.loc[:,'A'].astype(np.int64)
expected = DataFrame([[1,'2','3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
assert_frame_equal(df,expected)
df = df_orig.copy()
- df.loc[:,['B','C']] = df.loc[:,['B','C']].astype(int)
+ df.loc[:,['B','C']] = df.loc[:,['B','C']].astype(np.int64)
expected = DataFrame([['1',2,3,'.4',5,6.,'foo']],columns=list('ABCDEFG'))
assert_frame_equal(df,expected)
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 188d61f397f5c..21f94f0c5d9e1 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -1345,7 +1345,7 @@ def f():
s[0:3] = list(range(3))
expected = Series([0,1,2])
- assert_series_equal(s, expected)
+ assert_series_equal(s.astype(np.int64), expected, )
# slice with step
s = Series(list('abcdef'))
| DOC string updates for fillna
closes #5711
| https://api.github.com/repos/pandas-dev/pandas/pulls/5716 | 2013-12-17T00:14:42Z | 2013-12-17T01:18:26Z | 2013-12-17T01:18:26Z | 2014-07-16T08:43:26Z |
Add test for DataFrame.corrwith and np.corrcoef compatibility | diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 5b501de026c57..3a29fa41046ca 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -6463,6 +6463,15 @@ def test_corrwith_series(self):
assert_series_equal(result, expected)
+ def test_corrwith_matches_corrcoef(self):
+ df1 = DataFrame(np.arange(10000), columns=['a'])
+ df2 = DataFrame(np.arange(10000)**2, columns=['a'])
+ c1 = df1.corrwith(df2)['a']
+ c2 = np.corrcoef(df1['a'],df2['a'])[0][1]
+
+ assert_almost_equal(c1, c2)
+ self.assert_(c1 < 1)
+
def test_drop_names(self):
df = DataFrame([[1, 2, 3],[3, 4, 5],[5, 6, 7]], index=['a', 'b', 'c'],
columns=['d', 'e', 'f'])
| Add apparently-once-failing code taken from
http://stackoverflow.com/questions/20617854/is-there-a-bug-in-pandas-dataframe-corrwith-function
as a test.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5714 | 2013-12-16T19:22:20Z | 2013-12-16T19:54:23Z | 2013-12-16T19:54:23Z | 2014-06-21T02:58:03Z |
BUG: Bug in groupby transform with a datetime-like grouper (GH5712) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 0a853938f6cad..d5163b9dbc60b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -823,6 +823,7 @@ Bug Fixes
- Work around regression in numpy 1.7.0 which erroneously raises IndexError from ``ndarray.item`` (:issue:`5666`)
- Bug in repeated indexing of object with resultant non-unique index (:issue:`5678`)
- Bug in fillna with Series and a passed series/dict (:issue:`5703`)
+ - Bug in groupby transform with a datetime-like grouper (:issue:`5712`)
pandas 0.12.0
-------------
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 7569653fc650b..7b652c36ae47d 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -2009,6 +2009,14 @@ def needs_i8_conversion(arr_or_dtype):
is_timedelta64_dtype(arr_or_dtype))
+def is_numeric_dtype(arr_or_dtype):
+ if isinstance(arr_or_dtype, np.dtype):
+ tipo = arr_or_dtype.type
+ else:
+ tipo = arr_or_dtype.dtype.type
+ return (issubclass(tipo, (np.number, np.bool_))
+ and not issubclass(tipo, (np.datetime64, np.timedelta64)))
+
def is_float_dtype(arr_or_dtype):
if isinstance(arr_or_dtype, np.dtype):
tipo = arr_or_dtype.type
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 558843f55777c..46711e4917e4c 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -19,9 +19,11 @@
import pandas.core.algorithms as algos
import pandas.core.common as com
from pandas.core.common import(_possibly_downcast_to_dtype, isnull,
- notnull, _DATELIKE_DTYPES)
+ notnull, _DATELIKE_DTYPES, is_numeric_dtype,
+ is_timedelta64_dtype, is_datetime64_dtype)
import pandas.lib as lib
+from pandas.lib import Timestamp
import pandas.algos as _algos
import pandas.hashtable as _hash
@@ -257,6 +259,16 @@ def indices(self):
""" dict {group name -> group indices} """
return self.grouper.indices
+ def _get_index(self, name):
+ """ safe get index """
+ try:
+ return self.indices[name]
+ except:
+ if isinstance(name, Timestamp):
+ name = name.value
+ return self.indices[name]
+ raise
+
@property
def name(self):
if self._selection is None:
@@ -350,7 +362,7 @@ def get_group(self, name, obj=None):
if obj is None:
obj = self.obj
- inds = self.indices[name]
+ inds = self._get_index(name)
return obj.take(inds, axis=self.axis, convert=False)
def __iter__(self):
@@ -676,7 +688,7 @@ def _try_cast(self, result, obj):
def _cython_agg_general(self, how, numeric_only=True):
output = {}
for name, obj in self._iterate_slices():
- is_numeric = _is_numeric_dtype(obj.dtype)
+ is_numeric = is_numeric_dtype(obj.dtype)
if numeric_only and not is_numeric:
continue
@@ -714,7 +726,7 @@ def _python_agg_general(self, func, *args, **kwargs):
# since we are masking, make sure that we have a float object
values = result
- if _is_numeric_dtype(values.dtype):
+ if is_numeric_dtype(values.dtype):
values = com.ensure_float(values)
output[name] = self._try_cast(values[mask], result)
@@ -1080,7 +1092,7 @@ def aggregate(self, values, how, axis=0):
raise NotImplementedError
out_shape = (self.ngroups,) + values.shape[1:]
- if _is_numeric_dtype(values.dtype):
+ if is_numeric_dtype(values.dtype):
values = com.ensure_float(values)
is_numeric = True
else:
@@ -1474,6 +1486,15 @@ def __init__(self, index, grouper=None, name=None, level=None,
self.grouper = None # Try for sanity
raise AssertionError(errmsg)
+ # if we have a date/time-like grouper, make sure that we have Timestamps like
+ if getattr(self.grouper,'dtype',None) is not None:
+ if is_datetime64_dtype(self.grouper):
+ from pandas import to_datetime
+ self.grouper = to_datetime(self.grouper)
+ elif is_timedelta64_dtype(self.grouper):
+ from pandas import to_timedelta
+ self.grouper = to_timedelta(self.grouper)
+
def __repr__(self):
return 'Grouping(%s)' % self.name
@@ -1821,7 +1842,7 @@ 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 = Series(result)
- result.iloc[self.indices[name]] = res
+ result.iloc[self._get_index(name)] = res
result = result.values
# downcast if we can (and need)
@@ -1860,7 +1881,7 @@ def true_and_notnull(x, *args, **kwargs):
return b and notnull(b)
try:
- indices = [self.indices[name] if true_and_notnull(group) else []
+ indices = [self._get_index(name) if true_and_notnull(group) else []
for name, group in self]
except ValueError:
raise TypeError("the filter must return a boolean result")
@@ -1921,7 +1942,7 @@ def _cython_agg_blocks(self, how, numeric_only=True):
for block in data.blocks:
values = block.values
- is_numeric = _is_numeric_dtype(values.dtype)
+ is_numeric = is_numeric_dtype(values.dtype)
if numeric_only and not is_numeric:
continue
@@ -2412,7 +2433,7 @@ def filter(self, func, dropna=True, *args, **kwargs):
res = path(group)
def add_indices():
- indices.append(self.indices[name])
+ indices.append(self._get_index(name))
# interpret the result of the filter
if isinstance(res, (bool, np.bool_)):
@@ -2973,12 +2994,6 @@ def _reorder_by_uniques(uniques, labels):
}
-def _is_numeric_dtype(dt):
- typ = dt.type
- return (issubclass(typ, (np.number, np.bool_))
- and not issubclass(typ, (np.datetime64, np.timedelta64)))
-
-
def _intercept_function(func):
return _func_table.get(func, func)
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index f834094475c1b..fef6a18acd7ff 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -627,6 +627,14 @@ def test_transform_broadcast(self):
for idx in gp.index:
assert_fp_equal(res.xs(idx), agged[idx])
+ def test_transform_bug(self):
+ # GH 5712
+ # transforming on a datetime column
+ df = DataFrame(dict(A = Timestamp('20130101'), B = np.arange(5)))
+ result = df.groupby('A')['B'].transform(lambda x: x.rank(ascending=False))
+ expected = Series(np.arange(5,0,step=-1),name='B')
+ assert_series_equal(result,expected)
+
def test_transform_multiple(self):
grouped = self.ts.groupby([lambda x: x.year, lambda x: x.month])
| closes #5712
| https://api.github.com/repos/pandas-dev/pandas/pulls/5713 | 2013-12-16T18:49:31Z | 2013-12-16T19:53:58Z | 2013-12-16T19:53:58Z | 2014-06-24T10:34:39Z |
StataWriter: Replace non-isalnum characters in variable names by _ instead of integral represantation of replaced character. Eliminate duplicates created by replacement. | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 5d40cbe82e87b..fef086f8c5f57 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -221,6 +221,7 @@ Improvements to existing features
MultiIndex and Hierarchical Rows. Set the ``merge_cells`` to ``False`` to
restore the previous behaviour. (:issue:`5254`)
- The FRED DataReader now accepts multiple series (:issue`3413`)
+ - StataWriter adjusts variable names to Stata's limitations (:issue:`5709`)
API Changes
~~~~~~~~~~~
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 8c172db162cd6..55bcbd76c2248 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -1068,11 +1068,55 @@ def _write_descriptors(self, typlist=None, varlist=None, srtlist=None,
self._write(typ)
# varlist, length 33*nvar, char array, null terminated
+ converted_names = []
+ duplicate_var_id = 0
+ for j, name in enumerate(self.varlist):
+ orig_name = name
+ # Replaces all characters disallowed in .dta format by their integral representation.
+ for c in name:
+ if (c < 'A' or c > 'Z') and (c < 'a' or c > 'z') and (c < '0' or c > '9') and c != '_':
+ name = name.replace(c, '_')
+
+ # Variable name may not start with a number
+ if name[0] > '0' and name[0] < '9':
+ name = '_' + name
+
+ name = name[:min(len(name), 32)]
+
+ if not name == orig_name:
+ # check for duplicates
+ while self.varlist.count(name) > 0:
+ # prepend ascending number to avoid duplicates
+ name = '_' + str(duplicate_var_id) + name
+ name = name[:min(len(name), 32)]
+ duplicate_var_id += 1
+
+ # need to possibly encode the orig name if its unicode
+ try:
+ orig_name = orig_name.encode('utf-8')
+ except:
+ pass
+
+ converted_names.append('{0} -> {1}'.format(orig_name, name))
+ self.varlist[j] = name
+
for name in self.varlist:
name = self._null_terminate(name, True)
name = _pad_bytes(name[:32], 33)
self._write(name)
+ if converted_names:
+ from warnings import warn
+ warn("""Not all pandas column names were valid Stata variable names.
+ Made the following replacements:
+
+ {0}
+
+ If this is not what you expect, please make sure you have Stata-compliant
+ column names in your DataFrame (max 32 characters, only alphanumerics and
+ underscores)/
+ """.format('\n '.join(converted_names)))
+
# srtlist, 2*(nvar+1), int array, encoded by byteorder
srtlist = _pad_bytes("", (2*(nvar+1)))
self._write(srtlist)
diff --git a/pandas/io/tests/test_stata.py b/pandas/io/tests/test_stata.py
index 76dae396c04ed..f75cf7ebb18d1 100644
--- a/pandas/io/tests/test_stata.py
+++ b/pandas/io/tests/test_stata.py
@@ -231,6 +231,38 @@ def test_encoding(self):
self.assert_(result == expected)
self.assert_(isinstance(result, unicode))
+ def test_read_write_dta11(self):
+ original = DataFrame([(1, 2, 3, 4)],
+ columns=['good', compat.u('b\u00E4d'), '8number', 'astringwithmorethan32characters______'])
+ formatted = DataFrame([(1, 2, 3, 4)],
+ columns=['good', 'b_d', '_8number', 'astringwithmorethan32characters_'])
+ formatted.index.name = 'index'
+
+ with tm.ensure_clean() as path:
+ with warnings.catch_warnings(record=True) as w:
+ original.to_stata(path, None, False)
+ np.testing.assert_equal(
+ len(w), 1) # should get a warning for that format.
+
+ written_and_read_again = self.read_dta(path)
+ tm.assert_frame_equal(written_and_read_again.set_index('index'), formatted)
+
+ def test_read_write_dta12(self):
+ original = DataFrame([(1, 2, 3, 4)],
+ columns=['astringwithmorethan32characters_1', 'astringwithmorethan32characters_2', '+', '-'])
+ formatted = DataFrame([(1, 2, 3, 4)],
+ columns=['astringwithmorethan32characters_', '_0astringwithmorethan32character', '_', '_1_'])
+ formatted.index.name = 'index'
+
+ with tm.ensure_clean() as path:
+ with warnings.catch_warnings(record=True) as w:
+ original.to_stata(path, None, False)
+ np.testing.assert_equal(
+ len(w), 1) # should get a warning for that format.
+
+ written_and_read_again = self.read_dta(path)
+ tm.assert_frame_equal(written_and_read_again.set_index('index'), formatted)
+
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)
| New pull request as replacement for PR-#5525
| https://api.github.com/repos/pandas-dev/pandas/pulls/5709 | 2013-12-16T10:08:26Z | 2013-12-18T00:50:14Z | 2013-12-18T00:50:14Z | 2014-06-16T04:21:15Z |
Correct "sentinel" spelling. | diff --git a/doc/source/missing_data.rst b/doc/source/missing_data.rst
index 10053f61d8574..73ec9c47bc473 100644
--- a/doc/source/missing_data.rst
+++ b/doc/source/missing_data.rst
@@ -93,7 +93,7 @@ Datetimes
---------
For datetime64[ns] types, ``NaT`` represents missing values. This is a pseudo-native
-sentinal value that can be represented by numpy in a singular dtype (datetime64[ns]).
+sentinel value that can be represented by numpy in a singular dtype (datetime64[ns]).
Pandas objects provide intercompatibility between ``NaT`` and ``NaN``.
.. ipython:: python
diff --git a/pandas/core/common.py b/pandas/core/common.py
index d251a2617f98d..7569653fc650b 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -2332,11 +2332,11 @@ def _where_compat(mask, arr1, arr2):
return np.where(mask, arr1, arr2)
-def sentinal_factory():
- class Sentinal(object):
+def sentinel_factory():
+ class Sentinel(object):
pass
- return Sentinal()
+ return Sentinel()
def in_interactive_session():
diff --git a/pandas/core/format.py b/pandas/core/format.py
index e14d34c2abfbe..47745635bbc39 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -740,8 +740,8 @@ def _column_header():
template = 'colspan="%d" halign="left"'
# GH3547
- sentinal = com.sentinal_factory()
- levels = self.columns.format(sparsify=sentinal, adjoin=False,
+ sentinel = com.sentinel_factory()
+ levels = self.columns.format(sparsify=sentinel, adjoin=False,
names=False)
# Truncate column names
if len(levels[0]) > self.max_cols:
@@ -750,7 +750,7 @@ def _column_header():
else:
truncated = False
- level_lengths = _get_level_lengths(levels, sentinal)
+ level_lengths = _get_level_lengths(levels, sentinel)
row_levels = self.frame.index.nlevels
@@ -859,14 +859,14 @@ def _write_hierarchical_rows(self, fmt_values, indent):
if self.fmt.sparsify:
# GH3547
- sentinal = com.sentinal_factory()
- levels = frame.index[:nrows].format(sparsify=sentinal,
+ sentinel = com.sentinel_factory()
+ levels = frame.index[:nrows].format(sparsify=sentinel,
adjoin=False, names=False)
# Truncate row names
if truncate:
levels = [lev[:self.max_rows] for lev in levels]
- level_lengths = _get_level_lengths(levels, sentinal)
+ level_lengths = _get_level_lengths(levels, sentinel)
for i in range(min(len(frame), self.max_rows)):
row = []
@@ -905,14 +905,14 @@ def _write_hierarchical_rows(self, fmt_values, indent):
self.write_tr(row, indent, self.indent_delta, tags=None)
-def _get_level_lengths(levels, sentinal=''):
+def _get_level_lengths(levels, sentinel=''):
from itertools import groupby
def _make_grouper():
record = {'count': 0}
def grouper(x):
- if x != sentinal:
+ if x != sentinel:
record['count'] += 1
return record['count']
return grouper
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 18d6a1a04e3f9..7ae273d08fa87 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -2371,16 +2371,16 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False,
sparsify = get_option("display.multi_sparse")
if sparsify:
- sentinal = ''
+ sentinel = ''
# GH3547
- # use value of sparsify as sentinal, unless it's an obvious
+ # use value of sparsify as sentinel, unless it's an obvious
# "Truthey" value
if sparsify not in [True, 1]:
- sentinal = sparsify
+ sentinel = sparsify
# little bit of a kludge job for #1217
result_levels = _sparsify(result_levels,
start=int(names),
- sentinal=sentinal)
+ sentinel=sentinel)
if adjoin:
return com.adjoin(space, *result_levels).split('\n')
@@ -3379,7 +3379,7 @@ def _wrap_joined_index(self, joined, other):
# For utility purposes
-def _sparsify(label_list, start=0, sentinal=''):
+def _sparsify(label_list, start=0, sentinel=''):
pivoted = lzip(*label_list)
k = len(label_list)
@@ -3396,7 +3396,7 @@ def _sparsify(label_list, start=0, sentinal=''):
break
if p == t:
- sparse_cur.append(sentinal)
+ sparse_cur.append(sentinel)
else:
sparse_cur.extend(cur[i:])
result.append(sparse_cur)
| Closes #5706 -- more a test that my git PR pipeline is working than because of its significance.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5707 | 2013-12-16T03:31:30Z | 2013-12-16T13:43:16Z | 2013-12-16T13:43:16Z | 2014-06-16T16:35:38Z |
BUG: Bug in fillna with Series and a passed series/dict (GH5703) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 5d40cbe82e87b..0a853938f6cad 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -822,6 +822,7 @@ Bug Fixes
- Bug in groupby returning non-consistent types when user function returns a ``None``, (:issue:`5592`)
- Work around regression in numpy 1.7.0 which erroneously raises IndexError from ``ndarray.item`` (:issue:`5666`)
- Bug in repeated indexing of object with resultant non-unique index (:issue:`5678`)
+ - Bug in fillna with Series and a passed series/dict (:issue:`5703`)
pandas 0.12.0
-------------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 253136b9a11c3..5e79d05146de3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1905,7 +1905,16 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
if len(self._get_axis(axis)) == 0:
return self
- if isinstance(value, (dict, com.ABCSeries)):
+
+ if self.ndim == 1 and value is not None:
+ if isinstance(value, (dict, com.ABCSeries)):
+ from pandas import Series
+ value = Series(value)
+
+ new_data = self._data.fillna(value, inplace=inplace,
+ downcast=downcast)
+
+ elif isinstance(value, (dict, com.ABCSeries)):
if axis == 1:
raise NotImplementedError('Currently only can fill '
'with dict/Series column '
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index dbad353bab62c..6ec08fe501bcd 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -664,7 +664,7 @@ def putmask(self, mask, new, align=True, inplace=False):
# if we are passed a scalar None, convert it here
if not is_list_like(new) and isnull(new):
- new = np.nan
+ new = self.fill_value
if self._can_hold_element(new):
new = self._try_cast(new)
@@ -830,7 +830,7 @@ def _interpolate(self, method=None, index=None, values=None,
data = data.astype(np.float64)
if fill_value is None:
- fill_value = np.nan
+ fill_value = self.fill_value
if method in ('krogh', 'piecewise_polynomial', 'pchip'):
if not index.is_monotonic:
@@ -1196,6 +1196,10 @@ class TimeDeltaBlock(IntBlock):
_can_hold_na = True
is_numeric = False
+ @property
+ def fill_value(self):
+ return tslib.iNaT
+
def _try_fill(self, value):
""" if we are a NaT, return the actual fill value """
if isinstance(value, type(tslib.NaT)) or isnull(value):
@@ -1532,6 +1536,10 @@ def _try_coerce_result(self, result):
result = lib.Timestamp(result)
return result
+ @property
+ def fill_value(self):
+ return tslib.iNaT
+
def _try_fill(self, value):
""" if we are a NaT, return the actual fill value """
if isinstance(value, type(tslib.NaT)) or isnull(value):
@@ -3190,18 +3198,15 @@ def reindex_items(self, new_items, indexer=None, copy=True,
blk = blk.reindex_items_from(new_items)
else:
blk.ref_items = new_items
- if blk is not None:
- new_blocks.append(blk)
+ new_blocks.extend(_valid_blocks(blk))
else:
# unique
if self.axes[0].is_unique and new_items.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)
+ blk = block.reindex_items_from(new_items, copy=copy)
+ new_blocks.extend(_valid_blocks(blk))
# non-unique
else:
@@ -3411,7 +3416,11 @@ def __init__(self, block, axis, do_integrity_check=False, fastpath=True):
if fastpath:
self.axes = [axis]
if isinstance(block, list):
- if len(block) != 1:
+
+ # empty block
+ if len(block) == 0:
+ block = [np.array([])]
+ elif len(block) != 1:
raise ValueError('Cannot create SingleBlockManager with '
'more than 1 block')
block = block[0]
@@ -3875,6 +3884,13 @@ def _consolidate(blocks, items):
return new_blocks
+def _valid_blocks(newb):
+ if newb is None:
+ return []
+ if not isinstance(newb, list):
+ newb = [ newb ]
+ return [ b for b in newb if len(b.items) > 0 ]
+
def _merge_blocks(blocks, items, dtype=None, _can_consolidate=True):
if len(blocks) == 1:
return blocks[0]
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index d3104cdfad062..188d61f397f5c 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2760,6 +2760,35 @@ def test_fillna(self):
self.assertRaises(ValueError, ts.fillna)
self.assertRaises(ValueError, self.ts.fillna, value=0, method='ffill')
+ # GH 5703
+ s1 = Series([np.nan])
+ s2 = Series([1])
+ result = s1.fillna(s2)
+ expected = Series([1.])
+ assert_series_equal(result,expected)
+ result = s1.fillna({})
+ assert_series_equal(result,s1)
+ result = s1.fillna(Series(()))
+ assert_series_equal(result,s1)
+ result = s2.fillna(s1)
+ assert_series_equal(result,s2)
+ result = s1.fillna({ 0 : 1})
+ assert_series_equal(result,expected)
+ result = s1.fillna({ 1 : 1})
+ assert_series_equal(result,Series([np.nan]))
+ result = s1.fillna({ 0 : 1, 1 : 1})
+ assert_series_equal(result,expected)
+ result = s1.fillna(Series({ 0 : 1, 1 : 1}))
+ assert_series_equal(result,expected)
+ result = s1.fillna(Series({ 0 : 1, 1 : 1},index=[4,5]))
+ assert_series_equal(result,s1)
+
+ s1 = Series([0, 1, 2], list('abc'))
+ s2 = Series([0, np.nan, 2], list('bac'))
+ result = s2.fillna(s1)
+ expected = Series([0,0,2.], list('bac'))
+ assert_series_equal(result,expected)
+
def test_fillna_bug(self):
x = Series([nan, 1., nan, 3., nan], ['z', 'a', 'b', 'c', 'd'])
filled = x.fillna(method='ffill')
| closes #5703
```
In [1]: s1 = Series([np.nan])
In [2]: s2 = Series([1])
In [3]: s1.fillna(s2)
Out[3]:
0 1
dtype: float64
In [4]: s1.fillna({ 1 : 1})
Out[4]:
0 1
dtype: float64
In [5]: s1.fillna({ 1 : 2, 2 : 3})
ValueError: cannot fillna on a 1-dim object with more than one value
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5705 | 2013-12-15T23:52:58Z | 2013-12-16T16:23:30Z | 2013-12-16T16:23:30Z | 2014-06-21T11:40:12Z |
BUG: loc assignment with astype buggy, (GH5702) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index f6cbbd23011a8..5d40cbe82e87b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -636,8 +636,8 @@ Bug Fixes
(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
+ (:issue:`4312`, :issue:`5702`) 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`)
- Fix an issue with CacheableOffset not properly being used by many
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 471136dc2386b..dbad353bab62c 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -601,8 +601,12 @@ def setitem(self, indexer, value):
"different length than the value")
try:
- # set and return a block
- values[indexer] = value
+ # if we are an exact match (ex-broadcasting),
+ # then use the resultant dtype
+ if len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and np.prod(arr_value.shape) == np.prod(values.shape):
+ values = arr_value.reshape(values.shape)
+ else:
+ values[indexer] = value
# coerce and try to infer the dtypes of the result
if np.isscalar(value):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 59c7bda35c544..bfd2b784490ca 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1376,21 +1376,42 @@ def gen_expected(df,mask):
expected = gen_expected(df,mask)
assert_frame_equal(result,expected)
- def test_astype_assignment_with_iloc(self):
+ def test_astype_assignment(self):
- # GH4312
+ # GH4312 (iloc)
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.iloc[:,0:2] = df.iloc[:,0:2].astype(int)
+ expected = DataFrame([[1,2,'3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
+ assert_frame_equal(df,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()
+ df.iloc[:,0:2] = df.iloc[:,0:2].convert_objects(convert_numeric=True)
+ expected = DataFrame([[1,2,'3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
+ assert_frame_equal(df,expected)
+
+ # GH5702 (loc)
+ df = df_orig.copy()
+ df.loc[:,'A'] = df.loc[:,'A'].astype(int)
+ expected = DataFrame([[1,'2','3','.4',5,6.,'foo']],columns=list('ABCDEFG'))
+ assert_frame_equal(df,expected)
+
+ df = df_orig.copy()
+ df.loc[:,['B','C']] = df.loc[:,['B','C']].astype(int)
+ expected = DataFrame([['1',2,3,'.4',5,6.,'foo']],columns=list('ABCDEFG'))
+ assert_frame_equal(df,expected)
+
+ # full replacements / no nans
+ df = DataFrame({'A': [1., 2., 3., 4.]})
+ df.iloc[:, 0] = df['A'].astype(np.int64)
+ expected = DataFrame({'A': [1, 2, 3, 4]})
+ assert_frame_equal(df,expected)
+
+ df = DataFrame({'A': [1., 2., 3., 4.]})
+ df.loc[:, 'A'] = df['A'].astype(np.int64)
+ expected = DataFrame({'A': [1, 2, 3, 4]})
+ assert_frame_equal(df,expected)
def test_astype_assignment_with_dups(self):
@@ -1496,7 +1517,7 @@ def f():
assert_frame_equal(df,expected)
# mixed dtype frame, overwrite
- expected = DataFrame(dict({ 'A' : [0,2,4], 'B' : Series([0.,2.,4.]) }))
+ 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']
@@ -1504,14 +1525,14 @@ def f():
# single dtype frame, partial setting
expected = df_orig.copy()
- expected['C'] = df['A'].astype(np.float64)
+ expected['C'] = df['A']
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)
+ expected['C'] = df['A']
df = df_orig.copy()
df.ix[:,'C'] = df.ix[:,'A']
assert_frame_equal(df,expected)
| closes #5702
| https://api.github.com/repos/pandas-dev/pandas/pulls/5704 | 2013-12-15T23:18:37Z | 2013-12-15T23:56:16Z | 2013-12-15T23:56:16Z | 2014-06-21T03:16:05Z |
Smarter formatting of timedelta and datetime columns | diff --git a/doc/source/release.rst b/doc/source/release.rst
index fc9f18279087b..6d550d4f0b588 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -76,6 +76,8 @@ Improvements to existing features
- support ``dtypes`` on ``Panel``
- extend ``Panel.apply`` to allow arbitrary functions (rather than only ufuncs) (:issue:`1148`)
allow multiple axes to be used to operate on slabs of a ``Panel``
+ - The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
+ limit precision based on the values in the array (:issue:`3401`)
.. _release.bug_fixes-0.13.1:
@@ -99,6 +101,8 @@ Bug Fixes
- Bug in creating an empty DataFrame, copying, then assigning (:issue:`5932`)
- Bug in DataFrame.tail with empty frame (:issue:`5846`)
- Bug in propogating metadata on ``resample`` (:issue:`5862`)
+ - Fixed string-representation of ``NaT`` to be "NaT" (:issue:`5708`)
+ - Fixed string-representation for Timestamp to show nanoseconds if present (:issue:`5912`)
pandas 0.13.0
-------------
diff --git a/doc/source/v0.13.1.txt b/doc/source/v0.13.1.txt
index 76b915c519440..31004d24e56a6 100644
--- a/doc/source/v0.13.1.txt
+++ b/doc/source/v0.13.1.txt
@@ -83,6 +83,27 @@ Enhancements
result
result.loc[:,:,'ItemA']
+- The ``ArrayFormatter``s for ``datetime`` and ``timedelta64`` now intelligently
+ limit precision based on the values in the array (:issue:`3401`)
+
+ Previously output might look like:
+
+ .. code-block:: python
+
+ age today diff
+ 0 2001-01-01 00:00:00 2013-04-19 00:00:00 4491 days, 00:00:00
+ 1 2004-06-01 00:00:00 2013-04-19 00:00:00 3244 days, 00:00:00
+
+ Now the output looks like:
+
+ .. ipython:: python
+
+ df = DataFrame([ Timestamp('20010101'),
+ Timestamp('20040601') ], columns=['age'])
+ df['today'] = Timestamp('20130419')
+ df['diff'] = df['today']-df['age']
+ df
+
Experimental
~~~~~~~~~~~~
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 47745635bbc39..24b0554755ead 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -14,11 +14,13 @@
from pandas.core.config import get_option, set_option, reset_option
import pandas.core.common as com
import pandas.lib as lib
+from pandas.tslib import iNaT
import numpy as np
import itertools
import csv
+from datetime import time
from pandas.tseries.period import PeriodIndex, DatetimeIndex
@@ -1609,7 +1611,7 @@ def format_array(values, formatter, float_format=None, na_rep='NaN',
if digits is None:
digits = get_option("display.precision")
- fmt_obj = fmt_klass(values, digits, na_rep=na_rep,
+ fmt_obj = fmt_klass(values, digits=digits, na_rep=na_rep,
float_format=float_format,
formatter=formatter, space=space,
justify=justify)
@@ -1704,7 +1706,7 @@ def _val(x, threshold):
fmt_values = [_val(x, threshold) for x in self.values]
return _trim_zeros(fmt_values, self.na_rep)
- def get_result(self):
+ def _format_strings(self):
if self.formatter is not None:
fmt_values = [self.formatter(x) for x in self.values]
else:
@@ -1732,64 +1734,124 @@ def get_result(self):
fmt_str = '%% .%de' % (self.digits - 1)
fmt_values = self._format_with(fmt_str)
- return _make_fixed_width(fmt_values, self.justify)
+ return fmt_values
class IntArrayFormatter(GenericArrayFormatter):
- def get_result(self):
- if self.formatter:
- formatter = self.formatter
- else:
- formatter = lambda x: '% d' % x
+ def _format_strings(self):
+ formatter = self.formatter or (lambda x: '% d' % x)
fmt_values = [formatter(x) for x in self.values]
- return _make_fixed_width(fmt_values, self.justify)
+ return fmt_values
class Datetime64Formatter(GenericArrayFormatter):
+ def __init__(self, values, nat_rep='NaT', date_format=None, **kwargs):
+ super(Datetime64Formatter, self).__init__(values, **kwargs)
+ self.nat_rep = nat_rep
+ self.date_format = date_format
- def get_result(self):
- if self.formatter:
- formatter = self.formatter
- else:
- formatter = _format_datetime64
+ def _format_strings(self):
+ formatter = self.formatter or _get_format_datetime64_from_values(
+ self.values,
+ nat_rep=self.nat_rep,
+ date_format=self.date_format)
fmt_values = [formatter(x) for x in self.values]
- return _make_fixed_width(fmt_values, self.justify)
+ return fmt_values
-def _format_datetime64(x, tz=None):
- if isnull(x):
- return 'NaT'
- stamp = lib.Timestamp(x, tz=tz)
- return stamp._repr_base
+def _format_datetime64(x, tz=None, nat_rep='NaT'):
+ if x is None or lib.checknull(x):
+ return nat_rep
+ if tz is not None or not isinstance(x, lib.Timestamp):
+ x = lib.Timestamp(x, tz=tz)
-class Timedelta64Formatter(Datetime64Formatter):
+ return str(x)
- def get_result(self):
- if self.formatter:
- formatter = self.formatter
- else:
- formatter = _format_timedelta64
+def _format_datetime64_dateonly(x, nat_rep='NaT', date_format=None):
+ if x is None or lib.checknull(x):
+ return nat_rep
+
+ if not isinstance(x, lib.Timestamp):
+ x = lib.Timestamp(x)
+
+ if date_format:
+ return x.strftime(date_format)
+ else:
+ return x._date_repr
+
+
+def _is_dates_only(values):
+ for d in values:
+ if isinstance(d, np.datetime64):
+ d = lib.Timestamp(d)
+
+ if d is not None and not lib.checknull(d) and d._has_time_component():
+ return False
+ return True
+
+
+def _get_format_datetime64(is_dates_only, nat_rep='NaT', date_format=None):
+
+ if is_dates_only:
+ return lambda x, tz=None: _format_datetime64_dateonly(x,
+ nat_rep=nat_rep,
+ date_format=date_format)
+ else:
+ return lambda x, tz=None: _format_datetime64(x, tz=tz, nat_rep=nat_rep)
+
+
+def _get_format_datetime64_from_values(values,
+ nat_rep='NaT',
+ date_format=None):
+ is_dates_only = _is_dates_only(values)
+ return _get_format_datetime64(is_dates_only=is_dates_only,
+ nat_rep=nat_rep,
+ date_format=date_format)
+
+
+class Timedelta64Formatter(GenericArrayFormatter):
+
+ def _format_strings(self):
+ formatter = self.formatter or _get_format_timedelta64(self.values)
fmt_values = [formatter(x) for x in self.values]
- return _make_fixed_width(fmt_values, self.justify)
+ return fmt_values
+
+
+def _get_format_timedelta64(values):
+ values_int = values.astype(np.int64)
-def _format_timedelta64(x):
- if isnull(x):
- return 'NaT'
+ consider_values = values_int != iNaT
- return lib.repr_timedelta64(x)
+ one_day_in_nanos = (86400 * 1e9)
+ even_days = np.logical_and(consider_values, values_int % one_day_in_nanos != 0).sum() == 0
+ all_sub_day = np.logical_and(consider_values, np.abs(values_int) >= one_day_in_nanos).sum() == 0
+
+ format_short = even_days or all_sub_day
+ format = "short" if format_short else "long"
+
+ def impl(x):
+ if x is None or lib.checknull(x):
+ return 'NaT'
+ elif format_short and x == 0:
+ return "0 days" if even_days else "00:00:00"
+ else:
+ return lib.repr_timedelta64(x, format=format)
+
+ return impl
def _make_fixed_width(strings, justify='right', minimum=None, truncated=False):
- if len(strings) == 0:
+
+ if len(strings) == 0 or justify == 'all':
return strings
_strlen = _strlen_func()
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py
index f66c59fade2c1..a9855c4e73c6e 100644
--- a/pandas/tests/test_format.py
+++ b/pandas/tests/test_format.py
@@ -13,15 +13,17 @@
from numpy.random import randn
import numpy as np
-from pandas import DataFrame, Series, Index
+from pandas import DataFrame, Series, Index, _np_version_under1p7, Timestamp
import pandas.core.format as fmt
import pandas.util.testing as tm
from pandas.util.terminal import get_terminal_size
import pandas
+import pandas.tslib as tslib
import pandas as pd
from pandas.core.config import (set_option, get_option,
option_context, reset_option)
+from datetime import datetime
_frame = DataFrame(tm.getSeriesData())
@@ -55,6 +57,17 @@ def has_expanded_repr(df):
return True
return False
+def skip_if_np_version_under1p7():
+ if _np_version_under1p7:
+ import nose
+
+ raise nose.SkipTest('numpy >= 1.7 required')
+
+def _skip_if_no_pytz():
+ try:
+ import pytz
+ except ImportError:
+ raise nose.SkipTest("pytz not installed")
class TestDataFrameFormatting(tm.TestCase):
_multiprocess_can_split_ = True
@@ -770,11 +783,11 @@ def test_wide_repr(self):
with option_context('mode.sim_interactive', True):
col = lambda l, k: [tm.rands(k) for _ in range(l)]
max_cols = get_option('display.max_columns')
- df = DataFrame([col(max_cols-1, 25) for _ in range(10)])
+ df = DataFrame([col(max_cols - 1, 25) for _ in range(10)])
set_option('display.expand_frame_repr', False)
rep_str = repr(df)
- print(rep_str)
- assert "10 rows x %d columns" % (max_cols-1) in rep_str
+
+ assert "10 rows x %d columns" % (max_cols - 1) in rep_str
set_option('display.expand_frame_repr', True)
wide_repr = repr(df)
self.assert_(rep_str != wide_repr)
@@ -1749,7 +1762,7 @@ def test_float_trim_zeros(self):
def test_datetimeindex(self):
- from pandas import date_range, NaT, Timestamp
+ from pandas import date_range, NaT
index = date_range('20130102',periods=6)
s = Series(1,index=index)
result = s.to_string()
@@ -1779,32 +1792,33 @@ def test_timedelta64(self):
# adding NaTs
y = s-s.shift(1)
result = y.to_string()
- self.assertTrue('1 days, 00:00:00' in result)
+ self.assertTrue('1 days' in result)
+ self.assertTrue('00:00:00' not in result)
self.assertTrue('NaT' in result)
# with frac seconds
o = Series([datetime(2012,1,1,microsecond=150)]*3)
y = s-o
result = y.to_string()
- self.assertTrue('-00:00:00.000150' in result)
+ self.assertTrue('-0 days, 00:00:00.000150' in result)
# rounding?
o = Series([datetime(2012,1,1,1)]*3)
y = s-o
result = y.to_string()
- self.assertTrue('-01:00:00' in result)
+ self.assertTrue('-0 days, 01:00:00' in result)
self.assertTrue('1 days, 23:00:00' in result)
o = Series([datetime(2012,1,1,1,1)]*3)
y = s-o
result = y.to_string()
- self.assertTrue('-01:01:00' in result)
+ self.assertTrue('-0 days, 01:01:00' in result)
self.assertTrue('1 days, 22:59:00' in result)
o = Series([datetime(2012,1,1,1,1,microsecond=150)]*3)
y = s-o
result = y.to_string()
- self.assertTrue('-01:01:00.000150' in result)
+ self.assertTrue('-0 days, 01:01:00.000150' in result)
self.assertTrue('1 days, 22:58:59.999850' in result)
# neg time
@@ -2039,6 +2053,212 @@ class TestFloatArrayFormatter(tm.TestCase):
def test_misc(self):
obj = fmt.FloatArrayFormatter(np.array([], dtype=np.float64))
result = obj.get_result()
+ self.assertTrue(len(result) == 0)
+
+ def test_format(self):
+ obj = fmt.FloatArrayFormatter(np.array([12, 0], dtype=np.float64))
+ result = obj.get_result()
+ self.assertEqual(result[0], " 12")
+ self.assertEqual(result[1], " 0")
+
+
+class TestRepr_timedelta64(tm.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ skip_if_np_version_under1p7()
+
+ def test_legacy(self):
+ delta_1d = pd.to_timedelta(1, unit='D')
+ delta_0d = pd.to_timedelta(0, unit='D')
+ delta_1s = pd.to_timedelta(1, unit='s')
+ delta_500ms = pd.to_timedelta(500, unit='ms')
+
+ self.assertEqual(tslib.repr_timedelta64(delta_1d), "1 days, 00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(-delta_1d), "-1 days, 00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(delta_0d), "00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(delta_1s), "00:00:01")
+ self.assertEqual(tslib.repr_timedelta64(delta_500ms), "00:00:00.500000")
+ self.assertEqual(tslib.repr_timedelta64(delta_1d + delta_1s), "1 days, 00:00:01")
+ self.assertEqual(tslib.repr_timedelta64(delta_1d + delta_500ms), "1 days, 00:00:00.500000")
+
+ def test_short(self):
+ delta_1d = pd.to_timedelta(1, unit='D')
+ delta_0d = pd.to_timedelta(0, unit='D')
+ delta_1s = pd.to_timedelta(1, unit='s')
+ delta_500ms = pd.to_timedelta(500, unit='ms')
+
+ self.assertEqual(tslib.repr_timedelta64(delta_1d, format='short'), "1 days")
+ self.assertEqual(tslib.repr_timedelta64(-delta_1d, format='short'), "-1 days")
+ self.assertEqual(tslib.repr_timedelta64(delta_0d, format='short'), "00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(delta_1s, format='short'), "00:00:01")
+ self.assertEqual(tslib.repr_timedelta64(delta_500ms, format='short'), "00:00:00.500000")
+ self.assertEqual(tslib.repr_timedelta64(delta_1d + delta_1s, format='short'), "1 days, 00:00:01")
+ self.assertEqual(tslib.repr_timedelta64(delta_1d + delta_500ms, format='short'), "1 days, 00:00:00.500000")
+
+ def test_long(self):
+ delta_1d = pd.to_timedelta(1, unit='D')
+ delta_0d = pd.to_timedelta(0, unit='D')
+ delta_1s = pd.to_timedelta(1, unit='s')
+ delta_500ms = pd.to_timedelta(500, unit='ms')
+
+ self.assertEqual(tslib.repr_timedelta64(delta_1d, format='long'), "1 days, 00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(-delta_1d, format='long'), "-1 days, 00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(delta_0d, format='long'), "0 days, 00:00:00")
+ self.assertEqual(tslib.repr_timedelta64(delta_1s, format='long'), "0 days, 00:00:01")
+ self.assertEqual(tslib.repr_timedelta64(delta_500ms, format='long'), "0 days, 00:00:00.500000")
+ self.assertEqual(tslib.repr_timedelta64(delta_1d + delta_1s, format='long'), "1 days, 00:00:01")
+ self.assertEqual(tslib.repr_timedelta64(delta_1d + delta_500ms, format='long'), "1 days, 00:00:00.500000")
+
+
+class TestTimedelta64Formatter(tm.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ skip_if_np_version_under1p7()
+
+ def test_mixed(self):
+ x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D')
+ y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s')
+ result = fmt.Timedelta64Formatter(x + y).get_result()
+ self.assertEqual(result[0].strip(), "0 days, 00:00:00")
+ self.assertEqual(result[1].strip(), "1 days, 00:00:01")
+
+ def test_mixed_neg(self):
+ x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D')
+ y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s')
+ result = fmt.Timedelta64Formatter(-(x + y)).get_result()
+ self.assertEqual(result[0].strip(), "0 days, 00:00:00")
+ self.assertEqual(result[1].strip(), "-1 days, 00:00:01")
+
+ def test_days(self):
+ x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D')
+ result = fmt.Timedelta64Formatter(x).get_result()
+ self.assertEqual(result[0].strip(), "0 days")
+ self.assertEqual(result[1].strip(), "1 days")
+
+ result = fmt.Timedelta64Formatter(x[1:2]).get_result()
+ self.assertEqual(result[0].strip(), "1 days")
+
+ def test_days_neg(self):
+ x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D')
+ result = fmt.Timedelta64Formatter(-x).get_result()
+ self.assertEqual(result[0].strip(), "0 days")
+ self.assertEqual(result[1].strip(), "-1 days")
+
+ def test_subdays(self):
+ y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s')
+ result = fmt.Timedelta64Formatter(y).get_result()
+ self.assertEqual(result[0].strip(), "00:00:00")
+ self.assertEqual(result[1].strip(), "00:00:01")
+
+ def test_subdays_neg(self):
+ y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s')
+ result = fmt.Timedelta64Formatter(-y).get_result()
+ self.assertEqual(result[0].strip(), "00:00:00")
+ self.assertEqual(result[1].strip(), "-00:00:01")
+
+ def test_zero(self):
+ x = pd.to_timedelta(list(range(1)) + [pd.NaT], unit='D')
+ result = fmt.Timedelta64Formatter(x).get_result()
+ self.assertEqual(result[0].strip(), "0 days")
+
+ x = pd.to_timedelta(list(range(1)), unit='D')
+ result = fmt.Timedelta64Formatter(x).get_result()
+ self.assertEqual(result[0].strip(), "0 days")
+
+
+class TestDatetime64Formatter(tm.TestCase):
+ def test_mixed(self):
+ x = pd.Series([datetime(2013, 1, 1), datetime(2013, 1, 1, 12), pd.NaT])
+ result = fmt.Datetime64Formatter(x).get_result()
+ self.assertEqual(result[0].strip(), "2013-01-01 00:00:00")
+ self.assertEqual(result[1].strip(), "2013-01-01 12:00:00")
+
+ def test_dates(self):
+ x = pd.Series([datetime(2013, 1, 1), datetime(2013, 1, 2), pd.NaT])
+ result = fmt.Datetime64Formatter(x).get_result()
+ self.assertEqual(result[0].strip(), "2013-01-01")
+ self.assertEqual(result[1].strip(), "2013-01-02")
+
+ def test_date_nanos(self):
+ x = pd.Series([Timestamp(200)])
+ result = fmt.Datetime64Formatter(x).get_result()
+ self.assertEqual(result[0].strip(), "1970-01-01 00:00:00.000000200")
+
+
+class TestNaTFormatting(tm.TestCase):
+ def test_repr(self):
+ self.assertEqual(repr(pd.NaT), "NaT")
+
+ def test_str(self):
+ self.assertEqual(str(pd.NaT), "NaT")
+
+
+class TestDatetimeIndexFormat(tm.TestCase):
+ def test_datetime(self):
+ formatted = pd.to_datetime([datetime(2003, 1, 1, 12), pd.NaT]).format()
+ self.assertEqual(formatted[0], "2003-01-01 12:00:00")
+ self.assertEqual(formatted[1], "NaT")
+
+ def test_date(self):
+ formatted = pd.to_datetime([datetime(2003, 1, 1), pd.NaT]).format()
+ self.assertEqual(formatted[0], "2003-01-01")
+ self.assertEqual(formatted[1], "NaT")
+
+ def test_date_tz(self):
+ formatted = pd.to_datetime([datetime(2013,1,1)], utc=True).format()
+ self.assertEqual(formatted[0], "2013-01-01 00:00:00+00:00")
+
+ formatted = pd.to_datetime([datetime(2013,1,1), pd.NaT], utc=True).format()
+ self.assertEqual(formatted[0], "2013-01-01 00:00:00+00:00")
+
+ def test_date_explict_date_format(self):
+ formatted = pd.to_datetime([datetime(2003, 2, 1), pd.NaT]).format(date_format="%m-%d-%Y", na_rep="UT")
+ self.assertEqual(formatted[0], "02-01-2003")
+ self.assertEqual(formatted[1], "UT")
+
+
+class TestDatetimeIndexUnicode(tm.TestCase):
+ def test_dates(self):
+ text = str(pd.to_datetime([datetime(2013,1,1), datetime(2014,1,1)]))
+ self.assertTrue("[2013-01-01," in text)
+ self.assertTrue(", 2014-01-01]" in text)
+
+ def test_mixed(self):
+ text = str(pd.to_datetime([datetime(2013,1,1), datetime(2014,1,1,12), datetime(2014,1,1)]))
+ self.assertTrue("[2013-01-01 00:00:00," in text)
+ self.assertTrue(", 2014-01-01 00:00:00]" in text)
+
+
+class TestStringRepTimestamp(tm.TestCase):
+ def test_no_tz(self):
+ dt_date = datetime(2013, 1, 2)
+ self.assertEqual(str(dt_date), str(Timestamp(dt_date)))
+
+ dt_datetime = datetime(2013, 1, 2, 12, 1, 3)
+ self.assertEqual(str(dt_datetime), str(Timestamp(dt_datetime)))
+
+ dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45)
+ self.assertEqual(str(dt_datetime_us), str(Timestamp(dt_datetime_us)))
+
+ ts_nanos_only = Timestamp(200)
+ self.assertEqual(str(ts_nanos_only), "1970-01-01 00:00:00.000000200")
+
+ ts_nanos_micros = Timestamp(1200)
+ self.assertEqual(str(ts_nanos_micros), "1970-01-01 00:00:00.000001200")
+
+ def test_tz(self):
+ _skip_if_no_pytz()
+
+ import pytz
+
+ dt_date = datetime(2013, 1, 2, tzinfo=pytz.utc)
+ self.assertEqual(str(dt_date), str(Timestamp(dt_date)))
+
+ dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=pytz.utc)
+ self.assertEqual(str(dt_datetime), str(Timestamp(dt_datetime)))
+
+ dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=pytz.utc)
+ self.assertEqual(str(dt_datetime_us), str(Timestamp(dt_datetime_us)))
if __name__ == '__main__':
import nose
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 6779e1a61c081..e6115a7c0e95d 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -529,8 +529,16 @@ def _mpl_repr(self):
_na_value = tslib.NaT
"""The expected NA value to use with this index."""
+ @cache_readonly
+ def _is_dates_only(self):
+ from pandas.core.format import _is_dates_only
+ return _is_dates_only(self.values)
+
def __unicode__(self):
- from pandas.core.format import _format_datetime64
+ from pandas.core.format import _get_format_datetime64
+
+ formatter = _get_format_datetime64(is_dates_only=self._is_dates_only)
+
values = self.values
freq = None
@@ -539,15 +547,15 @@ def __unicode__(self):
summary = str(self.__class__)
if len(self) == 1:
- first = _format_datetime64(values[0], tz=self.tz)
+ first = formatter(values[0], tz=self.tz)
summary += '\n[%s]' % first
elif len(self) == 2:
- first = _format_datetime64(values[0], tz=self.tz)
- last = _format_datetime64(values[-1], tz=self.tz)
+ first = formatter(values[0], tz=self.tz)
+ last = formatter(values[-1], tz=self.tz)
summary += '\n[%s, %s]' % (first, last)
elif len(self) > 2:
- first = _format_datetime64(values[0], tz=self.tz)
- last = _format_datetime64(values[-1], tz=self.tz)
+ first = formatter(values[0], tz=self.tz)
+ last = formatter(values[-1], tz=self.tz)
summary += '\n[%s, ..., %s]' % (first, last)
tagline = '\nLength: %d, Freq: %s, Timezone: %s'
@@ -630,30 +638,14 @@ def __contains__(self, key):
def _format_with_header(self, header, **kwargs):
return header + self._format_native_types(**kwargs)
- def _format_native_types(self, na_rep=u('NaT'), date_format=None, **kwargs):
- data = list(self)
-
- # tz formatter or time formatter
- zero_time = time(0, 0)
- if date_format is None:
- for d in data:
- if d.time() != zero_time or d.tzinfo is not None:
- return [u('%s') % x for x in data]
-
- values = np.array(data, dtype=object)
- mask = isnull(self.values)
- values[mask] = na_rep
-
- imask = -mask
-
- if date_format is None:
- date_formatter = lambda x: u('%d-%.2d-%.2d' % (x.year, x.month, x.day))
- else:
- date_formatter = lambda x: u(x.strftime(date_format))
-
- values[imask] = np.array([date_formatter(dt) for dt in values[imask]])
-
- return values.tolist()
+ def _format_native_types(self, na_rep=u('NaT'),
+ date_format=None, **kwargs):
+ data = self._get_object_index()
+ from pandas.core.format import Datetime64Formatter
+ return Datetime64Formatter(values=data,
+ nat_rep=na_rep,
+ date_format=date_format,
+ justify='all').get_result()
def isin(self, values):
"""
diff --git a/pandas/tseries/tests/test_timezones.py b/pandas/tseries/tests/test_timezones.py
index d82f91767d413..8f0c817d33a2b 100644
--- a/pandas/tseries/tests/test_timezones.py
+++ b/pandas/tseries/tests/test_timezones.py
@@ -427,7 +427,7 @@ def test_index_with_timezone_repr(self):
rng_eastern = rng.tz_localize('US/Eastern')
- rng_repr = repr(rng)
+ rng_repr = repr(rng_eastern)
self.assert_('2010-04-13 00:00:00' in rng_repr)
def test_index_astype_asobject_tzinfos(self):
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index bda6625f3c3ad..0bac159404e34 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -125,6 +125,8 @@ def _is_fixed_offset(tz):
except AttributeError:
return True
+_zero_time = datetime_time(0, 0)
+
# Python front end to C extension type _Timestamp
# This serves as the box for datetime64
class Timestamp(_Timestamp):
@@ -203,13 +205,17 @@ class Timestamp(_Timestamp):
pass
zone = "'%s'" % zone if zone else 'None'
- return "Timestamp('%s', tz=%s)" % (result,zone)
+ return "Timestamp('%s', tz=%s)" % (result, zone)
@property
- def _repr_base(self):
- result = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (self.year, self.month,
- self.day, self.hour,
- self.minute, self.second)
+ def _date_repr(self):
+ # Ideal here would be self.strftime("%Y-%m-%d"), but
+ # the datetime strftime() methods require year >= 1900
+ return '%d-%.2d-%.2d' % (self.year, self.month, self.day)
+
+ @property
+ def _time_repr(self):
+ result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
if self.nanosecond != 0:
nanos = self.nanosecond + 1000 * self.microsecond
@@ -219,6 +225,10 @@ class Timestamp(_Timestamp):
return result
+ @property
+ def _repr_base(self):
+ return '%s %s' % (self._date_repr, self._time_repr)
+
@property
def tz(self):
"""
@@ -338,6 +348,32 @@ class Timestamp(_Timestamp):
ts.dts.hour, ts.dts.min, ts.dts.sec,
ts.dts.us, ts.tzinfo)
+ def isoformat(self, sep='T'):
+ base = super(_Timestamp, self).isoformat(sep=sep)
+ if self.nanosecond == 0:
+ return base
+
+ if self.tzinfo is not None:
+ base1, base2 = base[:-6], base[-6:]
+ else:
+ base1, base2 = base, ""
+
+ if self.microsecond != 0:
+ base1 += "%.3d" % self.nanosecond
+ else:
+ base1 += ".%.9d" % self.nanosecond
+
+ return base1 + base2
+
+ def _has_time_component(self):
+ """
+ Returns if the Timestamp has a time component
+ in addition to the date part
+ """
+ return (self.time() != _zero_time
+ or self.tzinfo is not None
+ or self.nanosecond != 0)
+
_nat_strings = set(['NaT','nat','NAT','nan','NaN','NAN'])
class NaTType(_NaT):
@@ -355,6 +391,9 @@ class NaTType(_NaT):
def __repr__(self):
return 'NaT'
+ def __str__(self):
+ return 'NaT'
+
def __hash__(self):
return iNaT
@@ -1140,8 +1179,21 @@ def array_to_timedelta64(ndarray[object] values, coerce=True):
return result
-def repr_timedelta64(object value):
- """ provide repr for timedelta64 """
+
+def repr_timedelta64(object value, format=None):
+ """
+ provide repr for timedelta64
+
+ Parameters
+ ----------
+ value : timedelta64
+ format : None|"short"|"long"
+
+ Returns
+ -------
+ converted : Timestamp
+
+ """
ivalue = value.view('i8')
@@ -1178,19 +1230,24 @@ def repr_timedelta64(object value):
seconds_pretty = "%02d" % seconds
else:
sp = abs(round(1e6*frac))
- seconds_pretty = "%02d.%06d" % (seconds,sp)
+ seconds_pretty = "%02d.%06d" % (seconds, sp)
if sign < 0:
sign_pretty = "-"
else:
sign_pretty = ""
- if days:
- return "%s%d days, %02d:%02d:%s" % (sign_pretty, days, hours, minutes,
+ if days or format == 'long':
+ if (hours or minutes or seconds or frac) or format != 'short':
+ return "%s%d days, %02d:%02d:%s" % (sign_pretty, days, hours, minutes,
seconds_pretty)
+ else:
+ return "%s%d days" % (sign_pretty, days)
+
return "%s%02d:%02d:%s" % (sign_pretty, hours, minutes, seconds_pretty)
+
def array_strptime(ndarray[object] values, object fmt, coerce=False):
cdef:
Py_ssize_t i, n = len(values)
| Closes #3401
Closes #5708
Closes #5912
| https://api.github.com/repos/pandas-dev/pandas/pulls/5701 | 2013-12-15T20:15:09Z | 2014-01-15T02:57:34Z | 2014-01-15T02:57:34Z | 2014-06-24T01:58:21Z |
DISP: show column dtype in DataFrame.info() output | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 90641a833f2a7..4aad541e3fcd1 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1426,10 +1426,12 @@ def info(self, verbose=True, buf=None, max_cols=None):
if len(cols) != len(counts): # pragma: no cover
raise AssertionError('Columns must equal counts (%d != %d)' %
(len(cols), len(counts)))
+ dtypes = self.dtypes
for col, count in compat.iteritems(counts):
+ dtype = dtypes[col]
col = com.pprint_thing(col)
lines.append(_put_str(col, space) +
- '%d non-null values' % count)
+ '%d non-null %s' % (count, dtype))
else:
lines.append(self.columns.summary(name='Columns'))
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 5b501de026c57..8103812a633df 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -6018,6 +6018,21 @@ def test_info_duplicate_columns(self):
columns=['a', 'a', 'b', 'b'])
frame.info(buf=io)
+ def test_info_shows_column_dtypes(self):
+ dtypes = ['int64', 'float64', 'datetime64[ns]', 'timedelta64[ns]',
+ 'complex128', 'object', 'bool']
+ data = {}
+ n = 10
+ for i, dtype in enumerate(dtypes):
+ data[i] = np.random.randint(2, size=n).astype(dtype)
+ df = DataFrame(data)
+ buf = StringIO()
+ df.info(buf=buf)
+ res = buf.getvalue()
+ for i, dtype in enumerate(dtypes):
+ name = '%d %d non-null %s' % (i, n, dtype)
+ assert name in res
+
def test_dtypes(self):
self.mixed_frame['bool'] = self.mixed_frame['A'] > 0
result = self.mixed_frame.dtypes
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index d3104cdfad062..3e0a719bd93bd 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2741,6 +2741,12 @@ def test_fillna_raise(self):
self.assertRaises(TypeError, s.fillna, [1, 2])
self.assertRaises(TypeError, s.fillna, (1, 2))
+ def test_raise_on_info(self):
+ s = Series(np.random.randn(10))
+ with tm.assertRaises(AttributeError):
+ s.info()
+
+
# TimeSeries-specific
def test_fillna(self):
| closes #3429.
Old:
```
In [39]: DataFrame(randn(10,2)).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10 entries, 0 to 9
Data columns (total 2 columns):
0 10 non-null values
1 10 non-null values
dtypes: float64(2)
```
New:
```
In [39]: DataFrame(randn(10,2)).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10 entries, 0 to 9
Data columns (total 2 columns):
0 10 non-null float64
1 10 non-null object
dtypes: float64(1), object(1)
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5682 | 2013-12-12T03:13:32Z | 2014-01-01T02:54:25Z | 2014-01-01T02:54:25Z | 2014-06-12T20:01:14Z |
BUG: Bug in repeated indexing of object with resultant non-unique index (GH5678) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 8a911a6e41d0b..f6cbbd23011a8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -821,6 +821,7 @@ Bug Fixes
- Bug in selecting from a non-unique index with ``loc`` (:issue:`5553`)
- Bug in groupby returning non-consistent types when user function returns a ``None``, (:issue:`5592`)
- Work around regression in numpy 1.7.0 which erroneously raises IndexError from ``ndarray.item`` (:issue:`5666`)
+ - Bug in repeated indexing of object with resultant non-unique index (:issue:`5678`)
pandas 0.12.0
-------------
diff --git a/pandas/core/series.py b/pandas/core/series.py
index bc9f6af61b9ec..ecfd99e61a090 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -481,7 +481,10 @@ def _slice(self, slobj, axis=0, raise_on_error=False, typ=None):
def __getitem__(self, key):
try:
- return self.index.get_value(self, key)
+ result = self.index.get_value(self, key)
+ if isinstance(result, np.ndarray):
+ return self._constructor(result,index=[key]*len(result)).__finalize__(self)
+ return result
except InvalidIndexError:
pass
except (KeyError, ValueError):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index b6e7b10232bf5..d941224fec52e 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -316,6 +316,14 @@ def test_at_timestamp(self):
def test_iat_invalid_args(self):
pass
+ def test_repeated_getitem_dups(self):
+ # GH 5678
+ # repeated gettitems on a dup index returing a ndarray
+ df = DataFrame(np.random.random_sample((20,5)), index=['ABCDE'[x%5] for x in range(20)])
+ expected = df.loc['A',0]
+ result = df.loc[:,0].loc['A']
+ assert_series_equal(result,expected)
+
def test_iloc_getitem_int(self):
# integer
| closes #5678
| https://api.github.com/repos/pandas-dev/pandas/pulls/5680 | 2013-12-11T14:33:26Z | 2013-12-11T15:26:47Z | 2013-12-11T15:26:47Z | 2014-07-09T16:15:48Z |
API/ENH: Detect trying to set inplace on copies in a nicer way, related (GH5597) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 93587cd11b597..90641a833f2a7 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1566,11 +1566,14 @@ def _ixs(self, i, axis=0, copy=False):
# a location index by definition
i = _maybe_convert_indices(i, len(self._get_axis(axis)))
- return self.reindex(i, takeable=True)._setitem_copy(True)
+ result = self.reindex(i, takeable=True)
+ copy=True
else:
new_values, copy = self._data.fast_2d_xs(i, copy=copy)
- return Series(new_values, index=self.columns,
- name=self.index[i])._setitem_copy(copy)
+ result = Series(new_values, index=self.columns,
+ name=self.index[i])
+ result.is_copy=copy
+ return result
# icol
else:
@@ -1680,7 +1683,7 @@ def _getitem_multilevel(self, key):
else:
new_values = self.values[:, loc]
result = DataFrame(new_values, index=self.index,
- columns=result_columns)
+ columns=result_columns).__finalize__(self)
if len(result.columns) == 1:
top = result.columns[0]
if ((type(top) == str and top == '') or
@@ -1689,6 +1692,7 @@ def _getitem_multilevel(self, key):
if isinstance(result, Series):
result = Series(result, index=self.index, name=key)
+ result.is_copy=True
return result
else:
return self._get_item_cache(key)
@@ -2136,7 +2140,8 @@ def xs(self, key, axis=0, level=None, copy=True, drop_level=True):
new_values, copy = self._data.fast_2d_xs(loc, copy=copy)
result = Series(new_values, index=self.columns,
- name=self.index[loc])._setitem_copy(copy)
+ name=self.index[loc])
+ result.is_copy=True
else:
result = self[loc]
@@ -2307,7 +2312,6 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
if inplace:
frame = self
-
else:
frame = self.copy()
@@ -2552,8 +2556,8 @@ def drop_duplicates(self, cols=None, take_last=False, inplace=False):
if inplace:
inds, = (-duplicated).nonzero()
- self._data = self._data.take(inds)
- self._clear_item_cache()
+ new_data = self._data.take(inds)
+ self._update_inplace(new_data)
else:
return self[-duplicated]
@@ -2717,13 +2721,12 @@ def trans(v):
if inplace:
if axis == 1:
- self._data = self._data.reindex_items(
+ new_data = self._data.reindex_items(
self._data.items[indexer],
copy=False)
elif axis == 0:
- self._data = self._data.take(indexer)
-
- self._clear_item_cache()
+ new_data = self._data.take(indexer)
+ self._update_inplace(new_data)
else:
return self.take(indexer, axis=axis, convert=False, is_copy=False)
@@ -2763,13 +2766,12 @@ def sortlevel(self, level=0, axis=0, ascending=True, inplace=False):
if inplace:
if axis == 1:
- self._data = self._data.reindex_items(
+ new_data = self._data.reindex_items(
self._data.items[indexer],
copy=False)
elif axis == 0:
- self._data = self._data.take(indexer)
-
- self._clear_item_cache()
+ new_data = self._data.take(indexer)
+ self._update_inplace(new_data)
else:
return self.take(indexer, axis=axis, convert=False, is_copy=False)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 624384e484dc0..253136b9a11c3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -59,7 +59,7 @@ def _single_replace(self, to_replace, method, inplace, limit):
dtype=self.dtype).__finalize__(self)
if inplace:
- self._data = result._data
+ self._update_inplace(result._data)
return
return result
@@ -562,9 +562,7 @@ def f(x):
result._clear_item_cache()
if inplace:
- self._data = result._data
- self._clear_item_cache()
-
+ self._update_inplace(result._data)
else:
return result.__finalize__(self)
@@ -994,12 +992,22 @@ def _maybe_update_cacher(self, clear=False):
if clear, then clear our cache """
cacher = getattr(self, '_cacher', None)
if cacher is not None:
- try:
- cacher[1]()._maybe_cache_changed(cacher[0], self)
- except:
+ ref = cacher[1]()
- # our referant is dead
+ # we are trying to reference a dead referant, hence
+ # a copy
+ if ref is None:
del self._cacher
+ self.is_copy = True
+ self._check_setitem_copy(stacklevel=5, t='referant')
+ else:
+ try:
+ ref._maybe_cache_changed(cacher[0], self)
+ except:
+ pass
+ if ref.is_copy:
+ self.is_copy = True
+ self._check_setitem_copy(stacklevel=5, t='referant')
if clear:
self._clear_item_cache()
@@ -1014,12 +1022,7 @@ def _set_item(self, key, value):
self._data.set(key, value)
self._clear_item_cache()
- def _setitem_copy(self, copy):
- """ set the _is_copy of the iiem """
- self.is_copy = copy
- return self
-
- def _check_setitem_copy(self, stacklevel=4):
+ def _check_setitem_copy(self, stacklevel=4, t='setting'):
""" validate if we are doing a settitem on a chained copy.
If you call this function, be sure to set the stacklevel such that the
@@ -1027,9 +1030,13 @@ def _check_setitem_copy(self, stacklevel=4):
if self.is_copy:
value = config.get_option('mode.chained_assignment')
- t = ("A value is trying to be set on a copy of a slice from a "
- "DataFrame.\nTry using .loc[row_index,col_indexer] = value "
- "instead")
+ if t == 'referant':
+ t = ("A value is trying to be set on a copy of a slice from a "
+ "DataFrame")
+ else:
+ t = ("A value is trying to be set on a copy of a slice from a "
+ "DataFrame.\nTry using .loc[row_index,col_indexer] = value "
+ "instead")
if value == 'raise':
raise SettingWithCopyError(t)
elif value == 'warn':
@@ -1103,7 +1110,7 @@ def take(self, indices, axis=0, convert=True, is_copy=True):
# maybe set copy if we didn't actually change the index
if is_copy and not result._get_axis(axis).equals(self._get_axis(axis)):
- result = result._setitem_copy(is_copy)
+ result.is_copy=is_copy
return result
@@ -1218,7 +1225,7 @@ def _update_inplace(self, result):
# decision that we may revisit in the future.
self._reset_cache()
self._clear_item_cache()
- self._data = result._data
+ self._data = getattr(result,'_data',result)
self._maybe_update_cacher()
def add_prefix(self, prefix):
@@ -1910,14 +1917,13 @@ def fillna(self, value=None, method=None, axis=0, inplace=False,
continue
obj = result[k]
obj.fillna(v, inplace=True)
- obj._maybe_update_cacher()
return result
else:
new_data = self._data.fillna(value, inplace=inplace,
downcast=downcast)
if inplace:
- self._data = new_data
+ self._update_inplace(new_data)
else:
return self._constructor(new_data).__finalize__(self)
@@ -2165,7 +2171,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
new_data = new_data.convert(copy=not inplace, convert_numeric=False)
if inplace:
- self._data = new_data
+ self._update_inplace(new_data)
else:
return self._constructor(new_data).__finalize__(self)
@@ -2272,10 +2278,10 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
if inplace:
if axis == 1:
- self._data = new_data
+ self._update_inplace(new_data)
self = self.T
else:
- self._data = new_data
+ self._update_inplace(new_data)
else:
res = self._constructor(new_data).__finalize__(self)
if axis == 1:
@@ -2856,8 +2862,9 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
if inplace:
# we may have different type blocks come out of putmask, so
# reconstruct the block manager
- self._data = self._data.putmask(cond, other, align=axis is None,
- inplace=True)
+ new_data = self._data.putmask(cond, other, align=axis is None,
+ inplace=True)
+ self._update_inplace(new_data)
else:
new_data = self._data.where(other, cond, align=axis is None,
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index a4e273c43e483..8444c7a9b2a00 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -209,7 +209,7 @@ def _setitem_with_indexer(self, indexer, value):
labels = _safe_append_to_index(index, key)
self.obj._data = self.obj.reindex_axis(labels, i)._data
self.obj._maybe_update_cacher(clear=True)
- self.obj._setitem_copy(False)
+ self.obj.is_copy=False
if isinstance(labels, MultiIndex):
self.obj.sortlevel(inplace=True)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index ffc30c81ededd..5b501de026c57 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -11607,6 +11607,7 @@ def _check_f(base, f):
_check_f(data.copy(), f)
# -----Series-----
+ d = data.copy()['c']
# reset_index
f = lambda x: x.reset_index(inplace=True, drop=True)
@@ -11614,15 +11615,15 @@ def _check_f(base, f):
# fillna
f = lambda x: x.fillna(0, inplace=True)
- _check_f(data.copy()['c'], f)
+ _check_f(d.copy(), f)
# replace
f = lambda x: x.replace(1, 0, inplace=True)
- _check_f(data.copy()['c'], f)
+ _check_f(d.copy(), f)
# rename
f = lambda x: x.rename({1: 'foo'}, inplace=True)
- _check_f(data.copy()['c'], f)
+ _check_f(d.copy(), f)
def test_isin(self):
# GH #4211
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 22c72e1e5d82e..f834094475c1b 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -365,7 +365,7 @@ def f(grp):
return None
return grp.iloc[0].loc['C']
result = df.groupby('A').apply(f)
- e = df.groupby('A').first()['C']
+ e = df.groupby('A').first()['C'].copy()
e.loc['Pony'] = np.nan
e.name = None
assert_series_equal(result,e)
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index d941224fec52e..59c7bda35c544 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1733,9 +1733,9 @@ def test_cache_updating(self):
df.index = index
# setting via chained assignment
- df.loc[0]['z'].iloc[0] = 1.
- result = df.loc[(0,0),'z']
- self.assert_(result == 1)
+ def f():
+ df.loc[0]['z'].iloc[0] = 1.
+ self.assertRaises(com.SettingWithCopyError, f)
# correct setting
df.loc[(0,0),'z'] = 2
@@ -1891,6 +1891,20 @@ def random_text(nobs=100):
self.assert_(df.is_copy is False)
df['a'] += 1
+ # inplace ops
+ # original from: http://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug
+ a = [12, 23]
+ b = [123, None]
+ c = [1234, 2345]
+ d = [12345, 23456]
+ tuples = [('eyes', 'left'), ('eyes', 'right'), ('ears', 'left'), ('ears', 'right')]
+ events = {('eyes', 'left'): a, ('eyes', 'right'): b, ('ears', 'left'): c, ('ears', 'right'): d}
+ multiind = MultiIndex.from_tuples(tuples, names=['part', 'side'])
+ zed = DataFrame(events, index=['a', 'b'], columns=multiind)
+ def f():
+ zed['eyes']['right'].fillna(value=555, inplace=True)
+ self.assertRaises(com.SettingWithCopyError, f)
+
pd.set_option('chained_assignment','warn')
def test_float64index_slicing_bug(self):
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index 151f222d7357a..7dd9dbd51d730 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -1141,14 +1141,27 @@ def test_is_lexsorted(self):
self.assert_(index.lexsort_depth == 0)
def test_frame_getitem_view(self):
- df = self.frame.T
+ df = self.frame.T.copy()
+
+ # this works because we are modifying the underlying array
+ # really a no-no
df['foo'].values[:] = 0
self.assert_((df['foo'].values == 0).all())
# but not if it's mixed-type
df['foo', 'four'] = 'foo'
df = df.sortlevel(0, axis=1)
- df['foo']['one'] = 2
+
+ # this will work, but will raise/warn as its chained assignment
+ def f():
+ df['foo']['one'] = 2
+ return df
+ self.assertRaises(com.SettingWithCopyError, f)
+
+ try:
+ df = f()
+ except:
+ pass
self.assert_((df['foo', 'one'] == 0).all())
def test_frame_getitem_not_sorted(self):
| related #5597
pretty common error that I have seen, originally from:
http://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug
```
In [1]: a = [12, 23]
In [2]: b = [123, None]
In [3]: c = [1234, 2345]
In [4]: d = [12345, 23456]
In [5]: tuples = [('eyes', 'left'), ('eyes', 'right'), ('ears', 'left'), ('ears', 'right')]
In [6]: events = {('eyes', 'left'): a, ('eyes', 'right'): b, ('ears', 'left'): c, ('ears', 'right'): d}
In [7]: multiind = pandas.MultiIndex.from_tuples(tuples, names=['part', 'side'])
In [8]: zed = pandas.DataFrame(events, index=['a', 'b'], columns=multiind)
```
Shows a warning (the message is comewhat generic)
```
In [9]: zed['eyes']['right'].fillna(value=555, inplace=True)
/usr/local/bin/ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
#!/usr/local/bin/python
In [10]: zed
Out[10]:
part eyes ears
side left right left right
a 12 123 1234 12345
b 23 NaN 2345 23456
[2 rows x 4 columns]
```
Correct method
```
In [11]: zed.loc[:,('eyes','right')].fillna(value=555, inplace=True)
In [12]: zed
Out[12]:
part eyes ears
side left right left right
a 12 123 1234 12345
b 23 555 2345 23456
[2 rows x 4 columns]
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/5679 | 2013-12-11T14:01:37Z | 2013-12-11T21:10:14Z | 2013-12-11T21:10:14Z | 2014-06-13T22:14:03Z |
BUG: properly handle a user function ingroupby that returns all scalars (GH5592) | diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 960baa503036c..558843f55777c 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -18,7 +18,8 @@
from pandas.util.decorators import cache_readonly, Appender
import pandas.core.algorithms as algos
import pandas.core.common as com
-from pandas.core.common import _possibly_downcast_to_dtype, isnull, notnull
+from pandas.core.common import(_possibly_downcast_to_dtype, isnull,
+ notnull, _DATELIKE_DTYPES)
import pandas.lib as lib
import pandas.algos as _algos
@@ -2169,11 +2170,12 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
break
if v is None:
return DataFrame()
- values = [
- x if x is not None else
- v._constructor(**v._construct_axes_dict())
- for x in values
- ]
+ elif isinstance(v, NDFrame):
+ values = [
+ x if x is not None else
+ v._constructor(**v._construct_axes_dict())
+ for x in values
+ ]
v = values[0]
@@ -2235,11 +2237,17 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
# through to the outer else caluse
return Series(values, index=key_index)
+ # if we have date/time like in the original, then coerce dates
+ # as we are stacking can easily have object dtypes here
+ cd = True
+ if self.obj.ndim == 2 and self.obj.dtypes.isin(_DATELIKE_DTYPES).any():
+ cd = 'coerce'
return DataFrame(stacked_values, index=index,
- columns=columns).convert_objects()
+ columns=columns).convert_objects(convert_dates=cd, convert_numeric=True)
else:
- return Series(values, index=key_index)
+ return Series(values, index=key_index).convert_objects(
+ convert_dates='coerce',convert_numeric=True)
else:
# Handle cases like BinGrouper
return self._concat_objects(keys, values,
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 6802b57bc39d1..22c72e1e5d82e 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -322,10 +322,12 @@ def func(dataf):
# GH5592
# inconcistent return type
df = DataFrame(dict(A = [ 'Tiger', 'Tiger', 'Tiger', 'Lamb', 'Lamb', 'Pony', 'Pony' ],
- B = Series(np.arange(7),dtype='int64')))
+ B = Series(np.arange(7),dtype='int64'),
+ C = date_range('20130101',periods=7)))
+
def f(grp):
return grp.iloc[0]
- expected = df.groupby('A').first()
+ expected = df.groupby('A').first()[['B']]
result = df.groupby('A').apply(f)[['B']]
assert_frame_equal(result,expected)
@@ -347,6 +349,27 @@ def f(grp):
e.loc['Pony'] = np.nan
assert_frame_equal(result,e)
+ # 5592 revisited, with datetimes
+ def f(grp):
+ if grp.name == 'Pony':
+ return None
+ return grp.iloc[0]
+ result = df.groupby('A').apply(f)[['C']]
+ e = df.groupby('A').first()[['C']]
+ e.loc['Pony'] = np.nan
+ assert_frame_equal(result,e)
+
+ # scalar outputs
+ def f(grp):
+ if grp.name == 'Pony':
+ return None
+ return grp.iloc[0].loc['C']
+ result = df.groupby('A').apply(f)
+ e = df.groupby('A').first()['C']
+ e.loc['Pony'] = np.nan
+ e.name = None
+ assert_series_equal(result,e)
+
def test_agg_regression1(self):
grouped = self.tsframe.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.mean)
| related #5592
BUG: handle coercion of None for date/time like dtypes in a groupby result
| https://api.github.com/repos/pandas-dev/pandas/pulls/5675 | 2013-12-10T22:07:47Z | 2013-12-10T22:42:06Z | 2013-12-10T22:42:06Z | 2014-06-21T12:51:25Z |
BUG: HDFStore improperly inferring a freq on datetimeindexes | diff --git a/doc/source/io.rst b/doc/source/io.rst
index d2ad38f1a2893..3e3ced2b8aba3 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -2089,6 +2089,7 @@ dict:
.. ipython:: python
+ np.random.seed(1234)
index = date_range('1/1/2000', periods=8)
s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
df = DataFrame(randn(8, 3), index=index,
@@ -2513,6 +2514,7 @@ be data_columns
df_dc.ix[4:6,'string'] = np.nan
df_dc.ix[7:9,'string'] = 'bar'
df_dc['string2'] = 'cool'
+ df_dc.ix[1:3,['B','C']] = 1.0
df_dc
# on-disk operations
@@ -2520,7 +2522,7 @@ be data_columns
store.select('df_dc', [ Term('B>0') ])
# getting creative
- store.select('df_dc', ['B > 0', 'C > 0', 'string == foo'])
+ store.select('df_dc', 'B > 0 & C > 0 & string == foo')
# this is in-memory version of this type of selection
df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == 'foo')]
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 6ebc33afdd43d..09618b77a2968 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1434,12 +1434,11 @@ 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,
+ # it should be None (see also 'doc example part 2')
if 'freq' in kwargs:
- kwargs['freq'] = 'infer'
- self.values = Index(
- _maybe_convert(values, self.kind, encoding), **kwargs)
+ kwargs['freq'] = None
+ self.values = Index(values, **kwargs)
# set the timezone if indicated
# we stored in utc, so reverse to local timezone
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 1953f79482a22..e9c04932aba40 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -1327,6 +1327,29 @@ def check_col(key,name,size):
df_dc.string == 'foo')]
tm.assert_frame_equal(result, expected)
+ with ensure_clean_store(self.path) as store:
+ # doc example part 2
+ np.random.seed(1234)
+ index = date_range('1/1/2000', periods=8)
+ df_dc = DataFrame(np.random.randn(8, 3), index=index,
+ columns=['A', 'B', 'C'])
+ df_dc['string'] = 'foo'
+ df_dc.ix[4:6,'string'] = np.nan
+ df_dc.ix[7:9,'string'] = 'bar'
+ df_dc.ix[:,['B','C']] = df_dc.ix[:,['B','C']].abs()
+ df_dc['string2'] = 'cool'
+
+ # on-disk operations
+ store.append('df_dc', df_dc, data_columns = ['B', 'C', 'string', 'string2'])
+
+ result = store.select('df_dc', [ Term('B>0') ])
+ expected = df_dc[df_dc.B>0]
+ tm.assert_frame_equal(result,expected)
+
+ result = store.select('df_dc', ['B > 0', 'C > 0', 'string == "foo"'])
+ expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == 'foo')]
+ tm.assert_frame_equal(result,expected)
+
def test_create_table_index(self):
with ensure_clean_store(self.path) as store:
| surfaced in a doc example
http://stackoverflow.com/questions/20489519/how-come-pandas-select-results-in-the-examples-dont-match
| https://api.github.com/repos/pandas-dev/pandas/pulls/5674 | 2013-12-10T14:28:19Z | 2013-12-10T14:48:29Z | 2013-12-10T14:48:29Z | 2014-07-16T08:42:49Z |
DOC: add pickle compat warning to docs | diff --git a/doc/source/conf.py b/doc/source/conf.py
index 695a954f78cfb..8e8ac4a61acf5 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -248,7 +248,7 @@
'wiki ')}
# remove the docstring of the flags attribute (inherited from numpy ndarray)
-# because these give doc build errors (see GH issue 5331)
+# because these give doc build errors (see GH issue 5331)
def remove_flags_docstring(app, what, name, obj, options, lines):
if what == "attribute" and name.endswith(".flags"):
del lines[:]
diff --git a/doc/source/io.rst b/doc/source/io.rst
index a6f022d85272e..d2ad38f1a2893 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -1967,9 +1967,16 @@ any pickled pandas object (or any other pickled object) from file:
See: http://docs.python.org/2.7/library/pickle.html
+.. warning::
+
+ In 0.13, pickle preserves compatibility with pickles created prior to 0.13. These must
+ be read with ``pd.read_pickle``, rather than the default python ``pickle.load``.
+ See `this question <http://stackoverflow.com/questions/20444593/pandas-compiled-from-source-default-pickle-behavior-changed>`__
+ for a detailed explanation.
+
.. note::
- These methods were previously ``save`` and ``load``, prior to 0.12.0, and are now deprecated.
+ These methods were previously ``pd.save`` and ``pd.load``, prior to 0.12.0, and are now deprecated.
.. _io.msgpack:
diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt
index 8763a5aafb39a..720150015909e 100644
--- a/doc/source/v0.13.0.txt
+++ b/doc/source/v0.13.0.txt
@@ -1,7 +1,7 @@
.. _whatsnew_0130:
-v0.13.0 (October ??, 2013)
---------------------------
+v0.13.0 (December ??, 2013)
+---------------------------
This is a major release from 0.12.0 and includes a number of API changes, several new features and
enhancements along with a large number of bug fixes.
@@ -817,6 +817,7 @@ Experimental
As of 10/10/13, there is a bug in Google's API preventing result sets
from being larger than 100,000 rows. A patch is scheduled for the week of
10/14/13.
+
.. _whatsnew_0130.refactoring:
Internal Refactoring
@@ -860,6 +861,8 @@ to unify methods and behaviors. Series formerly subclassed directly from
- ``Series(0.5)`` would previously return the scalar ``0.5``, instead this will return a 1-element ``Series``
+- Pickle compatibility is preserved for pickles created prior to 0.13. These must be unpickled with ``pd.read_pickle``, see :ref:`Pickling<io.pickle>`.
+
- Refactor of series.py/frame.py/panel.py to move common code to generic.py
- added ``_setup_axes`` to created generic NDFrame structures
| https://api.github.com/repos/pandas-dev/pandas/pulls/5667 | 2013-12-09T13:56:52Z | 2013-12-09T13:57:05Z | 2013-12-09T13:57:05Z | 2014-06-30T04:29:05Z | |
BUG: Work-around a numpy regression affecting pandas.eval() with numexpr | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 97b86703e73b8..8a911a6e41d0b 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -820,6 +820,7 @@ Bug Fixes
- Bug fix in apply when using custom function and objects are not mutated (:issue:`5545`)
- Bug in selecting from a non-unique index with ``loc`` (:issue:`5553`)
- Bug in groupby returning non-consistent types when user function returns a ``None``, (:issue:`5592`)
+ - Work around regression in numpy 1.7.0 which erroneously raises IndexError from ``ndarray.item`` (:issue:`5666`)
pandas 0.12.0
-------------
diff --git a/pandas/computation/align.py b/pandas/computation/align.py
index b61169e1f55e0..71adb74492425 100644
--- a/pandas/computation/align.py
+++ b/pandas/computation/align.py
@@ -249,6 +249,9 @@ def _reconstruct_object(typ, obj, axes, dtype):
try:
ret = ret_value.item()
- except ValueError:
+ except (ValueError, IndexError):
+ # XXX: we catch IndexError to absorb a
+ # regression in numpy 1.7.0
+ # fixed by numpy/numpy@04b89c63
ret = ret_value
return ret
| numpy 1.7.0 erroneously raises IndexError instead of ValueError
from ndarray.item() when the array is not of length 1. This can be
seen as a failure of
```
computation.tests.test_eval.TestScope.test_global_scope
```
for the cases that engine='numexpr'.
Absorb the splatter from this regression by explicitly catching the
erroneous IndexError.
closes #5535.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5666 | 2013-12-09T04:31:29Z | 2013-12-09T20:19:46Z | 2013-12-09T20:19:46Z | 2014-06-13T06:54:13Z |
CLN: PEP8 cleanup of the io module | diff --git a/pandas/computation/align.py b/pandas/computation/align.py
index b61169e1f55e0..b2b7fcc3e1158 100644
--- a/pandas/computation/align.py
+++ b/pandas/computation/align.py
@@ -152,7 +152,9 @@ def _align_core(terms):
copy=False)
# need to fill if we have a bool dtype/array
- if isinstance(ti, (np.ndarray, pd.Series)) and ti.dtype == object and pd.lib.is_bool_array(ti.values):
+ if (isinstance(ti, (np.ndarray, pd.Series))
+ and ti.dtype == object
+ and pd.lib.is_bool_array(ti.values)):
r = f(fill_value=True)
else:
r = f()
diff --git a/pandas/computation/expr.py b/pandas/computation/expr.py
index 0baa596778996..c16205ff34b1f 100644
--- a/pandas/computation/expr.py
+++ b/pandas/computation/expr.py
@@ -512,18 +512,21 @@ def _possibly_evaluate_binop(self, op, op_class, lhs, rhs,
res = op(lhs, rhs)
if self.engine != 'pytables':
- if (res.op in _cmp_ops_syms and getattr(lhs,'is_datetime',False) or getattr(rhs,'is_datetime',False)):
- # all date ops must be done in python bc numexpr doesn't work well
- # with NaT
+ if (res.op in _cmp_ops_syms
+ and getattr(lhs, 'is_datetime', False)
+ or getattr(rhs, 'is_datetime', False)):
+ # all date ops must be done in python bc numexpr doesn't work
+ # well with NaT
return self._possibly_eval(res, self.binary_ops)
if res.op in eval_in_python:
# "in"/"not in" ops are always evaluated in python
return self._possibly_eval(res, eval_in_python)
elif self.engine != 'pytables':
- if (getattr(lhs,'return_type',None) == object or getattr(rhs,'return_type',None) == object):
- # evaluate "==" and "!=" in python if either of our operands has an
- # object return type
+ if (getattr(lhs, 'return_type', None) == object
+ or getattr(rhs, 'return_type', None) == object):
+ # evaluate "==" and "!=" in python if either of our operands
+ # has an object return type
return self._possibly_eval(res, eval_in_python +
maybe_eval_in_python)
return res
diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py
index cfbd9335ef9a0..073526f526abe 100644
--- a/pandas/computation/tests/test_eval.py
+++ b/pandas/computation/tests/test_eval.py
@@ -1022,7 +1022,8 @@ def check_performance_warning_for_poor_alignment(self, engine, parser):
def test_performance_warning_for_poor_alignment(self):
for engine, parser in ENGINES_PARSERS:
- yield self.check_performance_warning_for_poor_alignment, engine, parser
+ yield (self.check_performance_warning_for_poor_alignment, engine,
+ parser)
#------------------------------------
diff --git a/pandas/core/format.py b/pandas/core/format.py
index 7135573d48644..45bf07b49eead 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -264,8 +264,8 @@ class DataFrameFormatter(TableFormatter):
def __init__(self, frame, buf=None, columns=None, col_space=None,
header=True, index=True, na_rep='NaN', formatters=None,
justify=None, float_format=None, sparsify=None,
- index_names=True, line_width=None, max_rows=None, max_cols=None,
- show_dimensions=False, **kwds):
+ index_names=True, line_width=None, max_rows=None,
+ max_cols=None, show_dimensions=False, **kwds):
self.frame = frame
self.buf = buf if buf is not None else StringIO()
self.show_index_names = index_names
@@ -284,7 +284,8 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
self.line_width = line_width
self.max_rows = max_rows
self.max_cols = max_cols
- self.max_rows_displayed = min(max_rows or len(self.frame),len(self.frame))
+ self.max_rows_displayed = min(max_rows or len(self.frame),
+ len(self.frame))
self.show_dimensions = show_dimensions
if justify is None:
@@ -330,7 +331,8 @@ def _to_str_columns(self):
*(_strlen(x) for x in cheader))
fmt_values = _make_fixed_width(fmt_values, self.justify,
- minimum=max_colwidth, truncated=truncate_v)
+ minimum=max_colwidth,
+ truncated=truncate_v)
max_len = max(np.max([_strlen(x) for x in fmt_values]),
max_colwidth)
@@ -349,8 +351,8 @@ def _to_str_columns(self):
if self.index:
strcols.insert(0, str_index)
if truncate_h:
- strcols.append(([''] * len(str_columns[-1])) \
- + (['...'] * min(len(self.frame), self.max_rows)) )
+ strcols.append(([''] * len(str_columns[-1]))
+ + (['...'] * min(len(self.frame), self.max_rows)))
return strcols
@@ -382,8 +384,8 @@ def to_string(self, force_unicode=None):
self.buf.writelines(text)
if self.show_dimensions:
- self.buf.write("\n\n[%d rows x %d columns]" \
- % (len(frame), len(frame.columns)) )
+ self.buf.write("\n\n[%d rows x %d columns]"
+ % (len(frame), len(frame.columns)))
def _join_multiline(self, *strcols):
lwidth = self.line_width
@@ -484,10 +486,11 @@ def write(buf, frame, column_format, strcols):
def _format_col(self, i):
formatter = self._get_formatter(i)
- return format_array((self.frame.iloc[:self.max_rows_displayed,i]).get_values(),
- formatter, float_format=self.float_format,
- na_rep=self.na_rep,
- space=self.col_space)
+ return format_array(
+ (self.frame.iloc[:self.max_rows_displayed, i]).get_values(),
+ formatter, float_format=self.float_format, na_rep=self.na_rep,
+ space=self.col_space
+ )
def to_html(self, classes=None):
"""
@@ -679,8 +682,6 @@ def write_result(self, buf):
'not %s') % type(self.classes))
_classes.extend(self.classes)
-
-
self.write('<table border="1" class="%s">' % ' '.join(_classes),
indent)
@@ -698,9 +699,9 @@ def write_result(self, buf):
self.write('</table>', indent)
if self.fmt.show_dimensions:
- by = chr(215) if compat.PY3 else unichr(215) # ×
+ by = chr(215) if compat.PY3 else unichr(215) # ×
self.write(u('<p>%d rows %s %d columns</p>') %
- (len(frame), by, len(frame.columns)) )
+ (len(frame), by, len(frame.columns)))
_put_lines(buf, self.elements)
def _write_header(self, indent):
@@ -783,8 +784,9 @@ def _column_header():
align=align)
if self.fmt.has_index_names:
- row = [x if x is not None else '' for x in self.frame.index.names] \
- + [''] * min(len(self.columns), self.max_cols)
+ row = [
+ x if x is not None else '' for x in self.frame.index.names
+ ] + [''] * min(len(self.columns), self.max_cols)
self.write_tr(row, indent, self.indent_delta, header=True)
indent -= self.indent_delta
@@ -851,7 +853,7 @@ def _write_hierarchical_rows(self, fmt_values, indent):
truncate = (len(frame) > self.max_rows)
idx_values = frame.index[:nrows].format(sparsify=False, adjoin=False,
- names=False)
+ names=False)
idx_values = lzip(*idx_values)
if self.fmt.sparsify:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index d0a1511ec1cca..93587cd11b597 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -432,8 +432,9 @@ def _repr_fits_horizontal_(self, ignore_width=False):
def _info_repr(self):
"""True if the repr should show the info view."""
info_repr_option = (get_option("display.large_repr") == "info")
- return info_repr_option and not \
- (self._repr_fits_horizontal_() and self._repr_fits_vertical_())
+ return info_repr_option and not (
+ self._repr_fits_horizontal_() and self._repr_fits_vertical_()
+ )
def __unicode__(self):
"""
@@ -486,8 +487,7 @@ def _repr_html_(self):
return ('<div style="max-height:1000px;'
'max-width:1500px;overflow:auto;">\n' +
self.to_html(max_rows=max_rows, max_cols=max_cols,
- show_dimensions=True) \
- + '\n</div>')
+ show_dimensions=True) + '\n</div>')
else:
return None
@@ -1283,7 +1283,8 @@ def to_string(self, buf=None, columns=None, col_space=None, colSpace=None,
index_names=index_names,
header=header, index=index,
line_width=line_width,
- max_rows=max_rows, max_cols=max_cols,
+ max_rows=max_rows,
+ max_cols=max_cols,
show_dimensions=show_dimensions)
formatter.to_string()
@@ -1310,7 +1311,8 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
escape : boolean, default True
Convert the characters <, >, and & to HTML-safe sequences.=
max_rows : int, optional
- Maximum number of rows to show before truncating. If None, show all.
+ Maximum number of rows to show before truncating. If None, show
+ all.
max_cols : int, optional
Maximum number of columns to show before truncating. If None, show
all.
@@ -1336,7 +1338,8 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
header=header, index=index,
bold_rows=bold_rows,
escape=escape,
- max_rows=max_rows, max_cols=max_cols,
+ max_rows=max_rows,
+ max_cols=max_cols,
show_dimensions=show_dimensions)
formatter.to_html(classes=classes)
@@ -1904,7 +1907,8 @@ def _ensure_valid_index(self, value):
if not isinstance(value, Series):
raise ValueError('Cannot set a frame with no defined index '
- 'and a value that cannot be converted to a Series')
+ 'and a value that cannot be converted to a '
+ 'Series')
self._data.set_axis(1, value.index.copy(), check_axis=False)
def _set_item(self, key, value):
@@ -4597,7 +4601,7 @@ def extract_index(data):
def _prep_ndarray(values, copy=True):
- if not isinstance(values, (np.ndarray,Series)):
+ if not isinstance(values, (np.ndarray, Series)):
if len(values) == 0:
return np.empty((0, 0), dtype=object)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 4089b13fca5c7..624384e484dc0 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -42,8 +42,8 @@ def is_dictlike(x):
def _single_replace(self, to_replace, method, inplace, limit):
if self.ndim != 1:
- raise TypeError('cannot replace {0} with method {1} on a {2}'.format(to_replace,
- method,type(self).__name__))
+ raise TypeError('cannot replace {0} with method {1} on a {2}'
+ .format(to_replace, method, type(self).__name__))
orig_dtype = self.dtype
result = self if inplace else self.copy()
@@ -2047,7 +2047,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
# passing a single value that is scalar like
# when value is None (GH5319), for compat
if not is_dictlike(to_replace) and not is_dictlike(regex):
- to_replace = [ to_replace ]
+ to_replace = [to_replace]
if isinstance(to_replace, (tuple, list)):
return _single_replace(self, to_replace, method, inplace,
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 7a7fe32963457..960baa503036c 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -649,9 +649,9 @@ def _index_with_as_index(self, b):
original = self.obj.index
gp = self.grouper
levels = chain((gp.levels[i][gp.labels[i][b]]
- for i in range(len(gp.groupings))),
- (original.get_level_values(i)[b]
- for i in range(original.nlevels)))
+ for i in range(len(gp.groupings))),
+ (original.get_level_values(i)[b]
+ for i in range(original.nlevels)))
new = MultiIndex.from_arrays(list(levels))
new.names = gp.names + original.names
return new
@@ -2161,7 +2161,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
else:
key_index = Index(keys, name=key_names[0])
-
# make Nones an empty object
if com._count_not_none(*values) != len(values):
v = None
@@ -2170,14 +2169,20 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
break
if v is None:
return DataFrame()
- values = [ x if x is not None else v._constructor(**v._construct_axes_dict()) for x in values ]
+ values = [
+ x if x is not None else
+ v._constructor(**v._construct_axes_dict())
+ for x in values
+ ]
v = values[0]
if isinstance(v, (np.ndarray, Series)):
if isinstance(v, Series):
applied_index = self.obj._get_axis(self.axis)
- all_indexed_same = _all_indexes_same([x.index for x in values ])
+ all_indexed_same = _all_indexes_same([
+ x.index for x in values
+ ])
singular_series = (len(values) == 1 and
applied_index.nlevels == 1)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 08f935539ecfc..a4e273c43e483 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -830,7 +830,9 @@ def _reindex(keys, level=None):
# see GH5553, make sure we use the right indexer
new_indexer = np.arange(len(indexer))
- new_indexer[cur_indexer] = np.arange(len(result._get_axis(axis)))
+ new_indexer[cur_indexer] = np.arange(
+ len(result._get_axis(axis))
+ )
new_indexer[missing_indexer] = -1
# we have a non_unique selector, need to use the original
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index e8b18ae93b287..471136dc2386b 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -3480,7 +3480,10 @@ def _delete_from_block(self, i, item):
super(SingleBlockManager, self)._delete_from_block(i, item)
# reset our state
- self._block = self.blocks[0] if len(self.blocks) else make_block(np.array([],dtype=self._block.dtype),[],[])
+ self._block = (
+ self.blocks[0] if len(self.blocks) else
+ make_block(np.array([], dtype=self._block.dtype), [], [])
+ )
self._values = self._block.values
def get_slice(self, slobj, raise_on_error=False):
diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py
index d421fa36326aa..1244d0140a01b 100644
--- a/pandas/core/reshape.py
+++ b/pandas/core/reshape.py
@@ -786,6 +786,7 @@ def lreshape(data, groups, dropna=True, label=None):
return DataFrame(mdata, columns=id_cols + pivot_cols)
+
def wide_to_long(df, stubnames, i, j):
"""
Wide panel to long format. Less flexible but more user-friendly than melt.
@@ -848,8 +849,8 @@ def get_var_names(df, regex):
def melt_stub(df, stub, i, j):
varnames = get_var_names(df, "^"+stub)
- newdf = melt(df, id_vars=i, value_vars=varnames,
- value_name=stub, var_name=j)
+ newdf = melt(df, id_vars=i, value_vars=varnames, value_name=stub,
+ var_name=j)
newdf_j = newdf[j].str.replace(stub, "")
try:
newdf_j = newdf_j.astype(int)
@@ -870,6 +871,7 @@ def melt_stub(df, stub, i, j):
newdf = newdf.merge(new, how="outer", on=id_vars + [j], copy=False)
return newdf.set_index([i, j])
+
def convert_dummies(data, cat_variables, prefix_sep='_'):
"""
Compute DataFrame with specified columns converted to dummy variables (0 /
diff --git a/pandas/io/auth.py b/pandas/io/auth.py
index 15e3eb70d91b2..74b6b13000108 100644
--- a/pandas/io/auth.py
+++ b/pandas/io/auth.py
@@ -117,6 +117,7 @@ def init_service(http):
"""
return gapi.build('analytics', 'v3', http=http)
+
def reset_default_token_store():
import os
os.remove(DEFAULT_TOKEN_FILE)
diff --git a/pandas/io/clipboard.py b/pandas/io/clipboard.py
index 13135d255d9e2..143b507c41c3f 100644
--- a/pandas/io/clipboard.py
+++ b/pandas/io/clipboard.py
@@ -2,6 +2,7 @@
from pandas import compat, get_option, DataFrame
from pandas.compat import StringIO
+
def read_clipboard(**kwargs): # pragma: no cover
"""
Read text from clipboard and pass to read_table. See read_table for the
@@ -20,7 +21,10 @@ def read_clipboard(**kwargs): # pragma: no cover
# 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'))
+ text = compat.bytes_to_str(
+ text, encoding=(kwargs.get('encoding') or
+ get_option('display.encoding'))
+ )
except:
pass
return read_table(StringIO(text), **kwargs)
@@ -58,7 +62,7 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
if sep is None:
sep = '\t'
buf = StringIO()
- obj.to_csv(buf,sep=sep, **kwargs)
+ obj.to_csv(buf, sep=sep, **kwargs)
clipboard_set(buf.getvalue())
return
except:
@@ -70,4 +74,3 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
else:
objstr = str(obj)
clipboard_set(objstr)
-
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 6b8186e253199..d6b2827f94d36 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -13,7 +13,8 @@
_urlopen = urlopen
from urllib.parse import urlparse as parse_url
import urllib.parse as compat_parse
- from urllib.parse import uses_relative, uses_netloc, uses_params, urlencode, urljoin
+ from urllib.parse import (uses_relative, uses_netloc, uses_params,
+ urlencode, urljoin)
from urllib.error import URLError
from http.client import HTTPException
else:
@@ -72,8 +73,8 @@ def _is_s3_url(url):
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
+ """read an encoded stream from the reader and transform the bytes to
+ unicode if required based on the encoding
Parameters
----------
@@ -84,7 +85,7 @@ def maybe_read_encoded_stream(reader, encoding=None):
-------
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:
@@ -97,6 +98,7 @@ def maybe_read_encoded_stream(reader, encoding=None):
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
@@ -114,7 +116,7 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None):
if _is_url(filepath_or_buffer):
req = _urlopen(str(filepath_or_buffer))
- return maybe_read_encoded_stream(req,encoding)
+ return maybe_read_encoded_stream(req, encoding)
if _is_s3_url(filepath_or_buffer):
try:
diff --git a/pandas/io/data.py b/pandas/io/data.py
index cf49515cac576..a3968446930e8 100644
--- a/pandas/io/data.py
+++ b/pandas/io/data.py
@@ -469,6 +469,7 @@ def fetch_data(url, name):
axis=1, join='outer')
return df
+
def get_data_famafrench(name):
# path of zip files
zip_file_url = ('http://mba.tuck.dartmouth.edu/pages/faculty/'
diff --git a/pandas/io/date_converters.py b/pandas/io/date_converters.py
index ef92b8692c07f..3ffcef4b21552 100644
--- a/pandas/io/date_converters.py
+++ b/pandas/io/date_converters.py
@@ -26,7 +26,7 @@ def parse_all_fields(year_col, month_col, day_col, hour_col, minute_col,
minute_col = _maybe_cast(minute_col)
second_col = _maybe_cast(second_col)
return lib.try_parse_datetime_components(year_col, month_col, day_col,
- hour_col, minute_col, second_col)
+ hour_col, minute_col, second_col)
def generic_parser(parse_func, *cols):
diff --git a/pandas/io/excel.py b/pandas/io/excel.py
index b97c9da0b0d18..ad7c37fba4c2f 100644
--- a/pandas/io/excel.py
+++ b/pandas/io/excel.py
@@ -547,8 +547,8 @@ def write_cells(self, cells, sheet_name=None, startrow=0, startcol=0):
colletter = get_column_letter(col)
xcell = wks.cell("%s%s" % (colletter, row))
for field in style.__fields__:
- xcell.style.__setattr__(field, \
- style.__getattribute__(field))
+ xcell.style.__setattr__(
+ field, style.__getattribute__(field))
@classmethod
def _convert_to_style(cls, style_dict):
@@ -778,10 +778,10 @@ def _convert_to_style(self, style_dict, num_format_str=None):
alignment = style_dict.get('alignment')
if alignment:
if (alignment.get('horizontal')
- and alignment['horizontal'] == 'center'):
+ and alignment['horizontal'] == 'center'):
xl_format.set_align('center')
if (alignment.get('vertical')
- and alignment['vertical'] == 'top'):
+ and alignment['vertical'] == 'top'):
xl_format.set_align('top')
# Map the cell borders to XlsxWriter border properties.
diff --git a/pandas/io/ga.py b/pandas/io/ga.py
index 4391b2637a837..f002994888932 100644
--- a/pandas/io/ga.py
+++ b/pandas/io/ga.py
@@ -48,8 +48,8 @@
%s
""" % _QUERY_PARAMS
-_GA_READER_DOC = """Given query parameters, return a DataFrame with all the data
-or an iterator that returns DataFrames containing chunks of the data
+_GA_READER_DOC = """Given query parameters, return a DataFrame with all the
+data or an iterator that returns DataFrames containing chunks of the data
Parameters
----------
@@ -89,12 +89,14 @@
Local host redirect if unspecified
"""
+
def reset_token_store():
"""
Deletes the default token store
"""
auth.reset_default_token_store()
+
@Substitution(extras=_AUTH_PARAMS)
@Appender(_GA_READER_DOC)
def read_ga(metrics, dimensions, start_date, **kwargs):
@@ -185,9 +187,8 @@ def _init_service(self, secrets):
return auth.init_service(http)
def get_account(self, name=None, id=None, **kwargs):
- """
- Retrieve an account that matches the name, id, or some account attribute
- specified in **kwargs
+ """ Retrieve an account that matches the name, id, or some account
+ attribute specified in **kwargs
Parameters
----------
@@ -385,6 +386,7 @@ def _maybe_add_arg(query, field, data, prefix='ga'):
data = ','.join(['%s:%s' % (prefix, x) for x in data])
query[field] = data
+
def _get_match(obj_store, name, id, **kwargs):
key, val = None, None
if len(kwargs) > 0:
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 2d490ec071b4e..010277533589c 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -38,7 +38,8 @@
# These are some custom exceptions that the
# to_gbq() method can throw
-class SchemaMissing(PandasError,IOError):
+
+class SchemaMissing(PandasError, IOError):
"""
Raised when attempting to write a DataFrame to
a new table in Google BigQuery without specifying
@@ -46,14 +47,16 @@ class SchemaMissing(PandasError,IOError):
"""
pass
-class InvalidSchema(PandasError,IOError):
+
+class InvalidSchema(PandasError, IOError):
"""
Raised when attempting to write a DataFrame to
Google BigQuery with an invalid table schema.
"""
pass
-class TableExistsFail(PandasError,IOError):
+
+class TableExistsFail(PandasError, IOError):
"""
Raised when attempting to write a DataFrame to
an existing Google BigQuery table without specifying
@@ -61,7 +64,8 @@ class TableExistsFail(PandasError,IOError):
"""
pass
-class InvalidColumnOrder(PandasError,IOError):
+
+class InvalidColumnOrder(PandasError, IOError):
"""
Raised when the provided column order for output
results DataFrame does not match the schema
@@ -83,6 +87,7 @@ def _authenticate():
"""
return bq.Client.Get()
+
def _parse_entry(field_value, field_type):
"""
Given a value and the corresponding BigQuery data type,
@@ -147,10 +152,7 @@ def _parse_page(raw_page, col_names, col_types, col_dtypes):
page_row_count = len(raw_page)
# Place to hold the results for a page of data
- page_array = np.zeros(
- (page_row_count,),
- dtype=zip(col_names,col_dtypes)
- )
+ page_array = np.zeros((page_row_count,), dtype=zip(col_names, col_dtypes))
for row_num, raw_row in enumerate(raw_page):
entries = raw_row.get('f', [])
# Iterate over each entry - setting proper field types
@@ -163,6 +165,7 @@ def _parse_page(raw_page, col_names, col_types, col_dtypes):
return page_array
+
def _parse_data(client, job, index_col=None, col_order=None):
"""
Iterate through the query results and piece together the
@@ -196,9 +199,9 @@ def _parse_data(client, job, index_col=None, col_order=None):
Notes:
-----
- This script relies on Google being consistent with their
+ This script relies on Google being consistent with their
pagination API. We are using the most flexible iteration method
- that we could find in the bq.py/bigquery_client.py API's, but
+ that we could find in the bq.py/bigquery_client.py API's, but
these have undergone large amounts of change recently.
We have encountered bugs with this functionality, see:
@@ -209,10 +212,11 @@ def _parse_data(client, job, index_col=None, col_order=None):
# see: http://pandas.pydata.org/pandas-docs/dev/missing_data.html#missing-data-casting-rules-and-indexing
dtype_map = {'INTEGER': np.dtype(float),
'FLOAT': np.dtype(float),
- 'TIMESTAMP': 'M8[ns]'} # This seems to be buggy without nanosecond indicator
+ 'TIMESTAMP': 'M8[ns]'} # This seems to be buggy without
+ # nanosecond indicator
# We first need the schema to get information about the columns of
- # our dataframe.
+ # our dataframe.
table_dict = job['configuration']['query']['destinationTable']
fields = client.GetTableSchema(table_dict)['fields']
@@ -226,23 +230,23 @@ def _parse_data(client, job, index_col=None, col_order=None):
# TODO: Do this in one clean step
for field in fields:
col_types.append(field['type'])
- # Note the encoding... numpy doesn't like titles that are UTF8, which is the return
- # type from the API
+ # Note the encoding... numpy doesn't like titles that are UTF8, which
+ # is the return type from the API
col_names.append(field['name'].encode('ascii', 'ignore'))
- # Note, it would be nice to use 'str' types, but BigQuery doesn't have a fixed length
- # in mind - just maxes out at 64k
- col_dtypes.append(dtype_map.get(field['type'],object))
+ # Note, it would be nice to use 'str' types, but BigQuery doesn't have
+ # a fixed length in mind - just maxes out at 64k
+ col_dtypes.append(dtype_map.get(field['type'], object))
-
# How many columns are there
num_columns = len(col_names)
-
+
# Iterate over the result rows.
# Since Google's API now requires pagination of results,
- # we do that here. The following is repurposed from
+ # we do that here. The following is repurposed from
# bigquery_client.py :: Client._JobTableReader._ReadOnePage
- # TODO: Enable Reading From Table, see Client._TableTableReader._ReadOnePage
+ # TODO: Enable Reading From Table,
+ # see Client._TableTableReader._ReadOnePage
# Initially, no page token is set
page_token = None
@@ -254,13 +258,12 @@ def _parse_data(client, job, index_col=None, col_order=None):
total_rows = max_rows
# This is the starting row for a particular page...
- # is ignored if page_token is present, though
+ # is ignored if page_token is present, though
# it may be useful if we wish to implement SQL like LIMITs
# with minimums
start_row = 0
- # Keep our page DataFrames until the end when we
- # concatentate them
+ # Keep our page DataFrames until the end when we concatenate them
dataframe_list = list()
current_job = job['jobReference']
@@ -298,7 +301,8 @@ def _parse_data(client, job, index_col=None, col_order=None):
start_row += len(raw_page)
if total_rows > 0:
completed = (100 * start_row) / total_rows
- logger.info('Remaining Rows: ' + str(total_rows - start_row) + '(' + str(completed) + '% Complete)')
+ logger.info('Remaining Rows: ' + str(total_rows - start_row) + '('
+ + str(completed) + '% Complete)')
else:
logger.info('No Rows')
@@ -308,8 +312,9 @@ def _parse_data(client, job, index_col=None, col_order=None):
# but we felt it was still a good idea.
if not page_token and not raw_page and start_row != total_rows:
raise bigquery_client.BigqueryInterfaceError(
- ("Not enough rows returned by server. Expected: {0}" + \
- " Rows, But Recieved {1}").format(total_rows, start_row))
+ 'Not enough rows returned by server. Expected: {0} Rows, But '
+ 'Received {1}'.format(total_rows, start_row)
+ )
# Build final dataframe
final_df = concat(dataframe_list, ignore_index=True)
@@ -320,14 +325,19 @@ def _parse_data(client, job, index_col=None, col_order=None):
final_df.set_index(index_col, inplace=True)
col_names.remove(index_col)
else:
- raise InvalidColumnOrder('Index column "{0}" does not exist in DataFrame.'.format(index_col))
+ raise InvalidColumnOrder(
+ 'Index column "{0}" does not exist in DataFrame.'
+ .format(index_col)
+ )
# Change the order of columns in the DataFrame based on provided list
if col_order is not None:
if sorted(col_order) == sorted(col_names):
final_df = final_df[col_order]
else:
- raise InvalidColumnOrder('Column order does not match this DataFrame.')
+ raise InvalidColumnOrder(
+ 'Column order does not match this DataFrame.'
+ )
# Downcast floats to integers and objects to booleans
# if there are no NaN's. This is presently due to a
@@ -335,13 +345,15 @@ def _parse_data(client, job, index_col=None, col_order=None):
final_df._data = final_df._data.downcast(dtypes='infer')
return final_df
-def to_gbq(dataframe, destination_table, schema=None, col_order=None, if_exists='fail', **kwargs):
- """Write a DataFrame to a Google BigQuery table.
-
- If the table exists, the DataFrame will be appended. If not, a new table
- will be created, in which case the schema will have to be specified. By default,
- rows will be written in the order they appear in the DataFrame, though
- the user may specify an alternative order.
+
+def to_gbq(dataframe, destination_table, schema=None, col_order=None,
+ if_exists='fail', **kwargs):
+ """Write a DataFrame to a Google BigQuery table.
+
+ If the table exists, the DataFrame will be appended. If not, a new table
+ will be created, in which case the schema will have to be specified. By
+ default, rows will be written in the order they appear in the DataFrame,
+ though the user may specify an alternative order.
Parameters
----------
@@ -350,9 +362,11 @@ def to_gbq(dataframe, destination_table, schema=None, col_order=None, if_exists=
destination_table : string
name of table to be written, in the form 'dataset.tablename'
schema : sequence (optional)
- list of column types in order for data to be inserted, e.g. ['INTEGER', 'TIMESTAMP', 'BOOLEAN']
+ list of column types in order for data to be inserted,
+ e.g. ['INTEGER', 'TIMESTAMP', 'BOOLEAN']
col_order : sequence (optional)
- order which columns are to be inserted, e.g. ['primary_key', 'birthday', 'username']
+ order which columns are to be inserted,
+ e.g. ['primary_key', 'birthday', 'username']
if_exists : {'fail', 'replace', 'append'} (optional)
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
@@ -362,42 +376,50 @@ def to_gbq(dataframe, destination_table, schema=None, col_order=None, if_exists=
Raises
------
SchemaMissing :
- Raised if the 'if_exists' parameter is set to 'replace', but no schema is specified
+ Raised if the 'if_exists' parameter is set to 'replace', but no schema
+ is specified
TableExists :
- Raised if the specified 'destination_table' exists but the 'if_exists' parameter is set to 'fail' (the default)
+ Raised if the specified 'destination_table' exists but the 'if_exists'
+ parameter is set to 'fail' (the default)
InvalidSchema :
Raised if the 'schema' parameter does not match the provided DataFrame
"""
if not _BQ_INSTALLED:
if sys.version_info >= (3, 0):
- raise NotImplementedError('gbq module does not support Python 3 yet')
+ raise NotImplementedError('gbq module does not support Python 3 '
+ 'yet')
else:
raise ImportError('Could not import Google BigQuery Client.')
if not _BQ_VALID_VERSION:
- raise ImportError("pandas requires bigquery >= 2.0.17 for Google BigQuery "
- "support, current version " + _BQ_VERSION)
+ raise ImportError("pandas requires bigquery >= 2.0.17 for Google "
+ "BigQuery support, current version " + _BQ_VERSION)
- ALLOWED_TYPES = ['STRING', 'INTEGER', 'FLOAT', 'BOOLEAN', 'TIMESTAMP', 'RECORD']
+ ALLOWED_TYPES = ['STRING', 'INTEGER', 'FLOAT', 'BOOLEAN', 'TIMESTAMP',
+ 'RECORD']
if if_exists == 'replace' and schema is None:
- raise SchemaMissing('Cannot replace a table without specifying the data schema')
+ raise SchemaMissing('Cannot replace a table without specifying the '
+ 'data schema')
else:
client = _authenticate()
table_reference = client.GetTableReference(destination_table)
if client.TableExists(table_reference):
if if_exists == 'fail':
- raise TableExistsFail('Cannot overwrite existing tables if \'if_exists="fail"\'')
+ raise TableExistsFail('Cannot overwrite existing tables if '
+ '\'if_exists="fail"\'')
else:
- # Build up a string representation of the
+ # Build up a string representation of the
# table's schema. Since the table already
# exists, we ask ask the API for it, which
# is returned in a list of dictionaries
# describing column data. Iterate over these
# and build up a string of form:
# "col_name1 : col_type1, col_name2 : col_type2..."
- schema_full = client.GetTableSchema(dict(table_reference))['fields']
+ schema_full = client.GetTableSchema(
+ dict(table_reference)
+ )['fields']
schema = ''
for count, row in enumerate(schema_full):
if count > 0:
@@ -406,11 +428,13 @@ def to_gbq(dataframe, destination_table, schema=None, col_order=None, if_exists=
else:
logger.info('Creating New Table')
if schema is None:
- raise SchemaMissing('Cannot create a new table without specifying the data schema')
+ raise SchemaMissing('Cannot create a new table without '
+ 'specifying the data schema')
else:
columns = dataframe.columns
if len(schema) != len(columns):
- raise InvalidSchema('Incorrect number of columns in schema')
+ raise InvalidSchema('Incorrect number of columns in '
+ 'schema')
else:
schema_string = ''
for count, name in enumerate(columns):
@@ -420,7 +444,9 @@ def to_gbq(dataframe, destination_table, schema=None, col_order=None, if_exists=
if column_type in ALLOWED_TYPES:
schema_string += name + ':' + schema[count].lower()
else:
- raise InvalidSchema('Invalid Type: ' + column_type + ". Must be one of: " + str(ALLOWED_TYPES))
+ raise InvalidSchema('Invalid Type: ' + column_type
+ + ". Must be one of: " +
+ str(ALLOWED_TYPES))
schema = schema_string
opts = kwargs
@@ -437,18 +463,22 @@ def to_gbq(dataframe, destination_table, schema=None, col_order=None, if_exists=
with tempfile.NamedTemporaryFile() as csv_file:
dataframe.to_csv(csv_file.name, index=False, encoding='utf-8')
- job = client.Load(table_reference, csv_file.name, schema=schema, **opts)
+ job = client.Load(table_reference, csv_file.name, schema=schema,
+ **opts)
-def read_gbq(query, project_id = None, destination_table = None, index_col=None, col_order=None, **kwargs):
+
+def read_gbq(query, project_id=None, destination_table=None, index_col=None,
+ col_order=None, **kwargs):
"""Load data from Google BigQuery.
-
- The main method a user calls to load data from Google BigQuery into a pandas DataFrame.
- This is a simple wrapper for Google's bq.py and bigquery_client.py, which we use
- to get the source data. Because of this, this script respects the user's bq settings
- file, '~/.bigqueryrc', if it exists. Such a file can be generated using 'bq init'. Further,
- additional parameters for the query can be specified as either ``**kwds`` in the command,
- or using FLAGS provided in the 'gflags' module. Particular options can be found in
- bigquery_client.py.
+
+ The main method a user calls to load data from Google BigQuery into a
+ pandas DataFrame. This is a simple wrapper for Google's bq.py and
+ bigquery_client.py, which we use to get the source data. Because of this,
+ this script respects the user's bq settings file, '~/.bigqueryrc', if it
+ exists. Such a file can be generated using 'bq init'. Further, additional
+ parameters for the query can be specified as either ``**kwds`` in the
+ command, or using FLAGS provided in the 'gflags' module. Particular options
+ can be found in bigquery_client.py.
Parameters
----------
@@ -464,8 +494,8 @@ def read_gbq(query, project_id = None, destination_table = None, index_col=None,
DataFrame
destination_table : string (optional)
If provided, send the results to the given table.
- **kwargs :
- To be passed to bq.Client.Create(). Particularly: 'trace',
+ **kwargs :
+ To be passed to bq.Client.Create(). Particularly: 'trace',
'sync', 'api', 'api_version'
Returns
@@ -476,13 +506,14 @@ def read_gbq(query, project_id = None, destination_table = None, index_col=None,
"""
if not _BQ_INSTALLED:
if sys.version_info >= (3, 0):
- raise NotImplementedError('gbq module does not support Python 3 yet')
+ raise NotImplementedError('gbq module does not support Python 3 '
+ 'yet')
else:
raise ImportError('Could not import Google BigQuery Client.')
if not _BQ_VALID_VERSION:
- raise ImportError("pandas requires bigquery >= 2.0.17 for Google BigQuery "
- "support, current version " + _BQ_VERSION)
+ raise ImportError('pandas requires bigquery >= 2.0.17 for Google '
+ 'BigQuery support, current version ' + _BQ_VERSION)
query_args = kwargs
query_args['project_id'] = project_id
@@ -493,5 +524,5 @@ def read_gbq(query, project_id = None, destination_table = None, index_col=None,
client = _authenticate()
job = client.Query(**query_args)
-
+
return _parse_data(client, job, index_col=index_col, col_order=col_order)
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index 08299738f31a2..5d392e94106e9 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -49,7 +49,8 @@
from pandas.compat import u, PY3
from pandas import (
Timestamp, Period, Series, DataFrame, Panel, Panel4D,
- Index, MultiIndex, Int64Index, PeriodIndex, DatetimeIndex, Float64Index, NaT
+ Index, MultiIndex, Int64Index, PeriodIndex, DatetimeIndex, Float64Index,
+ NaT
)
from pandas.sparse.api import SparseSeries, SparseDataFrame, SparsePanel
from pandas.sparse.array import BlockIndex, IntIndex
@@ -87,7 +88,8 @@ def to_msgpack(path_or_buf, *args, **kwargs):
args : an object or objects to serialize
append : boolean whether to append to an existing msgpack
(default is False)
- compress : type of compressor (zlib or blosc), default to None (no compression)
+ compress : type of compressor (zlib or blosc), default to None (no
+ compression)
"""
global compressor
compressor = kwargs.pop('compress', None)
@@ -111,6 +113,7 @@ def writer(fh):
else:
writer(path_or_buf)
+
def read_msgpack(path_or_buf, iterator=False, **kwargs):
"""
Load msgpack pandas object from the specified
@@ -153,7 +156,7 @@ def read(fh):
return read(fh)
# treat as a string-like
- if not hasattr(path_or_buf,'read'):
+ if not hasattr(path_or_buf, 'read'):
try:
fh = compat.BytesIO(path_or_buf)
@@ -230,6 +233,7 @@ def convert(values):
# ndarray (on original dtype)
return v.tostring()
+
def unconvert(values, dtype, compress=None):
if dtype == np.object_:
@@ -251,7 +255,8 @@ def unconvert(values, dtype, compress=None):
return np.frombuffer(values, dtype=dtype)
# from a string
- return np.fromstring(values.encode('latin1'),dtype=dtype)
+ return np.fromstring(values.encode('latin1'), dtype=dtype)
+
def encode(obj):
"""
@@ -264,11 +269,11 @@ def encode(obj):
return {'typ': 'period_index',
'klass': obj.__class__.__name__,
'name': getattr(obj, 'name', None),
- 'freq': getattr(obj,'freqstr',None),
+ 'freq': getattr(obj, 'freqstr', None),
'dtype': obj.dtype.num,
'data': convert(obj.asi8)}
elif isinstance(obj, DatetimeIndex):
- tz = getattr(obj,'tz',None)
+ tz = getattr(obj, 'tz', None)
# store tz info and data as UTC
if tz is not None:
@@ -279,8 +284,8 @@ def encode(obj):
'name': getattr(obj, 'name', None),
'dtype': obj.dtype.num,
'data': convert(obj.asi8),
- 'freq': getattr(obj,'freqstr',None),
- 'tz': tz }
+ 'freq': getattr(obj, 'freqstr', None),
+ 'tz': tz}
elif isinstance(obj, MultiIndex):
return {'typ': 'multi_index',
'klass': obj.__class__.__name__,
@@ -295,7 +300,9 @@ def encode(obj):
'data': convert(obj.values)}
elif isinstance(obj, Series):
if isinstance(obj, SparseSeries):
- raise NotImplementedError("msgpack sparse series is not implemented")
+ raise NotImplementedError(
+ 'msgpack sparse series is not implemented'
+ )
#d = {'typ': 'sparse_series',
# 'klass': obj.__class__.__name__,
# 'dtype': obj.dtype.num,
@@ -316,7 +323,9 @@ def encode(obj):
'compress': compressor}
elif issubclass(tobj, NDFrame):
if isinstance(obj, SparseDataFrame):
- raise NotImplementedError("msgpack sparse frame is not implemented")
+ raise NotImplementedError(
+ 'msgpack sparse frame is not implemented'
+ )
#d = {'typ': 'sparse_dataframe',
# 'klass': obj.__class__.__name__,
# 'columns': obj.columns}
@@ -326,7 +335,9 @@ def encode(obj):
# for name, ss in compat.iteritems(obj)])
#return d
elif isinstance(obj, SparsePanel):
- raise NotImplementedError("msgpack sparse frame is not implemented")
+ raise NotImplementedError(
+ 'msgpack sparse frame is not implemented'
+ )
#d = {'typ': 'sparse_panel',
# 'klass': obj.__class__.__name__,
# 'items': obj.items}
@@ -353,7 +364,8 @@ def encode(obj):
'compress': compressor
} for b in data.blocks]}
- elif isinstance(obj, (datetime, date, np.datetime64, timedelta, np.timedelta64)):
+ elif isinstance(obj, (datetime, date, np.datetime64, timedelta,
+ np.timedelta64)):
if isinstance(obj, Timestamp):
tz = obj.tzinfo
if tz is not None:
@@ -436,18 +448,22 @@ def decode(obj):
return Period(ordinal=obj['ordinal'], freq=obj['freq'])
elif typ == 'index':
dtype = dtype_for(obj['dtype'])
- data = unconvert(obj['data'], np.typeDict[obj['dtype']], obj.get('compress'))
+ data = unconvert(obj['data'], np.typeDict[obj['dtype']],
+ obj.get('compress'))
return globals()[obj['klass']](data, dtype=dtype, name=obj['name'])
elif typ == 'multi_index':
- data = unconvert(obj['data'], np.typeDict[obj['dtype']], obj.get('compress'))
- data = [ tuple(x) for x in data ]
+ data = unconvert(obj['data'], np.typeDict[obj['dtype']],
+ obj.get('compress'))
+ data = [tuple(x) for x in data]
return globals()[obj['klass']].from_tuples(data, names=obj['names'])
elif typ == 'period_index':
data = unconvert(obj['data'], np.int64, obj.get('compress'))
- return globals()[obj['klass']](data, name=obj['name'], freq=obj['freq'])
+ return globals()[obj['klass']](data, name=obj['name'],
+ freq=obj['freq'])
elif typ == 'datetime_index':
data = unconvert(obj['data'], np.int64, obj.get('compress'))
- result = globals()[obj['klass']](data, freq=obj['freq'], name=obj['name'])
+ result = globals()[obj['klass']](data, freq=obj['freq'],
+ name=obj['name'])
tz = obj['tz']
# reverse tz conversion
@@ -457,13 +473,17 @@ def decode(obj):
elif typ == 'series':
dtype = dtype_for(obj['dtype'])
index = obj['index']
- return globals()[obj['klass']](unconvert(obj['data'], dtype, obj['compress']), index=index, name=obj['name'])
+ return globals()[obj['klass']](unconvert(obj['data'], dtype,
+ obj['compress']),
+ index=index, name=obj['name'])
elif typ == 'block_manager':
axes = obj['axes']
def create_block(b):
dtype = dtype_for(b['dtype'])
- return make_block(unconvert(b['values'], dtype, b['compress']).reshape(b['shape']), b['items'], axes[0], klass=getattr(internals, b['klass']))
+ return make_block(unconvert(b['values'], dtype, b['compress'])
+ .reshape(b['shape']), b['items'], axes[0],
+ klass=getattr(internals, b['klass']))
blocks = [create_block(b) for b in obj['blocks']]
return globals()[obj['klass']](BlockManager(blocks, axes))
@@ -479,21 +499,29 @@ def create_block(b):
return np.timedelta64(int(obj['data']))
#elif typ == 'sparse_series':
# dtype = dtype_for(obj['dtype'])
- # return globals(
- # )[obj['klass']](unconvert(obj['sp_values'], dtype, obj['compress']), sparse_index=obj['sp_index'],
- # index=obj['index'], fill_value=obj['fill_value'], kind=obj['kind'], name=obj['name'])
+ # return globals()[obj['klass']](
+ # unconvert(obj['sp_values'], dtype, obj['compress']),
+ # sparse_index=obj['sp_index'], index=obj['index'],
+ # fill_value=obj['fill_value'], kind=obj['kind'], name=obj['name'])
#elif typ == 'sparse_dataframe':
- # return globals()[obj['klass']](obj['data'],
- # columns=obj['columns'], default_fill_value=obj['default_fill_value'], default_kind=obj['default_kind'])
+ # return globals()[obj['klass']](
+ # obj['data'], columns=obj['columns'],
+ # default_fill_value=obj['default_fill_value'],
+ # default_kind=obj['default_kind']
+ # )
#elif typ == 'sparse_panel':
- # return globals()[obj['klass']](obj['data'],
- # items=obj['items'], default_fill_value=obj['default_fill_value'], default_kind=obj['default_kind'])
+ # return globals()[obj['klass']](
+ # obj['data'], items=obj['items'],
+ # default_fill_value=obj['default_fill_value'],
+ # default_kind=obj['default_kind'])
elif typ == 'block_index':
- return globals()[obj['klass']](obj['length'], obj['blocs'], obj['blengths'])
+ return globals()[obj['klass']](obj['length'], obj['blocs'],
+ obj['blengths'])
elif typ == 'int_index':
return globals()[obj['klass']](obj['length'], obj['indices'])
elif typ == 'ndarray':
- return unconvert(obj['data'], np.typeDict[obj['dtype']], obj.get('compress')).reshape(obj['shape'])
+ return unconvert(obj['data'], np.typeDict[obj['dtype']],
+ obj.get('compress')).reshape(obj['shape'])
elif typ == 'np_scalar':
if obj.get('sub_typ') == 'np_complex':
return c2f(obj['real'], obj['imag'], obj['dtype'])
@@ -585,7 +613,7 @@ def __iter__(self):
try:
path_exists = os.path.exists(self.path)
- except (TypeError):
+ except TypeError:
path_exists = False
if path_exists:
@@ -595,7 +623,7 @@ def __iter__(self):
else:
- if not hasattr(self.path,'read'):
+ if not hasattr(self.path, 'read'):
fh = compat.BytesIO(self.path)
else:
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index e62ecd5a541df..bd0649a7a85f3 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -30,14 +30,15 @@
Parameters
----------
filepath_or_buffer : 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
+ 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.csv
%s
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. Quoted items can include the delimiter and it will be ignored.
+ The character to used to denote the start and end of a quoted item. Quoted
+ items can include the delimiter and it will be ignored.
quoting : int
Controls whether quotes should be recognized. Values are taken from
`csv.QUOTE_*` values. Acceptable values are 0, 1, 2, and 3 for
@@ -55,9 +56,9 @@
header : int row number(s) to use as the column names, and the start of the
data. Defaults to 0 if no ``names`` passed, otherwise ``None``. Explicitly
pass ``header=0`` to be able to replace existing names. The header can be
- a list of integers that specify row locations for a multi-index on the columns
- E.g. [0,1,3]. Intervening rows that are not specified will be skipped.
- (E.g. 2 in this example are skipped)
+ a list of integers that specify row locations for a multi-index on the
+ columns E.g. [0,1,3]. Intervening rows that are not specified will be
+ skipped. (E.g. 2 in this example are skipped)
skiprows : list-like or integer
Row numbers to skip (0-indexed) or number of rows to skip (int)
at the start of the file
@@ -251,7 +252,7 @@ def _read(filepath_or_buffer, kwds):
'squeeze': False,
'compression': None,
'mangle_dupe_cols': True,
- 'tupleize_cols':False,
+ 'tupleize_cols': False,
}
@@ -437,9 +438,10 @@ def read_fwf(filepath_or_buffer, colspecs='infer', widths=None, **kwds):
# common NA values
# no longer excluding inf representations
# '1.#INF','-1.#INF', '1.#INF000000',
-_NA_VALUES = set(['-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN',
- '#N/A','N/A', 'NA', '#NA', 'NULL', 'NaN',
- 'nan', ''])
+_NA_VALUES = set([
+ '-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN', '#N/A', 'N/A', 'NA', '#NA',
+ 'NULL', 'NaN', 'nan', ''
+])
class TextFileReader(object):
@@ -653,14 +655,14 @@ def __init__(self, kwds):
self.na_fvalues = kwds.get('na_fvalues')
self.true_values = kwds.get('true_values')
self.false_values = kwds.get('false_values')
- self.tupleize_cols = kwds.get('tupleize_cols',False)
+ self.tupleize_cols = kwds.get('tupleize_cols', False)
self._date_conv = _make_date_converter(date_parser=self.date_parser,
dayfirst=self.dayfirst)
# validate header options for mi
self.header = kwds.get('header')
- if isinstance(self.header,(list,tuple,np.ndarray)):
+ if isinstance(self.header, (list, tuple, np.ndarray)):
if kwds.get('as_recarray'):
raise ValueError("cannot specify as_recarray when "
"specifying a multi-index header")
@@ -702,7 +704,8 @@ def _should_parse_dates(self, i):
else:
return (j in self.parse_dates) or (name in self.parse_dates)
- def _extract_multi_indexer_columns(self, header, index_names, col_names, passed_names=False):
+ def _extract_multi_indexer_columns(self, header, index_names, col_names,
+ passed_names=False):
""" extract and return the names, index_names, col_names
header is a list-of-lists returned from the parsers """
if len(header) < 2:
@@ -715,8 +718,8 @@ def _extract_multi_indexer_columns(self, header, index_names, col_names, passed_
if ic is None:
ic = []
- if not isinstance(ic, (list,tuple,np.ndarray)):
- ic = [ ic ]
+ if not isinstance(ic, (list, tuple, np.ndarray)):
+ ic = [ic]
sic = set(ic)
# clean the index_names
@@ -726,22 +729,29 @@ def _extract_multi_indexer_columns(self, header, index_names, col_names, passed_
# extract the columns
field_count = len(header[0])
+
def extract(r):
- return tuple([ r[i] for i in range(field_count) if i not in sic ])
- columns = lzip(*[ extract(r) for r in header ])
+ return tuple([r[i] for i in range(field_count) if i not in sic])
+
+ columns = lzip(*[extract(r) for r in header])
names = ic + columns
- # if we find 'Unnamed' all of a single level, then our header was too long
+ # if we find 'Unnamed' all of a single level, then our header was too
+ # long
for n in range(len(columns[0])):
- if all([ 'Unnamed' in c[n] for c in columns ]):
- raise _parser.CParserError("Passed header=[%s] are too many rows for this "
- "multi_index of columns" % ','.join([ str(x) for x in self.header ]))
+ if all(['Unnamed' in c[n] for c in columns]):
+ raise _parser.CParserError(
+ "Passed header=[%s] are too many rows for this "
+ "multi_index of columns"
+ % ','.join([str(x) for x in self.header])
+ )
# clean the column names (if we have an index_col)
if len(ic):
- col_names = [ r[0] if len(r[0]) and 'Unnamed' not in r[0] else None for r in header ]
+ col_names = [r[0] if len(r[0]) and 'Unnamed' not in r[0] else None
+ for r in header]
else:
- col_names = [ None ] * len(header)
+ col_names = [None] * len(header)
passed_names = True
@@ -749,9 +759,10 @@ def extract(r):
def _maybe_make_multi_index_columns(self, columns, col_names=None):
# possibly create a column mi here
- if not self.tupleize_cols and len(columns) and not isinstance(
- columns, MultiIndex) and all([ isinstance(c,tuple) for c in columns]):
- columns = MultiIndex.from_tuples(columns,names=col_names)
+ if (not self.tupleize_cols and len(columns) and
+ not isinstance(columns, MultiIndex) and
+ all([isinstance(c, tuple) for c in columns])):
+ columns = MultiIndex.from_tuples(columns, names=col_names)
return columns
def _make_index(self, data, alldata, columns, indexnamerow=False):
@@ -849,9 +860,8 @@ def _agg_index(self, index, try_parse_dates=True):
if isinstance(self.na_values, dict):
col_name = self.index_names[i]
if col_name is not None:
- col_na_values, col_na_fvalues = _get_na_values(col_name,
- self.na_values,
- self.na_fvalues)
+ col_na_values, col_na_fvalues = _get_na_values(
+ col_name, self.na_values, self.na_fvalues)
arr, _ = self._convert_types(arr, col_na_values | col_na_fvalues)
arrays.append(arr)
@@ -865,14 +875,14 @@ def _convert_to_ndarrays(self, dct, na_values, na_fvalues, verbose=False,
result = {}
for c, values in compat.iteritems(dct):
conv_f = None if converters is None else converters.get(c, None)
- col_na_values, col_na_fvalues = _get_na_values(c, na_values, na_fvalues)
+ col_na_values, col_na_fvalues = _get_na_values(c, na_values,
+ na_fvalues)
coerce_type = True
if conv_f is not None:
values = lib.map_infer(values, conv_f)
coerce_type = False
- cvals, na_count = self._convert_types(values,
- set(col_na_values) | col_na_fvalues,
- coerce_type)
+ cvals, na_count = self._convert_types(
+ values, set(col_na_values) | col_na_fvalues, coerce_type)
result[c] = cvals
if verbose and na_count:
print('Filled %d NA values in column %s' % (na_count, str(c)))
@@ -951,8 +961,12 @@ def __init__(self, src, **kwds):
else:
if len(self._reader.header) > 1:
# we have a multi index in the columns
- self.names, self.index_names, self.col_names, passed_names = self._extract_multi_indexer_columns(
- self._reader.header, self.index_names, self.col_names, passed_names)
+ self.names, self.index_names, self.col_names, passed_names = (
+ self._extract_multi_indexer_columns(
+ self._reader.header, self.index_names, self.col_names,
+ passed_names
+ )
+ )
else:
self.names = list(self._reader.header[0])
@@ -963,8 +977,9 @@ def __init__(self, src, **kwds):
else:
self.names = lrange(self._reader.table_width)
- # If the names were inferred (not passed by user) and usedcols is defined,
- # then ensure names refers to the used columns, not the document's columns.
+ # If the names were inferred (not passed by user) and usedcols is
+ # defined, then ensure names refers to the used columns, not the
+ # document's columns.
if self.usecols and passed_names:
col_indices = []
for u in self.usecols:
@@ -972,7 +987,8 @@ def __init__(self, src, **kwds):
col_indices.append(self.names.index(u))
else:
col_indices.append(u)
- self.names = [n for i, n in enumerate(self.names) if i in col_indices]
+ self.names = [n for i, n in enumerate(self.names)
+ if i in col_indices]
if len(self.names) < len(self.usecols):
raise ValueError("Usecols do not match names.")
@@ -982,11 +998,12 @@ def __init__(self, src, **kwds):
if not self._has_complex_date_col:
if (self._reader.leading_cols == 0 and
- _is_index_col(self.index_col)):
+ _is_index_col(self.index_col)):
self._name_processed = True
(index_names, self.names,
- self.index_col) = _clean_index_names(self.names, self.index_col)
+ self.index_col) = _clean_index_names(self.names,
+ self.index_col)
if self.index_names is None:
self.index_names = index_names
@@ -1265,8 +1282,11 @@ def __init__(self, f, **kwds):
# The original set is stored in self.original_columns.
if len(self.columns) > 1:
# we are processing a multi index column
- self.columns, self.index_names, self.col_names, _ = self._extract_multi_indexer_columns(
- self.columns, self.index_names, self.col_names)
+ self.columns, self.index_names, self.col_names, _ = (
+ self._extract_multi_indexer_columns(
+ self.columns, self.index_names, self.col_names
+ )
+ )
# Update list of original names to include all indices.
self.num_original_columns = len(self.columns)
else:
@@ -1291,7 +1311,8 @@ def __init__(self, f, **kwds):
self._no_thousands_columns = None
def _set_no_thousands_columns(self):
- # Create a set of column ids that are not to be stripped of thousands operators.
+ # Create a set of column ids that are not to be stripped of thousands
+ # operators.
noconvert_columns = set()
def _set(x):
@@ -1478,7 +1499,8 @@ def _infer_columns(self):
for i, c in enumerate(line):
if c == '':
if have_mi_columns:
- this_columns.append('Unnamed: %d_level_%d' % (i, level))
+ this_columns.append('Unnamed: %d_level_%d'
+ % (i, level))
else:
this_columns.append('Unnamed: %d' % i)
unnamed_count += 1
@@ -1494,16 +1516,17 @@ def _infer_columns(self):
counts[col] = cur_count + 1
elif have_mi_columns:
- # if we have grabbed an extra line, but its not in our format
- # so save in the buffer, and create an blank extra line for the rest of the
- # parsing code
+ # if we have grabbed an extra line, but its not in our
+ # format so save in the buffer, and create an blank extra
+ # line for the rest of the parsing code
if hr == header[-1]:
lc = len(this_columns)
- ic = len(self.index_col) if self.index_col is not None else 0
+ ic = (len(self.index_col)
+ if self.index_col is not None else 0)
if lc != unnamed_count and lc-ic > unnamed_count:
clear_buffer = False
- this_columns = [ None ] * lc
- self.buf = [ self.buf[-1] ]
+ this_columns = [None] * lc
+ self.buf = [self.buf[-1]]
columns.append(this_columns)
if len(columns) == 1:
@@ -1513,17 +1536,19 @@ def _infer_columns(self):
self._clear_buffer()
if names is not None:
- if (self.usecols is not None and len(names) != len(self.usecols)) \
- or (self.usecols is None and len(names) != len(columns[0])):
-
+ if ((self.usecols is not None
+ and len(names) != len(self.usecols))
+ or (self.usecols is None
+ and len(names) != len(columns[0]))):
raise ValueError('Number of passed names did not match '
- 'number of header fields in the file')
+ 'number of header fields in the file')
if len(columns) > 1:
raise TypeError('Cannot pass names with multi-index '
'columns')
if self.usecols is not None:
- # Set _use_cols. We don't store columns because they are overwritten.
+ # Set _use_cols. We don't store columns because they are
+ # overwritten.
self._handle_usecols(columns, names)
else:
self._col_indices = None
@@ -1538,9 +1563,9 @@ def _infer_columns(self):
num_original_columns = ncols
if not names:
if self.prefix:
- columns = [ ['X%d' % i for i in range(ncols)] ]
+ columns = [['X%d' % i for i in range(ncols)]]
else:
- columns = [ lrange(ncols) ]
+ columns = [lrange(ncols)]
columns = self._handle_usecols(columns, columns[0])
else:
if self.usecols is None or len(names) == num_original_columns:
@@ -1548,8 +1573,10 @@ def _infer_columns(self):
num_original_columns = len(names)
else:
if self.usecols and len(names) != len(self.usecols):
- raise ValueError('Number of passed names did not match '
- 'number of header fields in the file')
+ raise ValueError(
+ 'Number of passed names did not match number of '
+ 'header fields in the file'
+ )
# Ignore output but set used columns.
self._handle_usecols([names], names)
columns = [names]
@@ -1566,7 +1593,8 @@ def _handle_usecols(self, columns, usecols_key):
if self.usecols is not None:
if any([isinstance(u, string_types) for u in self.usecols]):
if len(columns) > 1:
- raise ValueError("If using multiple headers, usecols must be integers.")
+ raise ValueError("If using multiple headers, usecols must "
+ "be integers.")
col_indices = []
for u in self.usecols:
if isinstance(u, string_types):
@@ -1576,7 +1604,8 @@ def _handle_usecols(self, columns, usecols_key):
else:
col_indices = self.usecols
- columns = [[n for i, n in enumerate(column) if i in col_indices] for column in columns]
+ columns = [[n for i, n in enumerate(column) if i in col_indices]
+ for column in columns]
self._col_indices = col_indices
return columns
@@ -1640,8 +1669,9 @@ def _check_thousands(self, lines):
for i, x in enumerate(l):
if (not isinstance(x, compat.string_types) or
self.thousands not in x or
- (self._no_thousands_columns and i in self._no_thousands_columns) or
- nonnum.search(x.strip())):
+ (self._no_thousands_columns
+ and i in self._no_thousands_columns)
+ or nonnum.search(x.strip())):
rl.append(x)
else:
rl.append(x.replace(self.thousands, ''))
@@ -1746,9 +1776,14 @@ def _rows_to_cols(self, content):
if self.usecols:
if self._implicit_index:
- zipped_content = [a for i, a in enumerate(zipped_content) if i < len(self.index_col) or i - len(self.index_col) in self._col_indices]
+ zipped_content = [
+ a for i, a in enumerate(zipped_content)
+ if (i < len(self.index_col)
+ or i - len(self.index_col) in self._col_indices)
+ ]
else:
- zipped_content = [a for i, a in enumerate(zipped_content) if i in self._col_indices]
+ zipped_content = [a for i, a in enumerate(zipped_content)
+ if i in self._col_indices]
return zipped_content
def _get_lines(self, rows=None):
@@ -1802,8 +1837,8 @@ def _get_lines(self, rows=None):
except csv.Error as inst:
if 'newline inside string' in str(inst):
row_num = str(self.pos + rows)
- msg = ('EOF inside string starting with line '
- + row_num)
+ msg = ('EOF inside string starting with '
+ 'line ' + row_num)
raise Exception(msg)
raise
except StopIteration:
@@ -1948,7 +1983,9 @@ def _clean_na_values(na_values, keep_default_na=True):
for k, v in compat.iteritems(na_values):
v = set(list(v)) | _NA_VALUES
na_values[k] = v
- na_fvalues = dict([ (k, _floatify_na_values(v)) for k, v in na_values.items() ])
+ na_fvalues = dict([
+ (k, _floatify_na_values(v)) for k, v in na_values.items()
+ ])
else:
if not com.is_list_like(na_values):
na_values = [na_values]
@@ -1987,7 +2024,8 @@ def _clean_index_names(columns, index_col):
index_names.append(name)
# hack
- if isinstance(index_names[0], compat.string_types) and 'Unnamed' in index_names[0]:
+ if isinstance(index_names[0], compat.string_types)\
+ and 'Unnamed' in index_names[0]:
index_names[0] = None
return index_names, columns, index_col
@@ -2071,10 +2109,13 @@ def _get_col_names(colspec, columns):
def _concat_date_cols(date_cols):
if len(date_cols) == 1:
if compat.PY3:
- return np.array([compat.text_type(x) for x in date_cols[0]], dtype=object)
+ return np.array([compat.text_type(x) for x in date_cols[0]],
+ dtype=object)
else:
- return np.array([str(x) if not isinstance(x, compat.string_types) else x
- for x in date_cols[0]], dtype=object)
+ return np.array([
+ str(x) if not isinstance(x, compat.string_types) else x
+ for x in date_cols[0]
+ ], dtype=object)
rs = np.array([' '.join([compat.text_type(y) for y in x])
for x in zip(*date_cols)], dtype=object)
@@ -2101,9 +2142,9 @@ def __init__(self, f, colspecs, delimiter, comment):
for colspec in self.colspecs:
if not (isinstance(colspec, (tuple, list)) and
- len(colspec) == 2 and
- isinstance(colspec[0], (int, np.integer)) and
- isinstance(colspec[1], (int, np.integer))):
+ len(colspec) == 2 and
+ isinstance(colspec[0], (int, np.integer)) and
+ isinstance(colspec[1], (int, np.integer))):
raise TypeError('Each column specification must be '
'2 element tuple or list of integers')
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index 97633873e7b40..915c1e9ae1574 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -1,5 +1,6 @@
from pandas.compat import cPickle as pkl, pickle_compat as pc, PY3
+
def to_pickle(obj, path):
"""
Pickle (serialize) object to input file path
@@ -19,8 +20,8 @@ def read_pickle(path):
Load pickled pandas object (or any other pickled object) from the specified
file path
- Warning: Loading pickled data received from untrusted sources can be unsafe.
- See: http://docs.python.org/2.7/library/pickle.html
+ Warning: Loading pickled data received from untrusted sources can be
+ unsafe. See: http://docs.python.org/2.7/library/pickle.html
Parameters
----------
@@ -38,10 +39,10 @@ def try_read(path, encoding=None):
# 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:
+ with open(path, 'rb') as fh:
return pc.load(fh, encoding=encoding, compat=True)
try:
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index db2028c70dc20..6ebc33afdd43d 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -74,10 +74,11 @@ def _ensure_term(where):
create the terms here with a frame_level=2 (we are 2 levels down)
"""
- # only consider list/tuple here as an ndarray is automaticaly a coordinate list
- if isinstance(where, (list,tuple)):
+ # only consider list/tuple here as an ndarray is automaticaly a coordinate
+ # list
+ if isinstance(where, (list, tuple)):
where = [w if not maybe_expression(w) else Term(w, scope_level=2)
- for w in where if w is not None ]
+ for w in where if w is not None]
elif maybe_expression(where):
where = Term(where, scope_level=2)
return where
@@ -124,11 +125,11 @@ class DuplicateWarning(Warning):
# formats
_FORMAT_MAP = {
- u('f') : 'fixed',
- u('fixed') : 'fixed',
- u('t') : 'table',
- u('table') : 'table',
- }
+ u('f'): 'fixed',
+ u('fixed'): 'fixed',
+ u('t'): 'table',
+ u('table'): 'table',
+}
format_deprecate_doc = """
the table keyword has been deprecated
@@ -169,7 +170,7 @@ class DuplicateWarning(Warning):
# table class map
_TABLE_MAP = {
u('generic_table'): 'GenericTable',
- u('appendable_series') : 'AppendableSeriesTable',
+ u('appendable_series'): 'AppendableSeriesTable',
u('appendable_multiseries'): 'AppendableMultiSeriesTable',
u('appendable_frame'): 'AppendableFrameTable',
u('appendable_multiframe'): 'AppendableMultiFrameTable',
@@ -202,8 +203,10 @@ class DuplicateWarning(Warning):
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]))
+ 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
@@ -271,7 +274,7 @@ def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None,
def read_hdf(path_or_buf, key, **kwargs):
- """ read from the store, closeit if we opened it
+ """ read from the store, close it if we opened it
Retrieve pandas object stored in file, optionally based on where
criteria
@@ -281,12 +284,16 @@ def read_hdf(path_or_buf, key, **kwargs):
path_or_buf : path (string), or buffer to read from
key : group identifier in the store
where : list of Term (or convertable) objects, optional
- start : optional, integer (defaults to None), row number to start selection
- stop : optional, integer (defaults to None), row number to stop selection
- columns : optional, a list of columns that if not None, will limit the return columns
+ start : optional, integer (defaults to None), row number to start
+ selection
+ stop : optional, integer (defaults to None), row number to stop
+ selection
+ columns : optional, a list of columns that if not None, will limit the
+ return columns
iterator : optional, boolean, return an iterator, default False
chunksize : optional, nrows to include in iteration, return an iterator
- auto_close : optional, boolean, should automatically close the store when finished, default is False
+ auto_close : optional, boolean, should automatically close the store
+ when finished, default is False
Returns
-------
@@ -442,8 +449,8 @@ def __unicode__(self):
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:
@@ -456,7 +463,8 @@ def __unicode__(self):
def keys(self):
"""
Return a (potentially unordered) list of the keys corresponding to the
- objects stored in the HDFStore. These are ABSOLUTE path-names (e.g. have the leading '/'
+ objects stored in the HDFStore. These are ABSOLUTE path-names (e.g.
+ have the leading '/'
"""
return [n._v_pathname for n in self.groups()]
@@ -482,15 +490,18 @@ def open(self, mode='a', **kwargs):
if self._mode != mode:
- # if we are chaning a write mode to read, ok
+ # if we are changing a write mode to read, ok
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))
+ raise PossibleDataLossError(
+ "Re-opening the file [{0}] with mode [{1}] "
+ "will delete the current file!"
+ .format(self._path, self._mode)
+ )
self._mode = mode
@@ -588,10 +599,12 @@ def select(self, key, where=None, start=None, stop=None, columns=None,
where : list of Term (or convertable) objects, optional
start : integer (defaults to None), row number to start selection
stop : integer (defaults to None), row number to stop selection
- columns : a list of columns that if not None, will limit the return columns
+ columns : a list of columns that if not None, will limit the return
+ columns
iterator : boolean, return an iterator, default False
chunksize : nrows to include in iteration, return an iterator
- auto_close : boolean, should automatically close the store when finished, default is False
+ auto_close : boolean, should automatically close the store when
+ finished, default is False
Returns
-------
@@ -636,16 +649,20 @@ def select_as_coordinates(
stop : integer (defaults to None), row number to stop selection
"""
where = _ensure_term(where)
- return self.get_storer(key).read_coordinates(where=where, start=start, stop=stop, **kwargs)
+ return self.get_storer(key).read_coordinates(where=where, start=start,
+ stop=stop, **kwargs)
def unique(self, key, column, **kwargs):
warnings.warn("unique(key,column) is deprecated\n"
- "use select_column(key,column).unique() instead",FutureWarning)
- 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):
"""
- return a single column from the table. This is generally only useful to select an indexable
+ return a single column from the table. This is generally only useful to
+ select an indexable
Parameters
----------
@@ -654,8 +671,10 @@ def select_column(self, key, column, **kwargs):
Exceptions
----------
- raises KeyError if the column is not found (or key is not a valid store)
- raises ValueError if the column can not be extracted indivually (it is part of a data block)
+ raises KeyError if the column is not found (or key is not a valid
+ store)
+ raises ValueError if the column can not be extracted individually (it
+ is part of a data block)
"""
return self.get_storer(key).read_column(column=column, **kwargs)
@@ -668,7 +687,8 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None,
Parameters
----------
keys : a list of the tables
- selector : the table to apply the where criteria (defaults to keys[0] if not supplied)
+ selector : the table to apply the where criteria (defaults to keys[0]
+ if not supplied)
columns : the columns I want back
start : integer (defaults to None), row number to start selection
stop : integer (defaults to None), row number to stop selection
@@ -677,7 +697,8 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None,
Exceptions
----------
- raise if any of the keys don't refer to tables or if they are not ALL THE SAME DIMENSIONS
+ raise if any of the keys don't refer to tables or if they are not ALL
+ THE SAME DIMENSIONS
"""
# default to single select
@@ -708,8 +729,9 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=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)
+ "object [%s] is not a table, and cannot be used in all "
+ "select as multiple" % t.pathname
+ )
if nrows is None:
nrows = t.nrows
@@ -735,12 +757,16 @@ def func(_start, _stop):
axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0]
# concat and return
- return concat(objs, axis=axis, verify_integrity=False).consolidate()
+ return concat(objs, axis=axis,
+ verify_integrity=False).consolidate()
if iterator or chunksize is not None:
- return TableIterator(self, func, nrows=nrows, start=start, stop=stop, chunksize=chunksize, auto_close=auto_close)
+ return TableIterator(self, func, nrows=nrows, start=start,
+ stop=stop, chunksize=chunksize,
+ auto_close=auto_close)
- return TableIterator(self, func, nrows=nrows, start=start, stop=stop, auto_close=auto_close).get_values()
+ return TableIterator(self, func, nrows=nrows, start=start, stop=stop,
+ auto_close=auto_close).get_values()
def put(self, key, value, format=None, append=False, **kwargs):
"""
@@ -754,11 +780,12 @@ def put(self, key, value, format=None, append=False, **kwargs):
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
+ 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
- This will force Table format, append the input data to the existing.
+ This will force Table format, append the input data to the
+ existing.
encoding : default None, provide an encoding for strings
"""
if format is None:
@@ -816,7 +843,8 @@ 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, format=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.
@@ -827,18 +855,20 @@ def append(self, key, value, format=None, append=True, columns=None, dropna=None
value : {Series, DataFrame, Panel, Panel4D}
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
+ 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
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'
+ 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
@@ -853,21 +883,24 @@ def append(self, key, value, format=None, append=True, columns=None, dropna=None
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)
+ self._write_to_group(key, value, append=append, dropna=dropna,
+ **kwargs)
- def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, dropna=True, **kwargs):
+ def append_to_multiple(self, d, value, selector, data_columns=None,
+ axes=None, dropna=True, **kwargs):
"""
Append to multiple tables
Parameters
----------
- d : a dict of table_name to table_columns, None is acceptable as the values of
- one node (this will get all the remaining columns)
+ d : a dict of table_name to table_columns, None is acceptable as the
+ values of one node (this will get all the remaining columns)
value : a pandas object
- 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
+ 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
@@ -879,15 +912,18 @@ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, d
if axes is not None:
raise TypeError("axes is currently not accepted as a parameter to"
" append_to_multiple; you can create the "
- "tables indepdently instead")
+ "tables independently instead")
if not isinstance(d, dict):
raise ValueError(
- "append_to_multiple must have a dictionary specified as the way to split the value")
+ "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")
+ "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]
@@ -899,7 +935,9 @@ def append_to_multiple(self, d, value, selector, data_columns=None, axes=None, d
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")
+ "append_to_multiple can only have one value in d that "
+ "is None"
+ )
remain_key = k
else:
remain_values.extend(v)
@@ -952,15 +990,23 @@ def create_table_index(self, key, **kwargs):
return
if not s.is_table:
- raise TypeError("cannot create table index on a Fixed format store")
+ raise TypeError(
+ "cannot create table index on a Fixed format store")
s.create_index(**kwargs)
def groups(self):
- """ return a list of all the top-level nodes (that are not themselves a pandas storage object) """
+ """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 """
@@ -981,16 +1027,16 @@ 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
----------
propindexes: restore indexes in copied file (defaults to True)
keys : list of keys to include in the copy (defaults to all)
- overwrite : overwrite (remove and replace) existing nodes in the new store (default is True)
+ overwrite : overwrite (remove and replace) existing nodes in the
+ new store (default is True)
mode, complib, complevel, fletcher32 same as in HDFStore.__init__
Returns
@@ -1022,8 +1068,11 @@ def copy(
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)
+ 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)
@@ -1039,10 +1088,10 @@ def _validate_format(self, format, kwargs):
kwargs = kwargs.copy()
# table arg
- table = kwargs.pop('table',None)
+ table = kwargs.pop('table', None)
if table is not None:
- warnings.warn(format_deprecate_doc,FutureWarning)
+ warnings.warn(format_deprecate_doc, FutureWarning)
if table:
format = 'table'
@@ -1053,17 +1102,21 @@ def _validate_format(self, format, kwargs):
try:
kwargs['format'] = _FORMAT_MAP[format.lower()]
except:
- raise TypeError("invalid HDFStore format specified [{0}]".format(format))
+ raise TypeError("invalid HDFStore format specified [{0}]"
+ .format(format))
return kwargs
- def _create_storer(self, group, format=None, value=None, append=False, **kwargs):
+ 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,format->%s,append->%s,kwargs->%s]" %
- (t, group, type(value), format, 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))
@@ -1073,12 +1126,14 @@ def error(t):
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")
+ "cannot create a storer if the object is not existing "
+ "nor a value are passed")
else:
try:
@@ -1104,14 +1159,14 @@ def error(t):
if value is not None:
if pt == u('series_table'):
- index = getattr(value,'index',None)
+ 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)
+ index = getattr(value, 'index', None)
if index is not None:
if index.nlevels == 1:
tt = u('appendable_frame')
@@ -1138,8 +1193,7 @@ def error(t):
except:
error('_TABLE_MAP')
- def _write_to_group(
- self, key, value, format, index=True, append=False,
+ def _write_to_group(self, key, value, format, index=True, append=False,
complib=None, encoding=None, **kwargs):
group = self.get_node(key)
@@ -1150,7 +1204,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 (format == 'table' or append):
+ if getattr(value, 'empty', None) and (format == 'table' or append):
return
if group is None:
@@ -1175,7 +1229,8 @@ def _write_to_group(
if append:
# 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 format == 'fixed' 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()
@@ -1183,7 +1238,9 @@ def _write_to_group(
s.set_object_info()
if not s.is_table and complib:
- raise ValueError('Compression not supported on Fixed format stores')
+ raise ValueError(
+ 'Compression not supported on Fixed format stores'
+ )
# write the object
s.write(obj=value, append=append, complib=complib, **kwargs)
@@ -1210,8 +1267,8 @@ class TableIterator(object):
start : the passed start value (default is None)
stop : the passed stop value (default is None)
chunksize : the passed chunking valeu (default is 50000)
- auto_close : boolean, automatically close the store at the end of iteration,
- default is False
+ auto_close : boolean, automatically close the store at the end of
+ iteration, default is False
kwargs : the passed kwargs
"""
@@ -1274,10 +1331,9 @@ class IndexCol(StringMixin):
is_data_indexable = True
_info_fields = ['freq', 'tz', 'index_name']
- 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):
+ 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
self.kind = kind
self.typ = typ
@@ -1335,7 +1391,8 @@ def __unicode__(self):
def __eq__(self, other):
""" compare 2 col items """
- return all([getattr(self, a, None) == getattr(other, a, None) for a in ['name', 'cname', 'axis', 'pos']])
+ return all([getattr(self, a, None) == getattr(other, a, None)
+ for a in ['name', 'cname', 'axis', 'pos']])
def __ne__(self, other):
return not self.__eq__(other)
@@ -1353,7 +1410,7 @@ def copy(self):
return new_self
def infer(self, table):
- """ infer this column from the table: create and return a new object """
+ """infer this column from the table: create and return a new object"""
new_self = self.copy()
new_self.set_table(table)
new_self.get_attr()
@@ -1420,7 +1477,8 @@ def __iter__(self):
def maybe_set_size(self, min_itemsize=None, **kwargs):
""" maybe set a string col itemsize:
- min_itemsize can be an interger or a dict with this columns name with an integer size """
+ min_itemsize can be an interger or a dict with this columns name
+ with an integer size """
if _ensure_decoded(self.kind) == u('string'):
if isinstance(min_itemsize, dict):
@@ -1446,10 +1504,11 @@ def validate_col(self, itemsize=None):
if itemsize is None:
itemsize = self.itemsize
if c.itemsize < itemsize:
- 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))
+ raise ValueError(
+ "Trying to store a string with len [%s] in [%s] "
+ "column but\nthis column has a limit of [%s]!\n"
+ "Consider using min_itemsize to preset the sizes on "
+ "these columns" % (itemsize, self.cname, c.itemsize))
return c.itemsize
return None
@@ -1484,9 +1543,10 @@ def update_info(self, info):
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))
+ raise ValueError(
+ "invalid info for [%s] for [%s], existing_value [%s] "
+ "conflicts with new value [%s]"
+ % (self.name, key, existing_value, value))
else:
if value is not None or existing_value is not None:
idx[key] = value
@@ -1537,7 +1597,8 @@ class DataCol(IndexCol):
----------
data : the actual data
- cname : the column name in the table to hold the data (typeically values)
+ cname : the column name in the table to hold the data (typically
+ values)
"""
is_an_indexable = False
is_data_indexable = False
@@ -1574,11 +1635,14 @@ def __init__(self, values=None, kind=None, typ=None,
self.set_data(data)
def __unicode__(self):
- return "name->%s,cname->%s,dtype->%s,shape->%s" % (self.name, self.cname, self.dtype, self.shape)
+ return "name->%s,cname->%s,dtype->%s,shape->%s" % (
+ self.name, self.cname, self.dtype, self.shape
+ )
def __eq__(self, other):
""" compare 2 col items """
- return all([getattr(self, a, None) == getattr(other, a, None) for a in ['name', 'cname', 'dtype', 'pos']])
+ return all([getattr(self, a, None) == getattr(other, a, None)
+ for a in ['name', 'cname', 'dtype', 'pos']])
def set_data(self, data, dtype=None):
self.data = data
@@ -1644,7 +1708,9 @@ def set_atom(self, block, existing_col, min_itemsize,
# if this block has more than one timezone, raise
if len(set([r.tzinfo for r in rvalues])) != 1:
raise TypeError(
- "too many timezones in this block, create separate data columns")
+ "too many timezones in this block, create separate "
+ "data columns"
+ )
# convert this column to datetime64[ns] utc, and save the tz
index = DatetimeIndex(rvalues)
@@ -1707,9 +1773,11 @@ def set_atom_string(
col = block.get(item)
inferred_type = lib.infer_dtype(col.ravel())
if inferred_type != 'string':
- raise TypeError("Cannot serialize the column [%s] because\n"
- "its data contents are [%s] object dtype" %
- (item, inferred_type))
+ raise TypeError(
+ "Cannot serialize the column [%s] because\n"
+ "its data contents are [%s] object dtype"
+ % (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()))
@@ -1781,7 +1849,7 @@ def cvalues(self):
return self.data
def validate_attr(self, append):
- """ validate that we have the same order as the existing & same dtype """
+ """validate that we have the same order as the existing & same dtype"""
if append:
existing_fields = getattr(self.attrs, self.kind_attr, None)
if (existing_fields is not None and
@@ -1792,11 +1860,13 @@ def validate_attr(self, append):
existing_dtype = getattr(self.attrs, self.dtype_attr, None)
if (existing_dtype is not None and
existing_dtype != self.dtype):
- raise ValueError("appended items dtype do not match existing items dtype"
- " in table!")
+ raise ValueError("appended items dtype do not match existing "
+ "items dtype in table!")
def convert(self, values, nan_rep, encoding):
- """ set the data from this selection (and convert to the correct dtype if we can) """
+ """set the data from this selection (and convert to the correct dtype
+ if we can)
+ """
try:
values = values[self.cname]
except:
@@ -1829,9 +1899,10 @@ def convert(self, values, nan_rep, encoding):
try:
self.data = np.array(
[date.fromordinal(v) for v in self.data], dtype=object)
- except (ValueError):
+ except ValueError:
self.data = np.array(
- [date.fromtimestamp(v) for v in self.data], dtype=object)
+ [date.fromtimestamp(v) for v in self.data],
+ dtype=object)
elif dtype == u('datetime'):
self.data = np.array(
[datetime.fromtimestamp(v) for v in self.data],
@@ -1914,7 +1985,8 @@ def __init__(self, parent, group, encoding=None, **kwargs):
@property
def is_old_version(self):
- return self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1
+ return (self.version[0] <= 0 and self.version[1] <= 10 and
+ self.version[2] < 1)
def set_version(self):
""" compute and set our version """
@@ -1929,7 +2001,8 @@ def set_version(self):
@property
def pandas_type(self):
- return _ensure_decoded(getattr(self.group._v_attrs, 'pandas_type', None))
+ return _ensure_decoded(getattr(self.group._v_attrs,
+ 'pandas_type', None))
@property
def format_type(self):
@@ -2041,7 +2114,9 @@ def write(self, **kwargs):
"cannot write on an abstract storer: sublcasses should implement")
def delete(self, where=None, **kwargs):
- """ support fully deleting the node in its entirety (only) - where specification must be None """
+ """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)
return None
@@ -2052,8 +2127,7 @@ def delete(self, where=None, **kwargs):
class GenericFixed(Fixed):
""" a generified fixed version """
- _index_type_map = {DatetimeIndex: 'datetime',
- PeriodIndex: 'period'}
+ _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'}
_reverse_index_map = dict([(v, k)
for k, v in compat.iteritems(_index_type_map)])
attributes = []
@@ -2078,11 +2152,13 @@ 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 Fixed format store."
- "this store must be selected in its entirety")
+ 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 Fixed format store."
- "this store must be selected in its entirety")
+ raise TypeError("cannot pass a where specification when reading "
+ "from a Fixed format store. this store must be "
+ "selected in its entirety")
@property
def is_exists(self):
@@ -2246,9 +2322,10 @@ 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'))
+ 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
@@ -2268,8 +2345,8 @@ def read_index_node(self, node):
if kind in (u('date'), u('datetime')):
index = factory(
- _unconvert_index(data, kind, encoding=self.encoding), dtype=object,
- **kwargs)
+ _unconvert_index(data, kind, encoding=self.encoding),
+ dtype=object, **kwargs)
else:
index = factory(
_unconvert_index(data, kind, encoding=self.encoding), **kwargs)
@@ -2351,10 +2428,12 @@ def write_array(self, key, value, items=None):
else:
if value.dtype.type == np.datetime64:
self._handle.createArray(self.group, key, value.view('i8'))
- getattr(self.group, key)._v_attrs.value_type = 'datetime64'
+ 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'
+ getattr(
+ self.group, key)._v_attrs.value_type = 'timedelta64'
else:
self._handle.createArray(self.group, key, value)
@@ -2423,7 +2502,8 @@ def read(self, **kwargs):
sp_values = self.read_array('sp_values')
sp_index = self.read_index('sp_index')
return SparseSeries(sp_values, index=index, sparse_index=sp_index,
- kind=self.kind or u('block'), fill_value=self.fill_value,
+ kind=self.kind or u('block'),
+ fill_value=self.fill_value,
name=self.name)
def write(self, obj, **kwargs):
@@ -2596,14 +2676,20 @@ class Table(Fixed):
Attrs in Table Node
-------------------
- These are attributes that are store in the main table node, they are necessary
- to recreate these tables when read back in.
-
- index_axes : a list of tuples of the (original indexing axis and index column)
- non_index_axes: a list of tuples of the (original index axis and columns on a non-indexing axis)
- values_axes : a list of the columns which comprise the data of this table
- data_columns : a list of the columns that we are allowing indexing (these become single columns in values_axes), or True to force all columns
- nan_rep : the string to use for nan representations for string objects
+ These are attributes that are store in the main table node, they are
+ necessary to recreate these tables when read back in.
+
+ index_axes : a list of tuples of the (original indexing axis and
+ index column)
+ non_index_axes: a list of tuples of the (original index axis and
+ columns on a non-indexing axis)
+ values_axes : a list of the columns which comprise the data of this
+ table
+ data_columns : a list of the columns that we are allowing indexing
+ (these become single columns in values_axes), or True to force all
+ columns
+ nan_rep : the string to use for nan representations for string
+ objects
levels : the names of levels
"""
@@ -2641,14 +2727,10 @@ def __unicode__(self):
if self.is_old_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]),
- dc)
+ 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]), dc
+ )
def __getitem__(self, c):
""" return the axis for c """
@@ -2676,25 +2758,30 @@ def validate(self, other):
oax = ov[i]
if sax != oax:
raise ValueError(
- "invalid combinate of [%s] on appending data [%s] vs current table [%s]" %
- (c, sax, oax))
+ "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))
+ "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)
+ """the levels attribute is 1 or a list in the case of a multi-index"""
+ return isinstance(self.levels, list)
def validate_multiindex(self, obj):
- """ validate that we can store the multi-index; reset and return the new object """
- levels = [ l if l is not None else "level_{0}".format(i) for i, l in enumerate(obj.index.names) ]
+ """validate that we can store the multi-index; reset and return the
+ new object
+ """
+ levels = [l if l is not None else "level_{0}".format(i)
+ for i, l in enumerate(obj.index.names)]
try:
return obj.reset_index(), levels
- except (ValueError):
- raise ValueError("duplicate names/columns in the multi-index when storing as a table")
+ except ValueError:
+ raise ValueError("duplicate names/columns in the multi-index when "
+ "storing as a table")
@property
def nrows_expected(self):
@@ -2738,17 +2825,21 @@ def is_transposed(self):
@property
def data_orientation(self):
- """ return a tuple of my permutated axes, non_indexable at the front """
- return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes], [int(a.axis) for a in self.index_axes]))
+ """return a tuple of my permutated axes, non_indexable at the front"""
+ return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes],
+ [int(a.axis) for a in self.index_axes]))
def queryables(self):
""" return a dict of the kinds allowable columns for this object """
# compute the values_axes queryables
- return dict([(a.cname, a.kind) for a in self.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)]
- )
+ return dict(
+ [(a.cname, a.kind) for a in self.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)]
+ )
def index_cols(self):
""" return a list of my index cols """
@@ -2788,22 +2879,26 @@ def get_attrs(self):
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):
""" 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:
+ 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])
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 """
+ """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):
@@ -2817,8 +2912,8 @@ def validate_min_itemsize(self, min_itemsize):
continue
if k not in q:
raise ValueError(
- "min_itemsize has the key [%s] which is not an axis or data_column" %
- k)
+ "min_itemsize has the key [%s] which is not an axis or "
+ "data_column" % k)
@property
def indexables(self):
@@ -2828,8 +2923,10 @@ 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)
@@ -2839,7 +2936,8 @@ def f(i, c):
klass = DataCol
if c in dc:
klass = DataIndexableCol
- return klass.create_for_block(i=i, name=c, pos=base_pos + i, version=self.version)
+ return klass.create_for_block(i=i, name=c, pos=base_pos + i,
+ version=self.version)
self._indexables.extend(
[f(i, c) for i, c in enumerate(self.attrs.values_cols)])
@@ -2854,7 +2952,8 @@ def create_index(self, columns=None, optlevel=None, kind=None):
Paramaters
----------
- columns : False (don't create an index), True (create all columns index), None or list_like (the indexers to index)
+ columns : False (don't create an index), True (create all columns
+ index), None or list_like (the indexers to index)
optlevel: optimization level (defaults to 6)
kind : kind of index (defaults to 'medium')
@@ -2907,7 +3006,9 @@ def create_index(self, columns=None, optlevel=None, kind=None):
v.createIndex(**kw)
def read_axes(self, where, **kwargs):
- """ create and return the axes sniffed from the table: return boolean for success """
+ """create and return the axes sniffed from the table: return boolean
+ for success
+ """
# validate the version
self.validate_version(where)
@@ -2932,15 +3033,18 @@ def get_object(self, obj):
return obj
def validate_data_columns(self, data_columns, min_itemsize):
- """ take the input data_columns and min_itemize and create a data_columns spec """
+ """take the input data_columns and min_itemize and create a data
+ columns spec
+ """
if not len(self.non_index_axes):
return []
axis, axis_labels = self.non_index_axes[0]
- info = self.info.get(axis,dict())
+ 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))
+ 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
@@ -2953,8 +3057,10 @@ def validate_data_columns(self, data_columns, min_itemsize):
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]
@@ -2962,17 +3068,21 @@ def validate_data_columns(self, data_columns, min_itemsize):
def create_axes(self, axes, obj, validate=True, nan_rep=None,
data_columns=None, min_itemsize=None, **kwargs):
""" create and return the axes
- leagcy tables create an indexable column, indexable index, non-indexable fields
+ leagcy tables create an indexable column, indexable index,
+ non-indexable fields
Parameters:
-----------
- axes: a list of the axes in order to create (names or numbers of the axes)
+ axes: a list of the axes in order to create (names or numbers of
+ the axes)
obj : the object to create axes on
- validate: validate the obj against an existiing object already written
+ validate: validate the obj against an existing object already
+ written
min_itemsize: a dict of the min size for a column in bytes
nan_rep : a values to use for string column nan_rep
encoding : the encoding for string values
- data_columns : a list of columns that we want to create separate to allow indexing (or True will force all colummns)
+ data_columns : a list of columns that we want to create separate to
+ allow indexing (or True will force all columns)
"""
@@ -2981,8 +3091,9 @@ def create_axes(self, axes, obj, validate=True, nan_rep=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]
@@ -3021,7 +3132,8 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None,
if i in axes:
name = obj._AXIS_NAMES[i]
index_axes_map[i] = _convert_index(
- a, self.encoding, self.format_type).set_name(name).set_axis(i)
+ a, self.encoding, self.format_type
+ ).set_name(name).set_axis(i)
else:
# we might be able to change the axes on the appending data if
@@ -3037,16 +3149,17 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None,
append_axis = exist_axis
# the non_index_axes info
- info = _get_info(self.info,i)
+ 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)
- self.index_axes = [index_axes_map[a].set_pos(
- j).update_info(self.info) for j,
- a in enumerate(axes)]
+ 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)
# check for column conflicts
@@ -3066,11 +3179,13 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None,
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
+ blocks = block_obj.reindex_axis(
+ Index(axis_labels) - Index(data_columns),
+ axis=axis
+ )._data.blocks
for c in data_columns:
- blocks.extend(block_obj.reindex_axis(
- [c], axis=axis)._data.blocks)
+ blocks.extend(
+ block_obj.reindex_axis([c], axis=axis)._data.blocks)
# reorder the blocks in the same order as the existing_table if we can
if existing_table is not None:
@@ -3097,7 +3212,8 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None,
name = None
# we have a data_column
- if data_columns and len(b.items) == 1 and b.items[0] in data_columns:
+ if (data_columns and len(b.items) == 1 and
+ b.items[0] in data_columns):
klass = DataIndexableCol
name = b.items[0]
self.data_columns.append(name)
@@ -3108,8 +3224,9 @@ def create_axes(self, axes, obj, validate=True, nan_rep=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
@@ -3128,9 +3245,12 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None,
self.values_axes.append(col)
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)))
+ except Exception as 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
@@ -3160,7 +3280,8 @@ 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)
+ 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:
@@ -3173,7 +3294,8 @@ def process_filter(field, filt):
if isinstance(obj, DataFrame):
axis_number = 1 - axis_number
takers = op(values, filt)
- return obj.ix._getitem_axis(takers, axis=axis_number)
+ return obj.ix._getitem_axis(takers,
+ axis=axis_number)
raise ValueError(
"cannot find the field [%s] for filtering!" % field)
@@ -3182,8 +3304,8 @@ def process_filter(field, filt):
return obj
- def create_description(
- self, complib=None, complevel=None, fletcher32=False, expectedrows=None):
+ def create_description(self, complib=None, complevel=None,
+ fletcher32=False, expectedrows=None):
""" create the description of the table from the axes & values """
# expected rows estimate
@@ -3197,9 +3319,9 @@ def create_description(
if complib:
if complevel is None:
complevel = self._complevel or 9
- filters = _tables().Filters(complevel=complevel,
- complib=complib,
- fletcher32=fletcher32 or self._fletcher32)
+ filters = _tables().Filters(
+ complevel=complevel, complib=complib,
+ fletcher32=fletcher32 or self._fletcher32)
d['filters'] = filters
elif self._filters is not None:
d['filters'] = self._filters
@@ -3207,7 +3329,9 @@ def create_description(
return d
def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
- """ select coordinates (row numbers) from a table; return the coordinates object """
+ """select coordinates (row numbers) from a table; return the
+ coordinates object
+ """
# validate the version
self.validate_version(where)
@@ -3222,7 +3346,9 @@ def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
return Index(self.selection.select_coords())
def read_column(self, column, where=None, **kwargs):
- """ return a single column from the table, generally only indexables are interesting """
+ """return a single column from the table, generally only indexables
+ are interesting
+ """
# validate the version
self.validate_version()
@@ -3241,13 +3367,14 @@ def read_column(self, column, where=None, **kwargs):
if not a.is_data_indexable:
raise ValueError(
- "column [%s] can not be extracted individually; it is not data indexable" %
- column)
+ "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)
a.set_info(self.info)
- return Series(a.convert(c[:], nan_rep=self.nan_rep, encoding=self.encoding).take_data())
+ return Series(a.convert(c[:], nan_rep=self.nan_rep,
+ encoding=self.encoding).take_data())
raise KeyError("column [%s] not found in the table" % column)
@@ -3268,7 +3395,8 @@ def read(self, **kwargs):
def write(self, **kwargs):
""" write in a format that we can search later on (but cannot append
to): write out the indicies and the values using _write_array
- (e.g. a CArray) create an indexing table so that we can search"""
+ (e.g. a CArray) create an indexing table so that we can search
+ """
raise NotImplementedError("WORKTable needs to implement write")
@@ -3279,11 +3407,12 @@ class LegacyTable(Table):
append (but doesn't require them), and stores the data in a format
that can be easily searched
- """
- _indexables = [IndexCol(name='index', axis=1, pos=0),
- IndexCol(name='column', axis=2,
- pos=1, index_kind='columns_kind'),
- DataCol(name='fields', cname='values', kind_attr='fields', pos=2)]
+ """
+ _indexables = [
+ IndexCol(name='index', axis=1, pos=0),
+ IndexCol(name='column', axis=2, pos=1, index_kind='columns_kind'),
+ DataCol(name='fields', cname='values', kind_attr='fields', pos=2)
+ ]
table_type = u('legacy')
ndim = 3
@@ -3291,7 +3420,9 @@ def write(self, **kwargs):
raise TypeError("write operations are not allowed on legacy tables!")
def read(self, where=None, columns=None, **kwargs):
- """ we have n indexable columns, with an arbitrary number of data axes """
+ """we have n indexable columns, with an arbitrary number of data
+ axes
+ """
if not self.read_axes(where=where, **kwargs):
return None
@@ -3395,8 +3526,8 @@ class AppendableTable(LegacyTable):
table_type = u('appendable')
def write(self, obj, axes=None, append=False, complib=None,
- complevel=None, fletcher32=None, min_itemsize=None, chunksize=None,
- expectedrows=None, dropna=True, **kwargs):
+ complevel=None, fletcher32=None, min_itemsize=None,
+ chunksize=None, expectedrows=None, dropna=True, **kwargs):
if not append and self.is_exists:
self._handle.removeNode(self.group, 'table')
@@ -3485,7 +3616,7 @@ def write_data(self, chunksize, dropna=True):
# 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]
+ for v in values]
bvalues = []
for i, v in enumerate(values):
new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
@@ -3617,7 +3748,8 @@ 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()
+ 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:
@@ -3630,7 +3762,7 @@ def read(self, where=None, columns=None, **kwargs):
cols = Index(a.values)
names = info.get('names')
if names is not None:
- cols.set_names(names,inplace=True)
+ cols.set_names(names, inplace=True)
if self.is_transposed:
values = a.cvalues
@@ -3679,9 +3811,10 @@ 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 = DataFrame({name: obj}, index=obj.index)
obj.columns = [name]
- return super(AppendableSeriesTable, self).write(obj=obj, data_columns=obj.columns, **kwargs)
+ return super(AppendableSeriesTable, self).write(
+ obj=obj, data_columns=obj.columns, **kwargs)
def read(self, columns=None, **kwargs):
@@ -3694,13 +3827,14 @@ def read(self, columns=None, **kwargs):
if is_multi_index:
s.set_index(self.levels, inplace=True)
- s = s.iloc[:,0]
+ 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')
@@ -3715,8 +3849,8 @@ def write(self, obj, **kwargs):
obj.columns = cols
return super(AppendableMultiSeriesTable, self).write(obj=obj, **kwargs)
-class GenericTable(AppendableFrameTable):
+class GenericTable(AppendableFrameTable):
""" a table that read/writes the generic pytables table format """
pandas_kind = u('frame_table')
table_type = u('generic_table')
@@ -3756,7 +3890,7 @@ def indexables(self):
for i, n in enumerate(d._v_names):
dc = GenericDataIndexableCol(
- name=n, pos=i, values=[n], version = self.version)
+ name=n, pos=i, values=[n], version=self.version)
self._indexables.append(dc)
return self._indexables
@@ -3786,7 +3920,8 @@ def write(self, obj, data_columns=None, **kwargs):
for n in self.levels:
if n not in data_columns:
data_columns.insert(0, n)
- return super(AppendableMultiFrameTable, self).write(obj=obj, data_columns=data_columns, **kwargs)
+ return super(AppendableMultiFrameTable, self).write(
+ obj=obj, data_columns=data_columns, **kwargs)
def read(self, columns=None, **kwargs):
if columns is not None:
@@ -3798,7 +3933,9 @@ def read(self, columns=None, **kwargs):
df = df.set_index(self.levels)
# remove names for 'level_%d'
- df.index = df.index.set_names([ None if self._re_levels.search(l) else l for l in df.index.names ])
+ df.index = df.index.set_names([
+ None if self._re_levels.search(l) else l for l in df.index.names
+ ])
return df
@@ -3844,11 +3981,12 @@ def _reindex_axis(obj, axis, labels, other=None):
if other is not None:
labels = labels & _ensure_index(other.unique())
if not labels.equals(ax):
- slicer = [ slice(None, None) ] * obj.ndim
+ slicer = [slice(None, None)] * obj.ndim
slicer[axis] = labels
obj = obj.loc[tuple(slicer)]
return obj
+
def _get_info(info, name):
""" get/create the info for this name """
try:
@@ -3857,19 +3995,21 @@ def _get_info(info, name):
idx = info[name] = dict()
return idx
+
def _convert_index(index, encoding=None, format_type=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),
- index_name=index_name)
+ index_name=index_name)
if isinstance(index, MultiIndex):
raise TypeError('MultiIndex not supported here!')
@@ -3881,7 +4021,8 @@ def _convert_index(index, encoding=None, format_type=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()) +
@@ -3901,15 +4042,18 @@ def _convert_index(index, encoding=None, format_type=None):
converted = _convert_string_array(values, encoding)
itemsize = converted.dtype.itemsize
return IndexCol(
- converted, 'string', _tables().StringCol(itemsize), itemsize=itemsize,
- index_name=index_name)
+ converted, 'string', _tables().StringCol(itemsize),
+ itemsize=itemsize, index_name=index_name
+ )
elif inferred_type == 'unicode':
if format_type == 'fixed':
atom = _tables().ObjectAtom()
return IndexCol(np.asarray(values, dtype='O'), 'object', atom,
index_name=index_name)
raise TypeError(
- "[unicode] is not supported as a in index type for [{0}] formats".format(format_type))
+ "[unicode] is not supported as a in index type for [{0}] formats"
+ .format(format_type)
+ )
elif inferred_type == 'integer':
# take a guess for now, hope the values fit
@@ -4027,6 +4171,7 @@ def _need_convert(kind):
return True
return False
+
class Selection(object):
"""
@@ -4065,9 +4210,14 @@ def __init__(self, table, where=None, start=None, stop=None, **kwargs):
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()):
+ 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")
+ "where must have index locations >= start and "
+ "< stop"
+ )
self.coordinates = where
except:
@@ -4089,21 +4239,27 @@ def generate(self, where):
q = self.table.queryables()
try:
return Expr(where, queryables=q, encoding=self.table.encoding)
- except (NameError) as detail:
-
- # raise a nice message, suggesting that the user should use data_columns
- raise ValueError("The passed where expression: {0}\n"
- " contains an invalid variable reference\n"
- " all of the variable refrences must be a reference to\n"
- " an axis (e.g. 'index' or 'columns'), or a data_column\n"
- " The currently defined references are: {1}\n".format(where,','.join(q.keys())))
+ except NameError as detail:
+ # raise a nice message, suggesting that the user should use
+ # data_columns
+ raise ValueError(
+ "The passed where expression: {0}\n"
+ " contains an invalid variable reference\n"
+ " all of the variable refrences must be a "
+ "reference to\n"
+ " an axis (e.g. 'index' or 'columns'), or a "
+ "data_column\n"
+ " The currently defined references are: {1}\n"
+ .format(where, ','.join(q.keys()))
+ )
def select(self):
"""
generate the selection
"""
if self.condition is not None:
- return self.table.table.readWhere(self.condition.format(), start=self.start, stop=self.stop)
+ return self.table.table.readWhere(self.condition.format(),
+ start=self.start, stop=self.stop)
elif self.coordinates is not None:
return self.table.table.readCoordinates(self.coordinates)
return self.table.table.read(start=self.start, stop=self.stop)
@@ -4115,7 +4271,9 @@ def select_coords(self):
if self.condition is None:
return np.arange(self.table.nrows)
- return self.table.table.getWhereList(self.condition.format(), start=self.start, stop=self.stop, sort=True)
+ return self.table.table.getWhereList(self.condition.format(),
+ start=self.start, stop=self.stop,
+ sort=True)
# utilities ###
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 1d0d1d17ec631..8c172db162cd6 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -2,9 +2,9 @@
Module contains tools for processing Stata files into DataFrames
The StataReader below was originally written by Joe Presbrey as part of PyDTA.
-It has been extended and improved by Skipper Seabold from the Statsmodels project
-who also developed the StataWriter and was finally added to pandas in an once again
-improved version.
+It has been extended and improved by Skipper Seabold from the Statsmodels
+project who also developed the StataWriter and was finally added to pandas in
+an once again improved version.
You can find more information on http://presbrey.mit.edu/PyDTA and
http://statsmodels.sourceforge.net/devel/
@@ -25,7 +25,8 @@
from pandas.io.common import get_filepath_or_buffer
-def read_stata(filepath_or_buffer, convert_dates=True, convert_categoricals=True, encoding=None, index=None):
+def read_stata(filepath_or_buffer, convert_dates=True,
+ convert_categoricals=True, encoding=None, index=None):
"""
Read Stata file into DataFrame
@@ -63,7 +64,8 @@ def _stata_elapsed_date_to_datetime(date, fmt):
Examples
--------
- >>> _stata_elapsed_date_to_datetime(52, "%tw") datetime.datetime(1961, 1, 1, 0, 0)
+ >>> _stata_elapsed_date_to_datetime(52, "%tw")
+ datetime.datetime(1961, 1, 1, 0, 0)
Notes
-----
@@ -199,8 +201,11 @@ def __init__(self, offset, value):
'.' or ('.' + chr(value - offset + 96))
else:
self._str = '.'
- string = property(lambda self: self._str, doc="The Stata representation of the missing value: '.', '.a'..'.z'")
- value = property(lambda self: self._value, doc='The binary representation of the missing value.')
+ string = property(lambda self: self._str,
+ doc="The Stata representation of the missing value: "
+ "'.', '.a'..'.z'")
+ value = property(lambda self: self._value,
+ doc='The binary representation of the missing value.')
def __unicode__(self):
return self.string
@@ -292,19 +297,22 @@ def _decode_bytes(self, str, errors=None):
class StataReader(StataParser):
"""
- Class for working with a Stata dataset. There are two possibilities for usage:
+ Class for working with a Stata dataset. There are two possibilities for
+ usage:
* The from_dta() method on the DataFrame class.
- This will return a DataFrame with the Stata dataset. Note that when using the
- from_dta() method, you will not have access to meta-information like variable
- labels or the data label.
-
- * Work with this object directly. Upon instantiation, the header of the Stata data
- file is read, giving you access to attributes like variable_labels(), data_label(),
- nobs(), ... A DataFrame with the data is returned by the read() method; this will
- also fill up the value_labels. Note that calling the value_labels() method will
- result in an error if the read() method has not been called yet. This is because
- the value labels are stored at the end of a Stata dataset, after the data.
+ This will return a DataFrame with the Stata dataset. Note that when
+ using the from_dta() method, you will not have access to
+ meta-information like variable labels or the data label.
+
+ * Work with this object directly. Upon instantiation, the header of the
+ Stata data file is read, giving you access to attributes like
+ variable_labels(), data_label(), nobs(), ... A DataFrame with the data
+ is returned by the read() method; this will also fill up the
+ value_labels. Note that calling the value_labels() method will result in
+ an error if the read() method has not been called yet. This is because
+ the value labels are stored at the end of a Stata dataset, after the
+ data.
Parameters
----------
@@ -323,7 +331,9 @@ 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=self._default_encoding)
+ 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')
@@ -334,17 +344,22 @@ def __init__(self, path_or_buf, encoding='cp1252'):
def _read_header(self):
first_char = self.path_or_buf.read(1)
- if struct.unpack('c', first_char)[0] == b'<': # format 117 or higher (XML like)
+ 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)")
+ 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.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.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)
@@ -354,20 +369,31 @@ def _read_header(self):
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
+ 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.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)]
+ 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
@@ -378,7 +404,8 @@ def _read_header(self):
self.typlist[i] = self.TYPE_MAP_XML[typ]
i += 1
except:
- raise ValueError("cannot convert stata types [{0}]".format(','.join(typlist)))
+ raise ValueError("cannot convert stata types [{0}]"
+ .format(','.join(typlist)))
self.dtyplist = [None]*self.nvar
try:
i = 0
@@ -389,33 +416,45 @@ def _read_header(self):
self.dtyplist[i] = self.DTYPE_MAP_XML[typ]
i += 1
except:
- raise ValueError("cannot convert stata dtypes [{0}]".format(','.join(typlist)))
+ raise ValueError("cannot convert stata dtypes [{0}]"
+ .format(','.join(typlist)))
self.path_or_buf.seek(seek_varnames)
- self.varlist = [self._null_terminate(self.path_or_buf.read(33)) for i in range(self.nvar)]
+ self.varlist = [self._null_terminate(self.path_or_buf.read(33))
+ for i in range(self.nvar)]
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.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)]
+ self.fmtlist = [self._null_terminate(self.path_or_buf.read(49))
+ for i in range(self.nvar)]
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)]
+ self.lbllist = [self._null_terminate(self.path_or_buf.read(33))
+ for i in range(self.nvar)]
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)]
+ self.vlblist = [self._null_terminate(self.path_or_buf.read(81))
+ for i in range(self.nvar)]
else:
# 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)")
+ 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]
+ 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:
@@ -425,51 +464,73 @@ def _read_header(self):
# descriptors
if self.format_version > 108:
- typlist = [ord(self.path_or_buf.read(1)) for i in range(self.nvar)]
+ 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)]
+ 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)))
+ 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)))
+ 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)]
+ 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]
+ 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)]
+ 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)]
+ 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)]
+ 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)]
+ 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)]
+ 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)]
+ 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)]
+ 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.
+ # 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]
+ 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]
+ 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]
+ 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)
@@ -477,13 +538,15 @@ def _read_header(self):
# 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.has_string_data = len([x for x in self.typlist
+ if type(x) is int]) > 0
"""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)
+ return (type(fmt) is int and fmt
+ or struct.calcsize(self.byteorder + fmt))
def _col_size(self, k=None):
if k is None:
@@ -503,7 +566,8 @@ def _unpack(self, fmt, byt):
return d
def _null_terminate(self, s):
- if compat.PY3 or self._encoding is not None: # 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)]
@@ -523,14 +587,24 @@ def _next(self):
data = [None] * self.nvar
for i in range(len(data)):
if type(typlist[i]) is int:
- data[i] = self._null_terminate(self.path_or_buf.read(typlist[i]))
+ data[i] = self._null_terminate(
+ self.path_or_buf.read(typlist[i])
+ )
else:
- data[i] = self._unpack(typlist[i], self.path_or_buf.read(self._col_size(i)))
+ data[i] = self._unpack(
+ typlist[i], self.path_or_buf.read(self._col_size(i))
+ )
return data
else:
- return list(map(lambda i: self._unpack(typlist[i],
- self.path_or_buf.read(self._col_size(i))),
- range(self.nvar)))
+ return list(
+ map(
+ lambda i: self._unpack(typlist[i],
+ self.path_or_buf.read(
+ self._col_size(i)
+ )),
+ range(self.nvar)
+ )
+ )
def _dataset(self):
"""
@@ -562,14 +636,17 @@ def _read_value_labels(self):
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.")
+ 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()
if self.format_version <= 108:
- return # Value labels are not supported in version 108 and earlier.
+ # Value labels are not supported in version 108 and earlier.
+ return
while True:
if self.format_version >= 117:
@@ -582,18 +659,24 @@ def _read_value_labels(self):
labname = self._null_terminate(self.path_or_buf.read(33))
self.path_or_buf.read(3) # padding
- n = struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0]
- txtlen = struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0]
+ n = struct.unpack(self.byteorder + 'I',
+ self.path_or_buf.read(4))[0]
+ txtlen = struct.unpack(self.byteorder + 'I',
+ self.path_or_buf.read(4))[0]
off = []
for i in range(n):
- off.append(struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0])
+ off.append(struct.unpack(self.byteorder + 'I',
+ self.path_or_buf.read(4))[0])
val = []
for i in range(n):
- val.append(struct.unpack(self.byteorder + 'I', self.path_or_buf.read(4))[0])
+ val.append(struct.unpack(self.byteorder + 'I',
+ self.path_or_buf.read(4))[0])
txt = self.path_or_buf.read(txtlen)
self.value_label_dict[labname] = dict()
for i in range(n):
- self.value_label_dict[labname][val[i]] = self._null_terminate(txt[off[i]:])
+ 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>
@@ -606,9 +689,11 @@ def _read_strls(self):
if self.path_or_buf.read(3) != b'GSO':
break
- v_o = struct.unpack(self.byteorder + 'L', self.path_or_buf.read(8))[0]
+ 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]
+ 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
@@ -621,7 +706,8 @@ def data(self, convert_dates=True, convert_categoricals=True, index=None):
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
+ Read value labels and convert columns to Categorical/Factor
+ variables
index : identifier of index column
identifier of column that should be used as index of the DataFrame
@@ -659,21 +745,28 @@ def data(self, convert_dates=True, convert_categoricals=True, index=None):
if self.dtyplist[i] is not None:
col = data.columns[i]
if data[col].dtype is not np.dtype(object):
- data[col] = Series(data[col], data[col].index, self.dtyplist[i])
+ data[col] = Series(data[col], data[col].index,
+ self.dtyplist[i])
if convert_dates:
- cols = np.where(lmap(lambda x: x in _date_formats, self.fmtlist))[0]
+ cols = np.where(lmap(lambda x: x in _date_formats,
+ self.fmtlist))[0]
for i in cols:
col = data.columns[i]
- data[col] = data[col].apply(_stata_elapsed_date_to_datetime, args=(self.fmtlist[i],))
+ data[col] = data[col].apply(_stata_elapsed_date_to_datetime,
+ args=(self.fmtlist[i],))
if convert_categoricals:
- cols = np.where(lmap(lambda x: x in compat.iterkeys(self.value_label_dict), self.lbllist))[0]
+ cols = np.where(
+ lmap(lambda x: x in compat.iterkeys(self.value_label_dict),
+ self.lbllist)
+ )[0]
for i in cols:
col = data.columns[i]
labeled_data = np.copy(data[col])
labeled_data = labeled_data.astype(object)
- for k, v in compat.iteritems(self.value_label_dict[self.lbllist[i]]):
+ for k, v in compat.iteritems(
+ self.value_label_dict[self.lbllist[i]]):
labeled_data[(data[col] == k).values] = v
data[col] = Categorical.from_array(labeled_data)
@@ -684,11 +777,15 @@ def data_label(self):
return self.data_label
def variable_labels(self):
- """Returns variable labels as a dict, associating each variable name with corresponding label"""
+ """Returns variable labels as a dict, associating each variable name
+ with corresponding label
+ """
return dict(zip(self.varlist, self.vlblist))
def value_labels(self):
- """Returns a dict, associating each variable name a dict, associating each value its corresponding label"""
+ """Returns a dict, associating each variable name a dict, associating
+ each value its corresponding label
+ """
if not self._value_labels_read:
self._read_value_labels()
@@ -745,7 +842,9 @@ def _maybe_convert_to_int_keys(convert_dates, varlist):
new_dict.update({varlist.index(key): convert_dates[key]})
else:
if not isinstance(key, int):
- raise ValueError("convery_dates key is not in varlist and is not an int")
+ raise ValueError(
+ "convery_dates key is not in varlist and is not an int"
+ )
new_dict.update({key: convert_dates[key]})
return new_dict
@@ -769,7 +868,8 @@ def _dtype_to_stata_type(dtype):
if dtype.type == np.string_:
return chr(dtype.itemsize)
elif dtype.type == np.object_: # try to coerce it to the biggest string
- # not memory efficient, what else could we do?
+ # not memory efficient, what else could we
+ # do?
return chr(244)
elif dtype == np.float64:
return chr(255)
@@ -856,8 +956,8 @@ class StataWriter(StataParser):
>>> writer = StataWriter('./date_data_file.dta', date, {2 : 'tw'})
>>> writer.write_file()
"""
- def __init__(self, fname, data, convert_dates=None, write_index=True, encoding="latin-1",
- byteorder=None):
+ def __init__(self, fname, data, convert_dates=None, write_index=True,
+ encoding="latin-1", byteorder=None):
super(StataWriter, self).__init__(encoding)
self._convert_dates = convert_dates
self._write_index = write_index
@@ -867,7 +967,9 @@ 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 or self._default_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):
@@ -875,7 +977,8 @@ 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 or self._default_encoding))
+ self._file.write(to_write.encode(self._encoding or
+ self._default_encoding))
else:
self._file.write(to_write)
@@ -898,9 +1001,13 @@ def __iter__(self):
self.varlist = data.columns.tolist()
dtypes = data.dtypes
if self._convert_dates is not None:
- self._convert_dates = _maybe_convert_to_int_keys(self._convert_dates, self.varlist)
+ self._convert_dates = _maybe_convert_to_int_keys(
+ self._convert_dates, self.varlist
+ )
for key in self._convert_dates:
- new_type = _convert_datetime_to_stata_type(self._convert_dates[key])
+ new_type = _convert_datetime_to_stata_type(
+ self._convert_dates[key]
+ )
dtypes[key] = np.dtype(new_type)
self.typlist = [_dtype_to_stata_type(dt) for dt in dtypes]
self.fmtlist = [_dtype_to_default_stata_fmt(dt) for dt in dtypes]
@@ -940,14 +1047,18 @@ def _write_header(self, data_label=None, time_stamp=None):
if data_label is None:
self._file.write(self._null_terminate(_pad_bytes("", 80)))
else:
- self._file.write(self._null_terminate(_pad_bytes(data_label[:80], 80)))
+ self._file.write(
+ self._null_terminate(_pad_bytes(data_label[:80], 80))
+ )
# time stamp, 18 bytes, char, null terminated
# format dd Mon yyyy hh:mm
if time_stamp is None:
time_stamp = datetime.datetime.now()
elif not isinstance(time_stamp, datetime):
raise ValueError("time_stamp should be datetime type")
- self._file.write(self._null_terminate(time_stamp.strftime("%d %b %Y %H:%M")))
+ self._file.write(
+ self._null_terminate(time_stamp.strftime("%d %b %Y %H:%M"))
+ )
def _write_descriptors(self, typlist=None, varlist=None, srtlist=None,
fmtlist=None, lbllist=None):
@@ -996,7 +1107,8 @@ def _write_data_nodates(self):
self._write(var)
else:
try:
- self._file.write(struct.pack(byteorder + TYPE_MAP[typ], var))
+ self._file.write(struct.pack(byteorder + TYPE_MAP[typ],
+ var))
except struct.error:
# have to be strict about type pack won't do any
# kind of casting
diff --git a/pandas/io/wb.py b/pandas/io/wb.py
index a585cb9adccbb..362b7b192f746 100644
--- a/pandas/io/wb.py
+++ b/pandas/io/wb.py
@@ -32,21 +32,22 @@ def download(country=['MX', 'CA', 'US'], indicator=['GDPPCKD', 'GDPPCKN'],
"""
# Are ISO-2 country codes valid?
- valid_countries = ["AG", "AL", "AM", "AO", "AR", "AT", "AU", "AZ", "BB",
- "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BO", "BR", "BS", "BW",
- "BY", "BZ", "CA", "CD", "CF", "CG", "CH", "CI", "CL", "CM", "CN",
- "CO", "CR", "CV", "CY", "CZ", "DE", "DK", "DM", "DO", "DZ", "EC",
- "EE", "EG", "ER", "ES", "ET", "FI", "FJ", "FR", "GA", "GB", "GE",
- "GH", "GM", "GN", "GQ", "GR", "GT", "GW", "GY", "HK", "HN", "HR",
- "HT", "HU", "ID", "IE", "IL", "IN", "IR", "IS", "IT", "JM", "JO",
- "JP", "KE", "KG", "KH", "KM", "KR", "KW", "KZ", "LA", "LB", "LC",
- "LK", "LS", "LT", "LU", "LV", "MA", "MD", "MG", "MK", "ML", "MN",
- "MR", "MU", "MW", "MX", "MY", "MZ", "NA", "NE", "NG", "NI", "NL",
- "NO", "NP", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PL", "PT",
- "PY", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SI",
- "SK", "SL", "SN", "SR", "SV", "SY", "SZ", "TD", "TG", "TH", "TN",
- "TR", "TT", "TW", "TZ", "UA", "UG", "US", "UY", "UZ", "VC", "VE",
- "VN", "VU", "YE", "ZA", "ZM", "ZW", "all"]
+ valid_countries = [
+ "AG", "AL", "AM", "AO", "AR", "AT", "AU", "AZ", "BB", "BD", "BE", "BF",
+ "BG", "BH", "BI", "BJ", "BO", "BR", "BS", "BW", "BY", "BZ", "CA", "CD",
+ "CF", "CG", "CH", "CI", "CL", "CM", "CN", "CO", "CR", "CV", "CY", "CZ",
+ "DE", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "ER", "ES", "ET", "FI",
+ "FJ", "FR", "GA", "GB", "GE", "GH", "GM", "GN", "GQ", "GR", "GT", "GW",
+ "GY", "HK", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IR", "IS",
+ "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KM", "KR", "KW", "KZ", "LA",
+ "LB", "LC", "LK", "LS", "LT", "LU", "LV", "MA", "MD", "MG", "MK", "ML",
+ "MN", "MR", "MU", "MW", "MX", "MY", "MZ", "NA", "NE", "NG", "NI", "NL",
+ "NO", "NP", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PL", "PT", "PY",
+ "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SI", "SK", "SL",
+ "SN", "SR", "SV", "SY", "SZ", "TD", "TG", "TH", "TN", "TR", "TT", "TW",
+ "TZ", "UA", "UG", "US", "UY", "UZ", "VC", "VE", "VN", "VU", "YE", "ZA",
+ "ZM", "ZW", "all"
+ ]
if type(country) == str:
country = [country]
bad_countries = np.setdiff1d(country, valid_countries)
@@ -68,7 +69,8 @@ def download(country=['MX', 'CA', 'US'], indicator=['GDPPCKD', 'GDPPCKN'],
# Warn
if len(bad_indicators) > 0:
print('Failed to obtain indicator(s): %s' % '; '.join(bad_indicators))
- print('The data may still be available for download at http://data.worldbank.org')
+ print('The data may still be available for download at '
+ 'http://data.worldbank.org')
if len(bad_countries) > 0:
print('Invalid ISO-2 codes: %s' % ' '.join(bad_countries))
# Merge WDI series
@@ -84,9 +86,9 @@ def download(country=['MX', 'CA', 'US'], indicator=['GDPPCKD', 'GDPPCKN'],
def _get_data(indicator="NY.GNS.ICTR.GN.ZS", country='US',
start=2002, end=2005):
# Build URL for api call
- url = "http://api.worldbank.org/countries/" + country + "/indicators/" + \
- indicator + "?date=" + str(start) + ":" + str(end) + "&per_page=25000" + \
- "&format=json"
+ url = ("http://api.worldbank.org/countries/" + country + "/indicators/" +
+ indicator + "?date=" + str(start) + ":" + str(end) +
+ "&per_page=25000&format=json")
# Download
with urlopen(url) as response:
data = response.read()
| https://api.github.com/repos/pandas-dev/pandas/pulls/5663 | 2013-12-08T00:18:30Z | 2013-12-09T18:54:59Z | 2013-12-09T18:54:59Z | 2014-06-14T15:40:54Z | |
BUG: compat_pickle should not modify global namespace | diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index 3365f1bb630b9..03b45336833d3 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -3,6 +3,7 @@
import sys
import numpy as np
import pandas
+import copy
import pickle as pkl
from pandas import compat
from pandas.compat import u, string_types
@@ -29,7 +30,7 @@ def load_reduce(self):
except:
# try to reencode the arguments
- if self.encoding is not None:
+ if getattr(self,'encoding',None) is not None:
args = tuple([arg.encode(self.encoding)
if isinstance(arg, string_types)
else arg for arg in args])
@@ -39,7 +40,7 @@ def load_reduce(self):
except:
pass
- if self.is_verbose:
+ if getattr(self,'is_verbose',None):
print(sys.exc_info())
print(func, args)
raise
@@ -53,6 +54,7 @@ class Unpickler(pkl._Unpickler):
class Unpickler(pkl.Unpickler):
pass
+Unpickler.dispatch = copy.copy(Unpickler.dispatch)
Unpickler.dispatch[pkl.REDUCE[0]] = load_reduce
| turns out was modifying the python pickle just by importing pandas
when sub classing have to copy a mutable property before modifying
http://stackoverflow.com/questions/20444593/pandas-compiled-from-source-default-pickle-behavior-changed
| https://api.github.com/repos/pandas-dev/pandas/pulls/5661 | 2013-12-07T19:17:52Z | 2013-12-08T15:17:30Z | 2013-12-08T15:17:30Z | 2014-06-24T11:20:04Z |
BUG: Fix for MultiIndex to_excel() with index=False. | diff --git a/pandas/core/format.py b/pandas/core/format.py
index 7135573d48644..f018e0ffdf561 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -1373,7 +1373,7 @@ def _format_header_mi(self):
coloffset = 0
lnum = 0
- if isinstance(self.df.index, MultiIndex):
+ if self.index and isinstance(self.df.index, MultiIndex):
coloffset = len(self.df.index[0]) - 1
if self.merge_cells:
@@ -1412,10 +1412,11 @@ def _format_header_regular(self):
has_aliases = isinstance(self.header, (tuple, list, np.ndarray))
if has_aliases or self.header:
coloffset = 0
+
if self.index:
coloffset = 1
- if isinstance(self.df.index, MultiIndex):
- coloffset = len(self.df.index[0])
+ if isinstance(self.df.index, MultiIndex):
+ coloffset = len(self.df.index[0])
colnames = self.columns
if has_aliases:
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 3446eb07a111e..eeeb914a3754e 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -615,7 +615,7 @@ def test_roundtrip_indexlabels(self):
has_index_names=self.merge_cells
).astype(np.int64)
frame.index.names = ['test']
- tm.assert_frame_equal(frame,recons.astype(bool))
+ tm.assert_frame_equal(frame, recons.astype(bool))
with ensure_clean(self.ext) as path:
@@ -715,6 +715,31 @@ def test_to_excel_multiindex_dates(self):
tm.assert_frame_equal(tsframe, recons)
self.assertEquals(recons.index.names, ('time', 'foo'))
+ def test_to_excel_multiindex_no_write_index(self):
+ _skip_if_no_xlrd()
+
+ # Test writing and re-reading a MI witout the index. GH 5616.
+
+ # Initial non-MI frame.
+ frame1 = pd.DataFrame({'a': [10, 20], 'b': [30, 40], 'c': [50, 60]})
+
+ # Add a MI.
+ frame2 = frame1.copy()
+ multi_index = pd.MultiIndex.from_tuples([(70, 80), (90, 100)])
+ frame2.index = multi_index
+
+ with ensure_clean(self.ext) as path:
+
+ # Write out to Excel without the index.
+ frame2.to_excel(path, 'test1', index=False)
+
+ # Read it back in.
+ reader = ExcelFile(path)
+ frame3 = reader.parse('test1')
+
+ # Test that it is the same as the initial frame.
+ tm.assert_frame_equal(frame1, frame3)
+
def test_to_excel_float_format(self):
_skip_if_no_xlrd()
| closes #5616 caused by the updated Excel MultiIndex handling.
This change should go into v0.13.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5659 | 2013-12-07T00:27:33Z | 2013-12-10T13:19:30Z | 2013-12-10T13:19:30Z | 2014-06-18T19:01:49Z |
API: change _is_copy to is_copy attribute on pandas objects GH(5650) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3a03d3b48ef19..4089b13fca5c7 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -77,11 +77,11 @@ class NDFrame(PandasObject):
axes : list
copy : boolean, default False
"""
- _internal_names = ['_data', 'name', '_cacher', '_is_copy', '_subtyp',
+ _internal_names = ['_data', 'name', '_cacher', 'is_copy', '_subtyp',
'_index', '_default_kind', '_default_fill_value']
_internal_names_set = set(_internal_names)
_metadata = []
- _is_copy = None
+ is_copy = None
def __init__(self, data, axes=None, copy=False, dtype=None,
fastpath=False):
@@ -96,7 +96,7 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
for i, ax in enumerate(axes):
data = data.reindex_axis(ax, axis=i)
- object.__setattr__(self, '_is_copy', False)
+ object.__setattr__(self, 'is_copy', False)
object.__setattr__(self, '_data', data)
object.__setattr__(self, '_item_cache', {})
@@ -1016,7 +1016,7 @@ def _set_item(self, key, value):
def _setitem_copy(self, copy):
""" set the _is_copy of the iiem """
- self._is_copy = copy
+ self.is_copy = copy
return self
def _check_setitem_copy(self, stacklevel=4):
@@ -1024,7 +1024,7 @@ def _check_setitem_copy(self, stacklevel=4):
If you call this function, be sure to set the stacklevel such that the
user will see the error *at the level of setting*"""
- if self._is_copy:
+ if self.is_copy:
value = config.get_option('mode.chained_assignment')
t = ("A value is trying to be set on a copy of a slice from a "
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 902440ec8e184..ffc30c81ededd 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -11125,7 +11125,7 @@ def test_xs_view(self):
self.assert_((dm.xs(2) == 5).all())
# prior to chained assignment (GH5390)
- # this would raise, but now just rrens a copy (and sets _is_copy)
+ # this would raise, but now just returns a copy (and sets is_copy)
# TODO (?): deal with mixed-type fiasco?
# with assertRaisesRegexp(TypeError, 'cannot get view of mixed-type'):
# self.mixed_frame.xs(self.mixed_frame.index[2], copy=False)
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index d102ac999cab0..1afabc8d4c882 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -1380,10 +1380,10 @@ def test_set_value_keeps_names(self):
columns=['one', 'two', 'three', 'four'],
index=idx)
df = df.sortlevel()
- self.assert_(df._is_copy is False)
+ self.assert_(df.is_copy is False)
self.assertEqual(df.index.names, ('Name', 'Number'))
df = df.set_value(('grethe', '4'), 'one', 99.34)
- self.assert_(df._is_copy is False)
+ self.assert_(df.is_copy is False)
self.assertEqual(df.index.names, ('Name', 'Number'))
def test_names(self):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 7b05a0b78b121..b6e7b10232bf5 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1776,7 +1776,7 @@ def test_detect_chained_assignment(self):
# work with the chain
expected = DataFrame([[-5,1],[-6,3]],columns=list('AB'))
df = DataFrame(np.arange(4).reshape(2,2),columns=list('AB'),dtype='int64')
- self.assert_(not df._is_copy)
+ self.assert_(not df.is_copy)
df['A'][0] = -5
df['A'][1] = -6
@@ -1784,11 +1784,11 @@ def test_detect_chained_assignment(self):
expected = DataFrame([[-5,2],[np.nan,3.]],columns=list('AB'))
df = DataFrame({ 'A' : Series(range(2),dtype='int64'), 'B' : np.array(np.arange(2,4),dtype=np.float64)})
- self.assert_(not df._is_copy)
+ self.assert_(not df.is_copy)
df['A'][0] = -5
df['A'][1] = np.nan
assert_frame_equal(df, expected)
- self.assert_(not df['A']._is_copy)
+ self.assert_(not df['A'].is_copy)
# using a copy (the chain), fails
df = DataFrame({ 'A' : Series(range(2),dtype='int64'), 'B' : np.array(np.arange(2,4),dtype=np.float64)})
@@ -1800,7 +1800,7 @@ def f():
df = DataFrame({'a' : ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c' : Series(range(7),dtype='int64') })
- self.assert_(not df._is_copy)
+ self.assert_(not df.is_copy)
expected = DataFrame({'a' : ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c' : [42,42,2,3,4,42,6]})
@@ -1826,10 +1826,10 @@ def f():
with tm.assert_produces_warning(expected_warning=com.SettingWithCopyWarning):
df.loc[0]['A'] = 111
- # make sure that _is_copy is picked up reconstruction
+ # make sure that is_copy is picked up reconstruction
# GH5475
df = DataFrame({"A": [1,2]})
- self.assert_(df._is_copy is False)
+ self.assert_(df.is_copy is False)
with tm.ensure_clean('__tmp__pickle') as path:
df.to_pickle(path)
df2 = pd.read_pickle(path)
@@ -1854,21 +1854,21 @@ def random_text(nobs=100):
# always a copy
x = df.iloc[[0,1,2]]
- self.assert_(x._is_copy is True)
+ self.assert_(x.is_copy is True)
x = df.iloc[[0,1,2,4]]
- self.assert_(x._is_copy is True)
+ self.assert_(x.is_copy is True)
# explicity copy
indexer = df.letters.apply(lambda x : len(x) > 10)
df = df.ix[indexer].copy()
- self.assert_(df._is_copy is False)
+ self.assert_(df.is_copy is False)
df['letters'] = df['letters'].apply(str.lower)
# implicity take
df = random_text(100000)
indexer = df.letters.apply(lambda x : len(x) > 10)
df = df.ix[indexer]
- self.assert_(df._is_copy is True)
+ self.assert_(df.is_copy is True)
df.loc[:,'letters'] = df['letters'].apply(str.lower)
# this will raise
@@ -1880,7 +1880,7 @@ def random_text(nobs=100):
# an identical take, so no copy
df = DataFrame({'a' : [1]}).dropna()
- self.assert_(df._is_copy is False)
+ self.assert_(df.is_copy is False)
df['a'] += 1
pd.set_option('chained_assignment','warn')
| closes #5650
| https://api.github.com/repos/pandas-dev/pandas/pulls/5658 | 2013-12-06T22:30:17Z | 2013-12-07T00:18:10Z | 2013-12-07T00:18:10Z | 2014-07-07T21:26:09Z |
PERF: performance regression in frame/apply (GH5654) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5e31b14fa7bd3..d0a1511ec1cca 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3434,7 +3434,7 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True):
if self._is_mixed_type: # maybe a hack for now
raise AssertionError('Must be mixed type DataFrame')
- values = self.values.ravel()
+ values = self.values
dummy = Series(NA, index=self._get_axis(axis),
dtype=values.dtype)
diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py
index 63b2a154c75e9..ee4d876d20233 100644
--- a/vb_suite/frame_methods.py
+++ b/vb_suite/frame_methods.py
@@ -289,3 +289,12 @@ def f(K=100):
frame_isnull = Benchmark('isnull(df)', setup,
start_date=datetime(2012,1,1))
+#----------------------------------------------------------------------
+# apply
+
+setup = common_setup + """
+s = Series(np.arange(1028.))
+df = DataFrame({ i:s for i in range(1028) })
+"""
+frame_apply_user_func = Benchmark('df.apply(lambda x: np.corrcoef(x,s)[0,1])', setup,
+ start_date=datetime(2012,1,1))
| closes #5654
| https://api.github.com/repos/pandas-dev/pandas/pulls/5656 | 2013-12-06T18:36:19Z | 2013-12-06T18:53:50Z | 2013-12-06T18:53:50Z | 2014-06-23T23:26:57Z |
BUG: repr_html, fix GH5588 for the MultiIndex case | diff --git a/pandas/core/format.py b/pandas/core/format.py
index 8bc74f2ff4c08..7135573d48644 100644
--- a/pandas/core/format.py
+++ b/pandas/core/format.py
@@ -846,9 +846,11 @@ def _write_hierarchical_rows(self, fmt_values, indent):
frame = self.frame
ncols = min(len(self.columns), self.max_cols)
+ nrows = min(len(self.frame), self.max_rows)
+
truncate = (len(frame) > self.max_rows)
- idx_values = frame.index.format(sparsify=False, adjoin=False,
+ idx_values = frame.index[:nrows].format(sparsify=False, adjoin=False,
names=False)
idx_values = lzip(*idx_values)
@@ -856,8 +858,8 @@ def _write_hierarchical_rows(self, fmt_values, indent):
# GH3547
sentinal = com.sentinal_factory()
- levels = frame.index.format(sparsify=sentinal, adjoin=False,
- names=False)
+ levels = frame.index[:nrows].format(sparsify=sentinal,
+ adjoin=False, names=False)
# Truncate row names
if truncate:
levels = [lev[:self.max_rows] for lev in levels]
diff --git a/vb_suite/frame_methods.py b/vb_suite/frame_methods.py
index a7c863345b9c5..63b2a154c75e9 100644
--- a/vb_suite/frame_methods.py
+++ b/vb_suite/frame_methods.py
@@ -157,7 +157,35 @@ def f(x):
"""
frame_to_html_mixed = Benchmark('df.to_html()', setup,
- start_date=datetime(2010, 6, 1))
+ start_date=datetime(2011, 11, 18))
+
+
+# truncated repr_html, single index
+
+setup = common_setup + """
+nrows=10000
+data=randn(nrows,10)
+idx=MultiIndex.from_arrays(np.tile(randn(3,nrows/100),100))
+df=DataFrame(data,index=idx)
+
+"""
+
+frame_html_repr_trunc_mi = Benchmark('df._repr_html_()', setup,
+ start_date=datetime(2013, 11, 25))
+
+# truncated repr_html, MultiIndex
+
+setup = common_setup + """
+nrows=10000
+data=randn(nrows,10)
+idx=randn(nrows)
+df=DataFrame(data,index=idx)
+
+"""
+
+frame_html_repr_trunc_si = Benchmark('df._repr_html_()', setup,
+ start_date=datetime(2013, 11, 25))
+
# insert many columns
| https://github.com/pydata/pandas/pull/5550#issuecomment-29938267
#5588
| https://api.github.com/repos/pandas-dev/pandas/pulls/5649 | 2013-12-05T22:57:49Z | 2013-12-05T22:57:54Z | 2013-12-05T22:57:54Z | 2014-07-06T14:18:09Z |
TST: prevent stderr from leaking to console in util.testing | diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 1904b5f0be49d..8c5704e151638 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -145,7 +145,8 @@ def check_output(*popenargs, **kwargs): # shamelessly taken from Python 2.7 sou
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
- process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
+ process = subprocess.Popen(stdout=subprocess.PIPE,stderr=subprocess.PIPE,
+ *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
@@ -160,7 +161,7 @@ def _default_locale_getter():
try:
raw_locales = check_output(['locale -a'], shell=True)
except subprocess.CalledProcessError as e:
- raise type(e)("%s, the 'locale -a' command cannot be foundon your "
+ raise type(e)("%s, the 'locale -a' command cannot be found on your "
"system" % e)
return raw_locales
| similar to https://github.com/pydata/pandas/pull/5627
Eliminate some more noise from tests, manifests only on system where `locale` isn't available.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5644 | 2013-12-04T22:11:11Z | 2013-12-04T22:30:18Z | 2013-12-04T22:30:18Z | 2014-06-21T13:28:05Z |
BUG: mixed column selection with dups is buggy (GH5639) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 3f148748081b9..97b86703e73b8 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -768,7 +768,7 @@ Bug Fixes
- Fixed segfault on ``isnull(MultiIndex)`` (now raises an error instead)
(:issue:`5123`, :issue:`5125`)
- Allow duplicate indices when performing operations that align
- (:issue:`5185`)
+ (:issue:`5185`, :issue:`5639`)
- Compound dtypes in a constructor raise ``NotImplementedError``
(:issue:`5191`)
- Bug in comparing duplicate frames (:issue:`4421`) related
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 959d0186030cd..e8b18ae93b287 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -250,10 +250,9 @@ def reindex_items_from(self, new_ref_items, indexer=None, method=None,
else:
masked_idx = indexer[indexer != -1]
+ new_items = self.items.take(masked_idx)
new_values = com.take_nd(self.values, masked_idx, axis=0,
allow_fill=False)
- new_items = self.items.take(masked_idx)
-
# fill if needed
if needs_fill:
new_values = com.interpolate_2d(new_values, method=method,
@@ -3192,7 +3191,8 @@ def reindex_items(self, new_items, indexer=None, copy=True,
else:
# unique
- if self.axes[0].is_unique:
+ if self.axes[0].is_unique and new_items.is_unique:
+
for block in self.blocks:
newb = block.reindex_items_from(new_items, copy=copy)
@@ -3201,7 +3201,7 @@ def reindex_items(self, new_items, indexer=None, copy=True,
# non-unique
else:
- rl = self._set_ref_locs()
+ rl = self._set_ref_locs(do_refs='force')
for i, idx in enumerate(indexer):
blk, lidx = rl[idx]
item = new_items.take([i])
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 9d9ebc1b95830..902440ec8e184 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3275,6 +3275,15 @@ def check(result, expected=None):
expected = DataFrame([[False,True],[True,False],[False,False],[True,False]],columns=['A','A'])
assert_frame_equal(result,expected)
+ # mixed column selection
+ # GH 5639
+ dfbool = DataFrame({'one' : Series([True, True, False], index=['a', 'b', 'c']),
+ 'two' : Series([False, False, True, False], index=['a', 'b', 'c', 'd']),
+ 'three': Series([False, True, True, True], index=['a', 'b', 'c', 'd'])})
+ expected = pd.concat([dfbool['one'],dfbool['three'],dfbool['one']],axis=1)
+ result = dfbool[['one', 'three', 'one']]
+ check(result,expected)
+
def test_insert_benchmark(self):
# from the vb_suite/frame_methods/frame_insert_columns
N = 10
| closes #5639
| https://api.github.com/repos/pandas-dev/pandas/pulls/5640 | 2013-12-04T14:16:30Z | 2013-12-04T14:50:54Z | 2013-12-04T14:50:54Z | 2014-06-19T11:13:37Z |
VIS: added ability to plot DataFrames and Series with errorbars | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 7cf2bec0f4144..b91e307bf7c69 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -59,6 +59,8 @@ New features
Date is used primarily in astronomy and represents the number of days from
noon, January 1, 4713 BC. Because nanoseconds are used to define the time
in pandas the actual range of dates that you can use is 1678 AD to 2262 AD. (:issue:`4041`)
+- Added error bar support to the ``.plot`` method of ``DataFrame`` and ``Series`` (:issue:`3796`)
+
API Changes
~~~~~~~~~~~
@@ -126,9 +128,9 @@ API Changes
DataFrame returned by ``GroupBy.apply`` (:issue:`6124`). This facilitates
``DataFrame.stack`` operations where the name of the column index is used as
the name of the inserted column containing the pivoted data.
-
-- The :func:`pivot_table`/:meth:`DataFrame.pivot_table` and :func:`crosstab` functions
- now take arguments ``index`` and ``columns`` instead of ``rows`` and ``cols``. A
+
+- The :func:`pivot_table`/:meth:`DataFrame.pivot_table` and :func:`crosstab` functions
+ now take arguments ``index`` and ``columns`` instead of ``rows`` and ``cols``. A
``FutureWarning`` is raised to alert that the old ``rows`` and ``cols`` arguments
will not be supported in a future release (:issue:`5505`)
diff --git a/doc/source/v0.14.0.txt b/doc/source/v0.14.0.txt
index ea321cbab545a..463e4f2a3a49c 100644
--- a/doc/source/v0.14.0.txt
+++ b/doc/source/v0.14.0.txt
@@ -286,6 +286,20 @@ You can use a right-hand-side of an alignable object as well.
df2.loc[idx[:,:,['C1','C3']],:] = df2*1000
df2
+Plotting With Errorbars
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Plotting with error bars is now supported in the ``.plot`` method of ``DataFrame`` and ``Series`` objects (:issue:`3796`).
+
+x and y errorbars are supported and can be supplied using the ``xerr`` and ``yerr`` keyword arguments to ``.plot()`` The error values can be specified using a variety of formats.
+
+- As a ``DataFrame`` or ``dict`` of errors with one or more of the column names (or dictionary keys) matching one or more of the column names of the plotting ``DataFrame`` or matching the ``name`` attribute of the ``Series``
+- As a ``str`` indicating which of the columns of plotting ``DataFrame`` contain the error values
+- As raw values (``list``, ``tuple``, or ``np.ndarray``). Must be the same length as the plotting ``DataFrame``/``Series``
+
+Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a ``M`` length ``Series``, a ``Mx2`` array should be provided indicating lower and upper (or left and right) errors. For a ``MxN`` ``DataFrame``, asymmetrical errors should be in a ``Mx2xN`` array.
+
+
Prior Version Deprecations/Changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index 5827f2e971e42..bc0bf69df1282 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -381,6 +381,40 @@ columns:
plt.close('all')
+.. _visualization.errorbars:
+
+Plotting With Error Bars
+~~~~~~~~~~~~~~~~~~~~~~~~
+Plotting with error bars is now supported in the ``.plot`` method of ``DataFrame`` and ``Series`` objects.
+
+x and y errorbars are supported and be supplied using the ``xerr`` and ``yerr`` keyword arguments to ``.plot()`` The error values can be specified using a variety of formats.
+
+- As a ``DataFrame`` or ``dict`` of errors with column names matching the ``columns`` attribute of the plotting ``DataFrame`` or matching the ``name`` attribute of the ``Series``
+- As a ``str`` indicating which of the columns of plotting ``DataFrame`` contain the error values
+- As raw values (``list``, ``tuple``, or ``np.ndarray``). Must be the same length as the plotting ``DataFrame``/``Series``
+
+Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a ``M`` length ``Series``, a ``Mx2`` array should be provided indicating lower and upper (or left and right) errors. For a ``MxN`` ``DataFrame``, asymmetrical errors should be in a ``Mx2xN`` array.
+
+Here is an example of one way to easily plot group means with standard deviations from the raw data.
+
+.. ipython:: python
+
+ # Generate the data
+ ix3 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['foo', 'foo', 'bar', 'bar', 'foo', 'foo', 'bar', 'bar']], names=['letter', 'word'])
+ df3 = pd.DataFrame({'data1': [3, 2, 4, 3, 2, 4, 3, 2], 'data2': [6, 5, 7, 5, 4, 5, 6, 5]}, index=ix3)
+
+ # Group by index labels and take the means and standard deviations for each group
+ gp3 = df3.groupby(level=('letter', 'word'))
+ means = gp3.mean()
+ errors = gp3.std()
+ means
+ errors
+
+ # Plot
+ fig, ax = plt.subplots()
+ @savefig errorbar_example.png
+ means.plot(yerr=errors, ax=ax, kind='bar')
+
.. _visualization.scatter_matrix:
Scatter plot matrix
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 30ba5cd5a70fe..2752d12765fad 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -360,6 +360,35 @@ def test_dup_datetime_index_plot(self):
s = Series(values, index=index)
_check_plot_works(s.plot)
+ @slow
+ def test_errorbar_plot(self):
+
+ s = Series(np.arange(10))
+ s_err = np.random.randn(10)
+
+ # test line and bar plots
+ kinds = ['line', 'bar']
+ for kind in kinds:
+ _check_plot_works(s.plot, yerr=Series(s_err), kind=kind)
+ _check_plot_works(s.plot, yerr=s_err, kind=kind)
+ _check_plot_works(s.plot, yerr=s_err.tolist(), kind=kind)
+
+ _check_plot_works(s.plot, xerr=s_err)
+
+ # test time series plotting
+ ix = date_range('1/1/2000', '1/1/2001', freq='M')
+ ts = Series(np.arange(12), index=ix)
+ ts_err = Series(np.random.randn(12), index=ix)
+
+ _check_plot_works(ts.plot, yerr=ts_err)
+
+ # check incorrect lengths and types
+ with tm.assertRaises(ValueError):
+ s.plot(yerr=np.arange(11))
+
+ s_err = ['zzz']*10
+ with tm.assertRaises(TypeError):
+ s.plot(yerr=s_err)
@tm.mplskip
class TestDataFramePlots(tm.TestCase):
@@ -1015,6 +1044,104 @@ def test_allow_cmap(self):
df.plot(kind='hexbin', x='A', y='B', cmap='YlGn',
colormap='BuGn')
+ def test_errorbar_plot(self):
+
+ d = {'x': np.arange(12), 'y': np.arange(12, 0, -1)}
+ df = DataFrame(d)
+ d_err = {'x': np.ones(12)*0.2, 'y': np.ones(12)*0.4}
+ df_err = DataFrame(d_err)
+
+ # check line plots
+ _check_plot_works(df.plot, yerr=df_err, logy=True)
+ _check_plot_works(df.plot, yerr=df_err, logx=True, logy=True)
+
+ kinds = ['line', 'bar', 'barh']
+ for kind in kinds:
+ _check_plot_works(df.plot, yerr=df_err['x'], kind=kind)
+ _check_plot_works(df.plot, yerr=d_err, kind=kind)
+ _check_plot_works(df.plot, yerr=df_err, xerr=df_err, kind=kind)
+ _check_plot_works(df.plot, yerr=df_err['x'], xerr=df_err['x'], kind=kind)
+ _check_plot_works(df.plot, yerr=df_err, xerr=df_err, subplots=True, kind=kind)
+
+ _check_plot_works((df+1).plot, yerr=df_err, xerr=df_err, kind='bar', log=True)
+
+ # yerr is raw error values
+ _check_plot_works(df['y'].plot, yerr=np.ones(12)*0.4)
+ _check_plot_works(df.plot, yerr=np.ones((2, 12))*0.4)
+
+ # yerr is column name
+ df['yerr'] = np.ones(12)*0.2
+ _check_plot_works(df.plot, y='y', x='x', yerr='yerr')
+
+ with tm.assertRaises(ValueError):
+ df.plot(yerr=np.random.randn(11))
+
+ df_err = DataFrame({'x': ['zzz']*12, 'y': ['zzz']*12})
+ with tm.assertRaises(TypeError):
+ df.plot(yerr=df_err)
+
+ @slow
+ def test_errorbar_with_integer_column_names(self):
+ # test with integer column names
+ df = DataFrame(np.random.randn(10, 2))
+ df_err = DataFrame(np.random.randn(10, 2))
+ _check_plot_works(df.plot, yerr=df_err)
+ _check_plot_works(df.plot, y=0, yerr=1)
+
+ @slow
+ def test_errorbar_with_partial_columns(self):
+ df = DataFrame(np.random.randn(10, 3))
+ df_err = DataFrame(np.random.randn(10, 2), columns=[0, 2])
+ kinds = ['line', 'bar']
+ for kind in kinds:
+ _check_plot_works(df.plot, yerr=df_err, kind=kind)
+
+ ix = date_range('1/1/2000', periods=10, freq='M')
+ df.set_index(ix, inplace=True)
+ df_err.set_index(ix, inplace=True)
+ _check_plot_works(df.plot, yerr=df_err, kind='line')
+
+ @slow
+ def test_errorbar_timeseries(self):
+
+ d = {'x': np.arange(12), 'y': np.arange(12, 0, -1)}
+ d_err = {'x': np.ones(12)*0.2, 'y': np.ones(12)*0.4}
+
+ # check time-series plots
+ ix = date_range('1/1/2000', '1/1/2001', freq='M')
+ tdf = DataFrame(d, index=ix)
+ tdf_err = DataFrame(d_err, index=ix)
+
+ kinds = ['line', 'bar', 'barh']
+ for kind in kinds:
+ _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
+ _check_plot_works(tdf.plot, yerr=d_err, kind=kind)
+ _check_plot_works(tdf.plot, y='y', kind=kind)
+ _check_plot_works(tdf.plot, y='y', yerr='x', kind=kind)
+ _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
+ _check_plot_works(tdf.plot, kind=kind, subplots=True)
+
+
+ def test_errorbar_asymmetrical(self):
+
+ np.random.seed(0)
+ err = np.random.rand(3, 2, 5)
+
+ data = np.random.randn(5, 3)
+ df = DataFrame(data)
+
+ ax = df.plot(yerr=err, xerr=err/2)
+
+ self.assertEqual(ax.lines[7].get_ydata()[0], data[0,1]-err[1,0,0])
+ self.assertEqual(ax.lines[8].get_ydata()[0], data[0,1]+err[1,1,0])
+
+ self.assertEqual(ax.lines[5].get_xdata()[0], -err[1,0,0]/2)
+ self.assertEqual(ax.lines[6].get_xdata()[0], err[1,1,0]/2)
+
+ with tm.assertRaises(ValueError):
+ df.plot(yerr=err.T)
+
+ tm.close()
@tm.mplskip
class TestDataFrameGroupByPlots(tm.TestCase):
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index 7038284b6c2a0..507e0127a5062 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -831,6 +831,11 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=True,
self.fig = fig
self.axes = None
+ # parse errorbar input if given
+ for err_dim in 'xy':
+ if err_dim+'err' in kwds:
+ kwds[err_dim+'err'] = self._parse_errorbars(error_dim=err_dim, **kwds)
+
if not isinstance(secondary_y, (bool, tuple, list, np.ndarray)):
secondary_y = [secondary_y]
self.secondary_y = secondary_y
@@ -971,6 +976,11 @@ def _setup_subplots(self):
axes = [ax]
+ if self.logx:
+ [a.set_xscale('log') for a in axes]
+ if self.logy:
+ [a.set_yscale('log') for a in axes]
+
self.fig = fig
self.axes = axes
@@ -1090,14 +1100,16 @@ def _is_datetype(self):
'time'))
def _get_plot_function(self):
- if self.logy:
- plotf = self.plt.Axes.semilogy
- elif self.logx:
- plotf = self.plt.Axes.semilogx
- elif self.loglog:
- plotf = self.plt.Axes.loglog
- else:
+ '''
+ Returns the matplotlib plotting function (plot or errorbar) based on
+ the presence of errorbar keywords.
+ '''
+
+ if ('xerr' not in self.kwds) and \
+ ('yerr' not in self.kwds):
plotf = self.plt.Axes.plot
+ else:
+ plotf = self.plt.Axes.errorbar
return plotf
@@ -1180,6 +1192,78 @@ def _get_marked_label(self, label, col_num):
else:
return label
+ def _parse_errorbars(self, error_dim='y', **kwds):
+ '''
+ Look for error keyword arguments and return the actual errorbar data
+ or return the error DataFrame/dict
+
+ Error bars can be specified in several ways:
+ Series: the user provides a pandas.Series object of the same
+ length as the data
+ ndarray: provides a np.ndarray of the same length as the data
+ DataFrame/dict: error values are paired with keys matching the
+ key in the plotted DataFrame
+ str: the name of the column within the plotted DataFrame
+ '''
+
+ err_kwd = kwds.pop(error_dim+'err', None)
+ if err_kwd is None:
+ return None
+
+ from pandas import DataFrame, Series
+
+ def match_labels(data, err):
+ err = err.reindex_axis(data.index)
+ return err
+
+ # key-matched DataFrame
+ if isinstance(err_kwd, DataFrame):
+ err = err_kwd
+ err = match_labels(self.data, err)
+
+ # key-matched dict
+ elif isinstance(err_kwd, dict):
+ err = err_kwd
+
+ # Series of error values
+ elif isinstance(err_kwd, Series):
+ # broadcast error series across data
+ err = match_labels(self.data, err_kwd)
+ err = np.atleast_2d(err)
+ err = np.tile(err, (self.nseries, 1))
+
+ # errors are a column in the dataframe
+ elif isinstance(err_kwd, str):
+ err = np.atleast_2d(self.data[err_kwd].values)
+ self.data = self.data[self.data.columns.drop(err_kwd)]
+ err = np.tile(err, (self.nseries, 1))
+
+ elif isinstance(err_kwd, (tuple, list, np.ndarray)):
+
+ # raw error values
+ err = np.atleast_2d(err_kwd)
+
+ err_shape = err.shape
+
+ # asymmetrical error bars
+ if err.ndim==3:
+ if (err_shape[0] != self.nseries) or \
+ (err_shape[1] != 2) or \
+ (err_shape[2] != len(self.data)):
+ msg = "Asymmetrical error bars should be provided " + \
+ "with the shape (%u, 2, %u)" % \
+ (self.nseries, len(self.data))
+ raise ValueError(msg)
+
+ # broadcast errors to each data series
+ if len(err)==1:
+ err = np.tile(err, (self.nseries, 1))
+
+ else:
+ msg = "No valid %serr detected" % error_dim
+ raise ValueError(msg)
+
+ return err
class KdePlot(MPLPlot):
def __init__(self, data, bw_method=None, ind=None, **kwargs):
@@ -1191,7 +1275,7 @@ def _make_plot(self):
from scipy.stats import gaussian_kde
from scipy import __version__ as spv
from distutils.version import LooseVersion
- plotf = self._get_plot_function()
+ plotf = self.plt.Axes.plot
colors = self._get_colors()
for i, (label, y) in enumerate(self._iter_data()):
ax = self._get_ax(i)
@@ -1376,8 +1460,9 @@ def _make_plot(self):
# this is slightly deceptive
if not self.x_compat and self.use_index and self._use_dynamic_x():
data = self._maybe_convert_index(self.data)
- self._make_ts_plot(data, **self.kwds)
+ self._make_ts_plot(data)
else:
+ from pandas.core.frame import DataFrame
lines = []
labels = []
x = self._get_xticks(convert_period=True)
@@ -1391,6 +1476,16 @@ def _make_plot(self):
kwds = self.kwds.copy()
self._maybe_add_color(colors, kwds, style, i)
+ for err_kw in ['xerr', 'yerr']:
+ # user provided label-matched dataframe of errors
+ if err_kw in kwds:
+ if isinstance(kwds[err_kw], (DataFrame, dict)):
+ if label in kwds[err_kw].keys():
+ kwds[err_kw] = kwds[err_kw][label]
+ else: del kwds[err_kw]
+ elif kwds[err_kw] is not None:
+ kwds[err_kw] = kwds[err_kw][i]
+
label = com.pprint_thing(label) # .encode('utf-8')
mask = com.isnull(y)
@@ -1399,10 +1494,11 @@ def _make_plot(self):
y = np.ma.masked_where(mask, y)
kwds['label'] = label
- if style is None:
- args = (ax, x, y)
- else:
+ # prevent style kwarg from going to errorbar, where it is unsupported
+ if style is not None and plotf.__name__=='plot':
args = (ax, x, y, style)
+ else:
+ args = (ax, x, y)
newline = plotf(*args, **kwds)[0]
lines.append(newline)
@@ -1422,6 +1518,8 @@ def _make_plot(self):
def _make_ts_plot(self, data, **kwargs):
from pandas.tseries.plotting import tsplot
+ from pandas.core.frame import DataFrame
+
kwargs = kwargs.copy()
colors = self._get_colors()
@@ -1430,8 +1528,15 @@ def _make_ts_plot(self, data, **kwargs):
labels = []
def _plot(data, col_num, ax, label, style, **kwds):
- newlines = tsplot(data, plotf, ax=ax, label=label,
- style=style, **kwds)
+
+ if plotf.__name__=='plot':
+ newlines = tsplot(data, plotf, ax=ax, label=label,
+ style=style, **kwds)
+ # errorbar function does not support style argument
+ elif plotf.__name__=='errorbar':
+ newlines = tsplot(data, plotf, ax=ax, label=label,
+ **kwds)
+
ax.grid(self.grid)
lines.append(newlines[0])
@@ -1444,19 +1549,33 @@ def _plot(data, col_num, ax, label, style, **kwds):
ax = self._get_ax(0) # self.axes[0]
style = self.style or ''
label = com.pprint_thing(self.label)
- kwds = kwargs.copy()
+ kwds = self.kwds.copy()
self._maybe_add_color(colors, kwds, style, 0)
+ if 'yerr' in kwds:
+ kwds['yerr'] = kwds['yerr'][0]
+
_plot(data, 0, ax, label, self.style, **kwds)
+
else:
for i, col in enumerate(data.columns):
label = com.pprint_thing(col)
ax = self._get_ax(i)
style = self._get_style(i, col)
- kwds = kwargs.copy()
+ kwds = self.kwds.copy()
self._maybe_add_color(colors, kwds, style, i)
+ # key-matched DataFrame of errors
+ if 'yerr' in kwds:
+ yerr = kwds['yerr']
+ if isinstance(yerr, (DataFrame, dict)):
+ if col in yerr.keys():
+ kwds['yerr'] = yerr[col]
+ else: del kwds['yerr']
+ else:
+ kwds['yerr'] = yerr[i]
+
_plot(data[col], i, ax, label, style, **kwds)
self._make_legend(lines, labels)
@@ -1581,6 +1700,7 @@ def f(ax, x, y, w, start=None, log=self.log, **kwds):
def _make_plot(self):
import matplotlib as mpl
+ from pandas import DataFrame, Series
# mpl decided to make their version string unicode across all Python
# versions for mpl >= 1.3 so we have to call str here for python 2
@@ -1599,10 +1719,25 @@ def _make_plot(self):
for i, (label, y) in enumerate(self._iter_data()):
ax = self._get_ax(i)
- label = com.pprint_thing(label)
kwds = self.kwds.copy()
kwds['color'] = colors[i % ncolors]
+ for err_kw in ['xerr', 'yerr']:
+ if err_kw in kwds:
+ # user provided label-matched dataframe of errors
+ if isinstance(kwds[err_kw], (DataFrame, dict)):
+ if label in kwds[err_kw].keys():
+ kwds[err_kw] = kwds[err_kw][label]
+ else: del kwds[err_kw]
+ elif kwds[err_kw] is not None:
+ kwds[err_kw] = kwds[err_kw][i]
+
+ label = com.pprint_thing(label)
+
+ if (('yerr' in kwds) or ('xerr' in kwds)) \
+ and (kwds.get('ecolor') is None):
+ kwds['ecolor'] = mpl.rcParams['xtick.color']
+
start = 0
if self.log:
start = 1
@@ -1694,6 +1829,9 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True,
x : label or position, default None
y : label or position, default None
Allows plotting of one column versus another
+ yerr : DataFrame (with matching labels), Series, list-type (tuple, list,
+ ndarray), or str of column name containing y error values
+ xerr : similar functionality as yerr, but for x error values
subplots : boolean, default False
Make separate subplots for each time series
sharex : boolean, default True
@@ -1807,6 +1945,15 @@ def plot_frame(frame=None, x=None, y=None, subplots=False, sharex=True,
label = kwds.pop('label', label)
ser = frame[y]
ser.index.name = label
+
+ for kw in ['xerr', 'yerr']:
+ if (kw in kwds) and \
+ (isinstance(kwds[kw], str) or com.is_integer(kwds[kw])):
+ try:
+ kwds[kw] = frame[kwds[kw]]
+ except (IndexError, KeyError, TypeError):
+ pass
+
return plot_series(ser, label=label, kind=kind,
use_index=use_index,
rot=rot, xticks=xticks, yticks=yticks,
@@ -1876,6 +2023,8 @@ def plot_series(series, label=None, kind='line', use_index=True, rot=None,
-----
See matplotlib documentation online for more on this subject
"""
+
+ from pandas import DataFrame
kind = _get_standard_kind(kind.lower().strip())
if kind == 'line':
klass = LinePlot
@@ -2611,6 +2760,7 @@ def _maybe_convert_date(x):
x = conv_func(x)
return x
+
if __name__ == '__main__':
# import pandas.rpy.common as com
# sales = com.load_data('sanfrancisco.home.sales', package='nutshell')
| close #3796
Addresses some of the concerns in issue #3796. New code allows the DataFrame and Series Line plots and Bar plot functions to include errorbars using `xerr` and `yerr` keyword arguments to `DataFrame/Series.plot()`. It supports specifying x and y errorbars as 1. a separate list/numpy/Series, 2. a DataFrame with the same column names as the plotting DataFrame. For example, using method 2 looks like this:
```
df = pd.DataFrame({'x':[1, 2, 3], 'y':[3, 2, 1]})
df_xerr = pd.DataFrame({'x':[0.6, 0.2, 0.3], 'y':[0.4, 0.5, 0.6]})
df_yerr = pd.DataFrame({'x':[0.5, 0.4, 0.6], 'y':[0.3, 0.7, 0.4]})
df.plot(xerr=df_xerr, yerr=df_yerr)
```
This is my first contribution. I tried to follow the contribution guidelines as best I could, but let me know if anything needs work!
| https://api.github.com/repos/pandas-dev/pandas/pulls/5638 | 2013-12-04T00:10:22Z | 2014-03-18T17:42:12Z | 2014-03-18T17:42:12Z | 2014-06-13T17:00:32Z |
BUG: Validate levels in a multi-index before storing in a HDFStore (GH5527) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 96004737c4d0f..3f148748081b9 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -549,6 +549,7 @@ Bug Fixes
- A zero length series written in Fixed format not deserializing properly.
(:issue:`4708`)
- Fixed decoding perf issue on pyt3 (:issue:`5441`)
+ - Validate levels in a multi-index before storing (:issue:`5527`)
- 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/pandas/io/pytables.py b/pandas/io/pytables.py
index d2fe1e0638192..db2028c70dc20 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2688,6 +2688,14 @@ 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)
+ def validate_multiindex(self, obj):
+ """ validate that we can store the multi-index; reset and return the new object """
+ levels = [ l if l is not None else "level_{0}".format(i) for i, l in enumerate(obj.index.names) ]
+ try:
+ return obj.reset_index(), levels
+ except (ValueError):
+ raise ValueError("duplicate names/columns in the multi-index when storing as a table")
+
@property
def nrows_expected(self):
""" based on our axes, compute the expected nrows """
@@ -3701,10 +3709,9 @@ class AppendableMultiSeriesTable(AppendableSeriesTable):
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)
+ obj, self.levels = self.validate_multiindex(obj)
+ cols = list(self.levels)
cols.append(name)
- self.levels = list(obj.index.names)
- obj = obj.reset_index()
obj.columns = cols
return super(AppendableMultiSeriesTable, self).write(obj=obj, **kwargs)
@@ -3764,6 +3771,7 @@ class AppendableMultiFrameTable(AppendableFrameTable):
table_type = u('appendable_multiframe')
obj_type = DataFrame
ndim = 2
+ _re_levels = re.compile("^level_\d+$")
@property
def table_type_short(self):
@@ -3774,11 +3782,11 @@ def write(self, obj, data_columns=None, **kwargs):
data_columns = []
elif data_columns is True:
data_columns = obj.columns[:]
- for n in obj.index.names:
+ obj, self.levels = self.validate_multiindex(obj)
+ for n in self.levels:
if n not in data_columns:
data_columns.insert(0, n)
- self.levels = obj.index.names
- return super(AppendableMultiFrameTable, self).write(obj=obj.reset_index(), data_columns=data_columns, **kwargs)
+ return super(AppendableMultiFrameTable, self).write(obj=obj, data_columns=data_columns, **kwargs)
def read(self, columns=None, **kwargs):
if columns is not None:
@@ -3787,7 +3795,11 @@ def read(self, columns=None, **kwargs):
columns.insert(0, n)
df = super(AppendableMultiFrameTable, self).read(
columns=columns, **kwargs)
- df.set_index(self.levels, inplace=True)
+ df = df.set_index(self.levels)
+
+ # remove names for 'level_%d'
+ df.index = df.index.set_names([ None if self._re_levels.search(l) else l for l in df.index.names ])
+
return df
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 3ab818a7fbe1a..1953f79482a22 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -1572,6 +1572,51 @@ def test_column_multiindex(self):
store.put('df1',df,format='table')
tm.assert_frame_equal(store['df1'],df,check_index_type=True,check_column_type=True)
+ def test_store_multiindex(self):
+
+ # validate multi-index names
+ # GH 5527
+ with ensure_clean_store(self.path) as store:
+
+ def make_index(names=None):
+ return MultiIndex.from_tuples([( datetime.datetime(2013,12,d), s, t) for d in range(1,3) for s in range(2) for t in range(3)],
+ names=names)
+
+
+ # no names
+ _maybe_remove(store, 'df')
+ df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index())
+ store.append('df',df)
+ tm.assert_frame_equal(store.select('df'),df)
+
+ # partial names
+ _maybe_remove(store, 'df')
+ df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date',None,None]))
+ store.append('df',df)
+ tm.assert_frame_equal(store.select('df'),df)
+
+ # series
+ _maybe_remove(store, 's')
+ s = Series(np.zeros(12), index=make_index(['date',None,None]))
+ store.append('s',s)
+ tm.assert_series_equal(store.select('s'),s)
+
+ # dup with column
+ _maybe_remove(store, 'df')
+ df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date','a','t']))
+ self.assertRaises(ValueError, store.append, 'df',df)
+
+ # dup within level
+ _maybe_remove(store, 'df')
+ df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date','date','date']))
+ self.assertRaises(ValueError, store.append, 'df',df)
+
+ # fully names
+ _maybe_remove(store, 'df')
+ df = DataFrame(np.zeros((12,2)), columns=['a','b'], index=make_index(['date','s','t']))
+ store.append('df',df)
+ tm.assert_frame_equal(store.select('df'),df)
+
def test_pass_spec_to_storer(self):
df = tm.makeDataFrame()
| close #5527
| https://api.github.com/repos/pandas-dev/pandas/pulls/5634 | 2013-12-03T02:41:10Z | 2013-12-03T03:00:46Z | 2013-12-03T03:00:46Z | 2014-06-22T06:01:57Z |
BUG: make sure partial setting with a Series like works with a completly empty frame (GH5632) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index f121928c06f72..96004737c4d0f 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -246,7 +246,7 @@ API Changes
(: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`, :issue:`5226`)
+ (:issue:`2578`, :issue:`5226`, :issue:`5632`)
- Default export for ``to_clipboard`` is now csv with a sep of `\t` for
compat (:issue:`3368`)
- ``at`` now will enlarge the object inplace (and return the same)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6ef6d8c75216f..5e31b14fa7bd3 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1895,9 +1895,16 @@ def _ensure_valid_index(self, value):
passed value
"""
if not len(self.index):
+
+ # GH5632, make sure that we are a Series convertible
+ try:
+ value = Series(value)
+ except:
+ pass
+
if not isinstance(value, Series):
raise ValueError('Cannot set a frame with no defined index '
- 'and a non-series')
+ 'and a value that cannot be converted to a Series')
self._data.set_axis(1, value.index.copy(), check_axis=False)
def _set_item(self, key, value):
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 44160609235df..7b05a0b78b121 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1635,6 +1635,42 @@ def f():
df.loc[:,1] = 1
self.assertRaises(ValueError, f)
+ # these work as they don't really change
+ # anything but the index
+ # GH5632
+ expected = DataFrame(columns=['foo'])
+ def f():
+ df = DataFrame()
+ df['foo'] = Series([])
+ return df
+ assert_frame_equal(f(), expected)
+ def f():
+ df = DataFrame()
+ df['foo'] = Series(df.index)
+ return df
+ assert_frame_equal(f(), expected)
+ def f():
+ df = DataFrame()
+ df['foo'] = Series(range(len(df)))
+ return df
+ assert_frame_equal(f(), expected)
+ def f():
+ df = DataFrame()
+ df['foo'] = []
+ return df
+ assert_frame_equal(f(), expected)
+ def f():
+ df = DataFrame()
+ df['foo'] = df.index
+ return df
+ assert_frame_equal(f(), expected)
+ def f():
+ df = DataFrame()
+ df['foo'] = range(len(df))
+ return df
+ assert_frame_equal(f(), expected)
+
+ df = DataFrame()
df2 = DataFrame()
df2[1] = Series([1],index=['foo'])
df.loc[:,1] = Series([1],index=['foo'])
| closes #5632
| https://api.github.com/repos/pandas-dev/pandas/pulls/5633 | 2013-12-02T22:19:33Z | 2013-12-03T01:59:04Z | 2013-12-03T01:59:04Z | 2014-06-18T03:40:04Z |
BUG: core/generic/_update_inplace not resetting item_cache (GH5628) | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 96da62077436f..f121928c06f72 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -209,7 +209,7 @@ Improvements to existing features
- ``NDFrame.drop()``, ``NDFrame.dropna()``, and ``.drop_duplicates()`` all
accept ``inplace`` as a kewyord argument; however, this only means that the
wrapper is updated inplace, a copy is still made internally.
- (:issue:`1960`, :issue:`5247`, and related :issue:`2325` [still not
+ (:issue:`1960`, :issue:`5247`, :issue:`5628`, and related :issue:`2325` [still not
closed])
- Fixed bug in `tools.plotting.andrews_curvres` so that lines are drawn grouped
by color as expected.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 5909885821b15..3a03d3b48ef19 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1217,6 +1217,7 @@ def _update_inplace(self, result):
# NOTE: This does *not* call __finalize__ and that's an explicit
# decision that we may revisit in the future.
self._reset_cache()
+ self._clear_item_cache()
self._data = result._data
self._maybe_update_cacher()
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 8f549eb12d825..9d9ebc1b95830 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -6806,6 +6806,13 @@ def test_drop(self):
assert_frame_equal(nu_df.drop('X', axis='rows'), nu_df.ix[["Y"], :])
assert_frame_equal(nu_df.drop(['X', 'Y'], axis=0), nu_df.ix[[], :])
+ # inplace cache issue
+ # GH 5628
+ df = pd.DataFrame(np.random.randn(10,3), columns=list('abc'))
+ expected = df[~(df.b>0)]
+ df.drop(labels=df[df.b>0].index, inplace=True)
+ assert_frame_equal(df,expected)
+
def test_fillna(self):
self.tsframe['A'][:5] = nan
self.tsframe['A'][-5:] = nan
| closes #5628
| https://api.github.com/repos/pandas-dev/pandas/pulls/5631 | 2013-12-02T12:42:39Z | 2013-12-02T12:53:01Z | 2013-12-02T12:53:01Z | 2014-07-02T08:55:16Z |
BUG/TST: importing util.clipboard shouldnt print to stdout (nosetests) | diff --git a/pandas/util/clipboard.py b/pandas/util/clipboard.py
index 3008a5d606c90..65c372bf7cd5b 100644
--- a/pandas/util/clipboard.py
+++ b/pandas/util/clipboard.py
@@ -133,12 +133,12 @@ def xselGetClipboard():
getcb = macGetClipboard
setcb = macSetClipboard
elif os.name == 'posix' or platform.system() == 'Linux':
- xclipExists = os.system('which xclip') == 0
+ xclipExists = os.system('which xclip > /dev/null') == 0
if xclipExists:
getcb = xclipGetClipboard
setcb = xclipSetClipboard
else:
- xselExists = os.system('which xsel') == 0
+ xselExists = os.system('which xsel > /dev/null') == 0
if xselExists:
getcb = xselGetClipboard
setcb = xselSetClipboard
| ```
$ nosetests
/usr/bin/xclip <<<< raise your hand if you've been ignoring this for 6 months
...........
```
`os.system` nastiness. The vbench package has similar problems.
https://github.com/pydata/pandas/pull/3848
:raised_hand:
| https://api.github.com/repos/pandas-dev/pandas/pulls/5627 | 2013-12-01T13:12:17Z | 2013-12-01T13:14:52Z | 2013-12-01T13:14:52Z | 2014-07-16T08:42:14Z |
TST: Always try to close file descriptors of tempfiles | diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 78d9dcb1fb888..3ab818a7fbe1a 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -3731,7 +3731,7 @@ def do_copy(f = None, new_f = None, keys = None, propindexes = True, **kwargs):
if new_f is None:
import tempfile
- new_f = tempfile.mkstemp()[1]
+ fd, new_f = tempfile.mkstemp()
tstore = store.copy(new_f, keys = keys, propindexes = propindexes, **kwargs)
@@ -3757,6 +3757,10 @@ def do_copy(f = None, new_f = None, keys = None, propindexes = True, **kwargs):
finally:
safe_close(store)
safe_close(tstore)
+ try:
+ os.close(fd)
+ except:
+ pass
safe_remove(new_f)
do_copy()
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 0c4e083b54eda..1904b5f0be49d 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -345,17 +345,20 @@ def ensure_clean(filename=None, return_filelike=False):
yield f
finally:
f.close()
-
else:
-
# don't generate tempfile if using a path with directory specified
if len(os.path.dirname(filename)):
raise ValueError("Can't pass a qualified name to ensure_clean()")
try:
- filename = tempfile.mkstemp(suffix=filename)[1]
+ fd, filename = tempfile.mkstemp(suffix=filename)
yield filename
finally:
+ try:
+ os.close(fd)
+ except Exception as e:
+ print("Couldn't close file descriptor: %d (file: %s)" %
+ (fd, filename))
try:
if os.path.exists(filename):
os.remove(filename)
| We weren't closing the file descriptors from `mkstemp`, which caused fun
segmentation faults for me. This should fix the issue.
| https://api.github.com/repos/pandas-dev/pandas/pulls/5626 | 2013-12-01T01:20:55Z | 2013-12-01T03:37:51Z | 2013-12-01T03:37:51Z | 2014-07-02T13:59:48Z |
CLN: Trim includes of absent files | diff --git a/MANIFEST.in b/MANIFEST.in
index 02de7790d11cf..5bf02ad867bd2 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -2,9 +2,7 @@ include MANIFEST.in
include LICENSE
include RELEASE.md
include README.rst
-include TODO.rst
include setup.py
-include setupegg.py
graft doc
prune doc/build
| https://api.github.com/repos/pandas-dev/pandas/pulls/5624 | 2013-11-30T21:35:46Z | 2013-11-30T22:02:35Z | 2013-11-30T22:02:35Z | 2014-07-16T08:42:12Z | |
BUG/API: autocorrelation_plot should accept kwargs | diff --git a/doc/source/release.rst b/doc/source/release.rst
index 9a0854494a897..51bf209ec4b04 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -61,6 +61,7 @@ API Changes
- Raise/Warn ``SettingWithCopyError`` (according to the option ``chained_assignment`` in more cases,
when detecting chained assignment, related (:issue:`5938`)
- DataFrame.head(0) returns self instead of empty frame (:issue:`5846`)
+ - ``autocorrelation_plot`` now accepts ``**kwargs``. (:issue:`5623`)
Experimental Features
~~~~~~~~~~~~~~~~~~~~~
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 7c8b17fb14abe..c3a19bb5714c7 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -299,6 +299,10 @@ def test_autocorrelation_plot(self):
_check_plot_works(autocorrelation_plot, self.ts)
_check_plot_works(autocorrelation_plot, self.ts.values)
+ ax = autocorrelation_plot(self.ts, label='Test')
+ t = ax.get_legend().get_texts()[0].get_text()
+ self.assertEqual(t, 'Test')
+
@slow
def test_lag_plot(self):
from pandas.tools.plotting import lag_plot
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index c4255e706b19f..aa5a5a017146b 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -672,13 +672,15 @@ def lag_plot(series, lag=1, ax=None, **kwds):
return ax
-def autocorrelation_plot(series, ax=None):
+def autocorrelation_plot(series, ax=None, **kwds):
"""Autocorrelation plot for time series.
Parameters:
-----------
series: Time series
ax: Matplotlib axis object, optional
+ kwds : keywords
+ Options to pass to matplotlib plotting method
Returns:
-----------
@@ -705,7 +707,9 @@ def r(h):
ax.axhline(y=-z99 / np.sqrt(n), linestyle='--', color='grey')
ax.set_xlabel("Lag")
ax.set_ylabel("Autocorrelation")
- ax.plot(x, y)
+ ax.plot(x, y, **kwds)
+ if 'label' in kwds:
+ ax.legend()
ax.grid()
return ax
| Unless there's a specific reason not to for this plot? All the others seem to accept them.
``` python
autocorrelation_plot(data, label='ACF')
```

| https://api.github.com/repos/pandas-dev/pandas/pulls/5623 | 2013-11-30T20:15:08Z | 2014-01-15T15:28:37Z | 2014-01-15T15:28:37Z | 2016-11-03T12:37:39Z |
TST: trim fixture to avoid xfails/skips | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 0734cf12cce0d..829ac64884dac 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -480,13 +480,41 @@ def index(request):
index_fixture2 = index
-@pytest.fixture(params=indices_dict.keys())
+@pytest.fixture(
+ params=[
+ key for key in indices_dict if not isinstance(indices_dict[key], MultiIndex)
+ ]
+)
+def index_flat(request):
+ """
+ index fixture, but excluding MultiIndex cases.
+ """
+ key = request.param
+ return indices_dict[key].copy()
+
+
+# Alias so we can test with cartesian product of index_flat
+index_flat2 = index_flat
+
+
+@pytest.fixture(
+ params=[
+ key
+ for key in indices_dict
+ if key not in ["int", "uint", "range", "empty", "repeats"]
+ and not isinstance(indices_dict[key], MultiIndex)
+ ]
+)
def index_with_missing(request):
"""
- Fixture for indices with missing values
+ Fixture for indices with missing values.
+
+ Integer-dtype and empty cases are excluded because they cannot hold missing
+ values.
+
+ MultiIndex is excluded because isna() is not defined for MultiIndex.
"""
- if request.param in ["int", "uint", "range", "empty", "repeats"]:
- pytest.skip("missing values not supported")
+
# GH 35538. Use deep copy to avoid illusive bug on np-dev
# Azure pipeline that writes into indices_dict despite copy
ind = indices_dict[request.param].copy(deep=True)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index b756ad6051a86..c70401ac14e7d 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -630,7 +630,7 @@ def test_map(self):
def test_map_dictlike(self, mapper):
index = self.create_index()
- if isinstance(index, (pd.CategoricalIndex, pd.IntervalIndex)):
+ if isinstance(index, pd.CategoricalIndex):
pytest.skip(f"skipping tests for {type(index)}")
identity = mapper(index.values, index)
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 092b1c447eb0d..42769e5daf059 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -878,14 +878,11 @@ def test_difference_name_preservation(self, index, second_name, expected, sort):
assert result.name == expected
def test_difference_empty_arg(self, index, sort):
- if isinstance(index, MultiIndex):
- pytest.skip("Not applicable")
first = index[5:20]
first.name = "name"
result = first.difference([], sort)
- assert tm.equalContents(result, first)
- assert result.name == first.name
+ tm.assert_index_equal(result, first)
@pytest.mark.parametrize("index", ["string"], indirect=True)
def test_difference_identity(self, index, sort):
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 931f01cecab0b..d622ea359bc53 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -52,11 +52,9 @@ def test_droplevel(self, index):
):
index.droplevel(level)
- def test_constructor_non_hashable_name(self, index):
+ def test_constructor_non_hashable_name(self, index_flat):
# GH 20527
-
- if isinstance(index, MultiIndex):
- pytest.skip("multiindex handled in test_multi.py")
+ index = index_flat
message = "Index.name must be a hashable type"
renamed = [["1"]]
@@ -69,27 +67,23 @@ def test_constructor_non_hashable_name(self, index):
with pytest.raises(TypeError, match=message):
index.set_names(names=renamed)
- def test_constructor_unwraps_index(self, index):
- if isinstance(index, pd.MultiIndex):
- raise pytest.skip("MultiIndex has no ._data")
- a = index
+ def test_constructor_unwraps_index(self, index_flat):
+ a = index_flat
b = type(a)(a)
tm.assert_equal(a._data, b._data)
- def test_to_flat_index(self, index):
+ def test_to_flat_index(self, index_flat):
# 22866
- if isinstance(index, MultiIndex):
- pytest.skip("Separate expectation for MultiIndex")
+ index = index_flat
result = index.to_flat_index()
tm.assert_index_equal(result, index)
- def test_set_name_methods(self, index):
+ def test_set_name_methods(self, index_flat):
+ # MultiIndex tested separately
+ index = index_flat
new_name = "This is the new name for this index"
- # don't tests a MultiIndex here (as its tested separated)
- if isinstance(index, MultiIndex):
- pytest.skip("Skip check for MultiIndex")
original_name = index.name
new_ind = index.set_names([new_name])
assert new_ind.name == new_name
@@ -113,11 +107,10 @@ def test_set_name_methods(self, index):
assert index.name == name
assert index.names == [name]
- def test_copy_and_deepcopy(self, index):
+ def test_copy_and_deepcopy(self, index_flat):
from copy import copy, deepcopy
- if isinstance(index, MultiIndex):
- pytest.skip("Skip check for MultiIndex")
+ index = index_flat
for func in (copy, deepcopy):
idx_copy = func(index)
@@ -127,10 +120,9 @@ def test_copy_and_deepcopy(self, index):
new_copy = index.copy(deep=True, name="banana")
assert new_copy.name == "banana"
- def test_unique(self, index):
+ def test_unique(self, index_flat):
# don't test a MultiIndex here (as its tested separated)
- if isinstance(index, MultiIndex):
- pytest.skip("Skip check for MultiIndex")
+ index = index_flat
# GH 17896
expected = index.drop_duplicates()
@@ -149,9 +141,10 @@ def test_unique(self, index):
with pytest.raises(KeyError, match=msg):
index.unique(level="wrong")
- def test_get_unique_index(self, index):
+ def test_get_unique_index(self, index_flat):
# MultiIndex tested separately
- if not len(index) or isinstance(index, MultiIndex):
+ index = index_flat
+ if not len(index):
pytest.skip("Skip check for empty Index and MultiIndex")
idx = index[[0] * 5]
@@ -200,11 +193,12 @@ def test_get_unique_index(self, index):
result = i._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, expected)
- def test_searchsorted_monotonic(self, index):
+ def test_searchsorted_monotonic(self, index_flat):
# GH17271
+ index = index_flat
# not implemented for tuple searches in MultiIndex
# or Intervals searches in IntervalIndex
- if isinstance(index, (MultiIndex, pd.IntervalIndex)):
+ if isinstance(index, pd.IntervalIndex):
pytest.skip("Skip check for MultiIndex/IntervalIndex")
# nothing to test if the index is empty
@@ -245,9 +239,9 @@ def test_searchsorted_monotonic(self, index):
with pytest.raises(ValueError, match=msg):
index._searchsorted_monotonic(value, side="left")
- def test_drop_duplicates(self, index, keep):
- if isinstance(index, MultiIndex):
- pytest.skip("MultiIndex is tested separately")
+ def test_drop_duplicates(self, index_flat, keep):
+ # MultiIndex is tested separately
+ index = index_flat
if isinstance(index, RangeIndex):
pytest.skip(
"RangeIndex is tested in test_drop_duplicates_no_duplicates "
@@ -279,9 +273,9 @@ def test_drop_duplicates(self, index, keep):
expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
- def test_drop_duplicates_no_duplicates(self, index):
- if isinstance(index, MultiIndex):
- pytest.skip("MultiIndex is tested separately")
+ def test_drop_duplicates_no_duplicates(self, index_flat):
+ # MultiIndex is tested separately
+ index = index_flat
# make unique index
if isinstance(index, RangeIndex):
@@ -305,9 +299,12 @@ def test_drop_duplicates_inplace(self, index):
with pytest.raises(TypeError, match=msg):
index.drop_duplicates(inplace=True)
- def test_has_duplicates(self, index):
+ def test_has_duplicates(self, index_flat):
+ # MultiIndex tested separately in:
+ # tests/indexes/multi/test_unique_and_duplicates.
+ index = index_flat
holder = type(index)
- if not len(index) or isinstance(index, (MultiIndex, RangeIndex)):
+ if not len(index) or isinstance(index, RangeIndex):
# MultiIndex tested separately in:
# tests/indexes/multi/test_unique_and_duplicates.
# RangeIndex is unique by definition.
@@ -363,29 +360,18 @@ def test_asi8_deprecation(self, index):
@pytest.mark.parametrize("na_position", [None, "middle"])
-def test_sort_values_invalid_na_position(request, index_with_missing, na_position):
- if isinstance(index_with_missing, MultiIndex):
- request.node.add_marker(
- pytest.mark.xfail(
- reason="missing value sorting order not defined for index type"
- )
- )
+def test_sort_values_invalid_na_position(index_with_missing, na_position):
- if na_position not in ["first", "last"]:
- with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
- index_with_missing.sort_values(na_position=na_position)
+ with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
+ index_with_missing.sort_values(na_position=na_position)
@pytest.mark.parametrize("na_position", ["first", "last"])
-def test_sort_values_with_missing(request, index_with_missing, na_position):
+def test_sort_values_with_missing(index_with_missing, na_position):
# GH 35584. Test that sort_values works with missing values,
# sort non-missing and place missing according to na_position
- if isinstance(index_with_missing, MultiIndex):
- request.node.add_marker(
- pytest.mark.xfail(reason="missing value sorting order not implemented")
- )
- elif isinstance(index_with_missing, CategoricalIndex):
+ if isinstance(index_with_missing, CategoricalIndex):
pytest.skip("missing value sorting order not well-defined")
missing_count = np.sum(index_with_missing.isna())
diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py
index f2a33df71e8e3..746b6d6fb6e2a 100644
--- a/pandas/tests/indexes/test_setops.py
+++ b/pandas/tests/indexes/test_setops.py
@@ -38,33 +38,39 @@ def test_union_same_types(index):
assert idx1.union(idx2).dtype == idx1.dtype
-def test_union_different_types(request, index, index_fixture2):
+def test_union_different_types(index_flat, index_flat2):
# This test only considers combinations of indices
# GH 23525
- idx1, idx2 = index, index_fixture2
- type_pair = tuple(sorted([type(idx1), type(idx2)], key=lambda x: str(x)))
- if type_pair in COMPATIBLE_INCONSISTENT_PAIRS:
- request.node.add_marker(
- pytest.mark.xfail(reason="This test only considers non compatible indexes.")
- )
-
- if any(isinstance(idx, pd.MultiIndex) for idx in (idx1, idx2)):
- pytest.skip("This test doesn't consider multiindixes.")
+ idx1 = index_flat
+ idx2 = index_flat2
- if is_dtype_equal(idx1.dtype, idx2.dtype):
- pytest.skip("This test only considers non matching dtypes.")
-
- # A union with a CategoricalIndex (even as dtype('O')) and a
- # non-CategoricalIndex can only be made if both indices are monotonic.
- # This is true before this PR as well.
+ type_pair = tuple(sorted([type(idx1), type(idx2)], key=lambda x: str(x)))
# Union with a non-unique, non-monotonic index raises error
# This applies to the boolean index
idx1 = idx1.sort_values()
idx2 = idx2.sort_values()
- assert idx1.union(idx2).dtype == np.dtype("O")
- assert idx2.union(idx1).dtype == np.dtype("O")
+ res1 = idx1.union(idx2)
+ res2 = idx2.union(idx1)
+
+ if is_dtype_equal(idx1.dtype, idx2.dtype):
+ assert res1.dtype == idx1.dtype
+ assert res2.dtype == idx1.dtype
+
+ elif type_pair not in COMPATIBLE_INCONSISTENT_PAIRS:
+ # A union with a CategoricalIndex (even as dtype('O')) and a
+ # non-CategoricalIndex can only be made if both indices are monotonic.
+ # This is true before this PR as well.
+ assert res1.dtype == np.dtype("O")
+ assert res2.dtype == np.dtype("O")
+
+ elif idx1.dtype.kind in ["f", "i", "u"] and idx2.dtype.kind in ["f", "i", "u"]:
+ assert res1.dtype == np.dtype("f8")
+ assert res2.dtype == np.dtype("f8")
+
+ else:
+ raise NotImplementedError
@pytest.mark.parametrize("idx_fact1,idx_fact2", COMPATIBLE_INCONSISTENT_PAIRS.values())
@@ -275,12 +281,12 @@ def test_symmetric_difference(self, index):
(None, None, None),
],
)
- def test_corner_union(self, index, fname, sname, expected_name):
+ def test_corner_union(self, index_flat, fname, sname, expected_name):
# GH#9943, GH#9862
# Test unions with various name combinations
# Do not test MultiIndex or repeats
-
- if isinstance(index, MultiIndex) or not index.is_unique:
+ index = index_flat
+ if not index.is_unique:
pytest.skip("Not for MultiIndex or repeated indices")
# Test copy.union(copy)
@@ -321,8 +327,9 @@ def test_corner_union(self, index, fname, sname, expected_name):
(None, None, None),
],
)
- def test_union_unequal(self, index, fname, sname, expected_name):
- if isinstance(index, MultiIndex) or not index.is_unique:
+ def test_union_unequal(self, index_flat, fname, sname, expected_name):
+ index = index_flat
+ if not index.is_unique:
pytest.skip("Not for MultiIndex or repeated indices")
# test copy.union(subset) - need sort for unicode and string
@@ -342,11 +349,11 @@ def test_union_unequal(self, index, fname, sname, expected_name):
(None, None, None),
],
)
- def test_corner_intersect(self, index, fname, sname, expected_name):
+ def test_corner_intersect(self, index_flat, fname, sname, expected_name):
# GH#35847
# Test intersections with various name combinations
-
- if isinstance(index, MultiIndex) or not index.is_unique:
+ index = index_flat
+ if not index.is_unique:
pytest.skip("Not for MultiIndex or repeated indices")
# Test copy.intersection(copy)
@@ -387,8 +394,9 @@ def test_corner_intersect(self, index, fname, sname, expected_name):
(None, None, None),
],
)
- def test_intersect_unequal(self, index, fname, sname, expected_name):
- if isinstance(index, MultiIndex) or not index.is_unique:
+ def test_intersect_unequal(self, index_flat, fname, sname, expected_name):
+ index = index_flat
+ if not index.is_unique:
pytest.skip("Not for MultiIndex or repeated indices")
# test copy.intersection(subset) - need sort for unicode and string
| https://api.github.com/repos/pandas-dev/pandas/pulls/39502 | 2021-01-31T16:57:47Z | 2021-02-02T13:35:18Z | 2021-02-02T13:35:18Z | 2021-02-02T15:11:23Z | |
DOC: add example to insert (#39313) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 82e984d36b6a1..7bcc6523bb2be 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3870,6 +3870,14 @@ def insert(self, loc, column, value, allow_duplicates: bool = False) -> None:
col1 col1 newcol col2
0 100 1 99 3
1 100 2 99 4
+
+ Notice that pandas uses index alignment in case of `value` from type `Series`:
+
+ >>> df.insert(0, "col0", pd.Series([5, 6], index=[1, 2]))
+ >>> df
+ col0 col1 col1 newcol col2
+ 0 NaN 100 1 99 3
+ 1 5.0 100 2 99 4
"""
if allow_duplicates and not self.flags.allows_duplicate_labels:
raise ValueError(
| - [x] closes #39313
- [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
- [ ] whatsnew entry - no
| https://api.github.com/repos/pandas-dev/pandas/pulls/39500 | 2021-01-31T14:00:36Z | 2021-02-01T19:15:10Z | 2021-02-01T19:15:09Z | 2021-02-02T14:55:41Z |
REF: Move agg helpers into apply | diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py
index 5c99f783c70d9..e3f159346cd51 100644
--- a/pandas/core/aggregation.py
+++ b/pandas/core/aggregation.py
@@ -27,18 +27,16 @@
AggFuncType,
AggFuncTypeBase,
AggFuncTypeDict,
- AggObjType,
Axis,
FrameOrSeries,
FrameOrSeriesUnion,
)
-from pandas.core.dtypes.cast import is_nested_object
from pandas.core.dtypes.common import is_dict_like, is_list_like
-from pandas.core.dtypes.generic import ABCDataFrame, ABCNDFrame, ABCSeries
+from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
from pandas.core.algorithms import safe_sort
-from pandas.core.base import DataError, SpecificationError
+from pandas.core.base import SpecificationError
import pandas.core.common as com
from pandas.core.indexes.api import Index
@@ -532,215 +530,3 @@ def transform_str_or_callable(
return obj.apply(func, args=args, **kwargs)
except Exception:
return func(obj, *args, **kwargs)
-
-
-def agg_list_like(
- obj: AggObjType,
- arg: List[AggFuncTypeBase],
- _axis: int,
-) -> FrameOrSeriesUnion:
- """
- Compute aggregation in the case of a list-like argument.
-
- Parameters
- ----------
- obj : Pandas object to compute aggregation on.
- arg : list
- Aggregations to compute.
- _axis : int, 0 or 1
- Axis to compute aggregation on.
-
- Returns
- -------
- Result of aggregation.
- """
- from pandas.core.reshape.concat import concat
-
- if _axis != 0:
- raise NotImplementedError("axis other than 0 is not supported")
-
- if obj._selected_obj.ndim == 1:
- selected_obj = obj._selected_obj
- else:
- selected_obj = obj._obj_with_exclusions
-
- results = []
- keys = []
-
- # degenerate case
- if selected_obj.ndim == 1:
- for a in arg:
- colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
- try:
- new_res = colg.aggregate(a)
-
- except TypeError:
- pass
- else:
- results.append(new_res)
-
- # make sure we find a good name
- name = com.get_callable_name(a) or a
- keys.append(name)
-
- # multiples
- else:
- for index, col in enumerate(selected_obj):
- colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
- try:
- new_res = colg.aggregate(arg)
- except (TypeError, DataError):
- pass
- except ValueError as err:
- # cannot aggregate
- if "Must produce aggregated value" in str(err):
- # raised directly in _aggregate_named
- pass
- elif "no results" in str(err):
- # raised directly in _aggregate_multiple_funcs
- pass
- else:
- raise
- else:
- results.append(new_res)
- keys.append(col)
-
- # if we are empty
- if not len(results):
- raise ValueError("no results")
-
- try:
- return concat(results, keys=keys, axis=1, sort=False)
- except TypeError as err:
-
- # we are concatting non-NDFrame objects,
- # e.g. a list of scalars
-
- from pandas import Series
-
- result = Series(results, index=keys, name=obj.name)
- if is_nested_object(result):
- raise ValueError(
- "cannot combine transform and aggregation operations"
- ) from err
- return result
-
-
-def agg_dict_like(
- obj: AggObjType,
- arg: AggFuncTypeDict,
- _axis: int,
-) -> FrameOrSeriesUnion:
- """
- Compute aggregation in the case of a dict-like argument.
-
- Parameters
- ----------
- obj : Pandas object to compute aggregation on.
- arg : dict
- label-aggregation pairs to compute.
- _axis : int, 0 or 1
- Axis to compute aggregation on.
-
- Returns
- -------
- Result of aggregation.
- """
- is_aggregator = lambda x: isinstance(x, (list, tuple, dict))
-
- if _axis != 0: # pragma: no cover
- raise ValueError("Can only pass dict with axis=0")
-
- selected_obj = obj._selected_obj
-
- # if we have a dict of any non-scalars
- # eg. {'A' : ['mean']}, normalize all to
- # be list-likes
- # Cannot use arg.values() because arg may be a Series
- if any(is_aggregator(x) for _, x in arg.items()):
- new_arg: AggFuncTypeDict = {}
- for k, v in arg.items():
- if not isinstance(v, (tuple, list, dict)):
- new_arg[k] = [v]
- else:
- new_arg[k] = v
-
- # the keys must be in the columns
- # for ndim=2, or renamers for ndim=1
-
- # ok for now, but deprecated
- # {'A': { 'ra': 'mean' }}
- # {'A': { 'ra': ['mean'] }}
- # {'ra': ['mean']}
-
- # not ok
- # {'ra' : { 'A' : 'mean' }}
- if isinstance(v, dict):
- raise SpecificationError("nested renamer is not supported")
- elif isinstance(selected_obj, ABCSeries):
- raise SpecificationError("nested renamer is not supported")
- elif (
- isinstance(selected_obj, ABCDataFrame) and k not in selected_obj.columns
- ):
- raise KeyError(f"Column '{k}' does not exist!")
-
- arg = new_arg
-
- else:
- # deprecation of renaming keys
- # GH 15931
- keys = list(arg.keys())
- if isinstance(selected_obj, ABCDataFrame) and len(
- selected_obj.columns.intersection(keys)
- ) != len(keys):
- cols = list(
- safe_sort(
- list(set(keys) - set(selected_obj.columns.intersection(keys))),
- )
- )
- raise SpecificationError(f"Column(s) {cols} do not exist")
-
- from pandas.core.reshape.concat import concat
-
- if selected_obj.ndim == 1:
- # key only used for output
- colg = obj._gotitem(obj._selection, ndim=1)
- results = {key: colg.agg(how) for key, how in arg.items()}
- else:
- # key used for column selection and output
- results = {key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items()}
-
- # set the final keys
- keys = list(arg.keys())
-
- # Avoid making two isinstance calls in all and any below
- is_ndframe = [isinstance(r, ABCNDFrame) for r in results.values()]
-
- # combine results
- if all(is_ndframe):
- keys_to_use = [k for k in keys if not results[k].empty]
- # Have to check, if at least one DataFrame is not empty.
- keys_to_use = keys_to_use if keys_to_use != [] else keys
- axis = 0 if isinstance(obj, ABCSeries) else 1
- result = concat({k: results[k] for k in keys_to_use}, axis=axis)
- elif any(is_ndframe):
- # There is a mix of NDFrames and scalars
- raise ValueError(
- "cannot perform both aggregation "
- "and transformation operations "
- "simultaneously"
- )
- else:
- from pandas import Series
-
- # we have a dict of scalars
- # GH 36212 use name only if obj is a series
- if obj.ndim == 1:
- obj = cast("Series", obj)
- name = obj.name
- else:
- name = None
-
- result = Series(results, name=name)
-
- return result
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 8207f4d6e33d4..533190e692891 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -30,15 +30,18 @@
)
from pandas.util._decorators import cache_readonly
+from pandas.core.dtypes.cast import is_nested_object
from pandas.core.dtypes.common import (
is_dict_like,
is_extension_array_dtype,
is_list_like,
is_sequence,
)
-from pandas.core.dtypes.generic import ABCSeries
+from pandas.core.dtypes.generic import ABCDataFrame, ABCNDFrame, ABCSeries
-from pandas.core.aggregation import agg_dict_like, agg_list_like
+from pandas.core.algorithms import safe_sort
+from pandas.core.base import DataError, SpecificationError
+import pandas.core.common as com
from pandas.core.construction import (
array as pd_array,
create_series_with_explicit_dtype,
@@ -171,12 +174,10 @@ def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]:
return result, None
if is_dict_like(arg):
- arg = cast(AggFuncTypeDict, arg)
- return agg_dict_like(obj, arg, _axis), True
+ return self.agg_dict_like(_axis), True
elif is_list_like(arg):
# we require a list, but not a 'str'
- arg = cast(List[AggFuncTypeBase], arg)
- return agg_list_like(obj, arg, _axis=_axis), None
+ return self.agg_list_like(_axis=_axis), None
else:
result = None
@@ -188,6 +189,211 @@ def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]:
# caller can react
return result, True
+ def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion:
+ """
+ Compute aggregation in the case of a list-like argument.
+
+ Parameters
+ ----------
+ _axis : int, 0 or 1
+ Axis to compute aggregation on.
+
+ Returns
+ -------
+ Result of aggregation.
+ """
+ from pandas.core.reshape.concat import concat
+
+ obj = self.obj
+ arg = cast(List[AggFuncTypeBase], self.f)
+
+ if _axis != 0:
+ raise NotImplementedError("axis other than 0 is not supported")
+
+ if obj._selected_obj.ndim == 1:
+ selected_obj = obj._selected_obj
+ else:
+ selected_obj = obj._obj_with_exclusions
+
+ results = []
+ keys = []
+
+ # degenerate case
+ if selected_obj.ndim == 1:
+ for a in arg:
+ colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
+ try:
+ new_res = colg.aggregate(a)
+
+ except TypeError:
+ pass
+ else:
+ results.append(new_res)
+
+ # make sure we find a good name
+ name = com.get_callable_name(a) or a
+ keys.append(name)
+
+ # multiples
+ else:
+ for index, col in enumerate(selected_obj):
+ colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
+ try:
+ new_res = colg.aggregate(arg)
+ except (TypeError, DataError):
+ pass
+ except ValueError as err:
+ # cannot aggregate
+ if "Must produce aggregated value" in str(err):
+ # raised directly in _aggregate_named
+ pass
+ elif "no results" in str(err):
+ # raised directly in _aggregate_multiple_funcs
+ pass
+ else:
+ raise
+ else:
+ results.append(new_res)
+ keys.append(col)
+
+ # if we are empty
+ if not len(results):
+ raise ValueError("no results")
+
+ try:
+ return concat(results, keys=keys, axis=1, sort=False)
+ except TypeError as err:
+
+ # we are concatting non-NDFrame objects,
+ # e.g. a list of scalars
+
+ from pandas import Series
+
+ result = Series(results, index=keys, name=obj.name)
+ if is_nested_object(result):
+ raise ValueError(
+ "cannot combine transform and aggregation operations"
+ ) from err
+ return result
+
+ def agg_dict_like(self, _axis: int) -> FrameOrSeriesUnion:
+ """
+ Compute aggregation in the case of a dict-like argument.
+
+ Parameters
+ ----------
+ _axis : int, 0 or 1
+ Axis to compute aggregation on.
+
+ Returns
+ -------
+ Result of aggregation.
+ """
+ obj = self.obj
+ arg = cast(AggFuncTypeDict, self.f)
+
+ is_aggregator = lambda x: isinstance(x, (list, tuple, dict))
+
+ if _axis != 0: # pragma: no cover
+ raise ValueError("Can only pass dict with axis=0")
+
+ selected_obj = obj._selected_obj
+
+ # if we have a dict of any non-scalars
+ # eg. {'A' : ['mean']}, normalize all to
+ # be list-likes
+ # Cannot use arg.values() because arg may be a Series
+ if any(is_aggregator(x) for _, x in arg.items()):
+ new_arg: AggFuncTypeDict = {}
+ for k, v in arg.items():
+ if not isinstance(v, (tuple, list, dict)):
+ new_arg[k] = [v]
+ else:
+ new_arg[k] = v
+
+ # the keys must be in the columns
+ # for ndim=2, or renamers for ndim=1
+
+ # ok for now, but deprecated
+ # {'A': { 'ra': 'mean' }}
+ # {'A': { 'ra': ['mean'] }}
+ # {'ra': ['mean']}
+
+ # not ok
+ # {'ra' : { 'A' : 'mean' }}
+ if isinstance(v, dict):
+ raise SpecificationError("nested renamer is not supported")
+ elif isinstance(selected_obj, ABCSeries):
+ raise SpecificationError("nested renamer is not supported")
+ elif (
+ isinstance(selected_obj, ABCDataFrame)
+ and k not in selected_obj.columns
+ ):
+ raise KeyError(f"Column '{k}' does not exist!")
+
+ arg = new_arg
+
+ else:
+ # deprecation of renaming keys
+ # GH 15931
+ keys = list(arg.keys())
+ if isinstance(selected_obj, ABCDataFrame) and len(
+ selected_obj.columns.intersection(keys)
+ ) != len(keys):
+ cols = list(
+ safe_sort(
+ list(set(keys) - set(selected_obj.columns.intersection(keys))),
+ )
+ )
+ raise SpecificationError(f"Column(s) {cols} do not exist")
+
+ from pandas.core.reshape.concat import concat
+
+ if selected_obj.ndim == 1:
+ # key only used for output
+ colg = obj._gotitem(obj._selection, ndim=1)
+ results = {key: colg.agg(how) for key, how in arg.items()}
+ else:
+ # key used for column selection and output
+ results = {
+ key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items()
+ }
+
+ # set the final keys
+ keys = list(arg.keys())
+
+ # Avoid making two isinstance calls in all and any below
+ is_ndframe = [isinstance(r, ABCNDFrame) for r in results.values()]
+
+ # combine results
+ if all(is_ndframe):
+ keys_to_use = [k for k in keys if not results[k].empty]
+ # Have to check, if at least one DataFrame is not empty.
+ keys_to_use = keys_to_use if keys_to_use != [] else keys
+ axis = 0 if isinstance(obj, ABCSeries) else 1
+ result = concat({k: results[k] for k in keys_to_use}, axis=axis)
+ elif any(is_ndframe):
+ # There is a mix of NDFrames and scalars
+ raise ValueError(
+ "cannot perform both aggregation "
+ "and transformation operations "
+ "simultaneously"
+ )
+ else:
+ from pandas import Series
+
+ # we have a dict of scalars
+ # GH 36212 use name only if obj is a series
+ if obj.ndim == 1:
+ obj = cast("Series", obj)
+ name = obj.name
+ else:
+ name = None
+
+ result = Series(results, name=name)
+
+ return result
+
def maybe_apply_str(self) -> Optional[FrameOrSeriesUnion]:
"""
Compute apply in case of a string.
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index a98ef15696339..ce3619d1ce488 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -56,7 +56,6 @@
from pandas.core import algorithms, nanops
from pandas.core.aggregation import (
- agg_list_like,
maybe_mangle_lambdas,
reconstruct_func,
validate_func_kwargs,
@@ -978,7 +977,9 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
# try to treat as if we are passing a list
try:
- result = agg_list_like(self, [func], _axis=self.axis)
+ result, _ = GroupByApply(
+ self, [func], args=(), kwds={"_axis": self.axis}
+ ).agg()
# select everything except for the last level, which is the one
# containing the name of the function(s), see GH 32040
| - [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39498 | 2021-01-31T01:27:22Z | 2021-02-03T00:29:09Z | 2021-02-03T00:29:09Z | 2021-02-03T02:20:06Z |
ENH: Enable parsing of ISO8601-like timestamps with negative signs using pd.Timedelta (GH37172) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 17d8c79994dbe..95aec64109489 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -57,7 +57,7 @@ Other enhancements
- :meth:`.Styler.set_tooltips_class` and :meth:`.Styler.set_table_styles` amended to optionally allow certain css-string input arguments (:issue:`39564`)
- :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`)
- :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files.
-
+- Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 748a4c27e64ad..25e0941db75bd 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -276,7 +276,7 @@ cdef convert_to_timedelta64(object ts, str unit):
ts = cast_from_unit(ts, unit)
ts = np.timedelta64(ts, "ns")
elif isinstance(ts, str):
- if len(ts) > 0 and ts[0] == "P":
+ if (len(ts) > 0 and ts[0] == "P") or (len(ts) > 1 and ts[:2] == "-P"):
ts = parse_iso_format_string(ts)
else:
ts = parse_timedelta_string(ts)
@@ -673,13 +673,17 @@ cdef inline int64_t parse_iso_format_string(str ts) except? -1:
cdef:
unicode c
int64_t result = 0, r
- int p = 0
+ int p = 0, sign = 1
object dec_unit = 'ms', err_msg
bint have_dot = 0, have_value = 0, neg = 0
list number = [], unit = []
err_msg = f"Invalid ISO 8601 Duration format - {ts}"
+ if ts[0] == "-":
+ sign = -1
+ ts = ts[1:]
+
for c in ts:
# number (ascii codes)
if 48 <= ord(c) <= 57:
@@ -711,6 +715,8 @@ cdef inline int64_t parse_iso_format_string(str ts) except? -1:
raise ValueError(err_msg)
else:
neg = 1
+ elif c == "+":
+ pass
elif c in ['W', 'D', 'H', 'M']:
if c in ['H', 'M'] and len(number) > 2:
raise ValueError(err_msg)
@@ -751,7 +757,7 @@ cdef inline int64_t parse_iso_format_string(str ts) except? -1:
# Received string only - never parsed any values
raise ValueError(err_msg)
- return result
+ return sign*result
cdef _to_py_int_float(v):
@@ -1252,7 +1258,9 @@ class Timedelta(_Timedelta):
elif isinstance(value, str):
if unit is not None:
raise ValueError("unit must not be specified if the value is a str")
- if len(value) > 0 and value[0] == 'P':
+ if (len(value) > 0 and value[0] == 'P') or (
+ len(value) > 1 and value[:2] == '-P'
+ ):
value = parse_iso_format_string(value)
else:
value = parse_timedelta_string(value)
diff --git a/pandas/tests/scalar/timedelta/test_constructors.py b/pandas/tests/scalar/timedelta/test_constructors.py
index 64d5a5e9b3fff..de7a0dc97d565 100644
--- a/pandas/tests/scalar/timedelta/test_constructors.py
+++ b/pandas/tests/scalar/timedelta/test_constructors.py
@@ -263,6 +263,9 @@ def test_construction_out_of_bounds_td64():
("P1W", Timedelta(days=7)),
("PT300S", Timedelta(seconds=300)),
("P1DT0H0M00000000000S", Timedelta(days=1)),
+ ("PT-6H3M", Timedelta(hours=-6, minutes=3)),
+ ("-PT6H3M", Timedelta(hours=-6, minutes=-3)),
+ ("-PT-6H+3M", Timedelta(hours=6, minutes=-3)),
],
)
def test_iso_constructor(fmt, exp):
@@ -277,6 +280,8 @@ def test_iso_constructor(fmt, exp):
"P0DT999H999M999S",
"P1DT0H0M0.0000000000000S",
"P1DT0H0M0.S",
+ "P",
+ "-P",
],
)
def test_iso_constructor_raises(fmt):
| - [x] closes #37172
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39497 | 2021-01-31T00:25:28Z | 2021-02-10T23:15:25Z | 2021-02-10T23:15:25Z | 2021-02-10T23:15:29Z |
TST: read_csv with custom date parser and na_filter=True results in ValueError | diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index 25d98928f1a6b..884e3875069a3 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -34,6 +34,43 @@
date_strategy = st.datetimes()
+def test_read_csv_with_custom_date_parser(all_parsers):
+ # GH36111
+ def __custom_date_parser(time):
+ time = time.astype(np.float)
+ time = time.astype(np.int) # convert float seconds to int type
+ return pd.to_timedelta(time, unit="s")
+
+ testdata = StringIO(
+ """time e n h
+ 41047.00 -98573.7297 871458.0640 389.0089
+ 41048.00 -98573.7299 871458.0640 389.0089
+ 41049.00 -98573.7300 871458.0642 389.0088
+ 41050.00 -98573.7299 871458.0643 389.0088
+ 41051.00 -98573.7302 871458.0640 389.0086
+ """
+ )
+ result = all_parsers.read_csv(
+ testdata,
+ delim_whitespace=True,
+ parse_dates=True,
+ date_parser=__custom_date_parser,
+ index_col="time",
+ )
+ time = [41047, 41048, 41049, 41050, 41051]
+ time = pd.TimedeltaIndex([pd.to_timedelta(i, unit="s") for i in time], name="time")
+ expected = DataFrame(
+ {
+ "e": [-98573.7297, -98573.7299, -98573.7300, -98573.7299, -98573.7302],
+ "n": [871458.0640, 871458.0640, 871458.0642, 871458.0643, 871458.0640],
+ "h": [389.0089, 389.0089, 389.0088, 389.0088, 389.0086],
+ },
+ index=time,
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+
def test_separator_date_conflict(all_parsers):
# Regression test for gh-4678
#
| previous PR #39079
- [ ] closes #36111
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39496 | 2021-01-31T00:11:42Z | 2021-02-02T00:27:39Z | 2021-02-02T00:27:39Z | 2021-02-02T00:27:43Z |
TST/REF: collect index tests | diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 96fc85fcf4ae6..b756ad6051a86 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -32,7 +32,6 @@ class Base:
""" base class for index sub-class tests """
_holder: Type[Index]
- _compat_props = ["shape", "ndim", "size", "nbytes"]
def create_index(self) -> Index:
raise NotImplementedError("Method not implemented")
@@ -191,29 +190,6 @@ def test_logical_compat(self):
with pytest.raises(TypeError, match="cannot perform any"):
idx.any()
- def test_reindex_base(self):
- idx = self.create_index()
- expected = np.arange(idx.size, dtype=np.intp)
-
- actual = idx.get_indexer(idx)
- tm.assert_numpy_array_equal(expected, actual)
-
- with pytest.raises(ValueError, match="Invalid fill method"):
- idx.get_indexer(idx, method="invalid")
-
- def test_ndarray_compat_properties(self):
- idx = self.create_index()
- assert idx.T.equals(idx)
- assert idx.transpose().equals(idx)
-
- values = idx.values
- for prop in self._compat_props:
- assert getattr(idx, prop) == getattr(values, prop)
-
- # test for validity
- idx.nbytes
- idx.values.nbytes
-
def test_repr_roundtrip(self):
idx = self.create_index()
@@ -681,21 +657,6 @@ def test_map_str(self):
expected = Index([str(x) for x in index], dtype=object)
tm.assert_index_equal(result, expected)
- def test_putmask_with_wrong_mask(self):
- # GH18368
- index = self.create_index()
- fill = index[0]
-
- msg = "putmask: mask and data must be the same size"
- with pytest.raises(ValueError, match=msg):
- index.putmask(np.ones(len(index) + 1, np.bool_), fill)
-
- with pytest.raises(ValueError, match=msg):
- index.putmask(np.ones(len(index) - 1, np.bool_), fill)
-
- with pytest.raises(ValueError, match=msg):
- index.putmask("foo", fill)
-
@pytest.mark.parametrize("copy", [True, False])
@pytest.mark.parametrize("name", [None, "foo"])
@pytest.mark.parametrize("ordered", [True, False])
@@ -760,25 +721,6 @@ def test_getitem_2d_deprecated(self):
assert isinstance(res, np.ndarray), type(res)
- def test_contains_requires_hashable_raises(self):
- idx = self.create_index()
-
- msg = "unhashable type: 'list'"
- with pytest.raises(TypeError, match=msg):
- [] in idx
-
- msg = "|".join(
- [
- r"unhashable type: 'dict'",
- r"must be real number, not dict",
- r"an integer is required",
- r"\{\}",
- r"pandas\._libs\.interval\.IntervalTree' is not iterable",
- ]
- )
- with pytest.raises(TypeError, match=msg):
- {} in idx._engine
-
def test_copy_shares_cache(self):
# GH32898, GH36840
idx = self.create_index()
diff --git a/pandas/tests/indexes/multi/conftest.py b/pandas/tests/indexes/multi/conftest.py
index a77af84ee1ed0..ce477485bb21e 100644
--- a/pandas/tests/indexes/multi/conftest.py
+++ b/pandas/tests/indexes/multi/conftest.py
@@ -5,6 +5,7 @@
from pandas import Index, MultiIndex
+# Note: identical the the "multi" entry in the top-level "index" fixture
@pytest.fixture
def idx():
# a MultiIndex used to test the general functionality of the
@@ -49,12 +50,6 @@ def index_names():
return ["first", "second"]
-@pytest.fixture
-def compat_props():
- # a MultiIndex must have these properties associated with it
- return ["shape", "ndim", "size"]
-
-
@pytest.fixture
def narrow_multi_index():
"""
diff --git a/pandas/tests/indexes/multi/test_compat.py b/pandas/tests/indexes/multi/test_compat.py
index 72b5ed0edaa78..d2b5a595b8454 100644
--- a/pandas/tests/indexes/multi/test_compat.py
+++ b/pandas/tests/indexes/multi/test_compat.py
@@ -35,32 +35,6 @@ def test_logical_compat(idx, method):
getattr(idx, method)()
-def test_boolean_context_compat(idx):
-
- msg = (
- "The truth value of a MultiIndex is ambiguous. "
- r"Use a.empty, a.bool\(\), a.item\(\), a.any\(\) or a.all\(\)."
- )
- with pytest.raises(ValueError, match=msg):
- bool(idx)
-
-
-def test_boolean_context_compat2():
-
- # boolean context compat
- # GH7897
- i1 = MultiIndex.from_tuples([("A", 1), ("A", 2)])
- i2 = MultiIndex.from_tuples([("A", 1), ("A", 3)])
- common = i1.intersection(i2)
-
- msg = (
- r"The truth value of a MultiIndex is ambiguous\. "
- r"Use a\.empty, a\.bool\(\), a\.item\(\), a\.any\(\) or a\.all\(\)\."
- )
- with pytest.raises(ValueError, match=msg):
- bool(common)
-
-
def test_inplace_mutation_resets_values():
levels = [["a", "b", "c"], [4]]
levels2 = [[1, 2, 3], ["a"]]
@@ -124,19 +98,6 @@ def test_inplace_mutation_resets_values():
assert "_values" in mi2._cache
-def test_ndarray_compat_properties(idx, compat_props):
- assert idx.T.equals(idx)
- assert idx.transpose().equals(idx)
-
- values = idx.values
- for prop in compat_props:
- assert getattr(idx, prop) == getattr(values, prop)
-
- # test for validity
- idx.nbytes
- idx.values.nbytes
-
-
def test_pickle_compat_construction():
# this is testing for pickle compat
# need an object to create with
diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py
index b0de16a25bcc3..377ae7533ba08 100644
--- a/pandas/tests/indexes/period/test_period.py
+++ b/pandas/tests/indexes/period/test_period.py
@@ -2,7 +2,6 @@
import pytest
from pandas._libs.tslibs.period import IncompatibleFrequency
-import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
@@ -329,10 +328,6 @@ def test_shift(self):
# This is tested in test_arithmetic
pass
- @td.skip_if_32bit
- def test_ndarray_compat_properties(self):
- super().test_ndarray_compat_properties()
-
def test_negative_ordinals(self):
Period(ordinal=-1000, freq="A")
Period(ordinal=0, freq="A")
diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py
index 40cd812ebe368..b34fb44a57c7e 100644
--- a/pandas/tests/indexes/ranges/test_range.py
+++ b/pandas/tests/indexes/ranges/test_range.py
@@ -18,7 +18,6 @@
class TestRangeIndex(Numeric):
_holder = RangeIndex
- _compat_props = ["shape", "ndim", "size"]
@pytest.fixture(
params=[
diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py
index c8629fdf1e3a6..c9c86f9eebde9 100644
--- a/pandas/tests/indexes/test_any_index.py
+++ b/pandas/tests/indexes/test_any_index.py
@@ -11,10 +11,14 @@
def test_boolean_context_compat(index):
+ # GH#7897
with pytest.raises(ValueError, match="The truth value of a"):
if index:
pass
+ with pytest.raises(ValueError, match="The truth value of a"):
+ bool(index)
+
def test_sort(index):
msg = "cannot sort an Index object in-place, use sort_values instead"
@@ -27,6 +31,12 @@ def test_hash_error(index):
hash(index)
+def test_copy_dtype_deprecated(index):
+ # GH#35853
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ index.copy(dtype=object)
+
+
def test_mutability(index):
if not len(index):
return
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 2b49ea00d3322..931f01cecab0b 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -9,6 +9,7 @@
import pytest
from pandas._libs.tslibs import iNaT
+from pandas.compat import IS64
from pandas.core.dtypes.common import is_period_dtype, needs_i8_conversion
@@ -398,3 +399,25 @@ def test_sort_values_with_missing(request, index_with_missing, na_position):
result = index_with_missing.sort_values(na_position=na_position)
tm.assert_index_equal(result, expected)
+
+
+def test_ndarray_compat_properties(index):
+ if isinstance(index, PeriodIndex) and not IS64:
+ pytest.skip("Overflow")
+ idx = index
+ assert idx.T.equals(idx)
+ assert idx.transpose().equals(idx)
+
+ values = idx.values
+
+ assert idx.shape == values.shape
+ assert idx.ndim == values.ndim
+ assert idx.size == values.size
+
+ if not isinstance(index, (RangeIndex, MultiIndex)):
+ # These two are not backed by an ndarray
+ assert idx.nbytes == values.nbytes
+
+ # test for validity
+ idx.nbytes
+ idx.values.nbytes
diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py
index 04f7a65bd5c56..8d2637e4a06f6 100644
--- a/pandas/tests/indexes/test_indexing.py
+++ b/pandas/tests/indexes/test_indexing.py
@@ -24,6 +24,7 @@
Index,
Int64Index,
IntervalIndex,
+ MultiIndex,
PeriodIndex,
Series,
TimedeltaIndex,
@@ -140,6 +141,26 @@ def test_contains_with_float_index(self):
assert 1.0 not in float_index
assert 1 not in float_index
+ def test_contains_requires_hashable_raises(self, index):
+ if isinstance(index, MultiIndex):
+ return # TODO: do we want this to raise?
+
+ msg = "unhashable type: 'list'"
+ with pytest.raises(TypeError, match=msg):
+ [] in index
+
+ msg = "|".join(
+ [
+ r"unhashable type: 'dict'",
+ r"must be real number, not dict",
+ r"an integer is required",
+ r"\{\}",
+ r"pandas\._libs\.interval\.IntervalTree' is not iterable",
+ ]
+ )
+ with pytest.raises(TypeError, match=msg):
+ {} in index._engine
+
class TestGetValue:
@pytest.mark.parametrize(
@@ -161,19 +182,30 @@ def test_get_value(self, index):
class TestGetIndexer:
+ def test_get_indexer_base(self, index):
+
+ if index._index_as_unique:
+ expected = np.arange(index.size, dtype=np.intp)
+ actual = index.get_indexer(index)
+ tm.assert_numpy_array_equal(expected, actual)
+ else:
+ msg = "Reindexing only valid with uniquely valued Index objects"
+ with pytest.raises(InvalidIndexError, match=msg):
+ index.get_indexer(index)
+
+ with pytest.raises(ValueError, match="Invalid fill method"):
+ index.get_indexer(index, method="invalid")
+
def test_get_indexer_consistency(self, index):
# See GH#16819
- if isinstance(index, IntervalIndex):
- # requires index.is_non_overlapping
- return
- if index.is_unique:
+ if index._index_as_unique:
indexer = index.get_indexer(index[0:2])
assert isinstance(indexer, np.ndarray)
assert indexer.dtype == np.intp
else:
- e = "Reindexing only valid with uniquely valued Index objects"
- with pytest.raises(InvalidIndexError, match=e):
+ msg = "Reindexing only valid with uniquely valued Index objects"
+ with pytest.raises(InvalidIndexError, match=msg):
index.get_indexer(index[0:2])
indexer, _ = index.get_indexer_non_unique(index[0:2])
@@ -197,6 +229,25 @@ def test_convert_almost_null_slice(self, index):
index._convert_slice_indexer(key, "loc")
+class TestPutmask:
+ def test_putmask_with_wrong_mask(self, index):
+ # GH#18368
+ if not len(index):
+ return
+
+ fill = index[0]
+
+ msg = "putmask: mask and data must be the same size"
+ with pytest.raises(ValueError, match=msg):
+ index.putmask(np.ones(len(index) + 1, np.bool_), fill)
+
+ with pytest.raises(ValueError, match=msg):
+ index.putmask(np.ones(len(index) - 1, np.bool_), fill)
+
+ with pytest.raises(ValueError, match=msg):
+ index.putmask("foo", fill)
+
+
@pytest.mark.parametrize(
"idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
)
| Moving away from creat_index and towards the index fixture | https://api.github.com/repos/pandas-dev/pandas/pulls/39495 | 2021-01-31T00:05:40Z | 2021-02-01T23:44:07Z | 2021-02-01T23:44:07Z | 2021-02-01T23:56:15Z |
CI: update for numpy 1.20 | diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index b6e4c38ef7f0e..1cd352e4e0899 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -7,7 +7,6 @@
import numpy as np
import pytest
-from pandas.compat import is_numpy_dev
import pandas.util._test_decorators as td
import pandas as pd
@@ -978,7 +977,6 @@ def test_loc_setitem_empty_append_single_value(self):
df.loc[0, "x"] = expected.loc[0, "x"]
tm.assert_frame_equal(df, expected)
- @pytest.mark.xfail(is_numpy_dev, reason="gh-35481")
def test_loc_setitem_empty_append_raises(self):
# GH6173, various appends to an empty dataframe
@@ -992,7 +990,12 @@ def test_loc_setitem_empty_append_raises(self):
with pytest.raises(KeyError, match=msg):
df.loc[[0, 1], "x"] = data
- msg = "cannot copy sequence with size 2 to array axis with dimension 0"
+ msg = "|".join(
+ [
+ "cannot copy sequence with size 2 to array axis with dimension 0",
+ r"could not broadcast input array from shape \(2,\) into shape \(0,\)",
+ ]
+ )
with pytest.raises(ValueError, match=msg):
df.loc[0:2, "x"] = data
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39494 | 2021-01-30T22:26:38Z | 2021-01-31T22:07:15Z | 2021-01-31T22:07:15Z | 2021-02-01T15:19:08Z |
ASV: add benchmarks for concatenating and appending of CategoricalIndex (GH38149) | diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py
index f3b005b704014..f4a6ed5f26c89 100644
--- a/asv_bench/benchmarks/categoricals.py
+++ b/asv_bench/benchmarks/categoricals.py
@@ -118,12 +118,29 @@ def setup(self):
self.a = pd.Categorical(list("aabbcd") * N)
self.b = pd.Categorical(list("bbcdjk") * N)
+ self.idx_a = pd.CategoricalIndex(range(N), range(N))
+ self.idx_b = pd.CategoricalIndex(range(N + 1), range(N + 1))
+ self.df_a = pd.DataFrame(range(N), columns=["a"], index=self.idx_a)
+ self.df_b = pd.DataFrame(range(N + 1), columns=["a"], index=self.idx_b)
+
def time_concat(self):
pd.concat([self.s, self.s])
def time_union(self):
union_categoricals([self.a, self.b])
+ def time_append_overlapping_index(self):
+ self.idx_a.append(self.idx_a)
+
+ def time_append_non_overlapping_index(self):
+ self.idx_a.append(self.idx_b)
+
+ def time_concat_overlapping_index(self):
+ pd.concat([self.df_a, self.df_a])
+
+ def time_concat_non_overlapping_index(self):
+ pd.concat([self.df_a, self.df_b])
+
class ValueCounts:
|
- [x] closes #38149
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39493 | 2021-01-30T22:13:02Z | 2021-02-07T16:48:03Z | 2021-02-07T16:48:03Z | 2021-02-07T16:48:07Z |
DOC: Document how encoding errors are handled | diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index 37814a5debf2e..5aa8a6f9f0ad4 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -270,6 +270,11 @@
Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .
+ .. versionchanged:: 1.2
+
+ When ``encoding`` is ``None``, ``errors="replace"`` is passed to
+ ``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``.
+ This behavior was previously only the case for ``engine="python"``.
dialect : str or csv.Dialect, optional
If provided, this parameter will override values (default or not) for the
following parameters: `delimiter`, `doublequote`, `escapechar`,
| xref #39450
This should probably go in 1.2.2.
<1.2.0: `engine=c` and `engine=python` handled encoding errors differently when `encoding=None` (python: "replace", c: "strict"). The `engine=c` further supported to ignore lines (`skiprows`) with encoding errors iff `encoding=None`.
1.2.0 (shared file opening code between `engine=c` and `engine=python`): both engine mistakenly used "strict" when `encoding=None`. `engine=c`+`encoding=None` can no longer skip encoding errors.
1.2.1: both engine use "replace" when `encoding=None`. Both engines can ignore encoding errors in skipped rows iff `encoding=None`.
Option for 1.3: default to "strict" but expose `errors` in `read_csv` (and other read calls that might need it)?
| https://api.github.com/repos/pandas-dev/pandas/pulls/39492 | 2021-01-30T21:37:13Z | 2021-02-02T01:39:26Z | 2021-02-02T01:39:26Z | 2021-02-02T10:07:00Z |
TST: Verify plot order of a Series (GH38865) | diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py
index 9cd13b2312ea7..b4848f80e9a2c 100644
--- a/pandas/tests/plotting/test_series.py
+++ b/pandas/tests/plotting/test_series.py
@@ -752,6 +752,25 @@ def test_plot_no_numeric_data(self):
with pytest.raises(TypeError, match="no numeric data to plot"):
df.plot()
+ @pytest.mark.parametrize(
+ "data, index",
+ [
+ ([1, 2, 3, 4], [3, 2, 1, 0]),
+ ([10, 50, 20, 30], [1910, 1920, 1980, 1950]),
+ ],
+ )
+ def test_plot_order(self, data, index):
+ # GH38865 Verify plot order of a Series
+ ser = Series(data=data, index=index)
+ ax = ser.plot(kind="bar")
+
+ expected = ser.tolist()
+ result = [
+ patch.get_bbox().ymax
+ for patch in sorted(ax.patches, key=lambda patch: patch.get_bbox().xmax)
+ ]
+ assert expected == result
+
def test_style_single_ok(self):
s = Series([1, 2])
ax = s.plot(style="s", color="C3")
| - [x] closes #38865
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39491 | 2021-01-30T20:37:14Z | 2021-02-02T01:42:42Z | 2021-02-02T01:42:42Z | 2021-02-02T01:42:46Z |
Backport PR #39487 on branch 1.2.x (CI: Pin pyarrow to 0.15.1 in 37 macos and linux) | diff --git a/ci/deps/azure-37.yaml b/ci/deps/azure-37.yaml
index 82cb6760b6d1e..4fe3de161960c 100644
--- a/ci/deps/azure-37.yaml
+++ b/ci/deps/azure-37.yaml
@@ -18,7 +18,7 @@ dependencies:
- numpy
- python-dateutil
- nomkl
- - pyarrow
+ - pyarrow=0.15.1
- pytz
- s3fs>=0.4.0
- moto>=1.3.14
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 0b8aff83fe230..d667adddda859 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -21,7 +21,7 @@ dependencies:
- numexpr
- numpy=1.16.5
- openpyxl
- - pyarrow>=0.15.0
+ - pyarrow=0.15.1
- pytables
- python-dateutil==2.7.3
- pytz
| Backport PR #39487: CI: Pin pyarrow to 0.15.1 in 37 macos and linux | https://api.github.com/repos/pandas-dev/pandas/pulls/39490 | 2021-01-30T20:27:21Z | 2021-02-01T13:43:31Z | 2021-02-01T13:43:31Z | 2021-02-01T13:43:31Z |
BUG: setting td64 value into numeric Series incorrectly casting to int | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 205bbcc07fc76..5303d337c8cd7 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4331,7 +4331,15 @@ def where(self, cond, other=None):
except (ValueError, TypeError):
return self.astype(object).where(cond, other)
- values = np.where(cond, values, other)
+ if isinstance(other, np.timedelta64) and self.dtype == object:
+ # https://github.com/numpy/numpy/issues/12550
+ # timedelta64 will incorrectly cast to int
+ other = [other] * (~cond).sum()
+ values = cast(np.ndarray, values).copy()
+ # error: Unsupported target for indexed assignment ("ArrayLike")
+ values[~cond] = other # type:ignore[index]
+ else:
+ values = np.where(cond, values, other)
return Index(values, name=self.name)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 77f4263214529..338f949e00142 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -29,7 +29,6 @@
infer_dtype_from,
maybe_downcast_numeric,
maybe_downcast_to_dtype,
- maybe_promote,
maybe_upcast,
soft_convert_objects,
)
@@ -1031,6 +1030,12 @@ def putmask(self, mask, new) -> List[Block]:
elif not mask.any():
return [self]
+ elif isinstance(new, np.timedelta64):
+ # using putmask with object dtype will incorrect cast to object
+ # Having excluded self._can_hold_element, we know we cannot operate
+ # in-place, so we are safe using `where`
+ return self.where(new, ~mask)
+
else:
# may need to upcast
if transpose:
@@ -1052,7 +1057,7 @@ def f(mask, val, idx):
n = np.array(new)
# type of the new block
- dtype, _ = maybe_promote(n.dtype)
+ dtype = find_common_type([n.dtype, val.dtype])
# we need to explicitly astype here to make a copy
n = n.astype(dtype)
@@ -1311,12 +1316,18 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
blocks = block.where(orig_other, cond, errors=errors, axis=axis)
return self._maybe_downcast(blocks, "infer")
- # convert datetime to datetime64, timedelta to timedelta64
- other = convert_scalar_for_putitemlike(other, values.dtype)
+ elif isinstance(other, np.timedelta64):
+ # expressions.where will cast np.timedelta64 to int
+ result = self.values.copy()
+ result[~cond] = [other] * (~cond).sum()
+
+ else:
+ # convert datetime to datetime64, timedelta to timedelta64
+ other = convert_scalar_for_putitemlike(other, values.dtype)
- # By the time we get here, we should have all Series/Index
- # args extracted to ndarray
- result = expressions.where(cond, values, other)
+ # By the time we get here, we should have all Series/Index
+ # args extracted to ndarray
+ result = expressions.where(cond, values, other)
if self._can_hold_na or self.ndim == 1:
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 8c40ef6261d19..bbf3715d8e022 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -3,6 +3,8 @@
import numpy as np
import pytest
+from pandas.compat import np_version_under1p20
+
from pandas import (
DatetimeIndex,
Index,
@@ -516,25 +518,127 @@ def test_setitem_slice_into_readonly_backing_data():
assert not array.any()
-@pytest.mark.parametrize(
- "key", [0, slice(0, 1), [0], np.array([0]), range(1)], ids=type
-)
-@pytest.mark.parametrize("dtype", [complex, int, float])
-def test_setitem_td64_into_complex(key, dtype, indexer_sli):
- # timedelta64 should not be treated as integers
- arr = np.arange(5).astype(dtype)
- ser = Series(arr)
- td = np.timedelta64(4, "ns")
-
- indexer_sli(ser)[key] = td
- assert ser.dtype == object
- assert arr[0] == 0 # original array is unchanged
-
- if not isinstance(key, int) and not (
- indexer_sli is tm.loc and isinstance(key, slice)
- ):
- # skip key/indexer_sli combinations that will have mismatched lengths
+class TestSetitemCastingEquivalentsTimedelta64IntoNumeric:
+ # timedelta64 should not be treated as integers when setting into
+ # numeric Series
+
+ @pytest.fixture
+ def val(self):
+ td = np.timedelta64(4, "ns")
+ return td
+ return np.full((1,), td)
+
+ @pytest.fixture(params=[complex, int, float])
+ def dtype(self, request):
+ return request.param
+
+ @pytest.fixture
+ def obj(self, dtype):
+ arr = np.arange(5).astype(dtype)
+ ser = Series(arr)
+ return ser
+
+ @pytest.fixture
+ def expected(self, dtype):
+ arr = np.arange(5).astype(dtype)
ser = Series(arr)
- indexer_sli(ser)[key] = np.full((1,), td)
- assert ser.dtype == object
- assert arr[0] == 0 # original array is unchanged
+ ser = ser.astype(object)
+ ser.values[0] = np.timedelta64(4, "ns")
+ return ser
+
+ @pytest.fixture
+ def key(self):
+ return 0
+
+ def check_indexer(self, obj, key, expected, val, indexer):
+ orig = obj
+ obj = obj.copy()
+ arr = obj._values
+
+ indexer(obj)[key] = val
+ tm.assert_series_equal(obj, expected)
+
+ tm.assert_equal(arr, orig._values) # original array is unchanged
+
+ def test_int_key(self, obj, key, expected, val, indexer_sli):
+ if not isinstance(key, int):
+ return
+
+ self.check_indexer(obj, key, expected, val, indexer_sli)
+
+ rng = range(key, key + 1)
+ self.check_indexer(obj, rng, expected, val, indexer_sli)
+
+ if indexer_sli is not tm.loc:
+ # Note: no .loc because that handles slice edges differently
+ slc = slice(key, key + 1)
+ self.check_indexer(obj, slc, expected, val, indexer_sli)
+
+ ilkey = [key]
+ self.check_indexer(obj, ilkey, expected, val, indexer_sli)
+
+ indkey = np.array(ilkey)
+ self.check_indexer(obj, indkey, expected, val, indexer_sli)
+
+ def test_slice_key(self, obj, key, expected, val, indexer_sli):
+ if not isinstance(key, slice):
+ return
+
+ if indexer_sli is not tm.loc:
+ # Note: no .loc because that handles slice edges differently
+ self.check_indexer(obj, key, expected, val, indexer_sli)
+
+ ilkey = list(range(len(obj)))[key]
+ self.check_indexer(obj, ilkey, expected, val, indexer_sli)
+
+ indkey = np.array(ilkey)
+ self.check_indexer(obj, indkey, expected, val, indexer_sli)
+
+ def test_mask_key(self, obj, key, expected, val, indexer_sli):
+ # setitem with boolean mask
+ mask = np.zeros(obj.shape, dtype=bool)
+ mask[key] = True
+
+ self.check_indexer(obj, mask, expected, val, indexer_sli)
+
+ def test_series_where(self, obj, key, expected, val):
+ mask = np.zeros(obj.shape, dtype=bool)
+ mask[key] = True
+
+ orig = obj
+ obj = obj.copy()
+ arr = obj._values
+ res = obj.where(~mask, val)
+ tm.assert_series_equal(res, expected)
+
+ tm.assert_equal(arr, orig._values) # original array is unchanged
+
+ def test_index_where(self, obj, key, expected, val, request):
+ if Index(obj).dtype != obj.dtype:
+ pytest.skip("test not applicable for this dtype")
+
+ mask = np.zeros(obj.shape, dtype=bool)
+ mask[key] = True
+
+ if obj.dtype == bool and not mask.all():
+ # When mask is all True, casting behavior does not apply
+ msg = "Index/Series casting behavior inconsistent GH#38692"
+ mark = pytest.mark.xfail(reason=msg)
+ request.node.add_marker(mark)
+
+ res = Index(obj).where(~mask, val)
+ tm.assert_index_equal(res, Index(expected))
+
+ @pytest.mark.xfail(
+ np_version_under1p20,
+ reason="Index/Series casting behavior inconsistent GH#38692",
+ )
+ def test_index_putmask(self, obj, key, expected, val):
+ if Index(obj).dtype != obj.dtype:
+ pytest.skip("test not applicable for this dtype")
+
+ mask = np.zeros(obj.shape, dtype=bool)
+ mask[key] = True
+
+ res = Index(obj).putmask(mask, val)
+ tm.assert_index_equal(res, Index(expected))
| - [ ] closes #xxxx
- [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
- [ ] whatsnew entry
We fixed this a few days ago for some of the setting-methods, but there were a few we missed. Re-using the TestSetitemEquivalents pattern is much more thorough.
We'll be able to de-duplicate the test class following #39477 | https://api.github.com/repos/pandas-dev/pandas/pulls/39488 | 2021-01-30T19:12:19Z | 2021-02-03T01:31:04Z | 2021-02-03T01:31:04Z | 2021-02-03T02:11:38Z |
CI: Pin pyarrow to 0.15.1 in 37 macos and linux | diff --git a/ci/deps/azure-37.yaml b/ci/deps/azure-37.yaml
index 82cb6760b6d1e..4fe3de161960c 100644
--- a/ci/deps/azure-37.yaml
+++ b/ci/deps/azure-37.yaml
@@ -18,7 +18,7 @@ dependencies:
- numpy
- python-dateutil
- nomkl
- - pyarrow
+ - pyarrow=0.15.1
- pytz
- s3fs>=0.4.0
- moto>=1.3.14
diff --git a/ci/deps/azure-macos-37.yaml b/ci/deps/azure-macos-37.yaml
index 0b8aff83fe230..d667adddda859 100644
--- a/ci/deps/azure-macos-37.yaml
+++ b/ci/deps/azure-macos-37.yaml
@@ -21,7 +21,7 @@ dependencies:
- numexpr
- numpy=1.16.5
- openpyxl
- - pyarrow>=0.15.0
+ - pyarrow=0.15.1
- pytables
- python-dateutil==2.7.3
- pytz
| Pyarrow 2.0.0 instead of 0.15.1 is fetched on these builds since today, which causes test failures | https://api.github.com/repos/pandas-dev/pandas/pulls/39487 | 2021-01-30T19:07:06Z | 2021-01-30T20:26:24Z | 2021-01-30T20:26:24Z | 2021-01-30T20:29:02Z |
BUG: read_excel with openpyxl and missing dimension | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 0ee1abaa2a0eb..cc5653fe2f360 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -31,6 +31,7 @@ Bug fixes
~~~~~~~~~
- :func:`pandas.read_excel` error message when a specified ``sheetname`` does not exist is now uniform across engines (:issue:`39250`)
+- Fixed bug in :func:`pandas.read_excel` producing incorrect results when the engine ``openpyxl`` is used and the excel file is missing or has incorrect dimension information; the fix requires ``openpyxl`` >= 3.0.0, prior versions may still fail (:issue:`38956`, :issue:`39001`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 35c7b6547431f..bcad9f1ddab09 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -17,7 +17,7 @@
"matplotlib": "2.2.3",
"numexpr": "2.6.8",
"odfpy": "1.3.0",
- "openpyxl": "2.5.7",
+ "openpyxl": "2.6.0",
"pandas_gbq": "0.12.0",
"pyarrow": "0.15.0",
"pytest": "5.0.1",
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index 56df791a40ce0..64c64b5009b0c 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -1,11 +1,12 @@
from __future__ import annotations
+from distutils.version import LooseVersion
from typing import TYPE_CHECKING, Dict, List, Optional
import numpy as np
from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
-from pandas.compat._optional import import_optional_dependency
+from pandas.compat._optional import get_version, import_optional_dependency
from pandas.io.excel._base import BaseExcelReader, ExcelWriter
from pandas.io.excel._util import validate_freeze_panes
@@ -505,14 +506,14 @@ def _convert_cell(self, cell, convert_float: bool) -> Scalar:
from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC
- if cell.is_date:
+ if cell.value is None:
+ return "" # compat with xlrd
+ elif cell.is_date:
return cell.value
elif cell.data_type == TYPE_ERROR:
return np.nan
elif cell.data_type == TYPE_BOOL:
return bool(cell.value)
- elif cell.value is None:
- return "" # compat with xlrd
elif cell.data_type == TYPE_NUMERIC:
# GH5394
if convert_float:
@@ -525,8 +526,29 @@ def _convert_cell(self, cell, convert_float: bool) -> Scalar:
return cell.value
def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
+ # GH 39001
+ # Reading of excel file depends on dimension data being correct but
+ # writers sometimes omit or get it wrong
+ import openpyxl
+
+ version = LooseVersion(get_version(openpyxl))
+
+ if version >= "3.0.0":
+ sheet.reset_dimensions()
+
data: List[List[Scalar]] = []
- for row in sheet.rows:
- data.append([self._convert_cell(cell, convert_float) for cell in row])
+ for row_number, row in enumerate(sheet.rows):
+ converted_row = [self._convert_cell(cell, convert_float) for cell in row]
+ data.append(converted_row)
+
+ if version >= "3.0.0" and len(data) > 0:
+ # With dimension reset, openpyxl no longer pads rows
+ max_width = max(len(data_row) for data_row in data)
+ if min(len(data_row) for data_row in data) < max_width:
+ empty_cell: List[Scalar] = [""]
+ data = [
+ data_row + (max_width - len(data_row)) * empty_cell
+ for data_row in data
+ ]
return data
diff --git a/pandas/tests/io/data/excel/dimension_large.xlsx b/pandas/tests/io/data/excel/dimension_large.xlsx
new file mode 100644
index 0000000000000..d57abdf2fbbae
Binary files /dev/null and b/pandas/tests/io/data/excel/dimension_large.xlsx differ
diff --git a/pandas/tests/io/data/excel/dimension_missing.xlsx b/pandas/tests/io/data/excel/dimension_missing.xlsx
new file mode 100644
index 0000000000000..9274896689a72
Binary files /dev/null and b/pandas/tests/io/data/excel/dimension_missing.xlsx differ
diff --git a/pandas/tests/io/data/excel/dimension_small.xlsx b/pandas/tests/io/data/excel/dimension_small.xlsx
new file mode 100644
index 0000000000000..78ce4723ebef4
Binary files /dev/null and b/pandas/tests/io/data/excel/dimension_small.xlsx differ
diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py
index 3155e22d3ff5d..640501baffc62 100644
--- a/pandas/tests/io/excel/test_openpyxl.py
+++ b/pandas/tests/io/excel/test_openpyxl.py
@@ -1,6 +1,10 @@
+from distutils.version import LooseVersion
+
import numpy as np
import pytest
+from pandas.compat._optional import get_version
+
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
@@ -116,3 +120,32 @@ def test_to_excel_with_openpyxl_engine(ext):
).highlight_max()
styled.to_excel(filename, engine="openpyxl")
+
+
+@pytest.mark.parametrize(
+ "header, expected_data",
+ [
+ (
+ 0,
+ {
+ "Title": [np.nan, "A", 1, 2, 3],
+ "Unnamed: 1": [np.nan, "B", 4, 5, 6],
+ "Unnamed: 2": [np.nan, "C", 7, 8, 9],
+ },
+ ),
+ (2, {"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}),
+ ],
+)
+@pytest.mark.parametrize(
+ "filename", ["dimension_missing", "dimension_small", "dimension_large"]
+)
+@pytest.mark.xfail(
+ LooseVersion(get_version(openpyxl)) < "3.0.0",
+ reason="openpyxl read-only sheet is incorrect when dimension data is wrong",
+)
+def test_read_with_bad_dimension(datapath, ext, header, expected_data, filename):
+ # GH 38956, 39001 - no/incorrect dimension information
+ path = datapath("io", "data", "excel", f"{filename}{ext}")
+ result = pd.read_excel(path, header=header)
+ expected = DataFrame(expected_data)
+ tm.assert_frame_equal(result, expected)
| - [x] closes #38956
- [x] closes #39001
- [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
Targeted for 1.2.2 because this resolves an issue that occurs from the change of default engine from xlrd to openpyxl in 1.2. | https://api.github.com/repos/pandas-dev/pandas/pulls/39486 | 2021-01-30T18:55:51Z | 2021-02-05T03:15:59Z | 2021-02-05T03:15:58Z | 2021-02-07T12:05:14Z |
TST/REF: collect index tests | diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 6874db66a8597..96fc85fcf4ae6 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -5,7 +5,6 @@
import pytest
from pandas._libs import iNaT
-from pandas.errors import InvalidIndexError
from pandas.core.dtypes.common import is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import CategoricalDtype
@@ -202,25 +201,6 @@ def test_reindex_base(self):
with pytest.raises(ValueError, match="Invalid fill method"):
idx.get_indexer(idx, method="invalid")
- def test_get_indexer_consistency(self, index):
- # See GH 16819
- if isinstance(index, IntervalIndex):
- # requires index.is_non_overlapping
- return
-
- if index.is_unique:
- indexer = index.get_indexer(index[0:2])
- assert isinstance(indexer, np.ndarray)
- assert indexer.dtype == np.intp
- else:
- e = "Reindexing only valid with uniquely valued Index objects"
- with pytest.raises(InvalidIndexError, match=e):
- index.get_indexer(index[0:2])
-
- indexer, _ = index.get_indexer_non_unique(index[0:2])
- assert isinstance(indexer, np.ndarray)
- assert indexer.dtype == np.intp
-
def test_ndarray_compat_properties(self):
idx = self.create_index()
assert idx.T.equals(idx)
diff --git a/pandas/tests/indexes/datetimelike_/test_indexing.py b/pandas/tests/indexes/datetimelike_/test_indexing.py
new file mode 100644
index 0000000000000..51de446eea3e3
--- /dev/null
+++ b/pandas/tests/indexes/datetimelike_/test_indexing.py
@@ -0,0 +1,43 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import DatetimeIndex, Index
+import pandas._testing as tm
+
+dtlike_dtypes = [
+ np.dtype("timedelta64[ns]"),
+ np.dtype("datetime64[ns]"),
+ pd.DatetimeTZDtype("ns", "Asia/Tokyo"),
+ pd.PeriodDtype("ns"),
+]
+
+
+@pytest.mark.parametrize("ldtype", dtlike_dtypes)
+@pytest.mark.parametrize("rdtype", dtlike_dtypes)
+def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype):
+
+ vals = np.tile(3600 * 10 ** 9 * np.arange(3), 2)
+
+ def construct(dtype):
+ if dtype is dtlike_dtypes[-1]:
+ # PeriodArray will try to cast ints to strings
+ return DatetimeIndex(vals).astype(dtype)
+ return Index(vals, dtype=dtype)
+
+ left = construct(ldtype)
+ right = construct(rdtype)
+
+ result = left.get_indexer_non_unique(right)
+
+ if ldtype is rdtype:
+ ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp)
+ ex2 = np.array([], dtype=np.intp)
+ tm.assert_numpy_array_equal(result[0], ex1)
+ tm.assert_numpy_array_equal(result[1], ex2)
+
+ else:
+ no_matches = np.array([-1] * 6, dtype=np.intp)
+ missing = np.arange(6, dtype=np.intp)
+ tm.assert_numpy_array_equal(result[0], no_matches)
+ tm.assert_numpy_array_equal(result[1], missing)
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py
index 7420cac2f9da4..33f927bdd7c04 100644
--- a/pandas/tests/indexes/numeric/test_indexing.py
+++ b/pandas/tests/indexes/numeric/test_indexing.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas import Float64Index, Index, Int64Index, Series, UInt64Index
+from pandas import Float64Index, Index, Int64Index, RangeIndex, Series, UInt64Index
import pandas._testing as tm
@@ -13,6 +13,54 @@ def index_large():
class TestGetLoc:
+ @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"])
+ def test_get_loc(self, method):
+ index = Index([0, 1, 2])
+ assert index.get_loc(1, method=method) == 1
+
+ if method:
+ assert index.get_loc(1, method=method, tolerance=0) == 1
+
+ @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"])
+ def test_get_loc_raises_bad_label(self, method):
+ index = Index([0, 1, 2])
+ if method:
+ msg = "not supported between"
+ else:
+ msg = "invalid key"
+
+ with pytest.raises(TypeError, match=msg):
+ index.get_loc([1, 2], method=method)
+
+ @pytest.mark.parametrize(
+ "method,loc", [("pad", 1), ("backfill", 2), ("nearest", 1)]
+ )
+ def test_get_loc_tolerance(self, method, loc):
+ index = Index([0, 1, 2])
+ assert index.get_loc(1.1, method) == loc
+ assert index.get_loc(1.1, method, tolerance=1) == loc
+
+ @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
+ def test_get_loc_outside_tolerance_raises(self, method):
+ index = Index([0, 1, 2])
+ with pytest.raises(KeyError, match="1.1"):
+ index.get_loc(1.1, method, tolerance=0.05)
+
+ def test_get_loc_bad_tolerance_raises(self):
+ index = Index([0, 1, 2])
+ with pytest.raises(ValueError, match="must be numeric"):
+ index.get_loc(1.1, "nearest", tolerance="invalid")
+
+ def test_get_loc_tolerance_no_method_raises(self):
+ index = Index([0, 1, 2])
+ with pytest.raises(ValueError, match="tolerance .* valid if"):
+ index.get_loc(1.1, tolerance=1)
+
+ def test_get_loc_raises_missized_tolerance(self):
+ index = Index([0, 1, 2])
+ with pytest.raises(ValueError, match="tolerance size must match"):
+ index.get_loc(1.1, "nearest", tolerance=[1, 1])
+
def test_get_loc_float64(self):
idx = Float64Index([0.0, 1.0, 2.0])
for method in [None, "pad", "backfill", "nearest"]:
@@ -82,6 +130,131 @@ def test_get_loc_missing_nan(self):
class TestGetIndexer:
+ def test_get_indexer(self):
+ index1 = Index([1, 2, 3, 4, 5])
+ index2 = Index([2, 4, 6])
+
+ r1 = index1.get_indexer(index2)
+ e1 = np.array([1, 3, -1], dtype=np.intp)
+ tm.assert_almost_equal(r1, e1)
+
+ @pytest.mark.parametrize("reverse", [True, False])
+ @pytest.mark.parametrize(
+ "expected,method",
+ [
+ (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "pad"),
+ (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "ffill"),
+ (np.array([0, 0, 1, 1, 2], dtype=np.intp), "backfill"),
+ (np.array([0, 0, 1, 1, 2], dtype=np.intp), "bfill"),
+ ],
+ )
+ def test_get_indexer_methods(self, reverse, expected, method):
+ index1 = Index([1, 2, 3, 4, 5])
+ index2 = Index([2, 4, 6])
+
+ if reverse:
+ index1 = index1[::-1]
+ expected = expected[::-1]
+
+ result = index2.get_indexer(index1, method=method)
+ tm.assert_almost_equal(result, expected)
+
+ def test_get_indexer_invalid(self):
+ # GH10411
+ index = Index(np.arange(10))
+
+ with pytest.raises(ValueError, match="tolerance argument"):
+ index.get_indexer([1, 0], tolerance=1)
+
+ with pytest.raises(ValueError, match="limit argument"):
+ index.get_indexer([1, 0], limit=1)
+
+ @pytest.mark.parametrize(
+ "method, tolerance, indexer, expected",
+ [
+ ("pad", None, [0, 5, 9], [0, 5, 9]),
+ ("backfill", None, [0, 5, 9], [0, 5, 9]),
+ ("nearest", None, [0, 5, 9], [0, 5, 9]),
+ ("pad", 0, [0, 5, 9], [0, 5, 9]),
+ ("backfill", 0, [0, 5, 9], [0, 5, 9]),
+ ("nearest", 0, [0, 5, 9], [0, 5, 9]),
+ ("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]),
+ ("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]),
+ ("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]),
+ ("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]),
+ ("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]),
+ ("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]),
+ ("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),
+ ("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),
+ ("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),
+ ],
+ )
+ def test_get_indexer_nearest(self, method, tolerance, indexer, expected):
+ index = Index(np.arange(10))
+
+ actual = index.get_indexer(indexer, method=method, tolerance=tolerance)
+ tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
+
+ @pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])
+ @pytest.mark.parametrize(
+ "tolerance, expected",
+ list(
+ zip(
+ [[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],
+ [[0, 2, -1], [0, -1, -1], [-1, 2, 9]],
+ )
+ ),
+ )
+ def test_get_indexer_nearest_listlike_tolerance(
+ self, tolerance, expected, listtype
+ ):
+ index = Index(np.arange(10))
+
+ actual = index.get_indexer(
+ [0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance)
+ )
+ tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
+
+ def test_get_indexer_nearest_error(self):
+ index = Index(np.arange(10))
+ with pytest.raises(ValueError, match="limit argument"):
+ index.get_indexer([1, 0], method="nearest", limit=1)
+
+ with pytest.raises(ValueError, match="tolerance size must match"):
+ index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3])
+
+ @pytest.mark.parametrize(
+ "method,expected",
+ [("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])],
+ )
+ def test_get_indexer_nearest_decreasing(self, method, expected):
+ index = Index(np.arange(10))[::-1]
+
+ actual = index.get_indexer([0, 5, 9], method=method)
+ tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))
+
+ actual = index.get_indexer([0.2, 1.8, 8.5], method=method)
+ tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
+
+ @pytest.mark.parametrize(
+ "idx_class", [Int64Index, RangeIndex, Float64Index, UInt64Index]
+ )
+ @pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"])
+ def test_get_indexer_numeric_index_boolean_target(self, method, idx_class):
+ # GH 16877
+
+ numeric_index = idx_class(RangeIndex(4))
+ other = Index([True, False, True])
+
+ result = getattr(numeric_index, method)(other)
+ expected = np.array([-1, -1, -1], dtype=np.intp)
+ if method == "get_indexer":
+ tm.assert_numpy_array_equal(result, expected)
+ else:
+ missing = np.arange(3, dtype=np.intp)
+ tm.assert_numpy_array_equal(result[0], expected)
+ tm.assert_numpy_array_equal(result[1], missing)
+
@pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
def test_get_indexer_with_method_numeric_vs_bool(self, method):
left = Index([1, 2, 3])
@@ -274,6 +447,62 @@ def test_contains_float64_not_nans(self):
assert 1.0 in index
+class TestSliceLocs:
+ @pytest.mark.parametrize("dtype", [int, float])
+ def test_slice_locs(self, dtype):
+ index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
+ n = len(index)
+
+ assert index.slice_locs(start=2) == (2, n)
+ assert index.slice_locs(start=3) == (3, n)
+ assert index.slice_locs(3, 8) == (3, 6)
+ assert index.slice_locs(5, 10) == (3, n)
+ assert index.slice_locs(end=8) == (0, 6)
+ assert index.slice_locs(end=9) == (0, 7)
+
+ # reversed
+ index2 = index[::-1]
+ assert index2.slice_locs(8, 2) == (2, 6)
+ assert index2.slice_locs(7, 3) == (2, 5)
+
+ @pytest.mark.parametrize("dtype", [int, float])
+ def test_slice_locs_float_locs(self, dtype):
+ index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
+ n = len(index)
+ assert index.slice_locs(5.0, 10.0) == (3, n)
+ assert index.slice_locs(4.5, 10.5) == (3, 8)
+
+ index2 = index[::-1]
+ assert index2.slice_locs(8.5, 1.5) == (2, 6)
+ assert index2.slice_locs(10.5, -1) == (0, n)
+
+ @pytest.mark.parametrize("dtype", [int, float])
+ def test_slice_locs_dup_numeric(self, dtype):
+ index = Index(np.array([10, 12, 12, 14], dtype=dtype))
+ assert index.slice_locs(12, 12) == (1, 3)
+ assert index.slice_locs(11, 13) == (1, 3)
+
+ index2 = index[::-1]
+ assert index2.slice_locs(12, 12) == (1, 3)
+ assert index2.slice_locs(13, 11) == (1, 3)
+
+ def test_slice_locs_na(self):
+ index = Index([np.nan, 1, 2])
+ assert index.slice_locs(1) == (1, 3)
+ assert index.slice_locs(np.nan) == (0, 3)
+
+ index = Index([0, np.nan, np.nan, 1, 2])
+ assert index.slice_locs(np.nan) == (1, 5)
+
+ def test_slice_locs_na_raises(self):
+ index = Index([np.nan, 1, 2])
+ with pytest.raises(KeyError, match=""):
+ index.slice_locs(start=1.5)
+
+ with pytest.raises(KeyError, match=""):
+ index.slice_locs(end=1.5)
+
+
class TestGetSliceBounds:
@pytest.mark.parametrize("kind", ["getitem", "loc", None])
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py
index 6cde3e2366062..27e19468dddd2 100644
--- a/pandas/tests/indexes/numeric/test_setops.py
+++ b/pandas/tests/indexes/numeric/test_setops.py
@@ -110,6 +110,24 @@ def test_intersection_monotonic(self, index2, keeps_name, sort):
expected = expected.sort_values()
tm.assert_index_equal(result, expected)
+ def test_symmetric_difference(self, sort):
+ # smoke
+ index1 = Index([5, 2, 3, 4], name="index1")
+ index2 = Index([2, 3, 4, 1])
+ result = index1.symmetric_difference(index2, sort=sort)
+ expected = Index([5, 1])
+ assert tm.equalContents(result, expected)
+ assert result.name is None
+ if sort is None:
+ expected = expected.sort_values()
+ tm.assert_index_equal(result, expected)
+
+ # __xor__ syntax
+ with tm.assert_produces_warning(FutureWarning):
+ expected = index1 ^ index2
+ assert tm.equalContents(result, expected)
+ assert result.name is None
+
class TestSetOpsSort:
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
diff --git a/pandas/tests/indexes/object/test_indexing.py b/pandas/tests/indexes/object/test_indexing.py
new file mode 100644
index 0000000000000..a683e9faed1f2
--- /dev/null
+++ b/pandas/tests/indexes/object/test_indexing.py
@@ -0,0 +1,110 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import Index
+import pandas._testing as tm
+
+
+class TestGetLoc:
+ def test_get_loc_raises_object_nearest(self):
+ index = Index(["a", "c"])
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ index.get_loc("a", method="nearest")
+
+ def test_get_loc_raises_object_tolerance(self):
+ index = Index(["a", "c"])
+ with pytest.raises(TypeError, match="unsupported operand type"):
+ index.get_loc("a", method="pad", tolerance="invalid")
+
+
+class TestGetIndexer:
+ @pytest.mark.parametrize(
+ "method,expected",
+ [
+ ("pad", np.array([-1, 0, 1, 1], dtype=np.intp)),
+ ("backfill", np.array([0, 0, 1, -1], dtype=np.intp)),
+ ],
+ )
+ def test_get_indexer_strings(self, method, expected):
+ index = Index(["b", "c"])
+ actual = index.get_indexer(["a", "b", "c", "d"], method=method)
+
+ tm.assert_numpy_array_equal(actual, expected)
+
+ def test_get_indexer_strings_raises(self):
+ index = Index(["b", "c"])
+
+ msg = r"unsupported operand type\(s\) for -: 'str' and 'str'"
+ with pytest.raises(TypeError, match=msg):
+ index.get_indexer(["a", "b", "c", "d"], method="nearest")
+
+ with pytest.raises(TypeError, match=msg):
+ index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2)
+
+ with pytest.raises(TypeError, match=msg):
+ index.get_indexer(
+ ["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2]
+ )
+
+ def test_get_indexer_with_NA_values(
+ self, unique_nulls_fixture, unique_nulls_fixture2
+ ):
+ # GH#22332
+ # check pairwise, that no pair of na values
+ # is mangled
+ if unique_nulls_fixture is unique_nulls_fixture2:
+ return # skip it, values are not unique
+ arr = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object)
+ index = Index(arr, dtype=object)
+ result = index.get_indexer(
+ [unique_nulls_fixture, unique_nulls_fixture2, "Unknown"]
+ )
+ expected = np.array([0, 1, -1], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+class TestSliceLocs:
+ @pytest.mark.parametrize(
+ "in_slice,expected",
+ [
+ # error: Slice index must be an integer or None
+ (pd.IndexSlice[::-1], "yxdcb"),
+ (pd.IndexSlice["b":"y":-1], ""), # type: ignore[misc]
+ (pd.IndexSlice["b"::-1], "b"), # type: ignore[misc]
+ (pd.IndexSlice[:"b":-1], "yxdcb"), # type: ignore[misc]
+ (pd.IndexSlice[:"y":-1], "y"), # type: ignore[misc]
+ (pd.IndexSlice["y"::-1], "yxdcb"), # type: ignore[misc]
+ (pd.IndexSlice["y"::-4], "yb"), # type: ignore[misc]
+ # absent labels
+ (pd.IndexSlice[:"a":-1], "yxdcb"), # type: ignore[misc]
+ (pd.IndexSlice[:"a":-2], "ydb"), # type: ignore[misc]
+ (pd.IndexSlice["z"::-1], "yxdcb"), # type: ignore[misc]
+ (pd.IndexSlice["z"::-3], "yc"), # type: ignore[misc]
+ (pd.IndexSlice["m"::-1], "dcb"), # type: ignore[misc]
+ (pd.IndexSlice[:"m":-1], "yx"), # type: ignore[misc]
+ (pd.IndexSlice["a":"a":-1], ""), # type: ignore[misc]
+ (pd.IndexSlice["z":"z":-1], ""), # type: ignore[misc]
+ (pd.IndexSlice["m":"m":-1], ""), # type: ignore[misc]
+ ],
+ )
+ def test_slice_locs_negative_step(self, in_slice, expected):
+ index = Index(list("bcdxy"))
+
+ s_start, s_stop = index.slice_locs(in_slice.start, in_slice.stop, in_slice.step)
+ result = index[s_start : s_stop : in_slice.step]
+ expected = Index(list(expected))
+ tm.assert_index_equal(result, expected)
+
+ def test_slice_locs_dup(self):
+ index = Index(["a", "a", "b", "c", "d", "d"])
+ assert index.slice_locs("a", "d") == (0, 6)
+ assert index.slice_locs(end="d") == (0, 6)
+ assert index.slice_locs("a", "c") == (0, 4)
+ assert index.slice_locs("b", "d") == (2, 6)
+
+ index2 = index[::-1]
+ assert index2.slice_locs("d", "a") == (0, 6)
+ assert index2.slice_locs(end="a") == (0, 6)
+ assert index2.slice_locs("d", "b") == (0, 4)
+ assert index2.slice_locs("c", "a") == (2, 6)
diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py
index afeeb63217489..c8629fdf1e3a6 100644
--- a/pandas/tests/indexes/test_any_index.py
+++ b/pandas/tests/indexes/test_any_index.py
@@ -3,6 +3,8 @@
TODO: consider using hypothesis for these.
"""
+import re
+
import pytest
import pandas._testing as tm
@@ -33,12 +35,27 @@ def test_mutability(index):
index[0] = index[0]
+def test_map_identity_mapping(index):
+ # GH#12766
+ tm.assert_index_equal(index, index.map(lambda x: x))
+
+
def test_wrong_number_names(index):
names = index.nlevels * ["apple", "banana", "carrot"]
with pytest.raises(ValueError, match="^Length"):
index.names = names
+def test_view_preserves_name(index):
+ assert index.view().name == index.name
+
+
+def test_ravel_deprecation(index):
+ # GH#19956 ravel returning ndarray is deprecated
+ with tm.assert_produces_warning(FutureWarning):
+ index.ravel()
+
+
class TestConversion:
def test_to_series(self, index):
# assert that we are creating a copy of the index
@@ -77,11 +94,28 @@ def test_pickle_roundtrip(self, index):
# GH#8367 round-trip with timezone
assert index.equal_levels(result)
+ def test_pickle_preserves_name(self, index):
+ original_name, index.name = index.name, "foo"
+ unpickled = tm.round_trip_pickle(index)
+ assert index.equals(unpickled)
+ index.name = original_name
+
class TestIndexing:
def test_slice_keeps_name(self, index):
assert index.name == index[1:].name
+ @pytest.mark.parametrize("item", [101, "no_int"])
+ # FutureWarning from non-tuple sequence of nd indexing
+ @pytest.mark.filterwarnings("ignore::FutureWarning")
+ def test_getitem_error(self, index, item):
+ msg = r"index 101 is out of bounds for axis 0 with size [\d]+|" + re.escape(
+ "only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) "
+ "and integer or boolean arrays are valid indices"
+ )
+ with pytest.raises(IndexError, match=msg):
+ index[item]
+
class TestRendering:
def test_str(self, index):
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 05bc577d159dc..092b1c447eb0d 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -748,10 +748,6 @@ def test_union_dt_as_obj(self, sort):
tm.assert_contains_all(index, second_cat)
tm.assert_contains_all(date_index, first_cat)
- def test_map_identity_mapping(self, index):
- # GH 12766
- tm.assert_index_equal(index, index.map(lambda x: x))
-
def test_map_with_tuples(self):
# GH 12766
@@ -881,8 +877,9 @@ def test_difference_name_preservation(self, index, second_name, expected, sort):
else:
assert result.name == expected
- @pytest.mark.parametrize("index", ["string"], indirect=True)
def test_difference_empty_arg(self, index, sort):
+ if isinstance(index, MultiIndex):
+ pytest.skip("Not applicable")
first = index[5:20]
first.name = "name"
result = first.difference([], sort)
@@ -912,24 +909,6 @@ def test_difference_sort(self, index, sort):
tm.assert_index_equal(result, expected)
- def test_symmetric_difference(self, sort):
- # smoke
- index1 = Index([5, 2, 3, 4], name="index1")
- index2 = Index([2, 3, 4, 1])
- result = index1.symmetric_difference(index2, sort=sort)
- expected = Index([5, 1])
- assert tm.equalContents(result, expected)
- assert result.name is None
- if sort is None:
- expected = expected.sort_values()
- tm.assert_index_equal(result, expected)
-
- # __xor__ syntax
- with tm.assert_produces_warning(FutureWarning):
- expected = index1 ^ index2
- assert tm.equalContents(result, expected)
- assert result.name is None
-
@pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
def test_difference_incomparable(self, opname):
a = Index([3, Timestamp("2000"), 1])
@@ -1119,331 +1098,6 @@ def test_logical_compat(self, op):
def _check_method_works(self, method, index):
method(index)
- def test_get_indexer(self):
- index1 = Index([1, 2, 3, 4, 5])
- index2 = Index([2, 4, 6])
-
- r1 = index1.get_indexer(index2)
- e1 = np.array([1, 3, -1], dtype=np.intp)
- tm.assert_almost_equal(r1, e1)
-
- @pytest.mark.parametrize("reverse", [True, False])
- @pytest.mark.parametrize(
- "expected,method",
- [
- (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "pad"),
- (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "ffill"),
- (np.array([0, 0, 1, 1, 2], dtype=np.intp), "backfill"),
- (np.array([0, 0, 1, 1, 2], dtype=np.intp), "bfill"),
- ],
- )
- def test_get_indexer_methods(self, reverse, expected, method):
- index1 = Index([1, 2, 3, 4, 5])
- index2 = Index([2, 4, 6])
-
- if reverse:
- index1 = index1[::-1]
- expected = expected[::-1]
-
- result = index2.get_indexer(index1, method=method)
- tm.assert_almost_equal(result, expected)
-
- def test_get_indexer_invalid(self):
- # GH10411
- index = Index(np.arange(10))
-
- with pytest.raises(ValueError, match="tolerance argument"):
- index.get_indexer([1, 0], tolerance=1)
-
- with pytest.raises(ValueError, match="limit argument"):
- index.get_indexer([1, 0], limit=1)
-
- @pytest.mark.parametrize(
- "method, tolerance, indexer, expected",
- [
- ("pad", None, [0, 5, 9], [0, 5, 9]),
- ("backfill", None, [0, 5, 9], [0, 5, 9]),
- ("nearest", None, [0, 5, 9], [0, 5, 9]),
- ("pad", 0, [0, 5, 9], [0, 5, 9]),
- ("backfill", 0, [0, 5, 9], [0, 5, 9]),
- ("nearest", 0, [0, 5, 9], [0, 5, 9]),
- ("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]),
- ("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]),
- ("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]),
- ("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]),
- ("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]),
- ("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]),
- ("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),
- ("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),
- ("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),
- ],
- )
- def test_get_indexer_nearest(self, method, tolerance, indexer, expected):
- index = Index(np.arange(10))
-
- actual = index.get_indexer(indexer, method=method, tolerance=tolerance)
- tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
-
- @pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])
- @pytest.mark.parametrize(
- "tolerance, expected",
- list(
- zip(
- [[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],
- [[0, 2, -1], [0, -1, -1], [-1, 2, 9]],
- )
- ),
- )
- def test_get_indexer_nearest_listlike_tolerance(
- self, tolerance, expected, listtype
- ):
- index = Index(np.arange(10))
-
- actual = index.get_indexer(
- [0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance)
- )
- tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
-
- def test_get_indexer_nearest_error(self):
- index = Index(np.arange(10))
- with pytest.raises(ValueError, match="limit argument"):
- index.get_indexer([1, 0], method="nearest", limit=1)
-
- with pytest.raises(ValueError, match="tolerance size must match"):
- index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3])
-
- @pytest.mark.parametrize(
- "method,expected",
- [("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])],
- )
- def test_get_indexer_nearest_decreasing(self, method, expected):
- index = Index(np.arange(10))[::-1]
-
- actual = index.get_indexer([0, 5, 9], method=method)
- tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))
-
- actual = index.get_indexer([0.2, 1.8, 8.5], method=method)
- tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
-
- @pytest.mark.parametrize(
- "method,expected",
- [
- ("pad", np.array([-1, 0, 1, 1], dtype=np.intp)),
- ("backfill", np.array([0, 0, 1, -1], dtype=np.intp)),
- ],
- )
- def test_get_indexer_strings(self, method, expected):
- index = Index(["b", "c"])
- actual = index.get_indexer(["a", "b", "c", "d"], method=method)
-
- tm.assert_numpy_array_equal(actual, expected)
-
- def test_get_indexer_strings_raises(self):
- index = Index(["b", "c"])
-
- msg = r"unsupported operand type\(s\) for -: 'str' and 'str'"
- with pytest.raises(TypeError, match=msg):
- index.get_indexer(["a", "b", "c", "d"], method="nearest")
-
- with pytest.raises(TypeError, match=msg):
- index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2)
-
- with pytest.raises(TypeError, match=msg):
- index.get_indexer(
- ["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2]
- )
-
- @pytest.mark.parametrize(
- "idx_class", [Int64Index, RangeIndex, Float64Index, UInt64Index]
- )
- @pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"])
- def test_get_indexer_numeric_index_boolean_target(self, method, idx_class):
- # GH 16877
-
- numeric_index = idx_class(RangeIndex(4))
- other = Index([True, False, True])
-
- result = getattr(numeric_index, method)(other)
- expected = np.array([-1, -1, -1], dtype=np.intp)
- if method == "get_indexer":
- tm.assert_numpy_array_equal(result, expected)
- else:
- missing = np.arange(3, dtype=np.intp)
- tm.assert_numpy_array_equal(result[0], expected)
- tm.assert_numpy_array_equal(result[1], missing)
-
- def test_get_indexer_with_NA_values(
- self, unique_nulls_fixture, unique_nulls_fixture2
- ):
- # GH 22332
- # check pairwise, that no pair of na values
- # is mangled
- if unique_nulls_fixture is unique_nulls_fixture2:
- return # skip it, values are not unique
- arr = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object)
- index = Index(arr, dtype=object)
- result = index.get_indexer(
- [unique_nulls_fixture, unique_nulls_fixture2, "Unknown"]
- )
- expected = np.array([0, 1, -1], dtype=np.intp)
- tm.assert_numpy_array_equal(result, expected)
-
- @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"])
- def test_get_loc(self, method):
- index = Index([0, 1, 2])
- assert index.get_loc(1, method=method) == 1
-
- if method:
- assert index.get_loc(1, method=method, tolerance=0) == 1
-
- @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"])
- def test_get_loc_raises_bad_label(self, method):
- index = Index([0, 1, 2])
- if method:
- msg = "not supported between"
- else:
- msg = "invalid key"
-
- with pytest.raises(TypeError, match=msg):
- index.get_loc([1, 2], method=method)
-
- @pytest.mark.parametrize(
- "method,loc", [("pad", 1), ("backfill", 2), ("nearest", 1)]
- )
- def test_get_loc_tolerance(self, method, loc):
- index = Index([0, 1, 2])
- assert index.get_loc(1.1, method) == loc
- assert index.get_loc(1.1, method, tolerance=1) == loc
-
- @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
- def test_get_loc_outside_tolerance_raises(self, method):
- index = Index([0, 1, 2])
- with pytest.raises(KeyError, match="1.1"):
- index.get_loc(1.1, method, tolerance=0.05)
-
- def test_get_loc_bad_tolerance_raises(self):
- index = Index([0, 1, 2])
- with pytest.raises(ValueError, match="must be numeric"):
- index.get_loc(1.1, "nearest", tolerance="invalid")
-
- def test_get_loc_tolerance_no_method_raises(self):
- index = Index([0, 1, 2])
- with pytest.raises(ValueError, match="tolerance .* valid if"):
- index.get_loc(1.1, tolerance=1)
-
- def test_get_loc_raises_missized_tolerance(self):
- index = Index([0, 1, 2])
- with pytest.raises(ValueError, match="tolerance size must match"):
- index.get_loc(1.1, "nearest", tolerance=[1, 1])
-
- def test_get_loc_raises_object_nearest(self):
- index = Index(["a", "c"])
- with pytest.raises(TypeError, match="unsupported operand type"):
- index.get_loc("a", method="nearest")
-
- def test_get_loc_raises_object_tolerance(self):
- index = Index(["a", "c"])
- with pytest.raises(TypeError, match="unsupported operand type"):
- index.get_loc("a", method="pad", tolerance="invalid")
-
- @pytest.mark.parametrize("dtype", [int, float])
- def test_slice_locs(self, dtype):
- index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
- n = len(index)
-
- assert index.slice_locs(start=2) == (2, n)
- assert index.slice_locs(start=3) == (3, n)
- assert index.slice_locs(3, 8) == (3, 6)
- assert index.slice_locs(5, 10) == (3, n)
- assert index.slice_locs(end=8) == (0, 6)
- assert index.slice_locs(end=9) == (0, 7)
-
- # reversed
- index2 = index[::-1]
- assert index2.slice_locs(8, 2) == (2, 6)
- assert index2.slice_locs(7, 3) == (2, 5)
-
- @pytest.mark.parametrize("dtype", [int, float])
- def test_slice_float_locs(self, dtype):
- index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
- n = len(index)
- assert index.slice_locs(5.0, 10.0) == (3, n)
- assert index.slice_locs(4.5, 10.5) == (3, 8)
-
- index2 = index[::-1]
- assert index2.slice_locs(8.5, 1.5) == (2, 6)
- assert index2.slice_locs(10.5, -1) == (0, n)
-
- def test_slice_locs_dup(self):
- index = Index(["a", "a", "b", "c", "d", "d"])
- assert index.slice_locs("a", "d") == (0, 6)
- assert index.slice_locs(end="d") == (0, 6)
- assert index.slice_locs("a", "c") == (0, 4)
- assert index.slice_locs("b", "d") == (2, 6)
-
- index2 = index[::-1]
- assert index2.slice_locs("d", "a") == (0, 6)
- assert index2.slice_locs(end="a") == (0, 6)
- assert index2.slice_locs("d", "b") == (0, 4)
- assert index2.slice_locs("c", "a") == (2, 6)
-
- @pytest.mark.parametrize("dtype", [int, float])
- def test_slice_locs_dup_numeric(self, dtype):
- index = Index(np.array([10, 12, 12, 14], dtype=dtype))
- assert index.slice_locs(12, 12) == (1, 3)
- assert index.slice_locs(11, 13) == (1, 3)
-
- index2 = index[::-1]
- assert index2.slice_locs(12, 12) == (1, 3)
- assert index2.slice_locs(13, 11) == (1, 3)
-
- def test_slice_locs_na(self):
- index = Index([np.nan, 1, 2])
- assert index.slice_locs(1) == (1, 3)
- assert index.slice_locs(np.nan) == (0, 3)
-
- index = Index([0, np.nan, np.nan, 1, 2])
- assert index.slice_locs(np.nan) == (1, 5)
-
- def test_slice_locs_na_raises(self):
- index = Index([np.nan, 1, 2])
- with pytest.raises(KeyError, match=""):
- index.slice_locs(start=1.5)
-
- with pytest.raises(KeyError, match=""):
- index.slice_locs(end=1.5)
-
- @pytest.mark.parametrize(
- "in_slice,expected",
- [
- # error: Slice index must be an integer or None
- (pd.IndexSlice[::-1], "yxdcb"),
- (pd.IndexSlice["b":"y":-1], ""), # type: ignore[misc]
- (pd.IndexSlice["b"::-1], "b"), # type: ignore[misc]
- (pd.IndexSlice[:"b":-1], "yxdcb"), # type: ignore[misc]
- (pd.IndexSlice[:"y":-1], "y"), # type: ignore[misc]
- (pd.IndexSlice["y"::-1], "yxdcb"), # type: ignore[misc]
- (pd.IndexSlice["y"::-4], "yb"), # type: ignore[misc]
- # absent labels
- (pd.IndexSlice[:"a":-1], "yxdcb"), # type: ignore[misc]
- (pd.IndexSlice[:"a":-2], "ydb"), # type: ignore[misc]
- (pd.IndexSlice["z"::-1], "yxdcb"), # type: ignore[misc]
- (pd.IndexSlice["z"::-3], "yc"), # type: ignore[misc]
- (pd.IndexSlice["m"::-1], "dcb"), # type: ignore[misc]
- (pd.IndexSlice[:"m":-1], "yx"), # type: ignore[misc]
- (pd.IndexSlice["a":"a":-1], ""), # type: ignore[misc]
- (pd.IndexSlice["z":"z":-1], ""), # type: ignore[misc]
- (pd.IndexSlice["m":"m":-1], ""), # type: ignore[misc]
- ],
- )
- def test_slice_locs_negative_step(self, in_slice, expected):
- index = Index(list("bcdxy"))
-
- s_start, s_stop = index.slice_locs(in_slice.start, in_slice.stop, in_slice.step)
- result = index[s_start : s_stop : in_slice.step]
- expected = Index(list(expected))
- tm.assert_index_equal(result, expected)
-
@pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True)
def test_drop_by_str_label(self, index):
n = len(index)
@@ -1555,23 +1209,6 @@ def test_set_value_deprecated(self):
idx.set_value(arr, idx[1], 80)
assert arr[1] == 80
- @pytest.mark.parametrize(
- "index", ["string", "int", "datetime", "timedelta"], indirect=True
- )
- def test_get_value(self, index):
- # TODO: Remove function? GH 19728
- values = np.random.randn(100)
- value = index[67]
-
- with pytest.raises(AttributeError, match="has no attribute '_values'"):
- # Index.get_value requires a Series, not an ndarray
- with tm.assert_produces_warning(FutureWarning):
- index.get_value(values, value)
-
- with tm.assert_produces_warning(FutureWarning):
- result = index.get_value(Series(values, index=values), value)
- tm.assert_almost_equal(result, values[67])
-
@pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}])
@pytest.mark.parametrize(
"index,expected",
@@ -2328,56 +1965,3 @@ def test_validate_1d_input():
ser = Series(0, range(4))
with pytest.raises(ValueError, match=msg):
ser.index = np.array([[2, 3]] * 4)
-
-
-def test_convert_almost_null_slice(index):
- # slice with None at both ends, but not step
-
- key = slice(None, None, "foo")
-
- if isinstance(index, pd.IntervalIndex):
- msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
- with pytest.raises(ValueError, match=msg):
- index._convert_slice_indexer(key, "loc")
- else:
- msg = "'>=' not supported between instances of 'str' and 'int'"
- with pytest.raises(TypeError, match=msg):
- index._convert_slice_indexer(key, "loc")
-
-
-dtlike_dtypes = [
- np.dtype("timedelta64[ns]"),
- np.dtype("datetime64[ns]"),
- pd.DatetimeTZDtype("ns", "Asia/Tokyo"),
- pd.PeriodDtype("ns"),
-]
-
-
-@pytest.mark.parametrize("ldtype", dtlike_dtypes)
-@pytest.mark.parametrize("rdtype", dtlike_dtypes)
-def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype):
-
- vals = np.tile(3600 * 10 ** 9 * np.arange(3), 2)
-
- def construct(dtype):
- if dtype is dtlike_dtypes[-1]:
- # PeriodArray will try to cast ints to strings
- return DatetimeIndex(vals).astype(dtype)
- return Index(vals, dtype=dtype)
-
- left = construct(ldtype)
- right = construct(rdtype)
-
- result = left.get_indexer_non_unique(right)
-
- if ldtype is rdtype:
- ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp)
- ex2 = np.array([], dtype=np.intp)
- tm.assert_numpy_array_equal(result[0], ex1)
- tm.assert_numpy_array_equal(result[1], ex2)
-
- else:
- no_matches = np.array([-1] * 6, dtype=np.intp)
- missing = np.arange(6, dtype=np.intp)
- tm.assert_numpy_array_equal(result[0], no_matches)
- tm.assert_numpy_array_equal(result[1], missing)
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 4ee1ba24df1d4..2b49ea00d3322 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -75,17 +75,6 @@ def test_constructor_unwraps_index(self, index):
b = type(a)(a)
tm.assert_equal(a._data, b._data)
- @pytest.mark.parametrize("itm", [101, "no_int"])
- # FutureWarning from non-tuple sequence of nd indexing
- @pytest.mark.filterwarnings("ignore::FutureWarning")
- def test_getitem_error(self, index, itm):
- msg = r"index 101 is out of bounds for axis 0 with size [\d]+|" + re.escape(
- "only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) "
- "and integer or boolean arrays are valid indices"
- )
- with pytest.raises(IndexError, match=msg):
- index[itm]
-
def test_to_flat_index(self, index):
# 22866
if isinstance(index, MultiIndex):
@@ -139,9 +128,8 @@ def test_copy_and_deepcopy(self, index):
def test_unique(self, index):
# don't test a MultiIndex here (as its tested separated)
- # don't test a CategoricalIndex because categories change (GH 18291)
- if isinstance(index, (MultiIndex, CategoricalIndex)):
- pytest.skip("Skip check for MultiIndex/CategoricalIndex")
+ if isinstance(index, MultiIndex):
+ pytest.skip("Skip check for MultiIndex")
# GH 17896
expected = index.drop_duplicates()
@@ -211,9 +199,6 @@ def test_get_unique_index(self, index):
result = i._get_unique_index(dropna=dropna)
tm.assert_index_equal(result, expected)
- def test_view(self, index):
- assert index.view().name == index.name
-
def test_searchsorted_monotonic(self, index):
# GH17271
# not implemented for tuple searches in MultiIndex
@@ -259,12 +244,6 @@ def test_searchsorted_monotonic(self, index):
with pytest.raises(ValueError, match=msg):
index._searchsorted_monotonic(value, side="left")
- def test_pickle(self, index):
- original_name, index.name = index.name, "foo"
- unpickled = tm.round_trip_pickle(index)
- assert index.equals(unpickled)
- index.name = original_name
-
def test_drop_duplicates(self, index, keep):
if isinstance(index, MultiIndex):
pytest.skip("MultiIndex is tested separately")
@@ -371,11 +350,6 @@ def test_astype_preserves_name(self, index, dtype):
else:
assert result.name == index.name
- def test_ravel_deprecation(self, index):
- # GH#19956 ravel returning ndarray is deprecated
- with tm.assert_produces_warning(FutureWarning):
- index.ravel()
-
def test_asi8_deprecation(self, index):
# GH#37877
if isinstance(index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py
index 538575781b4b2..04f7a65bd5c56 100644
--- a/pandas/tests/indexes/test_indexing.py
+++ b/pandas/tests/indexes/test_indexing.py
@@ -16,12 +16,16 @@
import numpy as np
import pytest
+from pandas.errors import InvalidIndexError
+
from pandas import (
DatetimeIndex,
Float64Index,
Index,
Int64Index,
+ IntervalIndex,
PeriodIndex,
+ Series,
TimedeltaIndex,
UInt64Index,
)
@@ -137,6 +141,62 @@ def test_contains_with_float_index(self):
assert 1 not in float_index
+class TestGetValue:
+ @pytest.mark.parametrize(
+ "index", ["string", "int", "datetime", "timedelta"], indirect=True
+ )
+ def test_get_value(self, index):
+ # TODO: Remove function? GH#19728
+ values = np.random.randn(100)
+ value = index[67]
+
+ with pytest.raises(AttributeError, match="has no attribute '_values'"):
+ # Index.get_value requires a Series, not an ndarray
+ with tm.assert_produces_warning(FutureWarning):
+ index.get_value(values, value)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = index.get_value(Series(values, index=values), value)
+ tm.assert_almost_equal(result, values[67])
+
+
+class TestGetIndexer:
+ def test_get_indexer_consistency(self, index):
+ # See GH#16819
+ if isinstance(index, IntervalIndex):
+ # requires index.is_non_overlapping
+ return
+
+ if index.is_unique:
+ indexer = index.get_indexer(index[0:2])
+ assert isinstance(indexer, np.ndarray)
+ assert indexer.dtype == np.intp
+ else:
+ e = "Reindexing only valid with uniquely valued Index objects"
+ with pytest.raises(InvalidIndexError, match=e):
+ index.get_indexer(index[0:2])
+
+ indexer, _ = index.get_indexer_non_unique(index[0:2])
+ assert isinstance(indexer, np.ndarray)
+ assert indexer.dtype == np.intp
+
+
+class TestConvertSliceIndexer:
+ def test_convert_almost_null_slice(self, index):
+ # slice with None at both ends, but not step
+
+ key = slice(None, None, "foo")
+
+ if isinstance(index, IntervalIndex):
+ msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
+ with pytest.raises(ValueError, match=msg):
+ index._convert_slice_indexer(key, "loc")
+ else:
+ msg = "'>=' not supported between instances of 'str' and 'int'"
+ with pytest.raises(TypeError, match=msg):
+ index._convert_slice_indexer(key, "loc")
+
+
@pytest.mark.parametrize(
"idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
)
| https://api.github.com/repos/pandas-dev/pandas/pulls/39485 | 2021-01-30T18:46:39Z | 2021-01-30T20:35:50Z | 2021-01-30T20:35:50Z | 2021-01-30T20:44:30Z | |
BUG: Regression in astype not casting to bytes | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 240acf787f9c9..0ee1abaa2a0eb 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -17,6 +17,7 @@ Fixed regressions
- Fixed regression in :func:`read_excel` that caused it to raise ``AttributeError`` when checking version of older xlrd versions (:issue:`38955`)
- Fixed regression in :class:`DataFrame` constructor reordering element when construction from datetime ndarray with dtype not ``"datetime64[ns]"`` (:issue:`39422`)
+- Fixed regression in :class:`DataFrame.astype` and :class:`Series.astype` not casting to bytes dtype (:issue:`39474`)
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 2f84ea3cf43c0..1cb592f18dd2c 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1221,7 +1221,7 @@ def soft_convert_objects(
values = lib.maybe_convert_objects(
values, convert_datetime=datetime, convert_timedelta=timedelta
)
- except OutOfBoundsDatetime:
+ except (OutOfBoundsDatetime, ValueError):
return values
if numeric and is_object_dtype(values.dtype):
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 52bf36e6fed43..661f5ad1fec08 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2254,7 +2254,7 @@ class ObjectBlock(Block):
_can_hold_na = True
def _maybe_coerce_values(self, values):
- if issubclass(values.dtype.type, (str, bytes)):
+ if issubclass(values.dtype.type, str):
values = np.array(values, dtype=object)
return values
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index df98c78e78fb6..46f5a20f38941 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -651,3 +651,8 @@ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request)
# For non-NA values, we should match what we get for non-EA str
alt = obj.astype(str)
assert np.all(alt.iloc[1:] == result.iloc[1:])
+
+ def test_astype_bytes(self):
+ # GH#39474
+ result = DataFrame(["foo", "bar", "baz"]).astype(bytes)
+ assert result.dtypes[0] == np.dtype("S3")
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 1a141e3201d57..d683503f22f28 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -341,6 +341,11 @@ def test_astype_unicode(self):
reload(sys)
sys.setdefaultencoding(former_encoding)
+ def test_astype_bytes(self):
+ # GH#39474
+ result = Series(["foo", "bar", "baz"]).astype(bytes)
+ assert result.dtypes == np.dtype("S3")
+
class TestAstypeCategorical:
def test_astype_categorical_invalid_conversions(self):
| - [x] closes #39474
- [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
Not sure if this is the right place | https://api.github.com/repos/pandas-dev/pandas/pulls/39484 | 2021-01-30T18:35:59Z | 2021-02-02T22:14:57Z | 2021-02-02T22:14:57Z | 2021-02-02T22:21:39Z |
ERR: Unify error message for bad excel sheetnames | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index baa0cc2ac9e18..8f80891576581 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -26,7 +26,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
--
+- :func:`pandas.read_excel` error message when a specified ``sheetname`` does not exist is now uniform across engines (:issue:`39250`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 11974d25d72d3..439090674c94b 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -434,6 +434,17 @@ def get_sheet_by_index(self, index):
def get_sheet_data(self, sheet, convert_float):
pass
+ def raise_if_bad_sheet_by_index(self, index: int) -> None:
+ n_sheets = len(self.sheet_names)
+ if index >= n_sheets:
+ raise ValueError(
+ f"Worksheet index {index} is invalid, {n_sheets} worksheets found"
+ )
+
+ def raise_if_bad_sheet_by_name(self, name: str) -> None:
+ if name not in self.sheet_names:
+ raise ValueError(f"Worksheet named '{name}' not found")
+
def parse(
self,
sheet_name=0,
diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py
index c5c3927216850..8987d5bb42057 100644
--- a/pandas/io/excel/_odfreader.py
+++ b/pandas/io/excel/_odfreader.py
@@ -57,12 +57,14 @@ def sheet_names(self) -> List[str]:
def get_sheet_by_index(self, index: int):
from odf.table import Table
+ self.raise_if_bad_sheet_by_index(index)
tables = self.book.getElementsByType(Table)
return tables[index]
def get_sheet_by_name(self, name: str):
from odf.table import Table
+ self.raise_if_bad_sheet_by_name(name)
tables = self.book.getElementsByType(Table)
for table in tables:
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index 71e1bf6b43ad5..56df791a40ce0 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -494,9 +494,11 @@ def sheet_names(self) -> List[str]:
return self.book.sheetnames
def get_sheet_by_name(self, name: str):
+ self.raise_if_bad_sheet_by_name(name)
return self.book[name]
def get_sheet_by_index(self, index: int):
+ self.raise_if_bad_sheet_by_index(index)
return self.book.worksheets[index]
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
diff --git a/pandas/io/excel/_pyxlsb.py b/pandas/io/excel/_pyxlsb.py
index de4f7bba1a179..f77a6bd5b1ad5 100644
--- a/pandas/io/excel/_pyxlsb.py
+++ b/pandas/io/excel/_pyxlsb.py
@@ -47,9 +47,11 @@ def sheet_names(self) -> List[str]:
return self.book.sheets
def get_sheet_by_name(self, name: str):
+ self.raise_if_bad_sheet_by_name(name)
return self.book.get_sheet(name)
def get_sheet_by_index(self, index: int):
+ self.raise_if_bad_sheet_by_index(index)
# pyxlsb sheets are indexed from 1 onwards
# There's a fix for this in the source, but the pypi package doesn't have it
return self.book.get_sheet(index + 1)
diff --git a/pandas/io/excel/_xlrd.py b/pandas/io/excel/_xlrd.py
index c655db4bc772b..5eb88a694218a 100644
--- a/pandas/io/excel/_xlrd.py
+++ b/pandas/io/excel/_xlrd.py
@@ -44,9 +44,11 @@ def sheet_names(self):
return self.book.sheet_names()
def get_sheet_by_name(self, name):
+ self.raise_if_bad_sheet_by_name(name)
return self.book.sheet_by_name(name)
def get_sheet_by_index(self, index):
+ self.raise_if_bad_sheet_by_index(index)
return self.book.sheet_by_index(index)
def get_sheet_data(self, sheet, convert_float):
diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py
index d6c6399f082c6..c99d9ae62bf54 100644
--- a/pandas/tests/io/excel/test_odf.py
+++ b/pandas/tests/io/excel/test_odf.py
@@ -42,5 +42,5 @@ def test_nonexistent_sheetname_raises(read_ext):
# GH-27676
# Specifying a non-existent sheet_name parameter should throw an error
# with the sheet name.
- with pytest.raises(ValueError, match="sheet xyz not found"):
+ with pytest.raises(ValueError, match="Worksheet named 'xyz' not found"):
pd.read_excel("blank.ods", sheet_name="xyz")
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 1b80b6429c8b5..b2e87de5580e6 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -665,6 +665,16 @@ def test_bad_engine_raises(self, read_ext):
with pytest.raises(ValueError, match="Unknown engine: foo"):
pd.read_excel("", engine=bad_engine)
+ @pytest.mark.parametrize(
+ "sheet_name",
+ [3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]],
+ )
+ def test_bad_sheetname_raises(self, read_ext, sheet_name):
+ # GH 39250
+ msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found"
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel("blank" + read_ext, sheet_name=sheet_name)
+
def test_missing_file_raises(self, read_ext):
bad_file = f"foo{read_ext}"
# CI tests with zh_CN.utf8, translates to "No such file or directory"
@@ -1263,6 +1273,17 @@ def test_sheet_name(self, request, read_ext, df_ref):
tm.assert_frame_equal(df1_parse, df_ref, check_names=False)
tm.assert_frame_equal(df2_parse, df_ref, check_names=False)
+ @pytest.mark.parametrize(
+ "sheet_name",
+ [3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]],
+ )
+ def test_bad_sheetname_raises(self, read_ext, sheet_name):
+ # GH 39250
+ msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found"
+ with pytest.raises(ValueError, match=msg):
+ with pd.ExcelFile("blank" + read_ext) as excel:
+ excel.parse(sheet_name=sheet_name)
+
def test_excel_read_buffer(self, engine, read_ext):
pth = "test1" + read_ext
expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0, engine=engine)
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index e23f7228cc7e1..14ad97c058a55 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -347,19 +347,9 @@ def test_excel_sheet_by_name_raise(self, path, engine):
tm.assert_frame_equal(gt, df)
- if engine == "odf":
- msg = "sheet 0 not found"
- with pytest.raises(ValueError, match=msg):
- pd.read_excel(xl, "0")
- elif engine == "xlwt":
- import xlrd
-
- msg = "No sheet named <'0'>"
- with pytest.raises(xlrd.XLRDError, match=msg):
- pd.read_excel(xl, sheet_name="0")
- else:
- with pytest.raises(KeyError, match="Worksheet 0 does not exist."):
- pd.read_excel(xl, sheet_name="0")
+ msg = "Worksheet named '0' not found"
+ with pytest.raises(ValueError, match=msg):
+ pd.read_excel(xl, "0")
def test_excel_writer_context_manager(self, frame, path):
with ExcelWriter(path) as writer:
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index 2d19b570e5d06..29055837a0721 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -43,9 +43,9 @@ def test_read_xlrd_book(read_ext, frame):
# TODO: test for openpyxl as well
def test_excel_table_sheet_by_index(datapath, read_ext):
path = datapath("io", "data", "excel", f"test1{read_ext}")
- msg = "No sheet named <'invalid_sheet_name'>"
+ msg = "Worksheet named 'invalid_sheet_name' not found"
with ExcelFile(path, engine="xlrd") as excel:
- with pytest.raises(xlrd.XLRDError, match=msg):
+ with pytest.raises(ValueError, match=msg):
pd.read_excel(excel, sheet_name="invalid_sheet_name")
| - [x] closes #39250
- [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
IMO the core issue in #39250 is upstream in openpyxl, providing a better error message is really tangential to it. Since the error message that openpyxl raises is not a regression, it seemed best to me to (a) target this for 1.3 and (b) unify all error messages across engines.
If, on the other hand, we really do want to improve the error message in 1.2.2 because of the switch from xlrd to openpyxl, then I will open a new PR for 1.2.2 that only impacts openpyxl.
Will do a followup to remove the duplicate tests.
cc @simonjayhawkins @jorisvandenbossche | https://api.github.com/repos/pandas-dev/pandas/pulls/39482 | 2021-01-30T16:43:48Z | 2021-02-01T13:49:12Z | 2021-02-01T13:49:12Z | 2021-02-01T23:09:03Z |
BUG: Series[bool].__setitem__(scalar, non_bool) | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 0be3970159fbd..2f84ea3cf43c0 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1904,12 +1904,15 @@ def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None:
):
raise ValueError("Cannot assign nan to integer series")
- if dtype.kind in ["i", "u", "f", "c"]:
+ elif dtype.kind in ["i", "u", "f", "c"]:
if is_bool(value) or isinstance(value, np.timedelta64):
# numpy will cast td64 to integer if we're not careful
raise ValueError(
f"Cannot assign {type(value).__name__} to float/integer series"
)
+ elif dtype.kind == "b":
+ if is_scalar(value) and not is_bool(value):
+ raise ValueError(f"Cannot assign {type(value).__name__} to bool series")
def can_hold_element(dtype: np.dtype, element: Any) -> bool:
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 6c8b1622e76aa..69b9e63d7e215 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -161,34 +161,19 @@ def test_setitem_series_complex128(self, val, exp_dtype):
@pytest.mark.parametrize(
"val,exp_dtype",
[
- (1, np.int64),
- (3, np.int64),
- (1.1, np.float64),
- (1 + 1j, np.complex128),
+ (1, object),
+ ("3", object),
+ (3, object),
+ (1.1, object),
+ (1 + 1j, object),
(True, np.bool_),
],
)
- def test_setitem_series_bool(self, val, exp_dtype, request):
+ def test_setitem_series_bool(self, val, exp_dtype):
obj = pd.Series([True, False, True, False])
assert obj.dtype == np.bool_
- mark = None
- if exp_dtype is np.int64:
- exp = pd.Series([True, True, True, False])
- self._assert_setitem_series_conversion(obj, val, exp, np.bool_)
- mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be int")
- elif exp_dtype is np.float64:
- exp = pd.Series([True, True, True, False])
- self._assert_setitem_series_conversion(obj, val, exp, np.bool_)
- mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be float")
- elif exp_dtype is np.complex128:
- exp = pd.Series([True, True, True, False])
- self._assert_setitem_series_conversion(obj, val, exp, np.bool_)
- mark = pytest.mark.xfail(reason="TODO_GH12747 The result must be complex")
- if mark is not None:
- request.node.add_marker(mark)
-
- exp = pd.Series([True, val, True, False])
+ exp = pd.Series([True, val, True, False], dtype=exp_dtype)
self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
@pytest.mark.parametrize(
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 9ace404930876..8c40ef6261d19 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -281,6 +281,22 @@ def test_setitem_dt64_into_int_series(self, dtype):
ser[:-1] = np.array([val, val])
tm.assert_series_equal(ser, expected)
+ @pytest.mark.parametrize("unique", [True, False])
+ @pytest.mark.parametrize("val", [3, 3.0, "3"], ids=type)
+ def test_setitem_non_bool_into_bool(self, val, indexer_sli, unique):
+ # dont cast these 3-like values to bool
+ ser = Series([True, False])
+ if not unique:
+ ser.index = [1, 1]
+
+ indexer_sli(ser)[1] = val
+ assert type(ser.iloc[1]) == type(val)
+
+ expected = Series([True, val], dtype=object, index=ser.index)
+ if not unique and indexer_sli is not tm.iloc:
+ expected = Series([val, val], dtype=object, index=[1, 1])
+ tm.assert_series_equal(ser, expected)
+
class SetitemCastingEquivalents:
"""
| - [ ] closes #xxxx
- [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
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39478 | 2021-01-30T03:35:16Z | 2021-02-02T13:36:27Z | 2021-02-02T13:36:27Z | 2021-02-02T15:26:02Z |
TST/REF: SetitemCastingEquivalents | diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 36cd6b0327ccd..9ace404930876 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -282,56 +282,9 @@ def test_setitem_dt64_into_int_series(self, dtype):
tm.assert_series_equal(ser, expected)
-@pytest.mark.parametrize(
- "obj,expected,key",
- [
- pytest.param(
- # these induce dtype changes
- Series([2, 3, 4, 5, 6, 7, 8, 9, 10]),
- Series([np.nan, 3, np.nan, 5, np.nan, 7, np.nan, 9, np.nan]),
- slice(None, None, 2),
- id="int_series_slice_key_step",
- ),
- pytest.param(
- Series([True, True, False, False]),
- Series([np.nan, True, np.nan, False], dtype=object),
- slice(None, None, 2),
- id="bool_series_slice_key_step",
- ),
- pytest.param(
- # these induce dtype changes
- Series(np.arange(10)),
- Series([np.nan, np.nan, np.nan, np.nan, np.nan, 5, 6, 7, 8, 9]),
- slice(None, 5),
- id="int_series_slice_key",
- ),
- pytest.param(
- # changes dtype GH#4463
- Series([1, 2, 3]),
- Series([np.nan, 2, 3]),
- 0,
- id="int_series_int_key",
- ),
- pytest.param(
- # changes dtype GH#4463
- Series([False]),
- Series([np.nan], dtype=object),
- # TODO: maybe go to float64 since we are changing the _whole_ Series?
- 0,
- id="bool_series_int_key_change_all",
- ),
- pytest.param(
- # changes dtype GH#4463
- Series([False, True]),
- Series([np.nan, True], dtype=object),
- 0,
- id="bool_series_int_key",
- ),
- ],
-)
-class TestSetitemCastingEquivalents:
+class SetitemCastingEquivalents:
"""
- Check each of several methods that _should_ be equivalent to `obj[key] = np.nan`
+ Check each of several methods that _should_ be equivalent to `obj[key] = val`
We assume that
- obj.index is the default Index(range(len(obj)))
@@ -346,26 +299,44 @@ def val(self, request):
"""
return request.param
+ def check_indexer(self, obj, key, expected, val, indexer):
+ obj = obj.copy()
+ indexer(obj)[key] = val
+ tm.assert_series_equal(obj, expected)
+
def test_int_key(self, obj, key, expected, val, indexer_sli):
if not isinstance(key, int):
return
- obj = obj.copy()
- indexer_sli(obj)[key] = val
- tm.assert_series_equal(obj, expected)
+ self.check_indexer(obj, key, expected, val, indexer_sli)
- def test_slice_key(self, obj, key, expected, val, indexer_si):
- # Note: no .loc because that handles slice edges differently
- obj = obj.copy()
- indexer_si(obj)[key] = val
- tm.assert_series_equal(obj, expected)
+ rng = range(key, key + 1)
+ self.check_indexer(obj, rng, expected, val, indexer_sli)
+
+ if indexer_sli is not tm.loc:
+ # Note: no .loc because that handles slice edges differently
+ slc = slice(key, key + 1)
+ self.check_indexer(obj, slc, expected, val, indexer_sli)
+
+ ilkey = [key]
+ self.check_indexer(obj, ilkey, expected, val, indexer_sli)
+
+ indkey = np.array(ilkey)
+ self.check_indexer(obj, indkey, expected, val, indexer_sli)
+
+ def test_slice_key(self, obj, key, expected, val, indexer_sli):
+ if not isinstance(key, slice):
+ return
+
+ if indexer_sli is not tm.loc:
+ # Note: no .loc because that handles slice edges differently
+ self.check_indexer(obj, key, expected, val, indexer_sli)
- def test_intlist_key(self, obj, key, expected, val, indexer_sli):
ilkey = list(range(len(obj)))[key]
+ self.check_indexer(obj, ilkey, expected, val, indexer_sli)
- obj = obj.copy()
- indexer_sli(obj)[ilkey] = val
- tm.assert_series_equal(obj, expected)
+ indkey = np.array(ilkey)
+ self.check_indexer(obj, indkey, expected, val, indexer_sli)
def test_mask_key(self, obj, key, expected, val, indexer_sli):
# setitem with boolean mask
@@ -412,6 +383,63 @@ def test_index_putmask(self, obj, key, expected, val):
tm.assert_index_equal(res, Index(expected))
+@pytest.mark.parametrize(
+ "obj,expected,key",
+ [
+ pytest.param(
+ # these induce dtype changes
+ Series([2, 3, 4, 5, 6, 7, 8, 9, 10]),
+ Series([np.nan, 3, np.nan, 5, np.nan, 7, np.nan, 9, np.nan]),
+ slice(None, None, 2),
+ id="int_series_slice_key_step",
+ ),
+ pytest.param(
+ Series([True, True, False, False]),
+ Series([np.nan, True, np.nan, False], dtype=object),
+ slice(None, None, 2),
+ id="bool_series_slice_key_step",
+ ),
+ pytest.param(
+ # these induce dtype changes
+ Series(np.arange(10)),
+ Series([np.nan, np.nan, np.nan, np.nan, np.nan, 5, 6, 7, 8, 9]),
+ slice(None, 5),
+ id="int_series_slice_key",
+ ),
+ pytest.param(
+ # changes dtype GH#4463
+ Series([1, 2, 3]),
+ Series([np.nan, 2, 3]),
+ 0,
+ id="int_series_int_key",
+ ),
+ pytest.param(
+ # changes dtype GH#4463
+ Series([False]),
+ Series([np.nan], dtype=object),
+ # TODO: maybe go to float64 since we are changing the _whole_ Series?
+ 0,
+ id="bool_series_int_key_change_all",
+ ),
+ pytest.param(
+ # changes dtype GH#4463
+ Series([False, True]),
+ Series([np.nan, True], dtype=object),
+ 0,
+ id="bool_series_int_key",
+ ),
+ ],
+)
+class TestSetitemCastingEquivalents(SetitemCastingEquivalents):
+ @pytest.fixture(params=[np.nan, np.float64("NaN")])
+ def val(self, request):
+ """
+ One python float NaN, one np.float64. Only np.float64 has a `dtype`
+ attribute.
+ """
+ return request.param
+
+
class TestSetitemWithExpansion:
def test_setitem_empty_series(self):
# GH#10193
| Separating this out in preparation of using this pattern for more of the setitem tests (e.g. test_setitem_td64_into_complex further down in this file) | https://api.github.com/repos/pandas-dev/pandas/pulls/39477 | 2021-01-30T03:25:49Z | 2021-01-30T20:40:54Z | 2021-01-30T20:40:54Z | 2021-01-30T20:44:09Z |
DOC: Move whatsnew for #39442 | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index baa0cc2ac9e18..c5825d0881515 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -14,6 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :class:`DataFrame` constructor reordering element when construction from datetime ndarray with dtype not ``"datetime64[ns]"`` (:issue:`39422`)
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 3aa41e1d53057..9b1819a7d4d9f 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -274,7 +274,6 @@ Datetimelike
- Bug in constructing a :class:`DataFrame` or :class:`Series` with mismatched ``datetime64`` data and ``timedelta64`` dtype, or vice-versa, failing to raise ``TypeError`` (:issue:`38575`, :issue:`38764`, :issue:`38792`)
- Bug in constructing a :class:`Series` or :class:`DataFrame` with a ``datetime`` object out of bounds for ``datetime64[ns]`` dtype or a ``timedelta`` object out of bounds for ``timedelta64[ns]`` dtype (:issue:`38792`, :issue:`38965`)
- Bug in :meth:`DatetimeIndex.intersection`, :meth:`DatetimeIndex.symmetric_difference`, :meth:`PeriodIndex.intersection`, :meth:`PeriodIndex.symmetric_difference` always returning object-dtype when operating with :class:`CategoricalIndex` (:issue:`38741`)
-- Bug in :class:`DataFrame` constructor reordering element when construction from datetime ndarray with dtype not ``"datetime64[ns]"`` (:issue:`39422`)
- Bug in :meth:`Series.where` incorrectly casting ``datetime64`` values to ``int64`` (:issue:`37682`)
- Bug in :class:`Categorical` incorrectly typecasting ``datetime`` object to ``Timestamp`` (:issue:`38878`)
- Bug in comparisons between :class:`Timestamp` object and ``datetime64`` objects just outside the implementation bounds for nanosecond ``datetime64`` (:issue:`39221`)
| - [x] whatsnew entry
Move the whatsnew for backport | https://api.github.com/repos/pandas-dev/pandas/pulls/39476 | 2021-01-30T01:57:17Z | 2021-01-30T08:36:36Z | 2021-01-30T08:36:36Z | 2021-12-10T09:23:09Z |
Backport PR #39442 BUG: DataFrame constructor reordering elements with ndarray from datetime dtype not datetime64[ns | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index baa0cc2ac9e18..c5825d0881515 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -14,6 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :class:`DataFrame` constructor reordering element when construction from datetime ndarray with dtype not ``"datetime64[ns]"`` (:issue:`39422`)
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 3b52b4d499694..07507d5f5d2d4 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -224,7 +224,7 @@ def ensure_datetime64ns(arr: ndarray, copy: bool=True):
ivalues = arr.view(np.int64).ravel("K")
- result = np.empty(shape, dtype=DT64NS_DTYPE)
+ result = np.empty_like(arr, dtype=DT64NS_DTYPE)
iresult = result.ravel("K").view(np.int64)
if len(iresult) == 0:
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 2300a8937991e..77287b6f1eab5 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -1936,6 +1936,70 @@ def test_constructor_datetimes_with_nulls(self, arr):
expected = Series([np.dtype("datetime64[ns]")])
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize("order", ["K", "A", "C", "F"])
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "datetime64[M]",
+ "datetime64[D]",
+ "datetime64[h]",
+ "datetime64[m]",
+ "datetime64[s]",
+ "datetime64[ms]",
+ "datetime64[us]",
+ "datetime64[ns]",
+ ],
+ )
+ def test_constructor_datetimes_non_ns(self, order, dtype):
+ na = np.array(
+ [
+ ["2015-01-01", "2015-01-02", "2015-01-03"],
+ ["2017-01-01", "2017-01-02", "2017-02-03"],
+ ],
+ dtype=dtype,
+ order=order,
+ )
+ df = DataFrame(na)
+ expected = DataFrame(
+ [
+ ["2015-01-01", "2015-01-02", "2015-01-03"],
+ ["2017-01-01", "2017-01-02", "2017-02-03"],
+ ]
+ )
+ expected = expected.astype(dtype=dtype)
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("order", ["K", "A", "C", "F"])
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "timedelta64[D]",
+ "timedelta64[h]",
+ "timedelta64[m]",
+ "timedelta64[s]",
+ "timedelta64[ms]",
+ "timedelta64[us]",
+ "timedelta64[ns]",
+ ],
+ )
+ def test_constructor_timedelta_non_ns(self, order, dtype):
+ na = np.array(
+ [
+ [np.timedelta64(1, "D"), np.timedelta64(2, "D")],
+ [np.timedelta64(4, "D"), np.timedelta64(5, "D")],
+ ],
+ dtype=dtype,
+ order=order,
+ )
+ df = DataFrame(na).astype("timedelta64[ns]")
+ expected = DataFrame(
+ [
+ [Timedelta(1, "D"), Timedelta(2, "D")],
+ [Timedelta(4, "D"), Timedelta(5, "D")],
+ ],
+ )
+ tm.assert_frame_equal(df, expected)
+
def test_constructor_for_list_with_dtypes(self):
# test list of lists/ndarrays
df = DataFrame([np.arange(5) for x in range(5)])
| - [x] closes #39422 | https://api.github.com/repos/pandas-dev/pandas/pulls/39475 | 2021-01-30T01:54:56Z | 2021-01-30T08:35:26Z | 2021-01-30T08:35:26Z | 2021-12-10T09:23:18Z |
BUG/TST: Address GH28283 calling __finalize__ in pivot_table, groupby.median and groupby.mean | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 388c5dbf6a7ee..d6dba9497054f 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -434,6 +434,8 @@ Groupby/resample/rolling
- Bug in :meth:`Series.resample` would raise when the index was a :class:`PeriodIndex` consisting of ``NaT`` (:issue:`39227`)
- Bug in :meth:`core.window.rolling.RollingGroupby.corr` and :meth:`core.window.expanding.ExpandingGroupby.corr` where the groupby column would return 0 instead of ``np.nan`` when providing ``other`` that was longer than each group (:issue:`39591`)
- Bug in :meth:`core.window.expanding.ExpandingGroupby.corr` and :meth:`core.window.expanding.ExpandingGroupby.cov` where 1 would be returned instead of ``np.nan`` when providing ``other`` that was longer than each group (:issue:`39591`)
+- Bug in :meth:`.GroupBy.mean`, :meth:`.GroupBy.median` and :meth:`DataFrame.pivot_table` not propagating metadata (:issue:`28283`)
+-
Reshaping
^^^^^^^^^
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index bc277bf67614d..e939c184d501a 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1546,11 +1546,12 @@ def mean(self, numeric_only: bool = True):
2 4.0
Name: B, dtype: float64
"""
- return self._cython_agg_general(
+ result = self._cython_agg_general(
"mean",
alt=lambda x, axis: Series(x).mean(numeric_only=numeric_only),
numeric_only=numeric_only,
)
+ return result.__finalize__(self.obj, method="groupby")
@final
@Substitution(name="groupby")
@@ -1572,11 +1573,12 @@ def median(self, numeric_only=True):
Series or DataFrame
Median of values within each group.
"""
- return self._cython_agg_general(
+ result = self._cython_agg_general(
"median",
alt=lambda x, axis: Series(x).median(axis=axis, numeric_only=numeric_only),
numeric_only=numeric_only,
)
+ return result.__finalize__(self.obj, method="groupby")
@final
@Substitution(name="groupby")
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 778e37bc07eb5..8feb379a82ada 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -17,6 +17,9 @@
import numpy as np
from pandas._typing import (
+ AggFuncType,
+ AggFuncTypeBase,
+ AggFuncTypeDict,
FrameOrSeriesUnion,
IndexLabel,
)
@@ -57,11 +60,11 @@
@Substitution("\ndata : DataFrame")
@Appender(_shared_docs["pivot_table"], indents=1)
def pivot_table(
- data,
+ data: DataFrame,
values=None,
index=None,
columns=None,
- aggfunc="mean",
+ aggfunc: AggFuncType = "mean",
fill_value=None,
margins=False,
dropna=True,
@@ -75,7 +78,7 @@ def pivot_table(
pieces: List[DataFrame] = []
keys = []
for func in aggfunc:
- table = pivot_table(
+ _table = __internal_pivot_table(
data,
values=values,
index=index,
@@ -87,11 +90,42 @@ def pivot_table(
margins_name=margins_name,
observed=observed,
)
- pieces.append(table)
+ pieces.append(_table)
keys.append(getattr(func, "__name__", func))
- return concat(pieces, keys=keys, axis=1)
+ table = concat(pieces, keys=keys, axis=1)
+ return table.__finalize__(data, method="pivot_table")
+
+ table = __internal_pivot_table(
+ data,
+ values,
+ index,
+ columns,
+ aggfunc,
+ fill_value,
+ margins,
+ dropna,
+ margins_name,
+ observed,
+ )
+ return table.__finalize__(data, method="pivot_table")
+
+def __internal_pivot_table(
+ data: DataFrame,
+ values,
+ index,
+ columns,
+ aggfunc: Union[AggFuncTypeBase, AggFuncTypeDict],
+ fill_value,
+ margins: bool,
+ dropna: bool,
+ margins_name: str,
+ observed: bool,
+) -> DataFrame:
+ """
+ Helper of :func:`pandas.pivot_table` for any non-list ``aggfunc``.
+ """
keys = index + columns
values_passed = values is not None
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py
index 73a68e8508644..15c51e5f3e6e4 100644
--- a/pandas/tests/generic/test_finalize.py
+++ b/pandas/tests/generic/test_finalize.py
@@ -149,13 +149,15 @@
marks=not_implemented_mark,
),
(pd.DataFrame, frame_data, operator.methodcaller("pivot", columns="A")),
- pytest.param(
- (
- pd.DataFrame,
- {"A": [1], "B": [1]},
- operator.methodcaller("pivot_table", columns="A"),
- ),
- marks=not_implemented_mark,
+ (
+ pd.DataFrame,
+ ({"A": [1], "B": [1]},),
+ operator.methodcaller("pivot_table", columns="A"),
+ ),
+ (
+ pd.DataFrame,
+ ({"A": [1], "B": [1]},),
+ operator.methodcaller("pivot_table", columns="A", aggfunc=["mean", "sum"]),
),
(pd.DataFrame, frame_data, operator.methodcaller("stack")),
pytest.param(
@@ -740,6 +742,8 @@ def test_categorical_accessor(method):
[
operator.methodcaller("sum"),
lambda x: x.agg("sum"),
+ lambda x: x.agg("mean"),
+ lambda x: x.agg("median"),
],
)
def test_groupby_finalize(obj, method):
@@ -757,6 +761,12 @@ def test_groupby_finalize(obj, method):
lambda x: x.agg(["sum", "count"]),
lambda x: x.transform(lambda y: y),
lambda x: x.apply(lambda y: y),
+ lambda x: x.agg("std"),
+ lambda x: x.agg("var"),
+ lambda x: x.agg("sem"),
+ lambda x: x.agg("size"),
+ lambda x: x.agg("ohlc"),
+ lambda x: x.agg("describe"),
],
)
@not_implemented_mark
| Progress towards #28283
1. refactor `pivot_table` function to avoid overhead of `_finalize__` calls when a list of aggfuncs passed
2. call `__finalize__` before returning `groupby.mean` and `groupby.median`
3. add tests for 1 and 2
4. add ignored test cases for `groupby.std/var/sem/size/ohlc/describe` as a reminder to fix(they are failing currently)
- [ ] closes #xxxx
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39473 | 2021-01-30T00:52:12Z | 2021-02-20T20:32:14Z | 2021-02-20T20:32:14Z | 2021-02-20T20:32:26Z |
TST/REF: directories for test_period, test_datetimes, test_timedeltas | diff --git a/pandas/tests/arrays/datetimes/__init__.py b/pandas/tests/arrays/datetimes/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/arrays/datetimes/test_constructors.py b/pandas/tests/arrays/datetimes/test_constructors.py
new file mode 100644
index 0000000000000..cd7d9a479ab38
--- /dev/null
+++ b/pandas/tests/arrays/datetimes/test_constructors.py
@@ -0,0 +1,156 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import DatetimeArray
+from pandas.core.arrays.datetimes import sequence_to_dt64ns
+
+
+class TestDatetimeArrayConstructor:
+ def test_from_sequence_invalid_type(self):
+ mi = pd.MultiIndex.from_product([np.arange(5), np.arange(5)])
+ with pytest.raises(TypeError, match="Cannot create a DatetimeArray"):
+ DatetimeArray._from_sequence(mi)
+
+ def test_only_1dim_accepted(self):
+ arr = np.array([0, 1, 2, 3], dtype="M8[h]").astype("M8[ns]")
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
+ DatetimeArray(arr.reshape(2, 2, 1))
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 0-dim
+ DatetimeArray(arr[[0]].squeeze())
+
+ def test_freq_validation(self):
+ # GH#24623 check that invalid instances cannot be created with the
+ # public constructor
+ arr = np.arange(5, dtype=np.int64) * 3600 * 10 ** 9
+
+ msg = (
+ "Inferred frequency H from passed values does not "
+ "conform to passed frequency W-SUN"
+ )
+ with pytest.raises(ValueError, match=msg):
+ DatetimeArray(arr, freq="W")
+
+ @pytest.mark.parametrize(
+ "meth",
+ [
+ DatetimeArray._from_sequence,
+ sequence_to_dt64ns,
+ pd.to_datetime,
+ pd.DatetimeIndex,
+ ],
+ )
+ def test_mixing_naive_tzaware_raises(self, meth):
+ # GH#24569
+ arr = np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")])
+
+ msg = (
+ "Cannot mix tz-aware with tz-naive values|"
+ "Tz-aware datetime.datetime cannot be converted "
+ "to datetime64 unless utc=True"
+ )
+
+ for obj in [arr, arr[::-1]]:
+ # check that we raise regardless of whether naive is found
+ # before aware or vice-versa
+ with pytest.raises(ValueError, match=msg):
+ meth(obj)
+
+ def test_from_pandas_array(self):
+ arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10 ** 9
+
+ result = DatetimeArray._from_sequence(arr)._with_freq("infer")
+
+ expected = pd.date_range("1970-01-01", periods=5, freq="H")._data
+ tm.assert_datetime_array_equal(result, expected)
+
+ def test_mismatched_timezone_raises(self):
+ arr = DatetimeArray(
+ np.array(["2000-01-01T06:00:00"], dtype="M8[ns]"),
+ dtype=DatetimeTZDtype(tz="US/Central"),
+ )
+ dtype = DatetimeTZDtype(tz="US/Eastern")
+ with pytest.raises(TypeError, match="Timezone of the array"):
+ DatetimeArray(arr, dtype=dtype)
+
+ def test_non_array_raises(self):
+ with pytest.raises(ValueError, match="list"):
+ DatetimeArray([1, 2, 3])
+
+ def test_bool_dtype_raises(self):
+ arr = np.array([1, 2, 3], dtype="bool")
+
+ with pytest.raises(
+ ValueError, match="The dtype of 'values' is incorrect.*bool"
+ ):
+ DatetimeArray(arr)
+
+ msg = r"dtype bool cannot be converted to datetime64\[ns\]"
+ with pytest.raises(TypeError, match=msg):
+ DatetimeArray._from_sequence(arr)
+
+ with pytest.raises(TypeError, match=msg):
+ sequence_to_dt64ns(arr)
+
+ with pytest.raises(TypeError, match=msg):
+ pd.DatetimeIndex(arr)
+
+ with pytest.raises(TypeError, match=msg):
+ pd.to_datetime(arr)
+
+ def test_incorrect_dtype_raises(self):
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
+
+ def test_freq_infer_raises(self):
+ with pytest.raises(ValueError, match="Frequency inference"):
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), freq="infer")
+
+ def test_copy(self):
+ data = np.array([1, 2, 3], dtype="M8[ns]")
+ arr = DatetimeArray(data, copy=False)
+ assert arr._data is data
+
+ arr = DatetimeArray(data, copy=True)
+ assert arr._data is not data
+
+
+class TestSequenceToDT64NS:
+ def test_tz_dtype_mismatch_raises(self):
+ arr = DatetimeArray._from_sequence(
+ ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
+ )
+ with pytest.raises(TypeError, match="data is already tz-aware"):
+ sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="UTC"))
+
+ def test_tz_dtype_matches(self):
+ arr = DatetimeArray._from_sequence(
+ ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
+ )
+ result, _, _ = sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="US/Central"))
+ tm.assert_numpy_array_equal(arr._data, result)
+
+ @pytest.mark.parametrize("order", ["F", "C"])
+ def test_2d(self, order):
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
+ arr = np.array(dti, dtype=object).reshape(3, 2)
+ if order == "F":
+ arr = arr.T
+
+ res = sequence_to_dt64ns(arr)
+ expected = sequence_to_dt64ns(arr.ravel())
+
+ tm.assert_numpy_array_equal(res[0].ravel(), expected[0])
+ assert res[1] == expected[1]
+ assert res[2] == expected[2]
+
+ res = DatetimeArray._from_sequence(arr)
+ expected = DatetimeArray._from_sequence(arr.ravel()).reshape(arr.shape)
+ tm.assert_datetime_array_equal(res, expected)
diff --git a/pandas/tests/arrays/datetimes/test_reductions.py b/pandas/tests/arrays/datetimes/test_reductions.py
new file mode 100644
index 0000000000000..0d30dc1bf2a6d
--- /dev/null
+++ b/pandas/tests/arrays/datetimes/test_reductions.py
@@ -0,0 +1,175 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
+
+import pandas as pd
+from pandas import NaT
+import pandas._testing as tm
+from pandas.core.arrays import DatetimeArray
+
+
+class TestReductions:
+ @pytest.fixture
+ def arr1d(self, tz_naive_fixture):
+ tz = tz_naive_fixture
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
+ arr = DatetimeArray._from_sequence(
+ [
+ "2000-01-03",
+ "2000-01-03",
+ "NaT",
+ "2000-01-02",
+ "2000-01-05",
+ "2000-01-04",
+ ],
+ dtype=dtype,
+ )
+ return arr
+
+ def test_min_max(self, arr1d):
+ arr = arr1d
+ tz = arr.tz
+
+ result = arr.min()
+ expected = pd.Timestamp("2000-01-02", tz=tz)
+ assert result == expected
+
+ result = arr.max()
+ expected = pd.Timestamp("2000-01-05", tz=tz)
+ assert result == expected
+
+ result = arr.min(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.max(skipna=False)
+ assert result is pd.NaT
+
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_min_max_empty(self, skipna, tz):
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
+ arr = DatetimeArray._from_sequence([], dtype=dtype)
+ result = arr.min(skipna=skipna)
+ assert result is pd.NaT
+
+ result = arr.max(skipna=skipna)
+ assert result is pd.NaT
+
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_median_empty(self, skipna, tz):
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
+ arr = DatetimeArray._from_sequence([], dtype=dtype)
+ result = arr.median(skipna=skipna)
+ assert result is pd.NaT
+
+ arr = arr.reshape(0, 3)
+ result = arr.median(axis=0, skipna=skipna)
+ expected = type(arr)._from_sequence([pd.NaT, pd.NaT, pd.NaT], dtype=arr.dtype)
+ tm.assert_equal(result, expected)
+
+ result = arr.median(axis=1, skipna=skipna)
+ expected = type(arr)._from_sequence([], dtype=arr.dtype)
+ tm.assert_equal(result, expected)
+
+ def test_median(self, arr1d):
+ arr = arr1d
+
+ result = arr.median()
+ assert result == arr[0]
+ result = arr.median(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.dropna().median(skipna=False)
+ assert result == arr[0]
+
+ result = arr.median(axis=0)
+ assert result == arr[0]
+
+ def test_median_axis(self, arr1d):
+ arr = arr1d
+ assert arr.median(axis=0) == arr.median()
+ assert arr.median(axis=0, skipna=False) is pd.NaT
+
+ msg = r"abs\(axis\) must be less than ndim"
+ with pytest.raises(ValueError, match=msg):
+ arr.median(axis=1)
+
+ @pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning")
+ def test_median_2d(self, arr1d):
+ arr = arr1d.reshape(1, -1)
+
+ # axis = None
+ assert arr.median() == arr1d.median()
+ assert arr.median(skipna=False) is pd.NaT
+
+ # axis = 0
+ result = arr.median(axis=0)
+ expected = arr1d
+ tm.assert_equal(result, expected)
+
+ # Since column 3 is all-NaT, we get NaT there with or without skipna
+ result = arr.median(axis=0, skipna=False)
+ expected = arr1d
+ tm.assert_equal(result, expected)
+
+ # axis = 1
+ result = arr.median(axis=1)
+ expected = type(arr)._from_sequence([arr1d.median()])
+ tm.assert_equal(result, expected)
+
+ result = arr.median(axis=1, skipna=False)
+ expected = type(arr)._from_sequence([pd.NaT], dtype=arr.dtype)
+ tm.assert_equal(result, expected)
+
+ def test_mean(self, arr1d):
+ arr = arr1d
+
+ # manually verified result
+ expected = arr[0] + 0.4 * pd.Timedelta(days=1)
+
+ result = arr.mean()
+ assert result == expected
+ result = arr.mean(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.dropna().mean(skipna=False)
+ assert result == expected
+
+ result = arr.mean(axis=0)
+ assert result == expected
+
+ def test_mean_2d(self):
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
+ dta = dti._data.reshape(3, 2)
+
+ result = dta.mean(axis=0)
+ expected = dta[1]
+ tm.assert_datetime_array_equal(result, expected)
+
+ result = dta.mean(axis=1)
+ expected = dta[:, 0] + pd.Timedelta(hours=12)
+ tm.assert_datetime_array_equal(result, expected)
+
+ result = dta.mean(axis=None)
+ expected = dti.mean()
+ assert result == expected
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_mean_empty(self, arr1d, skipna):
+ arr = arr1d[:0]
+
+ assert arr.mean(skipna=skipna) is NaT
+
+ arr2d = arr.reshape(0, 3)
+ result = arr2d.mean(axis=0, skipna=skipna)
+ expected = DatetimeArray._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
+ tm.assert_datetime_array_equal(result, expected)
+
+ result = arr2d.mean(axis=1, skipna=skipna)
+ expected = arr # i.e. 1D, empty
+ tm.assert_datetime_array_equal(result, expected)
+
+ result = arr2d.mean(axis=None, skipna=skipna)
+ assert result is NaT
diff --git a/pandas/tests/arrays/period/__init__.py b/pandas/tests/arrays/period/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/arrays/period/test_arrow_compat.py b/pandas/tests/arrays/period/test_arrow_compat.py
new file mode 100644
index 0000000000000..8dc9d2a996728
--- /dev/null
+++ b/pandas/tests/arrays/period/test_arrow_compat.py
@@ -0,0 +1,115 @@
+import pytest
+
+import pandas.util._test_decorators as td
+
+from pandas.core.dtypes.dtypes import PeriodDtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import PeriodArray, period_array
+
+pyarrow_skip = pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+
+
+@pyarrow_skip
+def test_arrow_extension_type():
+ from pandas.core.arrays._arrow_utils import ArrowPeriodType
+
+ p1 = ArrowPeriodType("D")
+ p2 = ArrowPeriodType("D")
+ p3 = ArrowPeriodType("M")
+
+ assert p1.freq == "D"
+ assert p1 == p2
+ assert not p1 == p3
+ assert hash(p1) == hash(p2)
+ assert not hash(p1) == hash(p3)
+
+
+@pyarrow_skip
+@pytest.mark.parametrize(
+ "data, freq",
+ [
+ (pd.date_range("2017", periods=3), "D"),
+ (pd.date_range("2017", periods=3, freq="A"), "A-DEC"),
+ ],
+)
+def test_arrow_array(data, freq):
+ import pyarrow as pa
+
+ from pandas.core.arrays._arrow_utils import ArrowPeriodType
+
+ periods = period_array(data, freq=freq)
+ result = pa.array(periods)
+ assert isinstance(result.type, ArrowPeriodType)
+ assert result.type.freq == freq
+ expected = pa.array(periods.asi8, type="int64")
+ assert result.storage.equals(expected)
+
+ # convert to its storage type
+ result = pa.array(periods, type=pa.int64())
+ assert result.equals(expected)
+
+ # unsupported conversions
+ msg = "Not supported to convert PeriodArray to 'double' type"
+ with pytest.raises(TypeError, match=msg):
+ pa.array(periods, type="float64")
+
+ with pytest.raises(TypeError, match="different 'freq'"):
+ pa.array(periods, type=ArrowPeriodType("T"))
+
+
+@pyarrow_skip
+def test_arrow_array_missing():
+ import pyarrow as pa
+
+ from pandas.core.arrays._arrow_utils import ArrowPeriodType
+
+ arr = PeriodArray([1, 2, 3], freq="D")
+ arr[1] = pd.NaT
+
+ result = pa.array(arr)
+ assert isinstance(result.type, ArrowPeriodType)
+ assert result.type.freq == "D"
+ expected = pa.array([1, None, 3], type="int64")
+ assert result.storage.equals(expected)
+
+
+@pyarrow_skip
+def test_arrow_table_roundtrip():
+ import pyarrow as pa
+
+ from pandas.core.arrays._arrow_utils import ArrowPeriodType
+
+ arr = PeriodArray([1, 2, 3], freq="D")
+ arr[1] = pd.NaT
+ df = pd.DataFrame({"a": arr})
+
+ table = pa.table(df)
+ assert isinstance(table.field("a").type, ArrowPeriodType)
+ result = table.to_pandas()
+ assert isinstance(result["a"].dtype, PeriodDtype)
+ tm.assert_frame_equal(result, df)
+
+ table2 = pa.concat_tables([table, table])
+ result = table2.to_pandas()
+ expected = pd.concat([df, df], ignore_index=True)
+ tm.assert_frame_equal(result, expected)
+
+
+@pyarrow_skip
+def test_arrow_table_roundtrip_without_metadata():
+ import pyarrow as pa
+
+ arr = PeriodArray([1, 2, 3], freq="H")
+ arr[1] = pd.NaT
+ df = pd.DataFrame({"a": arr})
+
+ table = pa.table(df)
+ # remove the metadata
+ table = table.replace_schema_metadata()
+ assert table.schema.metadata is None
+
+ result = table.to_pandas()
+ assert isinstance(result["a"].dtype, PeriodDtype)
+ tm.assert_frame_equal(result, df)
diff --git a/pandas/tests/arrays/period/test_astype.py b/pandas/tests/arrays/period/test_astype.py
new file mode 100644
index 0000000000000..52cd28c8d5acc
--- /dev/null
+++ b/pandas/tests/arrays/period/test_astype.py
@@ -0,0 +1,70 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.dtypes import PeriodDtype
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import period_array
+
+
+@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
+def test_astype(dtype):
+ # We choose to ignore the sign and size of integers for
+ # Period/Datetime/Timedelta astype
+ arr = period_array(["2000", "2001", None], freq="D")
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(dtype)
+
+ if np.dtype(dtype).kind == "u":
+ expected_dtype = np.dtype("uint64")
+ else:
+ expected_dtype = np.dtype("int64")
+
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ expected = arr.astype(expected_dtype)
+
+ assert result.dtype == expected_dtype
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_astype_copies():
+ arr = period_array(["2000", "2001", None], freq="D")
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(np.int64, copy=False)
+
+ # Add the `.base`, since we now use `.asi8` which returns a view.
+ # We could maybe override it in PeriodArray to return ._data directly.
+ assert result.base is arr._data
+
+ with tm.assert_produces_warning(FutureWarning):
+ # astype(int..) deprecated
+ result = arr.astype(np.int64, copy=True)
+ assert result is not arr._data
+ tm.assert_numpy_array_equal(result, arr._data.view("i8"))
+
+
+def test_astype_categorical():
+ arr = period_array(["2000", "2001", "2001", None], freq="D")
+ result = arr.astype("category")
+ categories = pd.PeriodIndex(["2000", "2001"], freq="D")
+ expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories)
+ tm.assert_categorical_equal(result, expected)
+
+
+def test_astype_period():
+ arr = period_array(["2000", "2001", None], freq="D")
+ result = arr.astype(PeriodDtype("M"))
+ expected = period_array(["2000", "2001", None], freq="M")
+ tm.assert_period_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("other", ["datetime64[ns]", "timedelta64[ns]"])
+def test_astype_datetime(other):
+ arr = period_array(["2000", "2001", None], freq="D")
+ # slice off the [ns] so that the regex matches.
+ with pytest.raises(TypeError, match=other[:-4]):
+ arr.astype(other)
diff --git a/pandas/tests/arrays/period/test_constructors.py b/pandas/tests/arrays/period/test_constructors.py
new file mode 100644
index 0000000000000..0a8a106767fb6
--- /dev/null
+++ b/pandas/tests/arrays/period/test_constructors.py
@@ -0,0 +1,95 @@
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs import iNaT
+from pandas._libs.tslibs.period import IncompatibleFrequency
+
+import pandas as pd
+import pandas._testing as tm
+from pandas.core.arrays import PeriodArray, period_array
+
+
+@pytest.mark.parametrize(
+ "data, freq, expected",
+ [
+ ([pd.Period("2017", "D")], None, [17167]),
+ ([pd.Period("2017", "D")], "D", [17167]),
+ ([2017], "D", [17167]),
+ (["2017"], "D", [17167]),
+ ([pd.Period("2017", "D")], pd.tseries.offsets.Day(), [17167]),
+ ([pd.Period("2017", "D"), None], None, [17167, iNaT]),
+ (pd.Series(pd.date_range("2017", periods=3)), None, [17167, 17168, 17169]),
+ (pd.date_range("2017", periods=3), None, [17167, 17168, 17169]),
+ (pd.period_range("2017", periods=4, freq="Q"), None, [188, 189, 190, 191]),
+ ],
+)
+def test_period_array_ok(data, freq, expected):
+ result = period_array(data, freq=freq).asi8
+ expected = np.asarray(expected, dtype=np.int64)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_period_array_readonly_object():
+ # https://github.com/pandas-dev/pandas/issues/25403
+ pa = period_array([pd.Period("2019-01-01")])
+ arr = np.asarray(pa, dtype="object")
+ arr.setflags(write=False)
+
+ result = period_array(arr)
+ tm.assert_period_array_equal(result, pa)
+
+ result = pd.Series(arr)
+ tm.assert_series_equal(result, pd.Series(pa))
+
+ result = pd.DataFrame({"A": arr})
+ tm.assert_frame_equal(result, pd.DataFrame({"A": pa}))
+
+
+def test_from_datetime64_freq_changes():
+ # https://github.com/pandas-dev/pandas/issues/23438
+ arr = pd.date_range("2017", periods=3, freq="D")
+ result = PeriodArray._from_datetime64(arr, freq="M")
+ expected = period_array(["2017-01-01", "2017-01-01", "2017-01-01"], freq="M")
+ tm.assert_period_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, freq, msg",
+ [
+ (
+ [pd.Period("2017", "D"), pd.Period("2017", "A")],
+ None,
+ "Input has different freq",
+ ),
+ ([pd.Period("2017", "D")], "A", "Input has different freq"),
+ ],
+)
+def test_period_array_raises(data, freq, msg):
+ with pytest.raises(IncompatibleFrequency, match=msg):
+ period_array(data, freq)
+
+
+def test_period_array_non_period_series_raies():
+ ser = pd.Series([1, 2, 3])
+ with pytest.raises(TypeError, match="dtype"):
+ PeriodArray(ser, freq="D")
+
+
+def test_period_array_freq_mismatch():
+ arr = period_array(["2000", "2001"], freq="D")
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ PeriodArray(arr, freq="M")
+
+ with pytest.raises(IncompatibleFrequency, match="freq"):
+ PeriodArray(arr, freq=pd.tseries.offsets.MonthEnd())
+
+
+def test_from_sequence_disallows_i8():
+ arr = period_array(["2000", "2001"], freq="D")
+
+ msg = str(arr[0].ordinal)
+ with pytest.raises(TypeError, match=msg):
+ PeriodArray._from_sequence(arr.asi8, dtype=arr.dtype)
+
+ with pytest.raises(TypeError, match=msg):
+ PeriodArray._from_sequence(list(arr.asi8), dtype=arr.dtype)
diff --git a/pandas/tests/arrays/period/test_reductions.py b/pandas/tests/arrays/period/test_reductions.py
new file mode 100644
index 0000000000000..2889cc786dd71
--- /dev/null
+++ b/pandas/tests/arrays/period/test_reductions.py
@@ -0,0 +1,42 @@
+import pytest
+
+import pandas as pd
+from pandas.core.arrays import period_array
+
+
+class TestReductions:
+ def test_min_max(self):
+ arr = period_array(
+ [
+ "2000-01-03",
+ "2000-01-03",
+ "NaT",
+ "2000-01-02",
+ "2000-01-05",
+ "2000-01-04",
+ ],
+ freq="D",
+ )
+
+ result = arr.min()
+ expected = pd.Period("2000-01-02", freq="D")
+ assert result == expected
+
+ result = arr.max()
+ expected = pd.Period("2000-01-05", freq="D")
+ assert result == expected
+
+ result = arr.min(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.max(skipna=False)
+ assert result is pd.NaT
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_min_max_empty(self, skipna):
+ arr = period_array([], freq="D")
+ result = arr.min(skipna=skipna)
+ assert result is pd.NaT
+
+ result = arr.max(skipna=skipna)
+ assert result is pd.NaT
diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py
index 587d3c466c631..86c4b4c5ce63d 100644
--- a/pandas/tests/arrays/test_datetimes.py
+++ b/pandas/tests/arrays/test_datetimes.py
@@ -9,123 +9,8 @@
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
-from pandas import NaT
import pandas._testing as tm
from pandas.core.arrays import DatetimeArray
-from pandas.core.arrays.datetimes import sequence_to_dt64ns
-
-
-class TestDatetimeArrayConstructor:
- def test_from_sequence_invalid_type(self):
- mi = pd.MultiIndex.from_product([np.arange(5), np.arange(5)])
- with pytest.raises(TypeError, match="Cannot create a DatetimeArray"):
- DatetimeArray._from_sequence(mi)
-
- def test_only_1dim_accepted(self):
- arr = np.array([0, 1, 2, 3], dtype="M8[h]").astype("M8[ns]")
-
- with pytest.raises(ValueError, match="Only 1-dimensional"):
- # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
- DatetimeArray(arr.reshape(2, 2, 1))
-
- with pytest.raises(ValueError, match="Only 1-dimensional"):
- # 0-dim
- DatetimeArray(arr[[0]].squeeze())
-
- def test_freq_validation(self):
- # GH#24623 check that invalid instances cannot be created with the
- # public constructor
- arr = np.arange(5, dtype=np.int64) * 3600 * 10 ** 9
-
- msg = (
- "Inferred frequency H from passed values does not "
- "conform to passed frequency W-SUN"
- )
- with pytest.raises(ValueError, match=msg):
- DatetimeArray(arr, freq="W")
-
- @pytest.mark.parametrize(
- "meth",
- [
- DatetimeArray._from_sequence,
- sequence_to_dt64ns,
- pd.to_datetime,
- pd.DatetimeIndex,
- ],
- )
- def test_mixing_naive_tzaware_raises(self, meth):
- # GH#24569
- arr = np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")])
-
- msg = (
- "Cannot mix tz-aware with tz-naive values|"
- "Tz-aware datetime.datetime cannot be converted "
- "to datetime64 unless utc=True"
- )
-
- for obj in [arr, arr[::-1]]:
- # check that we raise regardless of whether naive is found
- # before aware or vice-versa
- with pytest.raises(ValueError, match=msg):
- meth(obj)
-
- def test_from_pandas_array(self):
- arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10 ** 9
-
- result = DatetimeArray._from_sequence(arr)._with_freq("infer")
-
- expected = pd.date_range("1970-01-01", periods=5, freq="H")._data
- tm.assert_datetime_array_equal(result, expected)
-
- def test_mismatched_timezone_raises(self):
- arr = DatetimeArray(
- np.array(["2000-01-01T06:00:00"], dtype="M8[ns]"),
- dtype=DatetimeTZDtype(tz="US/Central"),
- )
- dtype = DatetimeTZDtype(tz="US/Eastern")
- with pytest.raises(TypeError, match="Timezone of the array"):
- DatetimeArray(arr, dtype=dtype)
-
- def test_non_array_raises(self):
- with pytest.raises(ValueError, match="list"):
- DatetimeArray([1, 2, 3])
-
- def test_bool_dtype_raises(self):
- arr = np.array([1, 2, 3], dtype="bool")
-
- with pytest.raises(
- ValueError, match="The dtype of 'values' is incorrect.*bool"
- ):
- DatetimeArray(arr)
-
- msg = r"dtype bool cannot be converted to datetime64\[ns\]"
- with pytest.raises(TypeError, match=msg):
- DatetimeArray._from_sequence(arr)
-
- with pytest.raises(TypeError, match=msg):
- sequence_to_dt64ns(arr)
-
- with pytest.raises(TypeError, match=msg):
- pd.DatetimeIndex(arr)
-
- with pytest.raises(TypeError, match=msg):
- pd.to_datetime(arr)
-
- def test_incorrect_dtype_raises(self):
- with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
- DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
-
- def test_freq_infer_raises(self):
- with pytest.raises(ValueError, match="Frequency inference"):
- DatetimeArray(np.array([1, 2, 3], dtype="i8"), freq="infer")
-
- def test_copy(self):
- data = np.array([1, 2, 3], dtype="M8[ns]")
- arr = DatetimeArray(data, copy=False)
- assert arr._data is data
-
- arr = DatetimeArray(data, copy=True)
- assert arr._data is not data
class TestDatetimeArrayComparisons:
@@ -471,203 +356,3 @@ def test_tz_localize_t2d(self):
roundtrip = expected.tz_localize("US/Pacific")
tm.assert_datetime_array_equal(roundtrip, dta)
-
-
-class TestSequenceToDT64NS:
- def test_tz_dtype_mismatch_raises(self):
- arr = DatetimeArray._from_sequence(
- ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
- )
- with pytest.raises(TypeError, match="data is already tz-aware"):
- sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="UTC"))
-
- def test_tz_dtype_matches(self):
- arr = DatetimeArray._from_sequence(
- ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
- )
- result, _, _ = sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="US/Central"))
- tm.assert_numpy_array_equal(arr._data, result)
-
- @pytest.mark.parametrize("order", ["F", "C"])
- def test_2d(self, order):
- dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
- arr = np.array(dti, dtype=object).reshape(3, 2)
- if order == "F":
- arr = arr.T
-
- res = sequence_to_dt64ns(arr)
- expected = sequence_to_dt64ns(arr.ravel())
-
- tm.assert_numpy_array_equal(res[0].ravel(), expected[0])
- assert res[1] == expected[1]
- assert res[2] == expected[2]
-
- res = DatetimeArray._from_sequence(arr)
- expected = DatetimeArray._from_sequence(arr.ravel()).reshape(arr.shape)
- tm.assert_datetime_array_equal(res, expected)
-
-
-class TestReductions:
- @pytest.fixture
- def arr1d(self, tz_naive_fixture):
- tz = tz_naive_fixture
- dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
- arr = DatetimeArray._from_sequence(
- [
- "2000-01-03",
- "2000-01-03",
- "NaT",
- "2000-01-02",
- "2000-01-05",
- "2000-01-04",
- ],
- dtype=dtype,
- )
- return arr
-
- def test_min_max(self, arr1d):
- arr = arr1d
- tz = arr.tz
-
- result = arr.min()
- expected = pd.Timestamp("2000-01-02", tz=tz)
- assert result == expected
-
- result = arr.max()
- expected = pd.Timestamp("2000-01-05", tz=tz)
- assert result == expected
-
- result = arr.min(skipna=False)
- assert result is pd.NaT
-
- result = arr.max(skipna=False)
- assert result is pd.NaT
-
- @pytest.mark.parametrize("tz", [None, "US/Central"])
- @pytest.mark.parametrize("skipna", [True, False])
- def test_min_max_empty(self, skipna, tz):
- dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
- arr = DatetimeArray._from_sequence([], dtype=dtype)
- result = arr.min(skipna=skipna)
- assert result is pd.NaT
-
- result = arr.max(skipna=skipna)
- assert result is pd.NaT
-
- @pytest.mark.parametrize("tz", [None, "US/Central"])
- @pytest.mark.parametrize("skipna", [True, False])
- def test_median_empty(self, skipna, tz):
- dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
- arr = DatetimeArray._from_sequence([], dtype=dtype)
- result = arr.median(skipna=skipna)
- assert result is pd.NaT
-
- arr = arr.reshape(0, 3)
- result = arr.median(axis=0, skipna=skipna)
- expected = type(arr)._from_sequence([pd.NaT, pd.NaT, pd.NaT], dtype=arr.dtype)
- tm.assert_equal(result, expected)
-
- result = arr.median(axis=1, skipna=skipna)
- expected = type(arr)._from_sequence([], dtype=arr.dtype)
- tm.assert_equal(result, expected)
-
- def test_median(self, arr1d):
- arr = arr1d
-
- result = arr.median()
- assert result == arr[0]
- result = arr.median(skipna=False)
- assert result is pd.NaT
-
- result = arr.dropna().median(skipna=False)
- assert result == arr[0]
-
- result = arr.median(axis=0)
- assert result == arr[0]
-
- def test_median_axis(self, arr1d):
- arr = arr1d
- assert arr.median(axis=0) == arr.median()
- assert arr.median(axis=0, skipna=False) is pd.NaT
-
- msg = r"abs\(axis\) must be less than ndim"
- with pytest.raises(ValueError, match=msg):
- arr.median(axis=1)
-
- @pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning")
- def test_median_2d(self, arr1d):
- arr = arr1d.reshape(1, -1)
-
- # axis = None
- assert arr.median() == arr1d.median()
- assert arr.median(skipna=False) is pd.NaT
-
- # axis = 0
- result = arr.median(axis=0)
- expected = arr1d
- tm.assert_equal(result, expected)
-
- # Since column 3 is all-NaT, we get NaT there with or without skipna
- result = arr.median(axis=0, skipna=False)
- expected = arr1d
- tm.assert_equal(result, expected)
-
- # axis = 1
- result = arr.median(axis=1)
- expected = type(arr)._from_sequence([arr1d.median()])
- tm.assert_equal(result, expected)
-
- result = arr.median(axis=1, skipna=False)
- expected = type(arr)._from_sequence([pd.NaT], dtype=arr.dtype)
- tm.assert_equal(result, expected)
-
- def test_mean(self, arr1d):
- arr = arr1d
-
- # manually verified result
- expected = arr[0] + 0.4 * pd.Timedelta(days=1)
-
- result = arr.mean()
- assert result == expected
- result = arr.mean(skipna=False)
- assert result is pd.NaT
-
- result = arr.dropna().mean(skipna=False)
- assert result == expected
-
- result = arr.mean(axis=0)
- assert result == expected
-
- def test_mean_2d(self):
- dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
- dta = dti._data.reshape(3, 2)
-
- result = dta.mean(axis=0)
- expected = dta[1]
- tm.assert_datetime_array_equal(result, expected)
-
- result = dta.mean(axis=1)
- expected = dta[:, 0] + pd.Timedelta(hours=12)
- tm.assert_datetime_array_equal(result, expected)
-
- result = dta.mean(axis=None)
- expected = dti.mean()
- assert result == expected
-
- @pytest.mark.parametrize("skipna", [True, False])
- def test_mean_empty(self, arr1d, skipna):
- arr = arr1d[:0]
-
- assert arr.mean(skipna=skipna) is NaT
-
- arr2d = arr.reshape(0, 3)
- result = arr2d.mean(axis=0, skipna=skipna)
- expected = DatetimeArray._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
- tm.assert_datetime_array_equal(result, expected)
-
- result = arr2d.mean(axis=1, skipna=skipna)
- expected = arr # i.e. 1D, empty
- tm.assert_datetime_array_equal(result, expected)
-
- result = arr2d.mean(axis=None, skipna=skipna)
- assert result is NaT
diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py
index 443eced3922ac..d044b191cf279 100644
--- a/pandas/tests/arrays/test_period.py
+++ b/pandas/tests/arrays/test_period.py
@@ -3,7 +3,6 @@
from pandas._libs.tslibs import iNaT
from pandas._libs.tslibs.period import IncompatibleFrequency
-import pandas.util._test_decorators as td
from pandas.core.dtypes.base import registry
from pandas.core.dtypes.dtypes import PeriodDtype
@@ -27,92 +26,6 @@ def test_registered():
# period_array
-@pytest.mark.parametrize(
- "data, freq, expected",
- [
- ([pd.Period("2017", "D")], None, [17167]),
- ([pd.Period("2017", "D")], "D", [17167]),
- ([2017], "D", [17167]),
- (["2017"], "D", [17167]),
- ([pd.Period("2017", "D")], pd.tseries.offsets.Day(), [17167]),
- ([pd.Period("2017", "D"), None], None, [17167, iNaT]),
- (pd.Series(pd.date_range("2017", periods=3)), None, [17167, 17168, 17169]),
- (pd.date_range("2017", periods=3), None, [17167, 17168, 17169]),
- (pd.period_range("2017", periods=4, freq="Q"), None, [188, 189, 190, 191]),
- ],
-)
-def test_period_array_ok(data, freq, expected):
- result = period_array(data, freq=freq).asi8
- expected = np.asarray(expected, dtype=np.int64)
- tm.assert_numpy_array_equal(result, expected)
-
-
-def test_period_array_readonly_object():
- # https://github.com/pandas-dev/pandas/issues/25403
- pa = period_array([pd.Period("2019-01-01")])
- arr = np.asarray(pa, dtype="object")
- arr.setflags(write=False)
-
- result = period_array(arr)
- tm.assert_period_array_equal(result, pa)
-
- result = pd.Series(arr)
- tm.assert_series_equal(result, pd.Series(pa))
-
- result = pd.DataFrame({"A": arr})
- tm.assert_frame_equal(result, pd.DataFrame({"A": pa}))
-
-
-def test_from_datetime64_freq_changes():
- # https://github.com/pandas-dev/pandas/issues/23438
- arr = pd.date_range("2017", periods=3, freq="D")
- result = PeriodArray._from_datetime64(arr, freq="M")
- expected = period_array(["2017-01-01", "2017-01-01", "2017-01-01"], freq="M")
- tm.assert_period_array_equal(result, expected)
-
-
-@pytest.mark.parametrize(
- "data, freq, msg",
- [
- (
- [pd.Period("2017", "D"), pd.Period("2017", "A")],
- None,
- "Input has different freq",
- ),
- ([pd.Period("2017", "D")], "A", "Input has different freq"),
- ],
-)
-def test_period_array_raises(data, freq, msg):
- with pytest.raises(IncompatibleFrequency, match=msg):
- period_array(data, freq)
-
-
-def test_period_array_non_period_series_raies():
- ser = pd.Series([1, 2, 3])
- with pytest.raises(TypeError, match="dtype"):
- PeriodArray(ser, freq="D")
-
-
-def test_period_array_freq_mismatch():
- arr = period_array(["2000", "2001"], freq="D")
- with pytest.raises(IncompatibleFrequency, match="freq"):
- PeriodArray(arr, freq="M")
-
- with pytest.raises(IncompatibleFrequency, match="freq"):
- PeriodArray(arr, freq=pd.tseries.offsets.MonthEnd())
-
-
-def test_from_sequence_disallows_i8():
- arr = period_array(["2000", "2001"], freq="D")
-
- msg = str(arr[0].ordinal)
- with pytest.raises(TypeError, match=msg):
- PeriodArray._from_sequence(arr.asi8, dtype=arr.dtype)
-
- with pytest.raises(TypeError, match=msg):
- PeriodArray._from_sequence(list(arr.asi8), dtype=arr.dtype)
-
-
def test_asi8():
result = period_array(["2000", "2001", None], freq="D").asi8
expected = np.array([10957, 11323, iNaT])
@@ -129,68 +42,6 @@ def test_take_raises():
arr.take([0, -1], allow_fill=True, fill_value="foo")
-@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
-def test_astype(dtype):
- # We choose to ignore the sign and size of integers for
- # Period/Datetime/Timedelta astype
- arr = period_array(["2000", "2001", None], freq="D")
- with tm.assert_produces_warning(FutureWarning):
- # astype(int..) deprecated
- result = arr.astype(dtype)
-
- if np.dtype(dtype).kind == "u":
- expected_dtype = np.dtype("uint64")
- else:
- expected_dtype = np.dtype("int64")
-
- with tm.assert_produces_warning(FutureWarning):
- # astype(int..) deprecated
- expected = arr.astype(expected_dtype)
-
- assert result.dtype == expected_dtype
- tm.assert_numpy_array_equal(result, expected)
-
-
-def test_astype_copies():
- arr = period_array(["2000", "2001", None], freq="D")
- with tm.assert_produces_warning(FutureWarning):
- # astype(int..) deprecated
- result = arr.astype(np.int64, copy=False)
-
- # Add the `.base`, since we now use `.asi8` which returns a view.
- # We could maybe override it in PeriodArray to return ._data directly.
- assert result.base is arr._data
-
- with tm.assert_produces_warning(FutureWarning):
- # astype(int..) deprecated
- result = arr.astype(np.int64, copy=True)
- assert result is not arr._data
- tm.assert_numpy_array_equal(result, arr._data.view("i8"))
-
-
-def test_astype_categorical():
- arr = period_array(["2000", "2001", "2001", None], freq="D")
- result = arr.astype("category")
- categories = pd.PeriodIndex(["2000", "2001"], freq="D")
- expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories)
- tm.assert_categorical_equal(result, expected)
-
-
-def test_astype_period():
- arr = period_array(["2000", "2001", None], freq="D")
- result = arr.astype(PeriodDtype("M"))
- expected = period_array(["2000", "2001", None], freq="M")
- tm.assert_period_array_equal(result, expected)
-
-
-@pytest.mark.parametrize("other", ["datetime64[ns]", "timedelta64[ns]"])
-def test_astype_datetime(other):
- arr = period_array(["2000", "2001", None], freq="D")
- # slice off the [ns] so that the regex matches.
- with pytest.raises(TypeError, match=other[:-4]):
- arr.astype(other)
-
-
def test_fillna_raises():
arr = period_array(["2000", "2001", "2002"], freq="D")
with pytest.raises(ValueError, match="Length"):
@@ -306,155 +157,3 @@ def test_repr_large():
"Length: 1000, dtype: period[D]"
)
assert result == expected
-
-
-# ----------------------------------------------------------------------------
-# Reductions
-
-
-class TestReductions:
- def test_min_max(self):
- arr = period_array(
- [
- "2000-01-03",
- "2000-01-03",
- "NaT",
- "2000-01-02",
- "2000-01-05",
- "2000-01-04",
- ],
- freq="D",
- )
-
- result = arr.min()
- expected = pd.Period("2000-01-02", freq="D")
- assert result == expected
-
- result = arr.max()
- expected = pd.Period("2000-01-05", freq="D")
- assert result == expected
-
- result = arr.min(skipna=False)
- assert result is pd.NaT
-
- result = arr.max(skipna=False)
- assert result is pd.NaT
-
- @pytest.mark.parametrize("skipna", [True, False])
- def test_min_max_empty(self, skipna):
- arr = period_array([], freq="D")
- result = arr.min(skipna=skipna)
- assert result is pd.NaT
-
- result = arr.max(skipna=skipna)
- assert result is pd.NaT
-
-
-# ----------------------------------------------------------------------------
-# Arrow interaction
-
-pyarrow_skip = pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.15.1.dev")
-
-
-@pyarrow_skip
-def test_arrow_extension_type():
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
-
- p1 = ArrowPeriodType("D")
- p2 = ArrowPeriodType("D")
- p3 = ArrowPeriodType("M")
-
- assert p1.freq == "D"
- assert p1 == p2
- assert not p1 == p3
- assert hash(p1) == hash(p2)
- assert not hash(p1) == hash(p3)
-
-
-@pyarrow_skip
-@pytest.mark.parametrize(
- "data, freq",
- [
- (pd.date_range("2017", periods=3), "D"),
- (pd.date_range("2017", periods=3, freq="A"), "A-DEC"),
- ],
-)
-def test_arrow_array(data, freq):
- import pyarrow as pa
-
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
-
- periods = period_array(data, freq=freq)
- result = pa.array(periods)
- assert isinstance(result.type, ArrowPeriodType)
- assert result.type.freq == freq
- expected = pa.array(periods.asi8, type="int64")
- assert result.storage.equals(expected)
-
- # convert to its storage type
- result = pa.array(periods, type=pa.int64())
- assert result.equals(expected)
-
- # unsupported conversions
- msg = "Not supported to convert PeriodArray to 'double' type"
- with pytest.raises(TypeError, match=msg):
- pa.array(periods, type="float64")
-
- with pytest.raises(TypeError, match="different 'freq'"):
- pa.array(periods, type=ArrowPeriodType("T"))
-
-
-@pyarrow_skip
-def test_arrow_array_missing():
- import pyarrow as pa
-
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
-
- arr = PeriodArray([1, 2, 3], freq="D")
- arr[1] = pd.NaT
-
- result = pa.array(arr)
- assert isinstance(result.type, ArrowPeriodType)
- assert result.type.freq == "D"
- expected = pa.array([1, None, 3], type="int64")
- assert result.storage.equals(expected)
-
-
-@pyarrow_skip
-def test_arrow_table_roundtrip():
- import pyarrow as pa
-
- from pandas.core.arrays._arrow_utils import ArrowPeriodType
-
- arr = PeriodArray([1, 2, 3], freq="D")
- arr[1] = pd.NaT
- df = pd.DataFrame({"a": arr})
-
- table = pa.table(df)
- assert isinstance(table.field("a").type, ArrowPeriodType)
- result = table.to_pandas()
- assert isinstance(result["a"].dtype, PeriodDtype)
- tm.assert_frame_equal(result, df)
-
- table2 = pa.concat_tables([table, table])
- result = table2.to_pandas()
- expected = pd.concat([df, df], ignore_index=True)
- tm.assert_frame_equal(result, expected)
-
-
-@pyarrow_skip
-def test_arrow_table_roundtrip_without_metadata():
- import pyarrow as pa
-
- arr = PeriodArray([1, 2, 3], freq="H")
- arr[1] = pd.NaT
- df = pd.DataFrame({"a": arr})
-
- table = pa.table(df)
- # remove the metadata
- table = table.replace_schema_metadata()
- assert table.schema.metadata is None
-
- result = table.to_pandas()
- assert isinstance(result["a"].dtype, PeriodDtype)
- tm.assert_frame_equal(result, df)
diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py
index 9d9ca41779b5a..9e2b8e0f1603e 100644
--- a/pandas/tests/arrays/test_timedeltas.py
+++ b/pandas/tests/arrays/test_timedeltas.py
@@ -4,81 +4,10 @@
import pandas as pd
from pandas import Timedelta
import pandas._testing as tm
-from pandas.core import nanops
from pandas.core.arrays import TimedeltaArray
-class TestTimedeltaArrayConstructor:
- def test_only_1dim_accepted(self):
- # GH#25282
- arr = np.array([0, 1, 2, 3], dtype="m8[h]").astype("m8[ns]")
-
- with pytest.raises(ValueError, match="Only 1-dimensional"):
- # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
- TimedeltaArray(arr.reshape(2, 2, 1))
-
- with pytest.raises(ValueError, match="Only 1-dimensional"):
- # 0-dim
- TimedeltaArray(arr[[0]].squeeze())
-
- def test_freq_validation(self):
- # ensure that the public constructor cannot create an invalid instance
- arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10 ** 9
-
- msg = (
- "Inferred frequency None from passed values does not "
- "conform to passed frequency D"
- )
- with pytest.raises(ValueError, match=msg):
- TimedeltaArray(arr.view("timedelta64[ns]"), freq="D")
-
- def test_non_array_raises(self):
- with pytest.raises(ValueError, match="list"):
- TimedeltaArray([1, 2, 3])
-
- def test_other_type_raises(self):
- with pytest.raises(ValueError, match="dtype bool cannot be converted"):
- TimedeltaArray(np.array([1, 2, 3], dtype="bool"))
-
- def test_incorrect_dtype_raises(self):
- # TODO: why TypeError for 'category' but ValueError for i8?
- with pytest.raises(
- ValueError, match=r"category cannot be converted to timedelta64\[ns\]"
- ):
- TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
-
- with pytest.raises(
- ValueError, match=r"dtype int64 cannot be converted to timedelta64\[ns\]"
- ):
- TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("int64"))
-
- def test_copy(self):
- data = np.array([1, 2, 3], dtype="m8[ns]")
- arr = TimedeltaArray(data, copy=False)
- assert arr._data is data
-
- arr = TimedeltaArray(data, copy=True)
- assert arr._data is not data
- assert arr._data.base is not data
-
-
class TestTimedeltaArray:
- # TODO: de-duplicate with test_npsum below
- def test_np_sum(self):
- # GH#25282
- vals = np.arange(5, dtype=np.int64).view("m8[h]").astype("m8[ns]")
- arr = TimedeltaArray(vals)
- result = np.sum(arr)
- assert result == vals.sum()
-
- result = np.sum(pd.TimedeltaIndex(arr))
- assert result == vals.sum()
-
- def test_from_sequence_dtype(self):
- msg = "dtype .*object.* cannot be converted to timedelta64"
- with pytest.raises(ValueError, match=msg):
- TimedeltaArray._from_sequence([], dtype=object)
-
@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
def test_astype_int(self, dtype):
arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")])
@@ -179,209 +108,3 @@ def test_neg_freq(self):
result = -arr
tm.assert_timedelta_array_equal(result, expected)
-
-
-class TestReductions:
- @pytest.mark.parametrize("name", ["std", "min", "max", "median", "mean"])
- @pytest.mark.parametrize("skipna", [True, False])
- def test_reductions_empty(self, name, skipna):
- tdi = pd.TimedeltaIndex([])
- arr = tdi.array
-
- result = getattr(tdi, name)(skipna=skipna)
- assert result is pd.NaT
-
- result = getattr(arr, name)(skipna=skipna)
- assert result is pd.NaT
-
- @pytest.mark.parametrize("skipna", [True, False])
- def test_sum_empty(self, skipna):
- tdi = pd.TimedeltaIndex([])
- arr = tdi.array
-
- result = tdi.sum(skipna=skipna)
- assert isinstance(result, Timedelta)
- assert result == Timedelta(0)
-
- result = arr.sum(skipna=skipna)
- assert isinstance(result, Timedelta)
- assert result == Timedelta(0)
-
- def test_min_max(self):
- arr = TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"])
-
- result = arr.min()
- expected = Timedelta("2H")
- assert result == expected
-
- result = arr.max()
- expected = Timedelta("5H")
- assert result == expected
-
- result = arr.min(skipna=False)
- assert result is pd.NaT
-
- result = arr.max(skipna=False)
- assert result is pd.NaT
-
- def test_sum(self):
- tdi = pd.TimedeltaIndex(["3H", "3H", "NaT", "2H", "5H", "4H"])
- arr = tdi.array
-
- result = arr.sum(skipna=True)
- expected = Timedelta(hours=17)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = tdi.sum(skipna=True)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = arr.sum(skipna=False)
- assert result is pd.NaT
-
- result = tdi.sum(skipna=False)
- assert result is pd.NaT
-
- result = arr.sum(min_count=9)
- assert result is pd.NaT
-
- result = tdi.sum(min_count=9)
- assert result is pd.NaT
-
- result = arr.sum(min_count=1)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = tdi.sum(min_count=1)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- def test_npsum(self):
- # GH#25335 np.sum should return a Timedelta, not timedelta64
- tdi = pd.TimedeltaIndex(["3H", "3H", "2H", "5H", "4H"])
- arr = tdi.array
-
- result = np.sum(tdi)
- expected = Timedelta(hours=17)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = np.sum(arr)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- def test_sum_2d_skipna_false(self):
- arr = np.arange(8).astype(np.int64).view("m8[s]").astype("m8[ns]").reshape(4, 2)
- arr[-1, -1] = "Nat"
-
- tda = TimedeltaArray(arr)
-
- result = tda.sum(skipna=False)
- assert result is pd.NaT
-
- result = tda.sum(axis=0, skipna=False)
- expected = pd.TimedeltaIndex([Timedelta(seconds=12), pd.NaT])._values
- tm.assert_timedelta_array_equal(result, expected)
-
- result = tda.sum(axis=1, skipna=False)
- expected = pd.TimedeltaIndex(
- [
- Timedelta(seconds=1),
- Timedelta(seconds=5),
- Timedelta(seconds=9),
- pd.NaT,
- ]
- )._values
- tm.assert_timedelta_array_equal(result, expected)
-
- # Adding a Timestamp makes this a test for DatetimeArray.std
- @pytest.mark.parametrize(
- "add",
- [
- Timedelta(0),
- pd.Timestamp.now(),
- pd.Timestamp.now("UTC"),
- pd.Timestamp.now("Asia/Tokyo"),
- ],
- )
- def test_std(self, add):
- tdi = pd.TimedeltaIndex(["0H", "4H", "NaT", "4H", "0H", "2H"]) + add
- arr = tdi.array
-
- result = arr.std(skipna=True)
- expected = Timedelta(hours=2)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = tdi.std(skipna=True)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- if getattr(arr, "tz", None) is None:
- result = nanops.nanstd(np.asarray(arr), skipna=True)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = arr.std(skipna=False)
- assert result is pd.NaT
-
- result = tdi.std(skipna=False)
- assert result is pd.NaT
-
- if getattr(arr, "tz", None) is None:
- result = nanops.nanstd(np.asarray(arr), skipna=False)
- assert result is pd.NaT
-
- def test_median(self):
- tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"])
- arr = tdi.array
-
- result = arr.median(skipna=True)
- expected = Timedelta(hours=2)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = tdi.median(skipna=True)
- assert isinstance(result, Timedelta)
- assert result == expected
-
- result = arr.median(skipna=False)
- assert result is pd.NaT
-
- result = tdi.median(skipna=False)
- assert result is pd.NaT
-
- def test_mean(self):
- tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"])
- arr = tdi._data
-
- # manually verified result
- expected = Timedelta(arr.dropna()._ndarray.mean())
-
- result = arr.mean()
- assert result == expected
- result = arr.mean(skipna=False)
- assert result is pd.NaT
-
- result = arr.dropna().mean(skipna=False)
- assert result == expected
-
- result = arr.mean(axis=0)
- assert result == expected
-
- def test_mean_2d(self):
- tdi = pd.timedelta_range("14 days", periods=6)
- tda = tdi._data.reshape(3, 2)
-
- result = tda.mean(axis=0)
- expected = tda[1]
- tm.assert_timedelta_array_equal(result, expected)
-
- result = tda.mean(axis=1)
- expected = tda[:, 0] + Timedelta(hours=12)
- tm.assert_timedelta_array_equal(result, expected)
-
- result = tda.mean(axis=None)
- expected = tdi.mean()
- assert result == expected
diff --git a/pandas/tests/arrays/timedeltas/__init__.py b/pandas/tests/arrays/timedeltas/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/arrays/timedeltas/test_constructors.py b/pandas/tests/arrays/timedeltas/test_constructors.py
new file mode 100644
index 0000000000000..d297e745f107b
--- /dev/null
+++ b/pandas/tests/arrays/timedeltas/test_constructors.py
@@ -0,0 +1,63 @@
+import numpy as np
+import pytest
+
+from pandas.core.arrays import TimedeltaArray
+
+
+class TestTimedeltaArrayConstructor:
+ def test_only_1dim_accepted(self):
+ # GH#25282
+ arr = np.array([0, 1, 2, 3], dtype="m8[h]").astype("m8[ns]")
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
+ TimedeltaArray(arr.reshape(2, 2, 1))
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 0-dim
+ TimedeltaArray(arr[[0]].squeeze())
+
+ def test_freq_validation(self):
+ # ensure that the public constructor cannot create an invalid instance
+ arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10 ** 9
+
+ msg = (
+ "Inferred frequency None from passed values does not "
+ "conform to passed frequency D"
+ )
+ with pytest.raises(ValueError, match=msg):
+ TimedeltaArray(arr.view("timedelta64[ns]"), freq="D")
+
+ def test_non_array_raises(self):
+ with pytest.raises(ValueError, match="list"):
+ TimedeltaArray([1, 2, 3])
+
+ def test_other_type_raises(self):
+ with pytest.raises(ValueError, match="dtype bool cannot be converted"):
+ TimedeltaArray(np.array([1, 2, 3], dtype="bool"))
+
+ def test_incorrect_dtype_raises(self):
+ # TODO: why TypeError for 'category' but ValueError for i8?
+ with pytest.raises(
+ ValueError, match=r"category cannot be converted to timedelta64\[ns\]"
+ ):
+ TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
+
+ with pytest.raises(
+ ValueError, match=r"dtype int64 cannot be converted to timedelta64\[ns\]"
+ ):
+ TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("int64"))
+
+ def test_copy(self):
+ data = np.array([1, 2, 3], dtype="m8[ns]")
+ arr = TimedeltaArray(data, copy=False)
+ assert arr._data is data
+
+ arr = TimedeltaArray(data, copy=True)
+ assert arr._data is not data
+ assert arr._data.base is not data
+
+ def test_from_sequence_dtype(self):
+ msg = "dtype .*object.* cannot be converted to timedelta64"
+ with pytest.raises(ValueError, match=msg):
+ TimedeltaArray._from_sequence([], dtype=object)
diff --git a/pandas/tests/arrays/timedeltas/test_reductions.py b/pandas/tests/arrays/timedeltas/test_reductions.py
new file mode 100644
index 0000000000000..5f278b09dc818
--- /dev/null
+++ b/pandas/tests/arrays/timedeltas/test_reductions.py
@@ -0,0 +1,225 @@
+import numpy as np
+import pytest
+
+import pandas as pd
+from pandas import Timedelta
+import pandas._testing as tm
+from pandas.core import nanops
+from pandas.core.arrays import TimedeltaArray
+
+
+class TestReductions:
+ @pytest.mark.parametrize("name", ["std", "min", "max", "median", "mean"])
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_reductions_empty(self, name, skipna):
+ tdi = pd.TimedeltaIndex([])
+ arr = tdi.array
+
+ result = getattr(tdi, name)(skipna=skipna)
+ assert result is pd.NaT
+
+ result = getattr(arr, name)(skipna=skipna)
+ assert result is pd.NaT
+
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_sum_empty(self, skipna):
+ tdi = pd.TimedeltaIndex([])
+ arr = tdi.array
+
+ result = tdi.sum(skipna=skipna)
+ assert isinstance(result, Timedelta)
+ assert result == Timedelta(0)
+
+ result = arr.sum(skipna=skipna)
+ assert isinstance(result, Timedelta)
+ assert result == Timedelta(0)
+
+ def test_min_max(self):
+ arr = TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"])
+
+ result = arr.min()
+ expected = Timedelta("2H")
+ assert result == expected
+
+ result = arr.max()
+ expected = Timedelta("5H")
+ assert result == expected
+
+ result = arr.min(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.max(skipna=False)
+ assert result is pd.NaT
+
+ def test_sum(self):
+ tdi = pd.TimedeltaIndex(["3H", "3H", "NaT", "2H", "5H", "4H"])
+ arr = tdi.array
+
+ result = arr.sum(skipna=True)
+ expected = Timedelta(hours=17)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = tdi.sum(skipna=True)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = arr.sum(skipna=False)
+ assert result is pd.NaT
+
+ result = tdi.sum(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.sum(min_count=9)
+ assert result is pd.NaT
+
+ result = tdi.sum(min_count=9)
+ assert result is pd.NaT
+
+ result = arr.sum(min_count=1)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = tdi.sum(min_count=1)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ # TODO: de-duplicate with test_npsum below
+ def test_np_sum(self):
+ # GH#25282
+ vals = np.arange(5, dtype=np.int64).view("m8[h]").astype("m8[ns]")
+ arr = TimedeltaArray(vals)
+ result = np.sum(arr)
+ assert result == vals.sum()
+
+ result = np.sum(pd.TimedeltaIndex(arr))
+ assert result == vals.sum()
+
+ def test_npsum(self):
+ # GH#25335 np.sum should return a Timedelta, not timedelta64
+ tdi = pd.TimedeltaIndex(["3H", "3H", "2H", "5H", "4H"])
+ arr = tdi.array
+
+ result = np.sum(tdi)
+ expected = Timedelta(hours=17)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = np.sum(arr)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ def test_sum_2d_skipna_false(self):
+ arr = np.arange(8).astype(np.int64).view("m8[s]").astype("m8[ns]").reshape(4, 2)
+ arr[-1, -1] = "Nat"
+
+ tda = TimedeltaArray(arr)
+
+ result = tda.sum(skipna=False)
+ assert result is pd.NaT
+
+ result = tda.sum(axis=0, skipna=False)
+ expected = pd.TimedeltaIndex([Timedelta(seconds=12), pd.NaT])._values
+ tm.assert_timedelta_array_equal(result, expected)
+
+ result = tda.sum(axis=1, skipna=False)
+ expected = pd.TimedeltaIndex(
+ [
+ Timedelta(seconds=1),
+ Timedelta(seconds=5),
+ Timedelta(seconds=9),
+ pd.NaT,
+ ]
+ )._values
+ tm.assert_timedelta_array_equal(result, expected)
+
+ # Adding a Timestamp makes this a test for DatetimeArray.std
+ @pytest.mark.parametrize(
+ "add",
+ [
+ Timedelta(0),
+ pd.Timestamp.now(),
+ pd.Timestamp.now("UTC"),
+ pd.Timestamp.now("Asia/Tokyo"),
+ ],
+ )
+ def test_std(self, add):
+ tdi = pd.TimedeltaIndex(["0H", "4H", "NaT", "4H", "0H", "2H"]) + add
+ arr = tdi.array
+
+ result = arr.std(skipna=True)
+ expected = Timedelta(hours=2)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = tdi.std(skipna=True)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ if getattr(arr, "tz", None) is None:
+ result = nanops.nanstd(np.asarray(arr), skipna=True)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = arr.std(skipna=False)
+ assert result is pd.NaT
+
+ result = tdi.std(skipna=False)
+ assert result is pd.NaT
+
+ if getattr(arr, "tz", None) is None:
+ result = nanops.nanstd(np.asarray(arr), skipna=False)
+ assert result is pd.NaT
+
+ def test_median(self):
+ tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"])
+ arr = tdi.array
+
+ result = arr.median(skipna=True)
+ expected = Timedelta(hours=2)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = tdi.median(skipna=True)
+ assert isinstance(result, Timedelta)
+ assert result == expected
+
+ result = arr.median(skipna=False)
+ assert result is pd.NaT
+
+ result = tdi.median(skipna=False)
+ assert result is pd.NaT
+
+ def test_mean(self):
+ tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"])
+ arr = tdi._data
+
+ # manually verified result
+ expected = Timedelta(arr.dropna()._ndarray.mean())
+
+ result = arr.mean()
+ assert result == expected
+ result = arr.mean(skipna=False)
+ assert result is pd.NaT
+
+ result = arr.dropna().mean(skipna=False)
+ assert result == expected
+
+ result = arr.mean(axis=0)
+ assert result == expected
+
+ def test_mean_2d(self):
+ tdi = pd.timedelta_range("14 days", periods=6)
+ tda = tdi._data.reshape(3, 2)
+
+ result = tda.mean(axis=0)
+ expected = tda[1]
+ tm.assert_timedelta_array_equal(result, expected)
+
+ result = tda.mean(axis=1)
+ expected = tda[:, 0] + Timedelta(hours=12)
+ tm.assert_timedelta_array_equal(result, expected)
+
+ result = tda.mean(axis=None)
+ expected = tdi.mean()
+ assert result == expected
| https://api.github.com/repos/pandas-dev/pandas/pulls/39472 | 2021-01-29T21:49:59Z | 2021-01-29T23:40:09Z | 2021-01-29T23:40:09Z | 2021-01-30T00:12:39Z | |
TST: fixturize in test_coercion | diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index b342942cd9f5f..6c8b1622e76aa 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -65,17 +65,6 @@ class CoercionBase:
def method(self):
raise NotImplementedError(self)
- def _assert(self, left, right, dtype):
- # explicitly check dtype to avoid any unexpected result
- if isinstance(left, pd.Series):
- tm.assert_series_equal(left, right)
- elif isinstance(left, pd.Index):
- tm.assert_index_equal(left, right)
- else:
- raise NotImplementedError
- assert left.dtype == dtype
- assert right.dtype == dtype
-
class TestSetitemCoercion(CoercionBase):
@@ -91,6 +80,7 @@ def _assert_setitem_series_conversion(
# check dtype explicitly for sure
assert temp.dtype == expected_dtype
+ # FIXME: dont leave commented-out
# .loc works different rule, temporary disable
# temp = original_series.copy()
# temp.loc[1] = loc_value
@@ -565,7 +555,8 @@ def _assert_where_conversion(
""" test coercion triggered by where """
target = original.copy()
res = target.where(cond, values)
- self._assert(res, expected, expected_dtype)
+ tm.assert_equal(res, expected)
+ assert res.dtype == expected_dtype
@pytest.mark.parametrize(
"fill_val,exp_dtype",
@@ -588,7 +579,7 @@ def test_where_object(self, index_or_series, fill_val, exp_dtype):
if fill_val is True:
values = klass([True, False, True, True])
else:
- values = klass(fill_val * x for x in [5, 6, 7, 8])
+ values = klass(x * fill_val for x in [5, 6, 7, 8])
exp = klass(["a", values[1], "c", values[3]])
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
@@ -647,18 +638,19 @@ def test_where_float64(self, index_or_series, fill_val, exp_dtype):
],
)
def test_where_series_complex128(self, fill_val, exp_dtype):
- obj = pd.Series([1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j])
+ klass = pd.Series
+ obj = klass([1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j])
assert obj.dtype == np.complex128
- cond = pd.Series([True, False, True, False])
+ cond = klass([True, False, True, False])
- exp = pd.Series([1 + 1j, fill_val, 3 + 3j, fill_val])
+ exp = klass([1 + 1j, fill_val, 3 + 3j, fill_val])
self._assert_where_conversion(obj, cond, fill_val, exp, exp_dtype)
if fill_val is True:
- values = pd.Series([True, False, True, True])
+ values = klass([True, False, True, True])
else:
- values = pd.Series(x * fill_val for x in [5, 6, 7, 8])
- exp = pd.Series([1 + 1j, values[1], 3 + 3j, values[3]])
+ values = klass(x * fill_val for x in [5, 6, 7, 8])
+ exp = klass([1 + 1j, values[1], 3 + 3j, values[3]])
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
@pytest.mark.parametrize(
@@ -666,19 +658,20 @@ def test_where_series_complex128(self, fill_val, exp_dtype):
[(1, object), (1.1, object), (1 + 1j, object), (True, np.bool_)],
)
def test_where_series_bool(self, fill_val, exp_dtype):
+ klass = pd.Series
- obj = pd.Series([True, False, True, False])
+ obj = klass([True, False, True, False])
assert obj.dtype == np.bool_
- cond = pd.Series([True, False, True, False])
+ cond = klass([True, False, True, False])
- exp = pd.Series([True, fill_val, True, fill_val])
+ exp = klass([True, fill_val, True, fill_val])
self._assert_where_conversion(obj, cond, fill_val, exp, exp_dtype)
if fill_val is True:
- values = pd.Series([True, False, True, True])
+ values = klass([True, False, True, True])
else:
- values = pd.Series(x * fill_val for x in [5, 6, 7, 8])
- exp = pd.Series([True, values[1], True, values[3]])
+ values = klass(x * fill_val for x in [5, 6, 7, 8])
+ exp = klass([True, values[1], True, values[3]])
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
@pytest.mark.parametrize(
@@ -871,7 +864,8 @@ def _assert_fillna_conversion(self, original, value, expected, expected_dtype):
""" test coercion triggered by fillna """
target = original.copy()
res = target.fillna(value)
- self._assert(res, expected, expected_dtype)
+ tm.assert_equal(res, expected)
+ assert res.dtype == expected_dtype
@pytest.mark.parametrize(
"fill_val, fill_dtype",
@@ -1040,10 +1034,12 @@ class TestReplaceSeriesCoercion(CoercionBase):
rep["timedelta64[ns]"] = [pd.Timedelta("1 day"), pd.Timedelta("2 day")]
- @pytest.mark.parametrize("how", ["dict", "series"])
- @pytest.mark.parametrize(
- "to_key",
- [
+ @pytest.fixture(params=["dict", "series"])
+ def how(self, request):
+ return request.param
+
+ @pytest.fixture(
+ params=[
"object",
"int64",
"float64",
@@ -1053,34 +1049,52 @@ class TestReplaceSeriesCoercion(CoercionBase):
"datetime64[ns, UTC]",
"datetime64[ns, US/Eastern]",
"timedelta64[ns]",
- ],
- ids=[
+ ]
+ )
+ def from_key(self, request):
+ return request.param
+
+ @pytest.fixture(
+ params=[
"object",
"int64",
"float64",
"complex128",
"bool",
- "datetime64",
- "datetime64tz",
- "datetime64tz",
- "timedelta64",
+ "datetime64[ns]",
+ "datetime64[ns, UTC]",
+ "datetime64[ns, US/Eastern]",
+ "timedelta64[ns]",
],
- )
- @pytest.mark.parametrize(
- "from_key",
- [
+ ids=[
"object",
"int64",
"float64",
"complex128",
"bool",
- "datetime64[ns]",
- "datetime64[ns, UTC]",
- "datetime64[ns, US/Eastern]",
- "timedelta64[ns]",
+ "datetime64",
+ "datetime64tz",
+ "datetime64tz",
+ "timedelta64",
],
)
- def test_replace_series(self, how, to_key, from_key):
+ def to_key(self, request):
+ return request.param
+
+ @pytest.fixture
+ def replacer(self, how, from_key, to_key):
+ """
+ Object we will pass to `Series.replace`
+ """
+ if how == "dict":
+ replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
+ elif how == "series":
+ replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
+ else:
+ raise ValueError
+ return replacer
+
+ def test_replace_series(self, how, to_key, from_key, replacer):
index = pd.Index([3, 4], name="xxx")
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
assert obj.dtype == from_key
@@ -1092,13 +1106,6 @@ def test_replace_series(self, how, to_key, from_key):
# tested below
return
- if how == "dict":
- replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
- elif how == "series":
- replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
- else:
- raise ValueError
-
result = obj.replace(replacer)
if (from_key == "float64" and to_key in ("int64")) or (
@@ -1117,53 +1124,40 @@ def test_replace_series(self, how, to_key, from_key):
tm.assert_series_equal(result, exp)
- @pytest.mark.parametrize("how", ["dict", "series"])
@pytest.mark.parametrize(
"to_key",
["timedelta64[ns]", "bool", "object", "complex128", "float64", "int64"],
+ indirect=True,
)
@pytest.mark.parametrize(
- "from_key", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"]
+ "from_key", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"], indirect=True
)
- def test_replace_series_datetime_tz(self, how, to_key, from_key):
+ def test_replace_series_datetime_tz(self, how, to_key, from_key, replacer):
index = pd.Index([3, 4], name="xyz")
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
assert obj.dtype == from_key
- if how == "dict":
- replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
- elif how == "series":
- replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
- else:
- raise ValueError
-
result = obj.replace(replacer)
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
assert exp.dtype == to_key
tm.assert_series_equal(result, exp)
- @pytest.mark.parametrize("how", ["dict", "series"])
@pytest.mark.parametrize(
"to_key",
["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
+ indirect=True,
)
@pytest.mark.parametrize(
"from_key",
["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
+ indirect=True,
)
- def test_replace_series_datetime_datetime(self, how, to_key, from_key):
+ def test_replace_series_datetime_datetime(self, how, to_key, from_key, replacer):
index = pd.Index([3, 4], name="xyz")
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
assert obj.dtype == from_key
- if how == "dict":
- replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
- elif how == "series":
- replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
- else:
- raise ValueError
-
result = obj.replace(replacer)
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
assert exp.dtype == to_key
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39471 | 2021-01-29T20:11:28Z | 2021-01-29T21:13:05Z | 2021-01-29T21:13:05Z | 2021-01-29T21:27:43Z |
CLN: remove NaT.__int__, __long__ | diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx
index 3a61de62daf39..d5582d65a0c11 100644
--- a/pandas/_libs/tslibs/nattype.pyx
+++ b/pandas/_libs/tslibs/nattype.pyx
@@ -286,12 +286,6 @@ cdef class _NaT(datetime):
def __hash__(self):
return NPY_NAT
- def __int__(self):
- return NPY_NAT
-
- def __long__(self):
- return NPY_NAT
-
@property
def is_leap_year(self) -> bool:
return False
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index ae7e8191fc482..3927fb04187f5 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -715,7 +715,7 @@ def factorize(
values, dtype = _ensure_data(values)
if original.dtype.kind in ["m", "M"]:
- na_value = na_value_for_dtype(original.dtype)
+ na_value = iNaT
else:
na_value = None
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 435da1ed062e6..1032559766ada 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1607,7 +1607,7 @@ def _round(self, freq, mode, ambiguous, nonexistent):
values = self.view("i8")
result = round_nsint64(values, mode, freq)
- result = self._maybe_mask_results(result, fill_value=NaT)
+ result = self._maybe_mask_results(result, fill_value=iNaT)
return self._simple_new(result, dtype=self.dtype)
@Appender((_round_doc + _round_example).format(op="round"))
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 5f3d2040b0201..c4afe971d533e 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -679,7 +679,7 @@ def test_tdi_add_overflow(self):
with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"):
Timestamp("2000") + pd.to_timedelta(106580, "D")
- _NaT = int(pd.NaT) + 1
+ _NaT = pd.NaT.value + 1
msg = "Overflow in int64 addition"
with pytest.raises(OverflowError, match=msg):
pd.to_timedelta([106580], "D") + Timestamp("2000")
diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py
index cd3286fa38056..86c9e2f5ffe52 100644
--- a/pandas/tests/frame/methods/test_sort_values.py
+++ b/pandas/tests/frame/methods/test_sort_values.py
@@ -323,7 +323,7 @@ def test_sort_values_nat_values_in_int_column(self):
# cause was that the int64 value NaT was considered as "na". Which is
# only correct for datetime64 columns.
- int_values = (2, int(NaT))
+ int_values = (2, int(NaT.value))
float_values = (2.0, -1.797693e308)
df = DataFrame(
| https://api.github.com/repos/pandas-dev/pandas/pulls/39470 | 2021-01-29T19:42:37Z | 2021-01-29T21:14:01Z | 2021-01-29T21:14:01Z | 2021-01-29T21:33:31Z | |
DOC: correct ipython code block in v0.8.0.rst file | diff --git a/doc/source/whatsnew/v0.8.0.rst b/doc/source/whatsnew/v0.8.0.rst
index 490175914cef1..781054fc4de7c 100644
--- a/doc/source/whatsnew/v0.8.0.rst
+++ b/doc/source/whatsnew/v0.8.0.rst
@@ -176,7 +176,7 @@ New plotting methods
Vytautas Jancauskas, the 2012 GSOC participant, has added many new plot
types. For example, ``'kde'`` is a new option:
-.. code-block:: python
+.. ipython:: python
s = pd.Series(
np.concatenate((np.random.randn(1000), np.random.randn(1000) * 0.5 + 3))
| Tiny follow-up on https://github.com/pandas-dev/pandas/pull/39043/files#r558333164 | https://api.github.com/repos/pandas-dev/pandas/pulls/39469 | 2021-01-29T16:47:52Z | 2021-01-29T21:15:28Z | 2021-01-29T21:15:28Z | 2021-01-30T08:34:35Z |
TYP, CLN annotate some variables, remove some possibly unused ones | diff --git a/pandas/_config/display.py b/pandas/_config/display.py
index e4553a2107f87..ec819481525da 100644
--- a/pandas/_config/display.py
+++ b/pandas/_config/display.py
@@ -4,12 +4,13 @@
import locale
import sys
+from typing import Optional
from pandas._config import config as cf
# -----------------------------------------------------------------------------
# Global formatting options
-_initial_defencoding = None
+_initial_defencoding: Optional[str] = None
def detect_console_encoding() -> str:
diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py
index e5ede3cd885be..087b7f39e3374 100644
--- a/pandas/core/computation/expressions.py
+++ b/pandas/core/computation/expressions.py
@@ -6,13 +6,15 @@
"""
import operator
-from typing import List, Set
+from typing import List, Optional, Set
import warnings
import numpy as np
from pandas._config import get_option
+from pandas._typing import FuncType
+
from pandas.core.dtypes.generic import ABCDataFrame
from pandas.core.computation.check import NUMEXPR_INSTALLED
@@ -21,11 +23,11 @@
if NUMEXPR_INSTALLED:
import numexpr as ne
-_TEST_MODE = None
+_TEST_MODE: Optional[bool] = None
_TEST_RESULT: List[bool] = []
USE_NUMEXPR = NUMEXPR_INSTALLED
-_evaluate = None
-_where = None
+_evaluate: Optional[FuncType] = None
+_where: Optional[FuncType] = None
# the set of dtypes that we will allow pass to numexpr
_ALLOWED_DTYPES = {
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index e1271cfec2bde..ec37da66760c3 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -180,7 +180,7 @@ class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
["_AXIS_NAMES", "_AXIS_NUMBERS", "get_values", "tshift"]
)
_metadata: List[str] = []
- _is_copy = None
+ _is_copy: Optional[weakref.ReferenceType[NDFrame]] = None
_mgr: Manager
_attrs: Dict[Optional[Hashable], Any]
_typ: str
@@ -389,7 +389,6 @@ def _data(self):
# Axis
_stat_axis_number = 0
_stat_axis_name = "index"
- _ix = None
_AXIS_ORDERS: List[str]
_AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {0: 0, "index": 0, "rows": 0}
_AXIS_REVERSED: bool
@@ -3815,7 +3814,7 @@ def _slice(self: FrameOrSeries, slobj: slice, axis=0) -> FrameOrSeries:
return result
@final
- def _set_is_copy(self, ref, copy: bool_t = True) -> None:
+ def _set_is_copy(self, ref: FrameOrSeries, copy: bool_t = True) -> None:
if not copy:
self._is_copy = None
else:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 3b8ee46cc480f..7d97c9f6189f3 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -444,7 +444,7 @@ def _constructor_expanddim(self) -> Type[DataFrame]:
def _can_hold_na(self) -> bool:
return self._mgr._can_hold_na
- _index = None
+ _index: Optional[Index] = None
def _set_axis(self, axis: int, labels, fastpath: bool = False) -> None:
"""
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 84b5cae09acce..f12a530ea6c34 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -758,7 +758,6 @@ def __new__(cls, path, engine=None, **kwargs):
return object.__new__(cls)
# declare external properties you can count on
- curr_sheet = None
path = None
@property
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py
index ab8e0fca4bf38..01ccc9d15a6a3 100644
--- a/pandas/io/excel/_util.py
+++ b/pandas/io/excel/_util.py
@@ -1,10 +1,10 @@
-from typing import List
+from typing import List, MutableMapping
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.common import is_integer, is_list_like
-_writers = {}
+_writers: MutableMapping[str, str] = {}
def register_writer(klass):
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index e1af3169420fc..725cb633918e7 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -35,7 +35,7 @@ class DatabaseError(IOError):
# -----------------------------------------------------------------------------
# -- Helper functions
-_SQLALCHEMY_INSTALLED = None
+_SQLALCHEMY_INSTALLED: Optional[bool] = None
def _is_sqlalchemy_connectable(con):
| - [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
The [mypy daemon](https://mypy.readthedocs.io/en/latest/mypy_daemon.html) throws some extra `var-annotated` errors compared with `mypy pandas`, so I've tried fixing some. Some of the variables it complains about seem to be unused (ExcelWriter.curr_sheet and NDFrame._ix) - are these safe to remove? | https://api.github.com/repos/pandas-dev/pandas/pulls/39466 | 2021-01-29T08:38:24Z | 2021-02-11T13:40:46Z | 2021-02-11T13:40:46Z | 2021-02-11T14:29:48Z |
BUG: Fix sort_values bug that creates unprintable object | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index fc49177a4736b..b019c5b3d30e8 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -412,6 +412,7 @@ Reshaping
- Bug in :meth:`DataFrame.join` not assigning values correctly when having :class:`MultiIndex` where at least one dimension is from dtype ``Categorical`` with non-alphabetically sorted categories (:issue:`38502`)
- :meth:`Series.value_counts` and :meth:`Series.mode` return consistent keys in original order (:issue:`12679`, :issue:`11227` and :issue:`39007`)
- Bug in :meth:`DataFrame.apply` would give incorrect results when used with a string argument and ``axis=1`` when the axis argument was not supported and now raises a ``ValueError`` instead (:issue:`39211`)
+- Bug in :meth:`DataFrame.sort_values` not reshaping index correctly after sorting on columns, when ``ignore_index=True`` (:issue:`39464`)
- Bug in :meth:`DataFrame.append` returning incorrect dtypes with combinations of ``ExtensionDtype`` dtypes (:issue:`39454`)
Sparse
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 57eb384d79868..6357b8feb348b 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5560,7 +5560,9 @@ def sort_values( # type: ignore[override]
)
if ignore_index:
- new_data.set_axis(1, ibase.default_index(len(indexer)))
+ new_data.set_axis(
+ self._get_block_manager_axis(axis), ibase.default_index(len(indexer))
+ )
result = self._constructor(new_data)
if inplace:
diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py
index 86c9e2f5ffe52..053684ba08484 100644
--- a/pandas/tests/frame/methods/test_sort_values.py
+++ b/pandas/tests/frame/methods/test_sort_values.py
@@ -579,6 +579,14 @@ def test_sort_values_item_cache(self, using_array_manager):
assert df.iloc[0, 0] == df["A"][0]
+ def test_sort_values_reshaping(self):
+ # GH 39426
+ values = list(range(21))
+ expected = DataFrame([values], columns=values)
+ df = expected.sort_values(expected.index[0], axis=1, ignore_index=True)
+
+ tm.assert_frame_equal(df, expected)
+
class TestDataFrameSortKey: # test key sorting (issue 27237)
def test_sort_values_inplace_key(self, sort_by_key):
| - [x] closes #39426
- [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
The problem occurs when sorting on columns and the `ignore_index` parameter is set to `True`. `sort_values` tries to refit the index after the columns have been sorted resulting in a corrupted dataframe. | https://api.github.com/repos/pandas-dev/pandas/pulls/39464 | 2021-01-29T03:46:02Z | 2021-02-04T00:50:51Z | 2021-02-04T00:50:51Z | 2021-02-04T00:50:57Z |
CLN: assorted cleanups, ported tests | diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index f3bf45f681b1f..f0150cf6a2d81 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -259,39 +259,39 @@ cdef convert_to_timedelta64(object ts, str unit):
ts = np.timedelta64(ts.value, "ns")
elif is_datetime64_object(ts):
# only accept a NaT here
- if ts.astype('int64') == NPY_NAT:
- return np.timedelta64(NPY_NAT)
+ if ts.astype("int64") == NPY_NAT:
+ return np.timedelta64(NPY_NAT, "ns")
elif is_timedelta64_object(ts):
ts = ensure_td64ns(ts)
elif is_integer_object(ts):
if ts == NPY_NAT:
return np.timedelta64(NPY_NAT, "ns")
else:
- if unit in ['Y', 'M', 'W']:
+ if unit in ["Y", "M", "W"]:
ts = np.timedelta64(ts, unit)
else:
ts = cast_from_unit(ts, unit)
ts = np.timedelta64(ts, "ns")
elif is_float_object(ts):
- if unit in ['Y', 'M', 'W']:
+ if unit in ["Y", "M", "W"]:
ts = np.timedelta64(int(ts), unit)
else:
ts = cast_from_unit(ts, unit)
ts = np.timedelta64(ts, "ns")
elif isinstance(ts, str):
- if len(ts) > 0 and ts[0] == 'P':
+ if len(ts) > 0 and ts[0] == "P":
ts = parse_iso_format_string(ts)
else:
ts = parse_timedelta_string(ts)
ts = np.timedelta64(ts, "ns")
elif is_tick_object(ts):
- ts = np.timedelta64(ts.nanos, 'ns')
+ ts = np.timedelta64(ts.nanos, "ns")
if PyDelta_Check(ts):
- ts = np.timedelta64(delta_to_nanoseconds(ts), 'ns')
+ ts = np.timedelta64(delta_to_nanoseconds(ts), "ns")
elif not is_timedelta64_object(ts):
raise ValueError(f"Invalid type for timedelta scalar: {type(ts)}")
- return ts.astype('timedelta64[ns]')
+ return ts.astype("timedelta64[ns]")
@cython.boundscheck(False)
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 5ed2ca469dd8a..f1cf1aa9a72cb 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -24,11 +24,7 @@
from pandas.errors import PerformanceWarning
from pandas.util._validators import validate_bool_kwarg
-from pandas.core.dtypes.cast import (
- find_common_type,
- infer_dtype_from_scalar,
- maybe_promote,
-)
+from pandas.core.dtypes.cast import find_common_type, infer_dtype_from_scalar
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
is_dtype_equal,
@@ -1332,7 +1328,7 @@ def _slice_take_blocks_ax0(
return [blk.getitem_block(slobj, new_mgr_locs=slice(0, sllen))]
elif not allow_fill or self.ndim == 1:
if allow_fill and fill_value is None:
- _, fill_value = maybe_promote(blk.dtype)
+ fill_value = blk.fill_value
if not allow_fill and only_slice:
# GH#33597 slice instead of take, so we get
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 2eb7d1c9353cf..8917be1f558b2 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3875,7 +3875,7 @@ def _create_axes(
# add my values
vaxes = []
- for i, (b, b_items) in enumerate(zip(blocks, blk_items)):
+ for i, (blk, b_items) in enumerate(zip(blocks, blk_items)):
# shape of the data column are the indexable axes
klass = DataCol
@@ -3907,13 +3907,13 @@ def _create_axes(
new_name = name or f"values_block_{i}"
data_converted = _maybe_convert_for_string_atom(
new_name,
- b,
+ blk,
existing_col=existing_col,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
encoding=self.encoding,
errors=self.errors,
- block_columns=b_items,
+ columns=b_items,
)
adj_name = _maybe_adjust_name(new_name, self.version)
@@ -4886,13 +4886,15 @@ def _maybe_convert_for_string_atom(
nan_rep,
encoding,
errors,
- block_columns: List[str],
+ columns: List[str],
):
- if not block.is_object:
- return block.values
+ bvalues = block.values
- dtype_name = block.dtype.name
- inferred_type = lib.infer_dtype(block.values, skipna=False)
+ if bvalues.dtype != object:
+ return bvalues
+
+ dtype_name = bvalues.dtype.name
+ inferred_type = lib.infer_dtype(bvalues, skipna=False)
if inferred_type == "date":
raise TypeError("[date] is not implemented as a table column")
@@ -4904,7 +4906,7 @@ def _maybe_convert_for_string_atom(
)
elif not (inferred_type == "string" or dtype_name == "object"):
- return block.values
+ return bvalues
blocks: List[Block] = block.fillna(nan_rep, downcast=False)
# Note: because block is always object dtype, fillna goes
@@ -4923,13 +4925,11 @@ def _maybe_convert_for_string_atom(
# expected behaviour:
# search block for a non-string object column by column
- for i in range(block.shape[0]):
+ for i in range(data.shape[0]):
col = block.iget(i)
inferred_type = lib.infer_dtype(col, skipna=False)
if inferred_type != "string":
- error_column_label = (
- block_columns[i] if len(block_columns) > i else f"No.{i}"
- )
+ error_column_label = columns[i] if len(columns) > i else f"No.{i}"
raise TypeError(
f"Cannot serialize the column [{error_column_label}]\n"
f"because its data contents are not [string] but "
@@ -4938,7 +4938,6 @@ def _maybe_convert_for_string_atom(
# itemsize is the maximum length of a string (along any dimension)
data_converted = _convert_string_array(data, encoding, errors).reshape(data.shape)
- assert data_converted.shape == block.shape, (data_converted.shape, block.shape)
itemsize = data_converted.itemsize
# specified min_itemsize?
diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py
index a7b3333e7c690..22b50310cedd6 100644
--- a/pandas/tests/frame/test_repr_info.py
+++ b/pandas/tests/frame/test_repr_info.py
@@ -23,6 +23,20 @@
class TestDataFrameReprInfoEtc:
+ def test_repr_bytes_61_lines(self):
+ # GH#12857
+ lets = list("ACDEFGHIJKLMNOP")
+ slen = 50
+ nseqs = 1000
+ words = [[np.random.choice(lets) for x in range(slen)] for _ in range(nseqs)]
+ df = DataFrame(words).astype("U1")
+ assert (df.dtypes == object).all()
+
+ # smoke tests; at one point this raised with 61 but not 60
+ repr(df)
+ repr(df.iloc[:60, :])
+ repr(df.iloc[:61, :])
+
def test_repr_unicode_level_names(self, frame_or_series):
index = MultiIndex.from_tuples([(0, 0), (1, 1)], names=["\u0394", "i1"])
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index f67341ab176d7..d490a23317fef 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -55,11 +55,10 @@ def test_setitem_ndarray_1d(self):
with pytest.raises(ValueError, match=msg):
df[2:5] = np.arange(1, 4) * 1j
- @pytest.mark.parametrize("idxr", [tm.getitem, tm.loc, tm.iloc])
- def test_getitem_ndarray_3d(self, index, frame_or_series, idxr):
+ def test_getitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
# GH 25567
obj = gen_obj(frame_or_series, index)
- idxr = idxr(obj)
+ idxr = indexer_sli(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
msg = "|".join(
@@ -78,19 +77,18 @@ def test_getitem_ndarray_3d(self, index, frame_or_series, idxr):
with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False):
idxr[nd3]
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc, tm.iloc])
- def test_setitem_ndarray_3d(self, index, frame_or_series, indexer):
+ def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
# GH 25567
obj = gen_obj(frame_or_series, index)
- idxr = indexer(obj)
+ idxr = indexer_sli(obj)
nd3 = np.random.randint(5, size=(2, 2, 2))
- if indexer.__name__ == "iloc":
+ if indexer_sli.__name__ == "iloc":
err = ValueError
msg = f"Cannot set values with ndim > {obj.ndim}"
elif (
isinstance(index, pd.IntervalIndex)
- and indexer.__name__ == "setitem"
+ and indexer_sli.__name__ == "setitem"
and obj.ndim == 1
):
err = AttributeError
@@ -948,8 +946,7 @@ def test_none_coercion_mixed_dtypes(self):
class TestDatetimelikeCoercion:
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc, tm.iloc])
- def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer):
+ def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer_sli):
# dispatching _can_hold_element to underling DatetimeArray
tz = tz_naive_fixture
@@ -961,7 +958,7 @@ def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer):
newval = "2018-01-01"
values._validate_setitem_value(newval)
- indexer(ser)[0] = newval
+ indexer_sli(ser)[0] = newval
if tz is None:
# TODO(EA2D): we can make this no-copy in tz-naive case too
@@ -974,12 +971,11 @@ def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer):
@pytest.mark.parametrize(
"key", [[0, 1], slice(0, 2), np.array([True, True, False])]
)
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc, tm.iloc])
- def test_setitem_dt64_string_values(self, tz_naive_fixture, indexer, key, box):
+ def test_setitem_dt64_string_values(self, tz_naive_fixture, indexer_sli, key, box):
# dispatching _can_hold_element to underling DatetimeArray
tz = tz_naive_fixture
- if isinstance(key, slice) and indexer is tm.loc:
+ if isinstance(key, slice) and indexer_sli is tm.loc:
key = slice(0, 1)
dti = date_range("2016-01-01", periods=3, tz=tz)
@@ -990,7 +986,7 @@ def test_setitem_dt64_string_values(self, tz_naive_fixture, indexer, key, box):
newvals = box(["2019-01-01", "2010-01-02"])
values._validate_setitem_value(newvals)
- indexer(ser)[key] = newvals
+ indexer_sli(ser)[key] = newvals
if tz is None:
# TODO(EA2D): we can make this no-copy in tz-naive case too
@@ -1000,8 +996,7 @@ def test_setitem_dt64_string_values(self, tz_naive_fixture, indexer, key, box):
assert ser._values is values
@pytest.mark.parametrize("scalar", ["3 Days", offsets.Hour(4)])
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc, tm.iloc])
- def test_setitem_td64_scalar(self, indexer, scalar):
+ def test_setitem_td64_scalar(self, indexer_sli, scalar):
# dispatching _can_hold_element to underling TimedeltaArray
tdi = timedelta_range("1 Day", periods=3)
ser = Series(tdi)
@@ -1009,17 +1004,16 @@ def test_setitem_td64_scalar(self, indexer, scalar):
values = ser._values
values._validate_setitem_value(scalar)
- indexer(ser)[0] = scalar
+ indexer_sli(ser)[0] = scalar
assert ser._values._data is values._data
@pytest.mark.parametrize("box", [list, np.array, pd.array])
@pytest.mark.parametrize(
"key", [[0, 1], slice(0, 2), np.array([True, True, False])]
)
- @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc, tm.iloc])
- def test_setitem_td64_string_values(self, indexer, key, box):
+ def test_setitem_td64_string_values(self, indexer_sli, key, box):
# dispatching _can_hold_element to underling TimedeltaArray
- if isinstance(key, slice) and indexer is tm.loc:
+ if isinstance(key, slice) and indexer_sli is tm.loc:
key = slice(0, 1)
tdi = timedelta_range("1 Day", periods=3)
@@ -1030,7 +1024,7 @@ def test_setitem_td64_string_values(self, indexer, key, box):
newvals = box(["10 Days", "44 hours"])
values._validate_setitem_value(newvals)
- indexer(ser)[key] = newvals
+ indexer_sli(ser)[key] = newvals
assert ser._values._data is values._data
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index fabc2dc8bbd1c..36cd6b0327ccd 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -273,6 +273,10 @@ def test_setitem_dt64_into_int_series(self, dtype):
tm.assert_series_equal(ser, expected)
assert isinstance(ser[0], type(val))
+ ser = orig.copy()
+ ser[:-1] = [val, val]
+ tm.assert_series_equal(ser, expected)
+
ser = orig.copy()
ser[:-1] = np.array([val, val])
tm.assert_series_equal(ser, expected)
diff --git a/pandas/tests/series/methods/test_item.py b/pandas/tests/series/methods/test_item.py
index a7ddc0c22dcf4..90e8f6d39c5cc 100644
--- a/pandas/tests/series/methods/test_item.py
+++ b/pandas/tests/series/methods/test_item.py
@@ -1,3 +1,7 @@
+"""
+Series.item method, mainly testing that we get python scalars as opposed to
+numpy scalars.
+"""
import pytest
from pandas import Series, Timedelta, Timestamp, date_range
@@ -5,6 +9,7 @@
class TestItem:
def test_item(self):
+ # We are testing that we get python scalars as opposed to numpy scalars
ser = Series([1])
result = ser.item()
assert result == 1
| https://api.github.com/repos/pandas-dev/pandas/pulls/39463 | 2021-01-29T03:40:31Z | 2021-01-29T14:50:48Z | 2021-01-29T14:50:48Z | 2021-01-29T15:55:49Z | |
BUG: accepting ndarray[object] of dt64(nat) in TimedeltaIndex | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 7fe0b53d7d2ff..3aa41e1d53057 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -284,7 +284,7 @@ Datetimelike
Timedelta
^^^^^^^^^
- Bug in constructing :class:`Timedelta` from ``np.timedelta64`` objects with non-nanosecond units that are out of bounds for ``timedelta64[ns]`` (:issue:`38965`)
--
+- Bug in constructing a :class:`TimedeltaIndex` incorrectly accepting ``np.datetime64("NaT")`` objects (:issue:`39462`)
-
Timezones
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index f0150cf6a2d81..25991cfbdb7a7 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -257,10 +257,6 @@ cdef convert_to_timedelta64(object ts, str unit):
elif isinstance(ts, _Timedelta):
# already in the proper format
ts = np.timedelta64(ts.value, "ns")
- elif is_datetime64_object(ts):
- # only accept a NaT here
- if ts.astype("int64") == NPY_NAT:
- return np.timedelta64(NPY_NAT, "ns")
elif is_timedelta64_object(ts):
ts = ensure_td64ns(ts)
elif is_integer_object(ts):
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index f23b8d559a00a..9ec745932514f 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -48,6 +48,17 @@
class TestDataFrameConstructors:
+ def test_array_of_dt64_nat_with_td64dtype_raises(self, frame_or_series):
+ # GH#39462
+ nat = np.datetime64("NaT", "ns")
+ arr = np.array([nat], dtype=object)
+ if frame_or_series is DataFrame:
+ arr = arr.reshape(1, 1)
+
+ msg = "Could not convert object to NumPy timedelta"
+ with pytest.raises(ValueError, match=msg):
+ frame_or_series(arr, dtype="m8[ns]")
+
def test_series_with_name_not_matching_column(self):
# GH#9232
x = Series(range(5), name=1)
diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py
index a07977702531e..ffc10faaf8150 100644
--- a/pandas/tests/indexes/timedeltas/test_constructors.py
+++ b/pandas/tests/indexes/timedeltas/test_constructors.py
@@ -6,10 +6,26 @@
import pandas as pd
from pandas import Timedelta, TimedeltaIndex, timedelta_range, to_timedelta
import pandas._testing as tm
-from pandas.core.arrays import TimedeltaArray
+from pandas.core.arrays.timedeltas import TimedeltaArray, sequence_to_td64ns
class TestTimedeltaIndex:
+ def test_array_of_dt64_nat_raises(self):
+ # GH#39462
+ nat = np.datetime64("NaT", "ns")
+ arr = np.array([nat], dtype=object)
+
+ # TODO: should be TypeError?
+ msg = "Invalid type for timedelta scalar"
+ with pytest.raises(ValueError, match=msg):
+ TimedeltaIndex(arr)
+
+ with pytest.raises(ValueError, match=msg):
+ TimedeltaArray._from_sequence(arr)
+
+ with pytest.raises(ValueError, match=msg):
+ sequence_to_td64ns(arr)
+
@pytest.mark.parametrize("unit", ["Y", "y", "M"])
def test_unit_m_y_raises(self, unit):
msg = "Units 'M', 'Y', and 'y' are no longer supported"
| - [ ] closes #xxxx
- [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
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39462 | 2021-01-29T01:23:12Z | 2021-01-29T21:14:39Z | 2021-01-29T21:14:39Z | 2021-01-29T21:29:31Z |
BUG: assert_attr_equal with numpy nat or pd.NA | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index e61f50afea838..77bba6c431053 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -432,7 +432,7 @@ Other
- Bug in :class:`Index` constructor sometimes silently ignorning a specified ``dtype`` (:issue:`38879`)
- Bug in constructing a :class:`Series` from a list and a :class:`PandasDtype` (:issue:`39357`)
- Bug in :class:`Styler` which caused CSS to duplicate on multiple renders. (:issue:`39395`)
--
+- Bug in :func:`pandas.testing.assert_series_equal`, :func:`pandas.testing.assert_frame_equal`, :func:`pandas.testing.assert_index_equal` and :func:`pandas.testing.assert_extension_array_equal` incorrectly raising when an attribute has an unrecognized NA type (:issue:`39461`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 494d9ac60dd96..024bfb02fe09d 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -459,13 +459,24 @@ def assert_attr_equal(attr: str, left, right, obj: str = "Attributes"):
):
# np.nan
return True
+ elif (
+ isinstance(left_attr, (np.datetime64, np.timedelta64))
+ and isinstance(right_attr, (np.datetime64, np.timedelta64))
+ and type(left_attr) is type(right_attr)
+ and np.isnat(left_attr)
+ and np.isnat(right_attr)
+ ):
+ # np.datetime64("nat") or np.timedelta64("nat")
+ return True
try:
result = left_attr == right_attr
except TypeError:
# datetimetz on rhs may raise TypeError
result = False
- if not isinstance(result, bool):
+ if (left_attr is pd.NA) ^ (right_attr is pd.NA):
+ result = False
+ elif not isinstance(result, bool):
result = result.all()
if result:
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 51920f1613c12..e55ddbcc783d0 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -715,6 +715,8 @@ def factorize(
values, dtype = _ensure_data(values)
if original.dtype.kind in ["m", "M"]:
+ # Note: factorize_array will cast NaT bc it has a __int__
+ # method, but will not cast the more-correct dtype.type("nat")
na_value = iNaT
else:
na_value = None
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 2c69096e56973..f87f40cd55e2c 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -382,6 +382,8 @@ def __init__(
stacklevel=2,
)
data = np.asarray(data, dtype="datetime64[ns]")
+ if fill_value is NaT:
+ fill_value = np.datetime64("NaT", "ns")
data = np.asarray(data)
sparse_values, sparse_index, fill_value = make_sparse(
data, kind=kind, fill_value=fill_value, dtype=dtype
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index f0455c01fa085..0db0b1f6a97ef 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -559,14 +559,14 @@ def na_value_for_dtype(dtype, compat: bool = True):
>>> na_value_for_dtype(np.dtype('bool'))
False
>>> na_value_for_dtype(np.dtype('datetime64[ns]'))
- NaT
+ numpy.datetime64('NaT')
"""
dtype = pandas_dtype(dtype)
if is_extension_array_dtype(dtype):
return dtype.na_value
- if needs_i8_conversion(dtype):
- return NaT
+ elif needs_i8_conversion(dtype):
+ return dtype.type("NaT", "ns")
elif is_float_dtype(dtype):
return np.nan
elif is_integer_dtype(dtype):
diff --git a/pandas/tests/arrays/sparse/test_dtype.py b/pandas/tests/arrays/sparse/test_dtype.py
index 8cd0d29a34ec8..58fedbd3e4231 100644
--- a/pandas/tests/arrays/sparse/test_dtype.py
+++ b/pandas/tests/arrays/sparse/test_dtype.py
@@ -14,8 +14,8 @@
("float", np.nan),
("bool", False),
("object", np.nan),
- ("datetime64[ns]", pd.NaT),
- ("timedelta64[ns]", pd.NaT),
+ ("datetime64[ns]", np.datetime64("NaT", "ns")),
+ ("timedelta64[ns]", np.timedelta64("NaT", "ns")),
],
)
def test_inferred_dtype(dtype, fill_value):
diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py
index c02185dd82043..0d92ef02e07c8 100644
--- a/pandas/tests/dtypes/test_missing.py
+++ b/pandas/tests/dtypes/test_missing.py
@@ -472,8 +472,8 @@ def test_array_equivalent_nested():
"dtype, na_value",
[
# Datetime-like
- (np.dtype("M8[ns]"), NaT),
- (np.dtype("m8[ns]"), NaT),
+ (np.dtype("M8[ns]"), np.datetime64("NaT", "ns")),
+ (np.dtype("m8[ns]"), np.timedelta64("NaT", "ns")),
(DatetimeTZDtype.construct_from_string("datetime64[ns, US/Eastern]"), NaT),
(PeriodDtype("M"), NaT),
# Integer
@@ -499,7 +499,11 @@ def test_array_equivalent_nested():
)
def test_na_value_for_dtype(dtype, na_value):
result = na_value_for_dtype(dtype)
- assert result is na_value
+ # identify check doesnt work for datetime64/timedelta64("NaT") bc they
+ # are not singletons
+ assert result is na_value or (
+ isna(result) and isna(na_value) and type(result) is type(na_value)
+ )
class TestNAObj:
diff --git a/pandas/tests/util/test_assert_attr_equal.py b/pandas/tests/util/test_assert_attr_equal.py
new file mode 100644
index 0000000000000..6fad38c2cd44e
--- /dev/null
+++ b/pandas/tests/util/test_assert_attr_equal.py
@@ -0,0 +1,30 @@
+from types import SimpleNamespace
+
+import pytest
+
+from pandas.core.dtypes.common import is_float
+
+import pandas._testing as tm
+
+
+def test_assert_attr_equal(nulls_fixture):
+ obj = SimpleNamespace()
+ obj.na_value = nulls_fixture
+ assert tm.assert_attr_equal("na_value", obj, obj)
+
+
+def test_assert_attr_equal_different_nulls(nulls_fixture, nulls_fixture2):
+ obj = SimpleNamespace()
+ obj.na_value = nulls_fixture
+
+ obj2 = SimpleNamespace()
+ obj2.na_value = nulls_fixture2
+
+ if nulls_fixture is nulls_fixture2:
+ assert tm.assert_attr_equal("na_value", obj, obj2)
+ elif is_float(nulls_fixture) and is_float(nulls_fixture2):
+ # we consider float("nan") and np.float64("nan") to be equivalent
+ assert tm.assert_attr_equal("na_value", obj, obj2)
+ else:
+ with pytest.raises(AssertionError, match='"na_value" are different'):
+ tm.assert_attr_equal("na_value", obj, obj2)
| - [ ] closes #xxxx
- [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
This started off with editing na_value_for_dtype so that it could be re-used in #39446, ended up snowballing into assert_attr_equal. If requested, I'll split off the bugfix into its own PR. | https://api.github.com/repos/pandas-dev/pandas/pulls/39461 | 2021-01-29T01:12:28Z | 2021-02-02T13:34:23Z | 2021-02-02T13:34:23Z | 2021-02-02T15:12:31Z |
REF: avoid using Block attributes | diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 0b611bfdb1f10..9e4f535ebcbbe 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -264,7 +264,9 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike:
fill_value = upcasted_na
if self.is_na:
- if getattr(self.block, "is_object", False):
+ blk_dtype = getattr(self.block, "dtype", None)
+
+ if blk_dtype == np.dtype(object):
# we want to avoid filling with np.nan if we are
# using None; we already know that we are all
# nulls
@@ -272,17 +274,16 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike:
if len(values) and values[0] is None:
fill_value = None
- if getattr(self.block, "is_datetimetz", False) or is_datetime64tz_dtype(
+ if is_datetime64tz_dtype(blk_dtype) or is_datetime64tz_dtype(
empty_dtype
):
if self.block is None:
# TODO(EA2D): special case unneeded with 2D EAs
- return DatetimeArray(
- np.full(self.shape[1], fill_value.value), dtype=empty_dtype
- )
- elif getattr(self.block, "is_categorical", False):
+ i8values = np.full(self.shape[1], fill_value.value)
+ return DatetimeArray(i8values, dtype=empty_dtype)
+ elif is_categorical_dtype(blk_dtype):
pass
- elif getattr(self.block, "is_extension", False):
+ elif is_extension_array_dtype(blk_dtype):
pass
elif is_extension_array_dtype(empty_dtype):
missing_arr = empty_dtype.construct_array_type()._from_sequence(
| Moves this chunk of code incrementally towards being BlockManager/ArrayManager agnostic | https://api.github.com/repos/pandas-dev/pandas/pulls/39460 | 2021-01-28T23:41:55Z | 2021-01-29T02:07:57Z | 2021-01-29T02:07:57Z | 2021-01-29T03:03:44Z |
REF: Move Resampler/Window.agg into core.apply | diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py
index 6fb11becf5d70..5c99f783c70d9 100644
--- a/pandas/core/aggregation.py
+++ b/pandas/core/aggregation.py
@@ -534,56 +534,6 @@ def transform_str_or_callable(
return func(obj, *args, **kwargs)
-def aggregate(
- obj: AggObjType,
- arg: AggFuncType,
- *args,
- **kwargs,
-):
- """
- Provide an implementation for the aggregators.
-
- Parameters
- ----------
- obj : Pandas object to compute aggregation on.
- arg : string, dict, function.
- *args : args to pass on to the function.
- **kwargs : kwargs to pass on to the function.
-
- Returns
- -------
- tuple of result, how.
-
- Notes
- -----
- how can be a string describe the required post-processing, or
- None if not required.
- """
- _axis = kwargs.pop("_axis", None)
- if _axis is None:
- _axis = getattr(obj, "axis", 0)
-
- if isinstance(arg, str):
- return obj._try_aggregate_string_function(arg, *args, **kwargs), None
- elif is_dict_like(arg):
- arg = cast(AggFuncTypeDict, arg)
- return agg_dict_like(obj, arg, _axis), True
- elif is_list_like(arg):
- # we require a list, but not an 'str'
- arg = cast(List[AggFuncTypeBase], arg)
- return agg_list_like(obj, arg, _axis=_axis), None
- else:
- result = None
-
- if callable(arg):
- f = obj._get_cython_func(arg)
- if f and not args and not kwargs:
- return getattr(obj, f)(), None
-
- # caller can react
- return result, True
-
-
def agg_list_like(
obj: AggObjType,
arg: List[AggFuncTypeBase],
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 3374e07c53cad..8207f4d6e33d4 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -47,6 +47,8 @@
if TYPE_CHECKING:
from pandas import DataFrame, Index, Series
from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
+ from pandas.core.resample import Resampler
+ from pandas.core.window.rolling import BaseWindow
ResType = Dict[int, Any]
@@ -684,3 +686,27 @@ def __init__(
def apply(self):
raise NotImplementedError
+
+
+class ResamplerWindowApply(Apply):
+ axis = 0
+ obj: Union[Resampler, BaseWindow]
+
+ def __init__(
+ self,
+ obj: Union[Resampler, BaseWindow],
+ func: AggFuncType,
+ args,
+ kwds,
+ ):
+ super().__init__(
+ obj,
+ func,
+ raw=False,
+ result_type=None,
+ args=args,
+ kwds=kwds,
+ )
+
+ def apply(self):
+ raise NotImplementedError
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 1c8f47374860c..965de2e04bf40 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -23,8 +23,8 @@
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
-from pandas.core.aggregation import aggregate
import pandas.core.algorithms as algos
+from pandas.core.apply import ResamplerWindowApply
from pandas.core.base import DataError
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.groupby.base import GotItemMixin, ShallowMixin
@@ -301,7 +301,7 @@ def pipe(
def aggregate(self, func, *args, **kwargs):
self._set_binner()
- result, how = aggregate(self, func, *args, **kwargs)
+ result, how = ResamplerWindowApply(self, func, args=args, kwds=kwargs).agg()
if result is None:
how = func
grouper = None
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 7b438c51b9ac7..439cd586825e1 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -48,7 +48,7 @@
)
from pandas.core.dtypes.missing import notna
-from pandas.core.aggregation import aggregate
+from pandas.core.apply import ResamplerWindowApply
from pandas.core.base import DataError, SelectionMixin
from pandas.core.construction import extract_array
from pandas.core.groupby.base import GotItemMixin, ShallowMixin
@@ -479,7 +479,7 @@ def calc(x):
return self._apply_tablewise(homogeneous_func, name)
def aggregate(self, func, *args, **kwargs):
- result, how = aggregate(self, func, *args, **kwargs)
+ result, how = ResamplerWindowApply(self, func, args=args, kwds=kwargs).agg()
if result is None:
return self.apply(func, raw=False, args=args, kwargs=kwargs)
return result
@@ -1150,7 +1150,7 @@ def calc(x):
axis="",
)
def aggregate(self, func, *args, **kwargs):
- result, how = aggregate(self, func, *args, **kwargs)
+ result, how = ResamplerWindowApply(self, func, args=args, kwds=kwargs).agg()
if result is None:
# these must apply directly
| - [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
Last move from aggregation.aggregate to apply. Will follow up with moving helper methods from aggregation into apply. | https://api.github.com/repos/pandas-dev/pandas/pulls/39459 | 2021-01-28T23:24:35Z | 2021-01-29T02:10:56Z | 2021-01-29T02:10:56Z | 2021-01-29T02:52:40Z |
CLN: add typing to dtype arg in core/frame.py (GH38808) | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c7585b21abe99..3e8cc43562a2e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -63,6 +63,7 @@
IndexLabel,
Level,
Manager,
+ NpDtype,
PythonFuncType,
Renamer,
StorageOptions,
@@ -1325,7 +1326,9 @@ def __rmatmul__(self, other):
# IO methods (to / from other formats)
@classmethod
- def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> DataFrame:
+ def from_dict(
+ cls, data, orient="columns", dtype: Optional[Dtype] = None, columns=None
+ ) -> DataFrame:
"""
Construct DataFrame from dict of array-like or dicts.
@@ -1404,7 +1407,10 @@ def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> DataFram
return cls(data, index=index, columns=columns, dtype=dtype)
def to_numpy(
- self, dtype=None, copy: bool = False, na_value=lib.no_default
+ self,
+ dtype: Optional[NpDtype] = None,
+ copy: bool = False,
+ na_value=lib.no_default,
) -> np.ndarray:
"""
Convert the DataFrame to a NumPy array.
| - [x] closes #38808
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39458 | 2021-01-28T21:59:25Z | 2021-01-29T02:04:26Z | 2021-01-29T02:04:26Z | 2021-01-29T02:04:31Z |
BUG: fixing mixup of bucket and element counts in hash tables | diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx
index 2c7780e0d95fd..3527fe2d8cd8d 100644
--- a/pandas/_libs/hashtable.pyx
+++ b/pandas/_libs/hashtable.pyx
@@ -19,6 +19,7 @@ from pandas._libs.khash cimport (
are_equivalent_float64_t,
are_equivalent_khcomplex64_t,
are_equivalent_khcomplex128_t,
+ kh_needed_n_buckets,
kh_str_t,
khcomplex64_t,
khcomplex128_t,
@@ -152,7 +153,7 @@ def unique_label_indices(const int64_t[:] labels):
ndarray[int64_t, ndim=1] arr
Int64VectorData *ud = idx.data
- kh_resize_int64(table, min(n, SIZE_HINT_LIMIT))
+ kh_resize_int64(table, min(kh_needed_n_buckets(n), SIZE_HINT_LIMIT))
with nogil:
for i in range(n):
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index a3e72ed858392..0b6bb170cc531 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -392,9 +392,8 @@ cdef class {{name}}HashTable(HashTable):
def __cinit__(self, int64_t size_hint=1):
self.table = kh_init_{{dtype}}()
- if size_hint is not None:
- size_hint = min(size_hint, SIZE_HINT_LIMIT)
- kh_resize_{{dtype}}(self.table, size_hint)
+ size_hint = min(kh_needed_n_buckets(size_hint), SIZE_HINT_LIMIT)
+ kh_resize_{{dtype}}(self.table, size_hint)
def __len__(self) -> int:
return self.table.size
@@ -420,6 +419,15 @@ cdef class {{name}}HashTable(HashTable):
sizeof(Py_ssize_t)) # vals
return overhead + for_flags + for_pairs
+ def get_state(self):
+ """ returns infos about the state of the hashtable"""
+ return {
+ 'n_buckets' : self.table.n_buckets,
+ 'size' : self.table.size,
+ 'n_occupied' : self.table.n_occupied,
+ 'upper_bound' : self.table.upper_bound,
+ }
+
cpdef get_item(self, {{dtype}}_t val):
cdef:
khiter_t k
@@ -731,9 +739,8 @@ cdef class StringHashTable(HashTable):
def __init__(self, int64_t size_hint=1):
self.table = kh_init_str()
- if size_hint is not None:
- size_hint = min(size_hint, SIZE_HINT_LIMIT)
- kh_resize_str(self.table, size_hint)
+ size_hint = min(kh_needed_n_buckets(size_hint), SIZE_HINT_LIMIT)
+ kh_resize_str(self.table, size_hint)
def __dealloc__(self):
if self.table is not NULL:
@@ -747,6 +754,15 @@ cdef class StringHashTable(HashTable):
sizeof(Py_ssize_t)) # vals
return overhead + for_flags + for_pairs
+ def get_state(self):
+ """ returns infos about the state of the hashtable"""
+ return {
+ 'n_buckets' : self.table.n_buckets,
+ 'size' : self.table.size,
+ 'n_occupied' : self.table.n_occupied,
+ 'upper_bound' : self.table.upper_bound,
+ }
+
cpdef get_item(self, str val):
cdef:
khiter_t k
@@ -1044,9 +1060,8 @@ cdef class PyObjectHashTable(HashTable):
def __init__(self, int64_t size_hint=1):
self.table = kh_init_pymap()
- if size_hint is not None:
- size_hint = min(size_hint, SIZE_HINT_LIMIT)
- kh_resize_pymap(self.table, size_hint)
+ size_hint = min(kh_needed_n_buckets(size_hint), SIZE_HINT_LIMIT)
+ kh_resize_pymap(self.table, size_hint)
def __dealloc__(self):
if self.table is not NULL:
@@ -1072,6 +1087,18 @@ cdef class PyObjectHashTable(HashTable):
sizeof(Py_ssize_t)) # vals
return overhead + for_flags + for_pairs
+ def get_state(self):
+ """
+ returns infos about the current state of the hashtable like size,
+ number of buckets and so on.
+ """
+ return {
+ 'n_buckets' : self.table.n_buckets,
+ 'size' : self.table.size,
+ 'n_occupied' : self.table.n_occupied,
+ 'upper_bound' : self.table.upper_bound,
+ }
+
cpdef get_item(self, object val):
cdef:
khiter_t k
diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in
index 4684ecb8716c0..772d83e67394c 100644
--- a/pandas/_libs/hashtable_func_helper.pxi.in
+++ b/pandas/_libs/hashtable_func_helper.pxi.in
@@ -121,7 +121,7 @@ def duplicated_{{dtype}}(const {{dtype}}_t[:] values, object keep='first'):
kh_{{ttype}}_t *table = kh_init_{{ttype}}()
ndarray[uint8_t, ndim=1, cast=True] out = np.empty(n, dtype='bool')
- kh_resize_{{ttype}}(table, min(n, SIZE_HINT_LIMIT))
+ kh_resize_{{ttype}}(table, min(kh_needed_n_buckets(n), SIZE_HINT_LIMIT))
if keep not in ('last', 'first', False):
raise ValueError('keep must be either "first", "last" or False')
diff --git a/pandas/_libs/khash.pxd b/pandas/_libs/khash.pxd
index 82b8ca4d443db..ba805e9ff1251 100644
--- a/pandas/_libs/khash.pxd
+++ b/pandas/_libs/khash.pxd
@@ -120,4 +120,7 @@ cdef extern from "khash_python.h":
bint kh_exist_strbox(kh_strbox_t*, khiter_t) nogil
+ khuint_t kh_needed_n_buckets(khuint_t element_n) nogil
+
+
include "khash_for_primitive_helper.pxi"
diff --git a/pandas/_libs/src/klib/khash_python.h b/pandas/_libs/src/klib/khash_python.h
index fc7a650eebba4..0073aaf0195c7 100644
--- a/pandas/_libs/src/klib/khash_python.h
+++ b/pandas/_libs/src/klib/khash_python.h
@@ -244,3 +244,13 @@ void PANDAS_INLINE kh_destroy_str_starts(kh_str_starts_t* table) {
void PANDAS_INLINE kh_resize_str_starts(kh_str_starts_t* table, khuint_t val) {
kh_resize_str(table->table, val);
}
+
+// utility function: given the number of elements
+// returns number of necessary buckets
+khuint_t PANDAS_INLINE kh_needed_n_buckets(khuint_t n_elements){
+ khuint_t candidate = n_elements;
+ kroundup32(candidate);
+ khuint_t upper_bound = (khuint_t)(candidate * __ac_HASH_UPPER + 0.5);
+ return (upper_bound < n_elements) ? 2*candidate : candidate;
+
+}
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c7585b21abe99..3d4d0d20f70bb 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5451,15 +5451,13 @@ def duplicated(
4 True
dtype: bool
"""
- from pandas._libs.hashtable import SIZE_HINT_LIMIT, duplicated_int64
+ from pandas._libs.hashtable import duplicated_int64
if self.empty:
return self._constructor_sliced(dtype=bool)
def f(vals):
- labels, shape = algorithms.factorize(
- vals, size_hint=min(len(self), SIZE_HINT_LIMIT)
- )
+ labels, shape = algorithms.factorize(vals, size_hint=len(self))
return labels.astype("i8", copy=False), len(shape)
if subset is None:
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index 2c2e0c16a4482..cfbabab491ae4 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -593,7 +593,7 @@ def compress_group_index(group_index, sort: bool = True):
space can be huge, so this function compresses it, by computing offsets
(comp_ids) into the list of unique labels (obs_group_ids).
"""
- size_hint = min(len(group_index), hashtable.SIZE_HINT_LIMIT)
+ size_hint = len(group_index)
table = hashtable.Int64HashTable(size_hint)
group_index = ensure_int64(group_index)
diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py
index 8393312004241..a28e2f22560eb 100644
--- a/pandas/tests/libs/test_hashtable.py
+++ b/pandas/tests/libs/test_hashtable.py
@@ -155,6 +155,28 @@ def test_tracemalloc_for_empty(self, table_type, dtype):
del table
assert get_allocated_khash_memory() == 0
+ def test_get_state(self, table_type, dtype):
+ table = table_type(1000)
+ state = table.get_state()
+ assert state["size"] == 0
+ assert state["n_occupied"] == 0
+ assert "n_buckets" in state
+ assert "upper_bound" in state
+
+ def test_no_reallocation(self, table_type, dtype):
+ for N in range(1, 110):
+ keys = np.arange(N).astype(dtype)
+ preallocated_table = table_type(N)
+ n_buckets_start = preallocated_table.get_state()["n_buckets"]
+ preallocated_table.map_locations(keys)
+ n_buckets_end = preallocated_table.get_state()["n_buckets"]
+ # orgininal number of buckets was enough:
+ assert n_buckets_start == n_buckets_end
+ # check with clean table (not too much preallocated)
+ clean_table = table_type()
+ clean_table.map_locations(keys)
+ assert n_buckets_start == clean_table.get_state()["n_buckets"]
+
def test_get_labels_groupby_for_Int64(writable):
table = ht.Int64HashTable()
@@ -190,6 +212,21 @@ def test_tracemalloc_for_empty_StringHashTable():
assert get_allocated_khash_memory() == 0
+def test_no_reallocation_StringHashTable():
+ for N in range(1, 110):
+ keys = np.arange(N).astype(np.compat.unicode).astype(np.object_)
+ preallocated_table = ht.StringHashTable(N)
+ n_buckets_start = preallocated_table.get_state()["n_buckets"]
+ preallocated_table.map_locations(keys)
+ n_buckets_end = preallocated_table.get_state()["n_buckets"]
+ # orgininal number of buckets was enough:
+ assert n_buckets_start == n_buckets_end
+ # check with clean table (not too much preallocated)
+ clean_table = ht.StringHashTable()
+ clean_table.map_locations(keys)
+ assert n_buckets_start == clean_table.get_state()["n_buckets"]
+
+
@pytest.mark.parametrize(
"table_type, dtype",
[
| - [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
- [ ] whatsnew entry
The issue is that, `kh_resize_##name` expects the number of buckets in the map as input: https://github.com/pandas-dev/pandas/blob/39e126199b1d2082d9d084f7a37c9745ab9a95ee/pandas/_libs/src/klib/khash.h#L324
it is however used with the number of elements throughout the pandas code, e.g. https://github.com/pandas-dev/pandas/blob/39e126199b1d2082d9d084f7a37c9745ab9a95ee/pandas/core/algorithms.py#L412
as can be seen in the `__cinit__` function: https://github.com/pandas-dev/pandas/blob/39e126199b1d2082d9d084f7a37c9745ab9a95ee/pandas/_libs/hashtable_class_helper.pxi.in#L400-L404
Thus, for some sizes (like 10^3) there still could be a rehashing even if size-hint was used with the idea to avoid it (because at most 75% of buckets can be occupied)
I think it make sense to do the less surprising thing with the size-hint (i.e. the number of elements and not buckets).
| https://api.github.com/repos/pandas-dev/pandas/pulls/39457 | 2021-01-28T21:39:09Z | 2021-02-02T01:59:49Z | 2021-02-02T01:59:49Z | 2021-02-02T02:00:00Z |
TST: use unique ports in test_user_agent.py | diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py
index fd3ca3919d416..0518ffca64cb2 100644
--- a/pandas/tests/io/test_user_agent.py
+++ b/pandas/tests/io/test_user_agent.py
@@ -189,15 +189,15 @@ def do_GET(self):
None,
marks=td.skip_array_manager_not_yet_implemented,
),
- (ParquetPyArrowUserAgentResponder, pd.read_parquet, 34268, "pyarrow"),
- (ParquetFastParquetUserAgentResponder, pd.read_parquet, 34273, "fastparquet"),
- (PickleUserAgentResponder, pd.read_pickle, 34271, None),
- (StataUserAgentResponder, pd.read_stata, 34272, None),
- (GzippedCSVUserAgentResponder, pd.read_csv, 34261, None),
+ (ParquetPyArrowUserAgentResponder, pd.read_parquet, 34261, "pyarrow"),
+ (ParquetFastParquetUserAgentResponder, pd.read_parquet, 34262, "fastparquet"),
+ (PickleUserAgentResponder, pd.read_pickle, 34263, None),
+ (StataUserAgentResponder, pd.read_stata, 34264, None),
+ (GzippedCSVUserAgentResponder, pd.read_csv, 34265, None),
pytest.param(
GzippedJSONUserAgentResponder,
pd.read_json,
- 34262,
+ 34266,
None,
marks=td.skip_array_manager_not_yet_implemented,
),
@@ -225,23 +225,23 @@ def test_server_and_default_headers(responder, read_method, port, parquet_engine
@pytest.mark.parametrize(
"responder, read_method, port, parquet_engine",
[
- (CSVUserAgentResponder, pd.read_csv, 34263, None),
+ (CSVUserAgentResponder, pd.read_csv, 34267, None),
pytest.param(
JSONUserAgentResponder,
pd.read_json,
- 34264,
+ 34268,
None,
marks=td.skip_array_manager_not_yet_implemented,
),
- (ParquetPyArrowUserAgentResponder, pd.read_parquet, 34270, "pyarrow"),
- (ParquetFastParquetUserAgentResponder, pd.read_parquet, 34275, "fastparquet"),
- (PickleUserAgentResponder, pd.read_pickle, 34273, None),
- (StataUserAgentResponder, pd.read_stata, 34274, None),
- (GzippedCSVUserAgentResponder, pd.read_csv, 34265, None),
+ (ParquetPyArrowUserAgentResponder, pd.read_parquet, 34269, "pyarrow"),
+ (ParquetFastParquetUserAgentResponder, pd.read_parquet, 34270, "fastparquet"),
+ (PickleUserAgentResponder, pd.read_pickle, 34271, None),
+ (StataUserAgentResponder, pd.read_stata, 34272, None),
+ (GzippedCSVUserAgentResponder, pd.read_csv, 34273, None),
pytest.param(
GzippedJSONUserAgentResponder,
pd.read_json,
- 34266,
+ 34274,
None,
marks=td.skip_array_manager_not_yet_implemented,
),
@@ -281,7 +281,7 @@ def test_server_and_custom_headers(responder, read_method, port, parquet_engine)
@pytest.mark.parametrize(
"responder, read_method, port",
[
- (AllHeaderCSVResponder, pd.read_csv, 34267),
+ (AllHeaderCSVResponder, pd.read_csv, 34275),
],
)
def test_server_and_all_custom_headers(responder, read_method, port):
| Should take care of the occasional `OSError: [Errno 98] Address already in use` in `test_server_and_default_headers`. | https://api.github.com/repos/pandas-dev/pandas/pulls/39455 | 2021-01-28T21:13:12Z | 2021-01-29T02:02:57Z | 2021-01-29T02:02:57Z | 2021-01-29T02:03:03Z |
BUG: incorrect casting in DataFrame.append | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 7fe0b53d7d2ff..3c9fea201eebf 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -411,7 +411,7 @@ Reshaping
- Bug in :meth:`DataFrame.join` not assigning values correctly when having :class:`MultiIndex` where at least one dimension is from dtype ``Categorical`` with non-alphabetically sorted categories (:issue:`38502`)
- :meth:`Series.value_counts` and :meth:`Series.mode` return consistent keys in original order (:issue:`12679`, :issue:`11227` and :issue:`39007`)
- Bug in :meth:`DataFrame.apply` would give incorrect results when used with a string argument and ``axis=1`` when the axis argument was not supported and now raises a ``ValueError`` instead (:issue:`39211`)
--
+- Bug in :meth:`DataFrame.append` returning incorrect dtypes with combinations of ``ExtensionDtype`` dtypes (:issue:`39454`)
Sparse
^^^^^^
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 0b611bfdb1f10..8d2af010fd1fe 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -11,7 +11,7 @@
from pandas._typing import ArrayLike, DtypeObj, Manager, Shape
from pandas.util._decorators import cache_readonly
-from pandas.core.dtypes.cast import maybe_promote
+from pandas.core.dtypes.cast import find_common_type, maybe_promote
from pandas.core.dtypes.common import (
get_dtype,
is_categorical_dtype,
@@ -393,7 +393,11 @@ def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, A
if _is_uniform_reindex(join_units):
# FIXME: integrate property
empty_dtype = join_units[0].block.dtype
- upcasted_na = join_units[0].block.fill_value
+ if is_extension_array_dtype(empty_dtype):
+ # for dt64tz we need this to get NaT instead of np.datetime64("NaT")
+ upcasted_na = empty_dtype.na_value
+ else:
+ upcasted_na = join_units[0].block.fill_value
return empty_dtype, upcasted_na
has_none_blocks = False
@@ -404,25 +408,29 @@ def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, A
else:
dtypes[i] = unit.dtype
+ filtered_dtypes = [
+ unit.dtype for unit in join_units if unit.block is not None and not unit.is_na
+ ]
+ if not len(filtered_dtypes):
+ filtered_dtypes = [unit.dtype for unit in join_units if unit.block is not None]
+ dtype_alt = find_common_type(filtered_dtypes)
+
upcast_classes = _get_upcast_classes(join_units, dtypes)
+ if is_extension_array_dtype(dtype_alt):
+ return dtype_alt, dtype_alt.na_value
+ elif dtype_alt == object:
+ return dtype_alt, np.nan
+
# TODO: de-duplicate with maybe_promote?
# create the result
if "extension" in upcast_classes:
- if len(upcast_classes) == 1:
- cls = upcast_classes["extension"][0]
- return cls, cls.na_value
- else:
- return np.dtype("object"), np.nan
- elif "object" in upcast_classes:
- return np.dtype(np.object_), np.nan
+ return np.dtype("object"), np.nan
elif "bool" in upcast_classes:
if has_none_blocks:
return np.dtype(np.object_), np.nan
else:
return np.dtype(np.bool_), None
- elif "category" in upcast_classes:
- return np.dtype(np.object_), np.nan
elif "datetimetz" in upcast_classes:
# GH-25014. We use NaT instead of iNaT, since this eventually
# ends up in DatetimeArray.take, which does not allow iNaT.
@@ -480,7 +488,7 @@ def _get_upcast_classes(
def _select_upcast_cls_from_dtype(dtype: DtypeObj) -> str:
"""Select upcast class name based on dtype."""
if is_categorical_dtype(dtype):
- return "category"
+ return "extension"
elif is_datetime64tz_dtype(dtype):
return "datetimetz"
elif is_extension_array_dtype(dtype):
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 9cea274a118c0..10e82a8c9bff1 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -117,9 +117,7 @@ class TestConstructors(base.BaseConstructorsTests):
class TestReshaping(base.BaseReshapingTests):
- @pytest.mark.xfail(reason="Deliberately upcast to object?")
- def test_concat_with_reindex(self, data):
- super().test_concat_with_reindex(data)
+ pass
class TestGetitem(base.BaseGetitemTests):
diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py
index ffeda703cd890..dd6dbd79113e5 100644
--- a/pandas/tests/reshape/concat/test_append.py
+++ b/pandas/tests/reshape/concat/test_append.py
@@ -365,13 +365,25 @@ def test_append_empty_tz_frame_with_datetime64ns(self):
# pd.NaT gets inferred as tz-naive, so append result is tz-naive
result = df.append({"a": pd.NaT}, ignore_index=True)
- expected = DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]")
+ expected = DataFrame({"a": [pd.NaT]}).astype(object)
tm.assert_frame_equal(result, expected)
# also test with typed value to append
df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]")
- result = df.append(
- Series({"a": pd.NaT}, dtype="datetime64[ns]"), ignore_index=True
- )
- expected = DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]")
+ other = Series({"a": pd.NaT}, dtype="datetime64[ns]")
+ result = df.append(other, ignore_index=True)
+ expected = DataFrame({"a": [pd.NaT]}).astype(object)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dtype_str", ["datetime64[ns, UTC]", "datetime64[ns]", "Int64", "int64"]
+ )
+ def test_append_empty_frame_with_timedelta64ns_nat(self, dtype_str):
+ # https://github.com/pandas-dev/pandas/issues/35460
+ df = DataFrame(columns=["a"]).astype(dtype_str)
+
+ other = DataFrame({"a": [np.timedelta64("NaT", "ns")]})
+ result = df.append(other, ignore_index=True)
+
+ expected = other.astype(object)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py
index 6dae28003d3b6..357274b66332f 100644
--- a/pandas/tests/reshape/concat/test_categorical.py
+++ b/pandas/tests/reshape/concat/test_categorical.py
@@ -42,6 +42,7 @@ def test_categorical_concat(self, sort):
"h": [None] * 6 + cat_values,
}
)
+ exp["h"] = exp["h"].astype(df2["h"].dtype)
tm.assert_frame_equal(res, exp)
def test_categorical_concat_dtypes(self):
| - [ ] closes #xxxx
- [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
I'm pretty sure we're going to end up with just using find_common_type instead of re-implementing similar stuff in internals.concat. | https://api.github.com/repos/pandas-dev/pandas/pulls/39454 | 2021-01-28T20:36:15Z | 2021-02-01T22:56:09Z | 2021-02-01T22:56:09Z | 2021-02-01T23:14:09Z |
REF: simplify _get_empty_dtype_and_na | diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 214fe0c1de9f4..3dcfa85ed5c08 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -3,11 +3,11 @@
from collections import defaultdict
import copy
import itertools
-from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Tuple, cast
+from typing import TYPE_CHECKING, Dict, List, Sequence, cast
import numpy as np
-from pandas._libs import NaT, internals as libinternals
+from pandas._libs import internals as libinternals
from pandas._typing import ArrayLike, DtypeObj, Manager, Shape
from pandas.util._decorators import cache_readonly
@@ -338,7 +338,10 @@ def _concatenate_join_units(
# Concatenating join units along ax0 is handled in _merge_blocks.
raise AssertionError("Concatenating join units along axis0")
- empty_dtype, upcasted_na = _get_empty_dtype_and_na(join_units)
+ empty_dtype = _get_empty_dtype(join_units)
+
+ has_none_blocks = any(unit.block is None for unit in join_units)
+ upcasted_na = _dtype_to_na_value(empty_dtype, has_none_blocks)
to_concat = [
ju.get_reindexed_values(empty_dtype=empty_dtype, upcasted_na=upcasted_na)
@@ -375,7 +378,28 @@ def _concatenate_join_units(
return concat_values
-def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, Any]:
+def _dtype_to_na_value(dtype: DtypeObj, has_none_blocks: bool):
+ """
+ Find the NA value to go with this dtype.
+ """
+ if is_extension_array_dtype(dtype):
+ return dtype.na_value
+ elif dtype.kind in ["m", "M"]:
+ return dtype.type("NaT")
+ elif dtype.kind in ["f", "c"]:
+ return dtype.type("NaN")
+ elif dtype.kind == "b":
+ return None
+ elif dtype.kind in ["i", "u"]:
+ if not has_none_blocks:
+ return None
+ return np.nan
+ elif dtype.kind == "O":
+ return np.nan
+ raise NotImplementedError
+
+
+def _get_empty_dtype(join_units: Sequence[JoinUnit]) -> DtypeObj:
"""
Return dtype and N/A values to use when concatenating specified units.
@@ -384,30 +408,19 @@ def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, A
Returns
-------
dtype
- na
"""
if len(join_units) == 1:
blk = join_units[0].block
if blk is None:
- return np.dtype(np.float64), np.nan
+ return np.dtype(np.float64)
if _is_uniform_reindex(join_units):
# FIXME: integrate property
empty_dtype = join_units[0].block.dtype
- if is_extension_array_dtype(empty_dtype):
- # for dt64tz we need this to get NaT instead of np.datetime64("NaT")
- upcasted_na = empty_dtype.na_value
- else:
- upcasted_na = join_units[0].block.fill_value
- return empty_dtype, upcasted_na
-
- has_none_blocks = False
- dtypes = [None] * len(join_units)
- for i, unit in enumerate(join_units):
- if unit.block is None:
- has_none_blocks = True
- else:
- dtypes[i] = unit.dtype
+ return empty_dtype
+
+ has_none_blocks = any(unit.block is None for unit in join_units)
+ dtypes = [None if unit.block is None else unit.dtype for unit in join_units]
filtered_dtypes = [
unit.dtype for unit in join_units if unit.block is not None and not unit.is_na
@@ -419,42 +432,42 @@ def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, A
upcast_classes = _get_upcast_classes(join_units, dtypes)
if is_extension_array_dtype(dtype_alt):
- return dtype_alt, dtype_alt.na_value
+ return dtype_alt
elif dtype_alt == object:
- return dtype_alt, np.nan
+ return dtype_alt
# TODO: de-duplicate with maybe_promote?
# create the result
if "extension" in upcast_classes:
- return np.dtype("object"), np.nan
+ return np.dtype("object")
elif "bool" in upcast_classes:
if has_none_blocks:
- return np.dtype(np.object_), np.nan
+ return np.dtype(np.object_)
else:
- return np.dtype(np.bool_), None
+ return np.dtype(np.bool_)
elif "datetimetz" in upcast_classes:
# GH-25014. We use NaT instead of iNaT, since this eventually
# ends up in DatetimeArray.take, which does not allow iNaT.
dtype = upcast_classes["datetimetz"]
- return dtype[0], NaT
+ return dtype[0]
elif "datetime" in upcast_classes:
- return np.dtype("M8[ns]"), np.datetime64("NaT", "ns")
+ return np.dtype("M8[ns]")
elif "timedelta" in upcast_classes:
- return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns")
+ return np.dtype("m8[ns]")
else:
try:
common_dtype = np.find_common_type(upcast_classes, [])
except TypeError:
# At least one is an ExtensionArray
- return np.dtype(np.object_), np.nan
+ return np.dtype(np.object_)
else:
if is_float_dtype(common_dtype):
- return common_dtype, common_dtype.type(np.nan)
+ return common_dtype
elif is_numeric_dtype(common_dtype):
if has_none_blocks:
- return np.dtype(np.float64), np.nan
+ return np.dtype(np.float64)
else:
- return common_dtype, None
+ return common_dtype
msg = "invalid dtype determination in get_concat_dtype"
raise AssertionError(msg)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39453 | 2021-01-28T20:00:32Z | 2021-02-02T02:42:26Z | 2021-02-02T02:42:26Z | 2021-02-02T02:46:09Z |
Backport PR #39440 on branch 1.2.x (REGR: prefer user-provided mode) | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 656e779055486..baa0cc2ac9e18 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
+- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 90622ef0c0f2c..be353fefdd1ef 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -845,12 +845,15 @@ def file_exists(filepath_or_buffer: FilePathOrBuffer) -> bool:
def _is_binary_mode(handle: FilePathOrBuffer, mode: str) -> bool:
"""Whether the handle is opened in binary mode"""
+ # specified by user
+ if "t" in mode or "b" in mode:
+ return "b" in mode
+
# classes that expect string but have 'b' in mode
- text_classes = (codecs.StreamReaderWriter,)
- if isinstance(handle, text_classes):
+ text_classes = (codecs.StreamWriter, codecs.StreamReader, codecs.StreamReaderWriter)
+ if issubclass(type(handle), text_classes):
return False
# classes that expect bytes
binary_classes = (BufferedIOBase, RawIOBase)
-
return isinstance(handle, binary_classes) or "b" in getattr(handle, "mode", mode)
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index 80e2b36764ba0..540f12841de1b 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -2,7 +2,7 @@
Tests for the pandas.io.common functionalities
"""
import codecs
-from io import StringIO
+from io import BytesIO, StringIO
import mmap
import os
from pathlib import Path
@@ -443,3 +443,33 @@ def test_codecs_encoding(encoding, format):
else:
df = pd.read_json(handle)
tm.assert_frame_equal(expected, df)
+
+
+def test_codecs_get_writer_reader():
+ # GH39247
+ expected = tm.makeDataFrame()
+ with tm.ensure_clean() as path:
+ with open(path, "wb") as handle:
+ with codecs.getwriter("utf-8")(handle) as encoded:
+ expected.to_csv(encoded)
+ with open(path, "rb") as handle:
+ with codecs.getreader("utf-8")(handle) as encoded:
+ df = pd.read_csv(encoded, index_col=0)
+ tm.assert_frame_equal(expected, df)
+
+
+@pytest.mark.parametrize(
+ "io_class,mode,msg",
+ [
+ (BytesIO, "t", "a bytes-like object is required, not 'str'"),
+ (StringIO, "b", "string argument expected, got 'bytes'"),
+ ],
+)
+def test_explicit_encoding(io_class, mode, msg):
+ # GH39247; this test makes sure that if a user provides mode="*t" or "*b",
+ # it is used. In the case of this test it leads to an error as intentionally the
+ # wrong mode is requested
+ expected = tm.makeDataFrame()
+ with io_class() as buffer:
+ with pytest.raises(TypeError, match=msg):
+ expected.to_csv(buffer, mode=f"w{mode}")
| Backport PR #39440: REGR: prefer user-provided mode | https://api.github.com/repos/pandas-dev/pandas/pulls/39452 | 2021-01-28T19:52:02Z | 2021-01-29T02:02:39Z | 2021-01-29T02:02:39Z | 2021-01-29T02:02:39Z |
BUG: raise when sort_index with ascending=None | diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst
index 28fc83459b69d..f72ee78bf243a 100644
--- a/doc/source/whatsnew/v1.2.3.rst
+++ b/doc/source/whatsnew/v1.2.3.rst
@@ -19,7 +19,11 @@ Fixed regressions
- Fixed regression in nullable integer unary ops propagating mask on assignment (:issue:`39943`)
- Fixed regression in :meth:`DataFrame.__setitem__` not aligning :class:`DataFrame` on right-hand side for boolean indexer (:issue:`39931`)
- Fixed regression in :meth:`~DataFrame.to_json` failing to use ``compression`` with URL-like paths that are internally opened in binary mode or with user-provided file objects that are opened in binary mode (:issue:`39985`)
--
+- Fixed regression in :meth:`~Series.sort_index` and :meth:`~DataFrame.sort_index`,
+ which exited with an ungraceful error when having kwarg ``ascending=None`` passed (:issue:`39434`).
+ Passing ``ascending=None`` is still considered invalid,
+ and the new error message suggests a proper usage
+ (``ascending`` must be a boolean or a list-like boolean).
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2c95e65c70899..a39aef9b91662 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5625,7 +5625,7 @@ def sort_index(
self,
axis: Axis = 0,
level: Optional[Level] = None,
- ascending: bool = True,
+ ascending: Union[Union[bool, int], Sequence[Union[bool, int]]] = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
@@ -5646,7 +5646,7 @@ def sort_index(
and 1 identifies the columns.
level : int or level name or list of ints or list of level names
If not None, sort on values in specified index level(s).
- ascending : bool or list of bools, default True
+ ascending : bool or list-like of bools, default True
Sort ascending vs. descending. When the index is a MultiIndex the
sort direction can be controlled for each level individually.
inplace : bool, default False
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index eb4c5c07af2c4..4774045849eb6 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -71,6 +71,7 @@
rewrite_axis_style_signature,
)
from pandas.util._validators import (
+ validate_ascending,
validate_bool_kwarg,
validate_fillna_kwargs,
)
@@ -4548,7 +4549,7 @@ def sort_index(
self,
axis=0,
level=None,
- ascending: bool_t = True,
+ ascending: Union[Union[bool_t, int], Sequence[Union[bool_t, int]]] = True,
inplace: bool_t = False,
kind: str = "quicksort",
na_position: str = "last",
@@ -4559,6 +4560,8 @@ def sort_index(
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
+ ascending = validate_ascending(ascending)
+
target = self._get_axis(axis)
indexer = get_indexer_indexer(
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 50a537aeb8623..5fece72ccddca 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -15,9 +15,11 @@
Iterable,
List,
Optional,
+ Sequence,
Tuple,
Type,
Union,
+ cast,
)
import warnings
@@ -3099,7 +3101,7 @@ def update(self, other) -> None:
def sort_values(
self,
axis=0,
- ascending=True,
+ ascending: Union[Union[bool, int], Sequence[Union[bool, int]]] = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
@@ -3117,7 +3119,7 @@ def sort_values(
axis : {0 or 'index'}, default 0
Axis to direct sorting. The value 'index' is accepted for
compatibility with DataFrame.sort_values.
- ascending : bool, default True
+ ascending : bool or list of bools, default True
If True, sort values in ascending order, otherwise descending.
inplace : bool, default False
If True, perform operation in-place.
@@ -3277,6 +3279,7 @@ def sort_values(
)
if is_list_like(ascending):
+ ascending = cast(Sequence[Union[bool, int]], ascending)
if len(ascending) != 1:
raise ValueError(
f"Length of ascending ({len(ascending)}) must be 1 for Series"
@@ -3291,7 +3294,7 @@ def sort_values(
# GH 35922. Make sorting stable by leveraging nargsort
values_to_sort = ensure_key_mapped(self, key)._values if key else self._values
- sorted_index = nargsort(values_to_sort, kind, ascending, na_position)
+ sorted_index = nargsort(values_to_sort, kind, bool(ascending), na_position)
result = self._constructor(
self._values[sorted_index], index=self.index[sorted_index]
@@ -3309,7 +3312,7 @@ def sort_index(
self,
axis=0,
level=None,
- ascending: bool = True,
+ ascending: Union[Union[bool, int], Sequence[Union[bool, int]]] = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
@@ -3329,7 +3332,7 @@ def sort_index(
Axis to direct sorting. This can only be 0 for Series.
level : int, optional
If not None, sort on values in specified index level(s).
- ascending : bool or list of bools, default True
+ ascending : bool or list-like of bools, default True
Sort ascending vs. descending. When the index is a MultiIndex the
sort direction can be controlled for each level individually.
inplace : bool, default False
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index 67863036929b3..0195969de1f17 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -10,6 +10,7 @@
Iterable,
List,
Optional,
+ Sequence,
Tuple,
Union,
)
@@ -45,7 +46,7 @@
def get_indexer_indexer(
target: Index,
level: Union[str, int, List[str], List[int]],
- ascending: bool,
+ ascending: Union[Sequence[Union[bool, int]], Union[bool, int]],
kind: str,
na_position: str,
sort_remaining: bool,
diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py
index 221296bfd6d76..5fa60b55f4e21 100644
--- a/pandas/tests/frame/methods/test_sort_index.py
+++ b/pandas/tests/frame/methods/test_sort_index.py
@@ -761,6 +761,23 @@ def test_sort_index_with_categories(self, categories):
)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize(
+ "ascending",
+ [
+ None,
+ [True, None],
+ [False, "True"],
+ ],
+ )
+ def test_sort_index_ascending_bad_value_raises(self, ascending):
+ # GH 39434
+ df = DataFrame(np.arange(64))
+ length = len(df.index)
+ df.index = [(i - length / 2) % length for i in range(length)]
+ match = 'For argument "ascending" expected type bool'
+ with pytest.raises(ValueError, match=match):
+ df.sort_index(axis=0, ascending=ascending, na_position="first")
+
class TestDataFrameSortIndexKey:
def test_sort_multi_index_key(self):
diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py
index d70abe2311acd..4df6f52e0fff4 100644
--- a/pandas/tests/series/methods/test_sort_index.py
+++ b/pandas/tests/series/methods/test_sort_index.py
@@ -203,6 +203,20 @@ def test_sort_index_ascending_list(self):
expected = ser.iloc[[0, 4, 1, 5, 2, 6, 3, 7]]
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "ascending",
+ [
+ None,
+ (True, None),
+ (False, "True"),
+ ],
+ )
+ def test_sort_index_ascending_bad_value_raises(self, ascending):
+ ser = Series(range(10), index=[0, 3, 2, 1, 4, 5, 7, 6, 8, 9])
+ match = 'For argument "ascending" expected type bool'
+ with pytest.raises(ValueError, match=match):
+ ser.sort_index(ascending=ascending)
+
class TestSeriesSortIndexKey:
def test_sort_index_multiindex_key(self):
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index 60a81ed63b005..087dccfadcce1 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -4,6 +4,7 @@
"""
from typing import (
Iterable,
+ Sequence,
Union,
)
import warnings
@@ -208,9 +209,39 @@ def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_ar
validate_kwargs(fname, kwargs, compat_args)
-def validate_bool_kwarg(value, arg_name):
- """ Ensures that argument passed in arg_name is of type bool. """
- if not (is_bool(value) or value is None):
+def validate_bool_kwarg(value, arg_name, none_allowed=True, int_allowed=False):
+ """
+ Ensure that argument passed in arg_name can be interpreted as boolean.
+
+ Parameters
+ ----------
+ value : bool
+ Value to be validated.
+ arg_name : str
+ Name of the argument. To be reflected in the error message.
+ none_allowed : bool, default True
+ Whether to consider None to be a valid boolean.
+ int_allowed : bool, default False
+ Whether to consider integer value to be a valid boolean.
+
+ Returns
+ -------
+ value
+ The same value as input.
+
+ Raises
+ ------
+ ValueError
+ If the value is not a valid boolean.
+ """
+ good_value = is_bool(value)
+ if none_allowed:
+ good_value = good_value or value is None
+
+ if int_allowed:
+ good_value = good_value or isinstance(value, int)
+
+ if not good_value:
raise ValueError(
f'For argument "{arg_name}" expected type bool, received '
f"type {type(value).__name__}."
@@ -384,3 +415,14 @@ def validate_percentile(q: Union[float, Iterable[float]]) -> np.ndarray:
if not all(0 <= qs <= 1 for qs in q_arr):
raise ValueError(msg.format(q_arr / 100.0))
return q_arr
+
+
+def validate_ascending(
+ ascending: Union[Union[bool, int], Sequence[Union[bool, int]]] = True,
+):
+ """Validate ``ascending`` kwargs for ``sort_index`` method."""
+ kwargs = {"none_allowed": False, "int_allowed": True}
+ if not isinstance(ascending, (list, tuple)):
+ return validate_bool_kwarg(ascending, "ascending", **kwargs)
+
+ return [validate_bool_kwarg(item, "ascending", **kwargs) for item in ascending]
| - [ ] closes #39434
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Added validation of ``ascending`` for ``sort_index`` methods.
Proposed a solution to raise ``ValueError`` when either of the elements of ``ascending`` turned out to be ``None``. | https://api.github.com/repos/pandas-dev/pandas/pulls/39451 | 2021-01-28T16:50:29Z | 2021-02-26T14:21:24Z | 2021-02-26T14:21:24Z | 2021-02-26T16:38:25Z |
Backport PR #39423: BUG: Assert_frame_equal always raising AssertionError when comparing extension dtypes | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 95fbbaf5d566e..656e779055486 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
+- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/_testing.py b/pandas/_testing.py
index 224c8d540c6bb..1df3351a7241c 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -1402,14 +1402,26 @@ def assert_series_equal(
assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
if check_exact and is_numeric_dtype(left.dtype) and is_numeric_dtype(right.dtype):
+ left_values = left._values
+ right_values = right._values
# Only check exact if dtype is numeric
- assert_numpy_array_equal(
- left._values,
- right._values,
- check_dtype=check_dtype,
- obj=str(obj),
- index_values=np.asarray(left.index),
- )
+ if is_extension_array_dtype(left_values) and is_extension_array_dtype(
+ right_values
+ ):
+ assert_extension_array_equal(
+ left_values,
+ right_values,
+ check_dtype=check_dtype,
+ index_values=np.asarray(left.index),
+ )
+ else:
+ assert_numpy_array_equal(
+ left_values,
+ right_values,
+ check_dtype=check_dtype,
+ obj=str(obj),
+ index_values=np.asarray(left.index),
+ )
elif check_datetimelike_compat and (
needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype)
):
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index bf80a1410e7d9..f8539e9031d28 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -305,3 +305,19 @@ def test_assert_frame_equal_columns_mixed_dtype():
# GH#39168
df = DataFrame([[0, 1, 2]], columns=["foo", "bar", 42], index=[1, "test", 2])
tm.assert_frame_equal(df, df, check_like=True)
+
+
+def test_frame_equal_extension_dtype(frame_or_series, any_numeric_dtype):
+ # GH#39410
+ obj = frame_or_series([1, 2], dtype=any_numeric_dtype)
+ tm.assert_equal(obj, obj, check_exact=True)
+
+
+@pytest.mark.parametrize("indexer", [(0, 1), (1, 0)])
+def test_frame_equal_mixed_dtypes(frame_or_series, any_numeric_dtype, indexer):
+ dtypes = (any_numeric_dtype, "int64")
+ obj1 = frame_or_series([1, 2], dtype=dtypes[indexer[0]])
+ obj2 = frame_or_series([1, 2], dtype=dtypes[indexer[1]])
+ msg = r'(Series|DataFrame.iloc\[:, 0\] \(column name="0"\) classes) are different'
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False)
| #39423 | https://api.github.com/repos/pandas-dev/pandas/pulls/39449 | 2021-01-28T08:46:11Z | 2021-01-28T10:02:19Z | 2021-01-28T10:02:19Z | 2021-01-28T10:58:38Z |
REF: dont pass fill_value to algos.take_nd from internals.concat | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index ae7e8191fc482..6c5c5d5d5b75e 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1658,8 +1658,25 @@ def take(arr, indices, axis: int = 0, allow_fill: bool = False, fill_value=None)
return result
+# TODO: can we de-duplicate with something in dtypes.missing?
+def _get_default_fill_value(dtype, fill_value):
+ if fill_value is lib.no_default:
+ if is_extension_array_dtype(dtype):
+ fill_value = dtype.na_value
+ elif dtype.kind in ["m", "M"]:
+ fill_value = dtype.type("NaT")
+ else:
+ fill_value = np.nan
+ return fill_value
+
+
def take_nd(
- arr, indexer, axis: int = 0, out=None, fill_value=np.nan, allow_fill: bool = True
+ arr,
+ indexer,
+ axis: int = 0,
+ out=None,
+ fill_value=lib.no_default,
+ allow_fill: bool = True,
):
"""
Specialized Cython take which sets NaN values in one pass
@@ -1694,6 +1711,8 @@ def take_nd(
"""
mask_info = None
+ fill_value = _get_default_fill_value(arr.dtype, fill_value)
+
if isinstance(arr, ABCExtensionArray):
# Check for EA to catch DatetimeArray, TimedeltaArray
return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill)
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 0b611bfdb1f10..166b630378c5a 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -322,7 +322,7 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike:
else:
for ax, indexer in self.indexers.items():
- values = algos.take_nd(values, indexer, axis=ax, fill_value=fill_value)
+ values = algos.take_nd(values, indexer, axis=ax)
return values
| The dtype-finding code in internals.concat is something else. Tried untangling it, but now I think we can make it unnecessary altogether. This is the first step in that process. | https://api.github.com/repos/pandas-dev/pandas/pulls/39446 | 2021-01-28T01:58:37Z | 2021-02-01T22:32:37Z | 2021-02-01T22:32:37Z | 2021-02-01T23:12:40Z |
TST: strictify xfails in sparse tests | diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py
index 013814681b5f6..86fbcb337b30e 100644
--- a/pandas/tests/arrays/sparse/test_arithmetics.py
+++ b/pandas/tests/arrays/sparse/test_arithmetics.py
@@ -124,8 +124,13 @@ def test_float_scalar(
if not np_version_under1p20:
if op in [operator.floordiv, ops.rfloordiv]:
- mark = pytest.mark.xfail(strict=False, reason="GH#38172")
- request.node.add_marker(mark)
+ if op is operator.floordiv and scalar != 0:
+ pass
+ elif op is ops.rfloordiv and scalar == 0:
+ pass
+ else:
+ mark = pytest.mark.xfail(reason="GH#38172")
+ request.node.add_marker(mark)
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
@@ -170,9 +175,10 @@ def test_float_same_index_with_nans(
op = all_arithmetic_functions
if not np_version_under1p20:
- if op in [operator.floordiv, ops.rfloordiv]:
- mark = pytest.mark.xfail(strict=False, reason="GH#38172")
- request.node.add_marker(mark)
+ if op is ops.rfloordiv:
+ if not (mix and kind == "block"):
+ mark = pytest.mark.xfail(reason="GH#38172")
+ request.node.add_marker(mark)
values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39445 | 2021-01-28T01:39:54Z | 2021-01-28T02:18:59Z | 2021-01-28T02:18:59Z | 2021-01-28T02:22:36Z |
REF: shallow_copy->simple_new/rename | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index efb2ba6c5eaa2..205bbcc07fc76 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -825,7 +825,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
taken = algos.take(
self._values, indices, allow_fill=allow_fill, fill_value=self._na_value
)
- return self._shallow_copy(taken)
+ return type(self)._simple_new(taken, name=self.name)
@final
def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool:
@@ -893,7 +893,9 @@ def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool:
def repeat(self, repeats, axis=None):
repeats = ensure_platform_int(repeats)
nv.validate_repeat((), {"axis": axis})
- return self._shallow_copy(self._values.repeat(repeats))
+ res_values = self._values.repeat(repeats)
+
+ return type(self)._simple_new(res_values, name=self.name)
# --------------------------------------------------------------------
# Copying Methods
@@ -2463,7 +2465,8 @@ def dropna(self, how="any"):
raise ValueError(f"invalid how option: {how}")
if self.hasnans:
- return self._shallow_copy(self._values[~self._isnan])
+ res_values = self._values[~self._isnan]
+ return type(self)._simple_new(res_values, name=self.name)
return self._shallow_copy()
# --------------------------------------------------------------------
@@ -4556,7 +4559,7 @@ def putmask(self, mask, value):
return self.astype(object).putmask(mask, value)
np.putmask(values, mask, converted)
- return self._shallow_copy(values)
+ return type(self)._simple_new(values, name=self.name)
def equals(self, other: Any) -> bool:
"""
@@ -5718,7 +5721,8 @@ def delete(self, loc):
>>> idx.delete([0, 2])
Index(['b'], dtype='object')
"""
- return self._shallow_copy(np.delete(self._data, loc))
+ res_values = np.delete(self._data, loc)
+ return type(self)._simple_new(res_values, name=self.name)
def insert(self, loc: int, item):
"""
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index fbc7f578d760e..f65102dbaa611 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -13,6 +13,7 @@
from pandas._typing import Dtype
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly, doc
+from pandas.util._exceptions import rewrite_exception
from pandas.core.dtypes.common import (
ensure_platform_int,
@@ -169,9 +170,16 @@ def _data(self):
return np.arange(self.start, self.stop, self.step, dtype=np.int64)
@cache_readonly
- def _int64index(self) -> Int64Index:
+ def _cached_int64index(self) -> Int64Index:
return Int64Index._simple_new(self._data, name=self.name)
+ @property
+ def _int64index(self):
+ # wrap _cached_int64index so we can be sure its name matches self.name
+ res = self._cached_int64index
+ res._name = self._name
+ return res
+
def _get_data_as_items(self):
""" return a list of tuples of start, stop, step """
rng = self._range
@@ -390,6 +398,22 @@ def _get_indexer(self, target, method=None, limit=None, tolerance=None):
# --------------------------------------------------------------------
+ def repeat(self, repeats, axis=None):
+ return self._int64index.repeat(repeats, axis=axis)
+
+ def delete(self, loc):
+ return self._int64index.delete(loc)
+
+ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
+ with rewrite_exception("Int64Index", type(self).__name__):
+ return self._int64index.take(
+ indices,
+ axis=axis,
+ allow_fill=allow_fill,
+ fill_value=fill_value,
+ **kwargs,
+ )
+
def tolist(self):
return list(self._range)
@@ -645,7 +669,7 @@ def _difference(self, other, sort=None):
overlap = overlap[::-1]
if len(overlap) == 0:
- return self._shallow_copy(name=res_name)
+ return self.rename(name=res_name)
if len(overlap) == len(self):
return self[:0].rename(res_name)
if not isinstance(overlap, RangeIndex):
| https://api.github.com/repos/pandas-dev/pandas/pulls/39444 | 2021-01-28T01:34:43Z | 2021-01-28T20:12:54Z | 2021-01-28T20:12:54Z | 2021-01-28T20:54:20Z | |
BUG: DataFrame constructor reordering elements with ndarray from datetime dtype not datetime64[ns] | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1dcde2000fc89..88e5971abea82 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -233,6 +233,7 @@ Datetimelike
- Bug in constructing a :class:`DataFrame` or :class:`Series` with mismatched ``datetime64`` data and ``timedelta64`` dtype, or vice-versa, failing to raise ``TypeError`` (:issue:`38575`, :issue:`38764`, :issue:`38792`)
- Bug in constructing a :class:`Series` or :class:`DataFrame` with a ``datetime`` object out of bounds for ``datetime64[ns]`` dtype or a ``timedelta`` object out of bounds for ``timedelta64[ns]`` dtype (:issue:`38792`, :issue:`38965`)
- Bug in :meth:`DatetimeIndex.intersection`, :meth:`DatetimeIndex.symmetric_difference`, :meth:`PeriodIndex.intersection`, :meth:`PeriodIndex.symmetric_difference` always returning object-dtype when operating with :class:`CategoricalIndex` (:issue:`38741`)
+- Bug in :class:`DataFrame` constructor reordering element when construction from datetime ndarray with dtype not ``"datetime64[ns]"`` (:issue:`39422`)
- Bug in :meth:`Series.where` incorrectly casting ``datetime64`` values to ``int64`` (:issue:`37682`)
- Bug in :class:`Categorical` incorrectly typecasting ``datetime`` object to ``Timestamp`` (:issue:`38878`)
- Bug in comparisons between :class:`Timestamp` object and ``datetime64`` objects just outside the implementation bounds for nanosecond ``datetime64`` (:issue:`39221`)
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 676ff7deb950f..0a22bd9b849a7 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -224,7 +224,7 @@ def ensure_datetime64ns(arr: ndarray, copy: bool=True):
ivalues = arr.view(np.int64).ravel("K")
- result = np.empty(shape, dtype=DT64NS_DTYPE)
+ result = np.empty_like(arr, dtype=DT64NS_DTYPE)
iresult = result.ravel("K").view(np.int64)
if len(iresult) == 0:
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index a6aaf3a6af750..f23b8d559a00a 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -1762,6 +1762,70 @@ def test_constructor_datetimes_with_nulls(self, arr):
expected = Series([np.dtype("datetime64[ns]")])
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize("order", ["K", "A", "C", "F"])
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "datetime64[M]",
+ "datetime64[D]",
+ "datetime64[h]",
+ "datetime64[m]",
+ "datetime64[s]",
+ "datetime64[ms]",
+ "datetime64[us]",
+ "datetime64[ns]",
+ ],
+ )
+ def test_constructor_datetimes_non_ns(self, order, dtype):
+ na = np.array(
+ [
+ ["2015-01-01", "2015-01-02", "2015-01-03"],
+ ["2017-01-01", "2017-01-02", "2017-02-03"],
+ ],
+ dtype=dtype,
+ order=order,
+ )
+ df = DataFrame(na)
+ expected = DataFrame(
+ [
+ ["2015-01-01", "2015-01-02", "2015-01-03"],
+ ["2017-01-01", "2017-01-02", "2017-02-03"],
+ ]
+ )
+ expected = expected.astype(dtype=dtype)
+ tm.assert_frame_equal(df, expected)
+
+ @pytest.mark.parametrize("order", ["K", "A", "C", "F"])
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "timedelta64[D]",
+ "timedelta64[h]",
+ "timedelta64[m]",
+ "timedelta64[s]",
+ "timedelta64[ms]",
+ "timedelta64[us]",
+ "timedelta64[ns]",
+ ],
+ )
+ def test_constructor_timedelta_non_ns(self, order, dtype):
+ na = np.array(
+ [
+ [np.timedelta64(1, "D"), np.timedelta64(2, "D")],
+ [np.timedelta64(4, "D"), np.timedelta64(5, "D")],
+ ],
+ dtype=dtype,
+ order=order,
+ )
+ df = DataFrame(na).astype("timedelta64[ns]")
+ expected = DataFrame(
+ [
+ [Timedelta(1, "D"), Timedelta(2, "D")],
+ [Timedelta(4, "D"), Timedelta(5, "D")],
+ ],
+ )
+ tm.assert_frame_equal(df, expected)
+
def test_constructor_for_list_with_dtypes(self):
# test list of lists/ndarrays
df = DataFrame([np.arange(5) for x in range(5)])
| - [x] closes #39422
- [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
The ravel("K") was a problem when passing in a view on the underlying object, which was done here. | https://api.github.com/repos/pandas-dev/pandas/pulls/39442 | 2021-01-27T20:00:15Z | 2021-01-28T20:11:56Z | 2021-01-28T20:11:56Z | 2021-01-30T08:36:59Z |
REGR: prefer user-provided mode | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 656e779055486..baa0cc2ac9e18 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
+- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/common.py b/pandas/io/common.py
index f71522b5c9555..e5a1f58ec6cd2 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -857,12 +857,15 @@ def file_exists(filepath_or_buffer: FilePathOrBuffer) -> bool:
def _is_binary_mode(handle: FilePathOrBuffer, mode: str) -> bool:
"""Whether the handle is opened in binary mode"""
+ # specified by user
+ if "t" in mode or "b" in mode:
+ return "b" in mode
+
# classes that expect string but have 'b' in mode
- text_classes = (codecs.StreamReaderWriter,)
- if isinstance(handle, text_classes):
+ text_classes = (codecs.StreamWriter, codecs.StreamReader, codecs.StreamReaderWriter)
+ if issubclass(type(handle), text_classes):
return False
# classes that expect bytes
binary_classes = (BufferedIOBase, RawIOBase)
-
return isinstance(handle, binary_classes) or "b" in getattr(handle, "mode", mode)
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index 8edfd3f16efdf..69a1427cec34f 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -2,7 +2,7 @@
Tests for the pandas.io.common functionalities
"""
import codecs
-from io import StringIO
+from io import BytesIO, StringIO
import mmap
import os
from pathlib import Path
@@ -446,3 +446,33 @@ def test_codecs_encoding(encoding, format):
else:
df = pd.read_json(handle)
tm.assert_frame_equal(expected, df)
+
+
+def test_codecs_get_writer_reader():
+ # GH39247
+ expected = tm.makeDataFrame()
+ with tm.ensure_clean() as path:
+ with open(path, "wb") as handle:
+ with codecs.getwriter("utf-8")(handle) as encoded:
+ expected.to_csv(encoded)
+ with open(path, "rb") as handle:
+ with codecs.getreader("utf-8")(handle) as encoded:
+ df = pd.read_csv(encoded, index_col=0)
+ tm.assert_frame_equal(expected, df)
+
+
+@pytest.mark.parametrize(
+ "io_class,mode,msg",
+ [
+ (BytesIO, "t", "a bytes-like object is required, not 'str'"),
+ (StringIO, "b", "string argument expected, got 'bytes'"),
+ ],
+)
+def test_explicit_encoding(io_class, mode, msg):
+ # GH39247; this test makes sure that if a user provides mode="*t" or "*b",
+ # it is used. In the case of this test it leads to an error as intentionally the
+ # wrong mode is requested
+ expected = tm.makeDataFrame()
+ with io_class() as buffer:
+ with pytest.raises(TypeError, match=msg):
+ expected.to_csv(buffer, mode=f"w{mode}")
| follow-up to #39253
- [x] closes #39247
- [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
Make sure that the user-provided mode is always preferred (if it contains 't' or 'b') and extend list of text-only classes. | https://api.github.com/repos/pandas-dev/pandas/pulls/39440 | 2021-01-27T17:22:23Z | 2021-01-28T19:50:04Z | 2021-01-28T19:50:04Z | 2021-02-23T21:59:23Z |
BUG: RangeIndex concatenating incorrectly a single object of length 1 | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 3035e54823718..7851962587e2c 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -294,6 +294,7 @@ Indexing
- Bug in setting ``timedelta64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`)
- Bug in setting :class:`Interval` values into a :class:`Series` or :class:`DataFrame` with mismatched :class:`IntervalDtype` incorrectly casting the new values to the existing dtype (:issue:`39120`)
- Bug in incorrectly raising in :meth:`Index.insert`, when setting a new column that cannot be held in the existing ``frame.columns``, or in :meth:`Series.reset_index` or :meth:`DataFrame.reset_index` instead of casting to a compatible dtype (:issue:`39068`)
+- Bug in :meth:`RangeIndex.append` where a single object of length 1 was concatenated incorrectly (:issue:`39401`)
Missing
^^^^^^^
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index fbc7f578d760e..06d2abad653bd 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -697,6 +697,9 @@ def _concat(self, indexes, name):
if not all(isinstance(x, RangeIndex) for x in indexes):
return super()._concat(indexes, name)
+ elif len(indexes) == 1:
+ return indexes[0]
+
start = step = next_ = None
# Filter the empty indexes
diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py
index 8c1272a6e971b..40cd812ebe368 100644
--- a/pandas/tests/indexes/ranges/test_range.py
+++ b/pandas/tests/indexes/ranges/test_range.py
@@ -506,3 +506,18 @@ def test_format_empty(self):
empty_idx = self._holder(0)
assert empty_idx.format() == []
assert empty_idx.format(name=True) == [""]
+
+ @pytest.mark.parametrize(
+ "RI",
+ [
+ RangeIndex(0, -1, -1),
+ RangeIndex(0, 1, 1),
+ RangeIndex(1, 3, 2),
+ RangeIndex(0, -1, -2),
+ RangeIndex(-3, -5, -2),
+ ],
+ )
+ def test_append_len_one(self, RI):
+ # GH39401
+ result = RI.append([])
+ tm.assert_index_equal(result, RI, exact=True)
diff --git a/pandas/tests/reshape/concat/test_series.py b/pandas/tests/reshape/concat/test_series.py
index 2d681e792914c..44e29f08f282e 100644
--- a/pandas/tests/reshape/concat/test_series.py
+++ b/pandas/tests/reshape/concat/test_series.py
@@ -143,3 +143,9 @@ def test_concat_series_partial_columns_names(self):
result = concat([foo, bar, baz], axis=1, ignore_index=True)
expected = DataFrame({0: [1, 2], 1: [1, 2], 2: [4, 5]})
tm.assert_frame_equal(result, expected)
+
+ def test_concat_series_length_one_reversed(self, frame_or_series):
+ # GH39401
+ obj = frame_or_series([100])
+ result = pd.concat([obj.iloc[::-1]])
+ tm.assert_equal(result, obj)
| - [x] closes #39401
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39439 | 2021-01-27T16:40:30Z | 2021-01-28T15:04:20Z | 2021-01-28T15:04:20Z | 2021-01-28T15:04:29Z |
REF: Index.insert maybe_promote -> find_common_type | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 40215ea87f978..a412b8477897d 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -41,8 +41,8 @@
from pandas.core.dtypes.cast import (
find_common_type,
+ infer_dtype_from,
maybe_cast_to_integer_array,
- maybe_promote,
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
@@ -87,7 +87,7 @@
ABCTimedeltaIndex,
)
from pandas.core.dtypes.inference import is_dict_like
-from pandas.core.dtypes.missing import array_equivalent, isna
+from pandas.core.dtypes.missing import array_equivalent, is_valid_nat_for_dtype, isna
from pandas.core import missing, ops
from pandas.core.accessor import CachedAccessor
@@ -5735,16 +5735,14 @@ def insert(self, loc: int, item):
# Note: this method is overridden by all ExtensionIndex subclasses,
# so self is never backed by an EA.
item = lib.item_from_zerodim(item)
+ if is_valid_nat_for_dtype(item, self.dtype) and self.dtype != object:
+ item = self._na_value
try:
item = self._validate_fill_value(item)
except TypeError:
- if is_scalar(item):
- dtype, item = maybe_promote(self.dtype, item)
- else:
- # maybe_promote would raise ValueError
- dtype = np.dtype(object)
-
+ inferred, _ = infer_dtype_from(item)
+ dtype = find_common_type([self.dtype, inferred])
return self.astype(dtype).insert(loc, item)
arr = np.asarray(self)
| https://api.github.com/repos/pandas-dev/pandas/pulls/39437 | 2021-01-27T16:24:56Z | 2021-01-28T02:05:50Z | 2021-01-28T02:05:50Z | 2021-01-28T02:35:57Z | |
ENH: Add compression to read_stata and StataReader | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index e61f50afea838..ac1f74a5fceb6 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -55,6 +55,7 @@ Other enhancements
- :meth:`DataFrame.plot.scatter` can now accept a categorical column as the argument to ``c`` (:issue:`12380`, :issue:`31357`)
- :meth:`.Styler.set_tooltips` allows on hover tooltips to be added to styled HTML dataframes.
- :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`)
+- :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files.
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 9a5c9e4a2e2b2..8f8c435fae4f3 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -98,6 +98,19 @@
Return StataReader object for iterations, returns chunks with
given number of lines."""
+_compression_params = f"""\
+compression : str or dict, default None
+ If string, specifies compression mode. If dict, value at key 'method'
+ specifies compression mode. Compression mode must be one of {{'infer',
+ 'gzip', 'bz2', 'zip', 'xz', None}}. If compression mode is 'infer'
+ and `filepath_or_buffer` is path-like, then detect compression from
+ the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise
+ no compression). If dict and compression mode is one of
+ {{'zip', 'gzip', 'bz2'}}, or inferred as one of the above,
+ other entries passed as additional compression options.
+{generic._shared_docs["storage_options"]}"""
+
+
_iterator_params = """\
iterator : bool, default False
Return StataReader object."""
@@ -129,6 +142,7 @@
{_statafile_processing_params2}
{_chunksize_params}
{_iterator_params}
+{_compression_params}
Returns
-------
@@ -180,6 +194,7 @@
{_statafile_processing_params1}
{_statafile_processing_params2}
{_chunksize_params}
+{_compression_params}
{_reader_notes}
"""
@@ -1026,6 +1041,7 @@ def __init__(
columns: Optional[Sequence[str]] = None,
order_categoricals: bool = True,
chunksize: Optional[int] = None,
+ compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
):
super().__init__()
@@ -1064,10 +1080,10 @@ def __init__(
"rb",
storage_options=storage_options,
is_text=False,
+ compression=compression,
) as handles:
# Copy to BytesIO, and ensure no encoding
- contents = handles.handle.read()
- self.path_or_buf = BytesIO(contents) # type: ignore[arg-type]
+ self.path_or_buf = BytesIO(handles.handle.read()) # type: ignore[arg-type]
self._read_header()
self._setup_dtype()
@@ -1898,6 +1914,7 @@ def read_stata(
order_categoricals: bool = True,
chunksize: Optional[int] = None,
iterator: bool = False,
+ compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
) -> Union[DataFrame, StataReader]:
@@ -1912,6 +1929,7 @@ def read_stata(
order_categoricals=order_categoricals,
chunksize=chunksize,
storage_options=storage_options,
+ compression=compression,
)
if iterator or chunksize:
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
index 5897b91a5fa70..058dc7659fc95 100644
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -2003,3 +2003,48 @@ def test_precision_loss():
tm.assert_series_equal(reread.dtypes, expected_dt)
assert reread.loc[0, "little"] == df.loc[0, "little"]
assert reread.loc[0, "big"] == float(df.loc[0, "big"])
+
+
+def test_compression_roundtrip(compression):
+ df = DataFrame(
+ [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ index=["A", "B"],
+ columns=["X", "Y", "Z"],
+ )
+ df.index.name = "index"
+
+ with tm.ensure_clean() as path:
+
+ df.to_stata(path, compression=compression)
+ reread = read_stata(path, compression=compression, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+ # explicitly ensure file was compressed.
+ with tm.decompress_file(path, compression) as fh:
+ contents = io.BytesIO(fh.read())
+ reread = pd.read_stata(contents, index_col="index")
+ tm.assert_frame_equal(df, reread)
+
+
+@pytest.mark.parametrize("to_infer", [True, False])
+@pytest.mark.parametrize("read_infer", [True, False])
+def test_stata_compression(compression_only, read_infer, to_infer):
+ compression = compression_only
+
+ ext = "gz" if compression == "gzip" else compression
+ filename = f"test.{ext}"
+
+ df = DataFrame(
+ [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
+ index=["A", "B"],
+ columns=["X", "Y", "Z"],
+ )
+ df.index.name = "index"
+
+ to_compression = "infer" if to_infer else compression
+ read_compression = "infer" if read_infer else compression
+
+ with tm.ensure_clean(filename) as path:
+ df.to_stata(path, compression=to_compression)
+ result = pd.read_stata(path, compression=read_compression, index_col="index")
+ tm.assert_frame_equal(result, df)
| Add support for reading compressed dta files directly
xref #26599
- [X] closes #26599
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39432 | 2021-01-27T10:37:38Z | 2021-02-02T13:19:21Z | 2021-02-02T13:19:21Z | 2021-02-02T13:19:25Z |
Backport PR #39406 on branch 1.2.x (DOC: link to correct PR) | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 395f353b561eb..8a935f269e1a6 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -518,7 +518,7 @@ Deprecations
- Deprecated parameter ``dtype`` of method :meth:`~Index.copy` for all :class:`Index` subclasses. Use the :meth:`~Index.astype` method instead for changing dtype (:issue:`35853`)
- Deprecated parameters ``levels`` and ``codes`` in :meth:`MultiIndex.copy`. Use the :meth:`~MultiIndex.set_levels` and :meth:`~MultiIndex.set_codes` methods instead (:issue:`36685`)
- Date parser functions :func:`~pandas.io.date_converters.parse_date_time`, :func:`~pandas.io.date_converters.parse_date_fields`, :func:`~pandas.io.date_converters.parse_all_fields` and :func:`~pandas.io.date_converters.generic_parser` from ``pandas.io.date_converters`` are deprecated and will be removed in a future version; use :func:`to_datetime` instead (:issue:`35741`)
-- :meth:`DataFrame.lookup` is deprecated and will be removed in a future version, use :meth:`DataFrame.melt` and :meth:`DataFrame.loc` instead (:issue:`18682`)
+- :meth:`DataFrame.lookup` is deprecated and will be removed in a future version, use :meth:`DataFrame.melt` and :meth:`DataFrame.loc` instead (:issue:`35224`)
- The method :meth:`Index.to_native_types` is deprecated. Use ``.astype(str)`` instead (:issue:`28867`)
- Deprecated indexing :class:`DataFrame` rows with a single datetime-like string as ``df[string]`` (given the ambiguity whether it is indexing the rows or selecting a column), use ``df.loc[string]`` instead (:issue:`36179`)
- Deprecated :meth:`Index.is_all_dates` (:issue:`27744`)
| Backport PR #39406: DOC: link to correct PR | https://api.github.com/repos/pandas-dev/pandas/pulls/39429 | 2021-01-26T23:33:09Z | 2021-01-27T08:39:00Z | 2021-01-27T08:39:00Z | 2021-01-27T08:39:00Z |
Backport PR #39376 on branch 1.2.x (REGR: write compressed pickle files with protocol=5) | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 5e96587a326d9..95fbbaf5d566e 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -14,7 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
--
+- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index a5507259b7b6a..2dcbaf38fa51a 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -94,7 +94,19 @@ def to_pickle(
is_text=False,
storage_options=storage_options,
) as handles:
- pickle.dump(obj, handles.handle, protocol=protocol) # type: ignore[arg-type]
+ if handles.compression["method"] in ("bz2", "xz") and protocol >= 5:
+ # some weird TypeError GH#39002 with pickle 5: fallback to letting
+ # pickle create the entire object and then write it to the buffer.
+ # "zip" would also be here if pandas.io.common._BytesZipFile
+ # wouldn't buffer write calls
+ handles.handle.write(
+ pickle.dumps(obj, protocol=protocol) # type: ignore[arg-type]
+ )
+ else:
+ # letting pickle write directly to the buffer is more memory-efficient
+ pickle.dump(
+ obj, handles.handle, protocol=protocol # type: ignore[arg-type]
+ )
@doc(storage_options=generic._shared_docs["storage_options"])
diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py
index 34b36e2549b62..24844c4f2eb85 100644
--- a/pandas/tests/io/test_pickle.py
+++ b/pandas/tests/io/test_pickle.py
@@ -13,6 +13,7 @@
import bz2
import datetime
import functools
+from functools import partial
import glob
import gzip
import io
@@ -588,3 +589,14 @@ def test_pickle_preserves_block_ndim():
# GH#37631 OP issue was about indexing, underlying problem was pickle
tm.assert_series_equal(res[[True]], ser)
+
+
+@pytest.mark.parametrize("protocol", [pickle.DEFAULT_PROTOCOL, pickle.HIGHEST_PROTOCOL])
+def test_pickle_big_dataframe_compression(protocol, compression):
+ # GH#39002
+ df = pd.DataFrame(range(100000))
+ result = tm.round_trip_pathlib(
+ partial(df.to_pickle, protocol=protocol, compression=compression),
+ partial(pd.read_pickle, compression=compression),
+ )
+ tm.assert_frame_equal(df, result)
| Backport PR #39376: REGR: write compressed pickle files with protocol=5 | https://api.github.com/repos/pandas-dev/pandas/pulls/39428 | 2021-01-26T23:32:57Z | 2021-01-27T10:15:20Z | 2021-01-27T10:15:20Z | 2021-01-27T10:15:20Z |
REF: reuse can_hold_element for NumericIndex._validate_fill_value | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 52f3c14e59184..0be3970159fbd 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1952,4 +1952,7 @@ def can_hold_element(dtype: np.dtype, element: Any) -> bool:
return tipo.kind == "b"
return lib.is_bool(element)
+ elif dtype == object:
+ return True
+
raise NotImplementedError(dtype)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 9861a466b2d2f..dc6d0784df217 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1677,7 +1677,7 @@ def _is_dtype_type(arr_or_dtype, condition) -> bool:
return condition(tipo)
-def infer_dtype_from_object(dtype):
+def infer_dtype_from_object(dtype) -> DtypeObj:
"""
Get a numpy dtype.type-style object for a dtype object.
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 40215ea87f978..98fbb9c761b47 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -40,6 +40,7 @@
from pandas.util._decorators import Appender, cache_readonly, doc
from pandas.core.dtypes.cast import (
+ can_hold_element,
find_common_type,
maybe_cast_to_integer_array,
maybe_promote,
@@ -4360,6 +4361,8 @@ def _validate_fill_value(self, value):
TypeError
If the value cannot be inserted into an array of this dtype.
"""
+ if not can_hold_element(self.dtype, value):
+ raise TypeError
return value
@final
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index dca3a4458bc68..55317938d528d 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -609,6 +609,12 @@ def insert(self, loc: int, item):
result._data._freq = self._get_insert_freq(loc, item)
return result
+ def _validate_fill_value(self, value):
+ """
+ Convert value to be insertable to ndarray.
+ """
+ return self._data._validate_setitem_value(value)
+
# --------------------------------------------------------------------
# Join/Set Methods
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index abe9a9c26c663..a6d71cadddd64 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -342,12 +342,6 @@ def __reduce__(self):
d.update(self._get_attributes_dict())
return _new_DatetimeIndex, (type(self), d), None
- def _validate_fill_value(self, value):
- """
- Convert value to be insertable to ndarray.
- """
- return self._data._validate_setitem_value(value)
-
def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
"""
Can we compare values of the given dtype to our own?
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index 26599bd6ab871..a432b3952666e 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -10,13 +10,11 @@
from pandas.core.dtypes.cast import astype_nansafe
from pandas.core.dtypes.common import (
is_bool,
- is_bool_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_float,
is_float_dtype,
is_integer_dtype,
- is_number,
is_numeric_dtype,
is_scalar,
is_signed_integer_dtype,
@@ -25,7 +23,6 @@
pandas_dtype,
)
from pandas.core.dtypes.generic import ABCSeries
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
@@ -122,42 +119,6 @@ def _shallow_copy(self, values=None, name: Hashable = lib.no_default):
return Float64Index._simple_new(values, name=name)
return super()._shallow_copy(values=values, name=name)
- @doc(Index._validate_fill_value)
- def _validate_fill_value(self, value):
- if is_bool(value) or is_bool_dtype(value):
- # force conversion to object
- # so we don't lose the bools
- raise TypeError
- elif is_scalar(value) and isna(value):
- if is_valid_nat_for_dtype(value, self.dtype):
- value = self._na_value
- if self.dtype.kind != "f":
- # raise so that caller can cast
- raise TypeError
- else:
- # NaT, np.datetime64("NaT"), np.timedelta64("NaT")
- raise TypeError
-
- elif is_scalar(value):
- if not is_number(value):
- # e.g. datetime64, timedelta64, datetime, ...
- raise TypeError
-
- elif lib.is_complex(value):
- # at least until we have a ComplexIndx
- raise TypeError
-
- elif is_float(value) and self.dtype.kind != "f":
- if not value.is_integer():
- raise TypeError
- value = int(value)
-
- elif hasattr(value, "dtype") and value.dtype.kind in ["m", "M"]:
- # TODO: if we're checking arraylike here, do so systematically
- raise TypeError
-
- return value
-
def _convert_tolerance(self, tolerance, target):
tolerance = np.asarray(tolerance)
if target.size != tolerance.size and tolerance.size > 1:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39427 | 2021-01-26T23:05:12Z | 2021-01-28T02:06:42Z | 2021-01-28T02:06:42Z | 2021-01-28T02:35:29Z |
REF: de-duplicate MultiIndex validation | diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 064d052806e27..0d30c1665df34 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -881,16 +881,7 @@ def set_levels(self, levels, level=None, inplace=None, verify_integrity=True):
if is_list_like(levels) and not isinstance(levels, Index):
levels = list(levels)
- if level is not None and not is_list_like(level):
- if not is_list_like(levels):
- raise TypeError("Levels must be list-like")
- if is_list_like(levels[0]):
- raise TypeError("Levels must be list-like")
- level = [level]
- levels = [levels]
- elif level is None or is_list_like(level):
- if not is_list_like(levels) or not is_list_like(levels[0]):
- raise TypeError("Levels must be list of lists-like")
+ level, levels = _require_listlike(level, levels, "Levels")
if inplace:
idx = self
@@ -1050,16 +1041,7 @@ def set_codes(self, codes, level=None, inplace=None, verify_integrity=True):
else:
inplace = False
- if level is not None and not is_list_like(level):
- if not is_list_like(codes):
- raise TypeError("Codes must be list-like")
- if is_list_like(codes[0]):
- raise TypeError("Codes must be list-like")
- level = [level]
- codes = [codes]
- elif level is None or is_list_like(level):
- if not is_list_like(codes) or not is_list_like(codes[0]):
- raise TypeError("Codes must be list of lists-like")
+ level, codes = _require_listlike(level, codes, "Codes")
if inplace:
idx = self
@@ -3870,3 +3852,20 @@ def _coerce_indexer_frozen(array_like, categories, copy: bool = False) -> np.nda
array_like = array_like.copy()
array_like.flags.writeable = False
return array_like
+
+
+def _require_listlike(level, arr, arrname: str):
+ """
+ Ensure that level is either None or listlike, and arr is list-of-listlike.
+ """
+ if level is not None and not is_list_like(level):
+ if not is_list_like(arr):
+ raise TypeError(f"{arrname} must be list-like")
+ if is_list_like(arr[0]):
+ raise TypeError(f"{arrname} must be list-like")
+ level = [level]
+ arr = [arr]
+ elif level is None or is_list_like(level):
+ if not is_list_like(arr) or not is_list_like(arr[0]):
+ raise TypeError(f"{arrname} must be list of lists-like")
+ return level, arr
| https://api.github.com/repos/pandas-dev/pandas/pulls/39425 | 2021-01-26T21:35:11Z | 2021-01-28T02:07:15Z | 2021-01-28T02:07:15Z | 2021-01-28T02:36:50Z | |
BUG: Assert_frame_equal always raising AssertionError when comparing extension dtypes | diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst
index 95fbbaf5d566e..656e779055486 100644
--- a/doc/source/whatsnew/v1.2.2.rst
+++ b/doc/source/whatsnew/v1.2.2.rst
@@ -15,6 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
+- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index b20cc0897ec18..494d9ac60dd96 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -968,14 +968,26 @@ def assert_series_equal(
assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}")
if check_exact and is_numeric_dtype(left.dtype) and is_numeric_dtype(right.dtype):
+ left_values = left._values
+ right_values = right._values
# Only check exact if dtype is numeric
- assert_numpy_array_equal(
- left._values,
- right._values,
- check_dtype=check_dtype,
- obj=str(obj),
- index_values=np.asarray(left.index),
- )
+ if is_extension_array_dtype(left_values) and is_extension_array_dtype(
+ right_values
+ ):
+ assert_extension_array_equal(
+ left_values,
+ right_values,
+ check_dtype=check_dtype,
+ index_values=np.asarray(left.index),
+ )
+ else:
+ assert_numpy_array_equal(
+ left_values,
+ right_values,
+ check_dtype=check_dtype,
+ obj=str(obj),
+ index_values=np.asarray(left.index),
+ )
elif check_datetimelike_compat and (
needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype)
):
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index a594751808532..bf1311460a5f5 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -305,3 +305,19 @@ def test_assert_frame_equal_columns_mixed_dtype():
# GH#39168
df = DataFrame([[0, 1, 2]], columns=["foo", "bar", 42], index=[1, "test", 2])
tm.assert_frame_equal(df, df, check_like=True)
+
+
+def test_frame_equal_extension_dtype(frame_or_series, any_nullable_numeric_dtype):
+ # GH#39410
+ obj = frame_or_series([1, 2], dtype=any_nullable_numeric_dtype)
+ tm.assert_equal(obj, obj, check_exact=True)
+
+
+@pytest.mark.parametrize("indexer", [(0, 1), (1, 0)])
+def test_frame_equal_mixed_dtypes(frame_or_series, any_nullable_numeric_dtype, indexer):
+ dtypes = (any_nullable_numeric_dtype, "int64")
+ obj1 = frame_or_series([1, 2], dtype=dtypes[indexer[0]])
+ obj2 = frame_or_series([1, 2], dtype=dtypes[indexer[1]])
+ msg = r'(Series|DataFrame.iloc\[:, 0\] \(column name="0"\) classes) are different'
+ with pytest.raises(AssertionError, match=msg):
+ tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False)
| - [x] closes #39410
- [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
| https://api.github.com/repos/pandas-dev/pandas/pulls/39423 | 2021-01-26T21:23:03Z | 2021-01-28T02:34:13Z | 2021-01-28T02:34:12Z | 2021-01-28T08:48:38Z |
BUG: Subset slicer on Styler failed on MultiIndex with slice(None) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 6abe70e56b9b9..e19c98039f279 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -437,6 +437,8 @@ Other
- Bug in :class:`Styler` which caused CSS to duplicate on multiple renders. (:issue:`39395`)
- :meth:`Index.where` behavior now mirrors :meth:`Index.putmask` behavior, i.e. ``index.where(mask, other)`` matches ``index.putmask(~mask, other)`` (:issue:`39412`)
- Bug in :func:`pandas.testing.assert_series_equal`, :func:`pandas.testing.assert_frame_equal`, :func:`pandas.testing.assert_index_equal` and :func:`pandas.testing.assert_extension_array_equal` incorrectly raising when an attribute has an unrecognized NA type (:issue:`39461`)
+- Bug in :class:`Styler` where ``subset`` arg in methods raised an error for some valid multiindex slices (:issue:`33562`)
+-
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index ce7d5b511e811..cc7c5f666feda 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -2407,9 +2407,11 @@ def pred(part) -> bool:
"""
# true when slice does *not* reduce, False when part is a tuple,
# i.e. MultiIndex slice
- return (isinstance(part, slice) or is_list_like(part)) and not isinstance(
- part, tuple
- )
+ if isinstance(part, tuple):
+ # GH#39421 check for sub-slice:
+ return any((isinstance(s, slice) or is_list_like(s)) for s in part)
+ else:
+ return isinstance(part, slice) or is_list_like(part)
if not is_list_like(slice_):
if not isinstance(slice_, slice):
diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py
index b60135a802b8e..6c7d5f06ac355 100644
--- a/pandas/tests/indexing/multiindex/test_slice.py
+++ b/pandas/tests/indexing/multiindex/test_slice.py
@@ -780,6 +780,42 @@ def test_non_reducing_slice_on_multiindex(self):
expected = DataFrame({("b", "d"): [4, 1]})
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize(
+ "slice_",
+ [
+ pd.IndexSlice[:, :],
+ # check cols
+ pd.IndexSlice[:, pd.IndexSlice[["a"]]], # inferred deeper need list
+ pd.IndexSlice[:, pd.IndexSlice[["a"], ["c"]]], # inferred deeper need list
+ pd.IndexSlice[:, pd.IndexSlice["a", "c", :]],
+ pd.IndexSlice[:, pd.IndexSlice["a", :, "e"]],
+ pd.IndexSlice[:, pd.IndexSlice[:, "c", "e"]],
+ pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d"], :]], # check list
+ pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], :]], # allow missing
+ pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], "e"]], # no slice
+ # check rows
+ pd.IndexSlice[pd.IndexSlice[["U"]], :], # inferred deeper need list
+ pd.IndexSlice[pd.IndexSlice[["U"], ["W"]], :], # inferred deeper need list
+ pd.IndexSlice[pd.IndexSlice["U", "W", :], :],
+ pd.IndexSlice[pd.IndexSlice["U", :, "Y"], :],
+ pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], :],
+ pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z"]], :], # check list
+ pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z", "-"]], :], # allow missing
+ pd.IndexSlice[pd.IndexSlice["U", "W", ["Y", "Z", "-"]], :], # no slice
+ # check simultaneous
+ pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], pd.IndexSlice["a", "c", :]],
+ ],
+ )
+ def test_non_reducing_multi_slice_on_multiindex(self, slice_):
+ # GH 33562
+ cols = pd.MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]])
+ idxs = pd.MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]])
+ df = DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs)
+
+ expected = df.loc[slice_]
+ result = df.loc[non_reducing_slice(slice_)]
+ tm.assert_frame_equal(result, expected)
+
def test_loc_slice_negative_stepsize(self):
# GH#38071
mi = MultiIndex.from_product([["a", "b"], [0, 1]])
diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py
index 6556075272308..0e732ddc0a27b 100644
--- a/pandas/tests/io/formats/test_style.py
+++ b/pandas/tests/io/formats/test_style.py
@@ -377,29 +377,26 @@ def f(x):
}
assert result == expected
- def test_applymap_subset_multiindex(self):
+ @pytest.mark.parametrize(
+ "slice_",
+ [
+ pd.IndexSlice[:, pd.IndexSlice["x", "A"]],
+ pd.IndexSlice[:, pd.IndexSlice[:, "A"]],
+ pd.IndexSlice[:, pd.IndexSlice[:, ["A", "C"]]], # missing col element
+ pd.IndexSlice[pd.IndexSlice["a", 1], :],
+ pd.IndexSlice[pd.IndexSlice[:, 1], :],
+ pd.IndexSlice[pd.IndexSlice[:, [1, 3]], :], # missing row element
+ pd.IndexSlice[:, ("x", "A")],
+ pd.IndexSlice[("a", 1), :],
+ ],
+ )
+ def test_applymap_subset_multiindex(self, slice_):
# GH 19861
- # Smoke test for applymap
- def color_negative_red(val):
- """
- Takes a scalar and returns a string with
- the css property `'color: red'` for negative
- strings, black otherwise.
- """
- color = "red" if val < 0 else "black"
- return f"color: {color}"
-
- dic = {
- ("a", "d"): [-1.12, 2.11],
- ("a", "c"): [2.78, -2.88],
- ("b", "c"): [-3.99, 3.77],
- ("b", "d"): [4.21, -1.22],
- }
-
- idx = pd.IndexSlice
- df = DataFrame(dic, index=[0, 1])
-
- (df.style.applymap(color_negative_red, subset=idx[:, idx["b", "d"]]).render())
+ # edited for GH 33562
+ idx = pd.MultiIndex.from_product([["a", "b"], [1, 2]])
+ col = pd.MultiIndex.from_product([["x", "y"], ["A", "B"]])
+ df = DataFrame(np.random.rand(4, 4), columns=col, index=idx)
+ df.style.applymap(lambda x: "color: red;", subset=slice_).render()
def test_applymap_subset_multiindex_code(self):
# https://github.com/pandas-dev/pandas/issues/25858
| - [x] closes #33562
- [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
The problem with above issue was with the function `non_reducing_slice`. It didn't correctly re-format slicing tuples on multiindices when rows or cols also contained a `slice(None)`. An additional check is now done. This method is only used for `Styler` currently.
Tests Added / reformmatted. | https://api.github.com/repos/pandas-dev/pandas/pulls/39421 | 2021-01-26T21:03:49Z | 2021-02-04T00:51:34Z | 2021-02-04T00:51:34Z | 2021-02-04T06:42:32Z |
Read hdf returns unexpected values for categorical | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1dcde2000fc89..3be38e123b5d5 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -330,6 +330,7 @@ I/O
- Bug in :func:`read_csv` not switching ``true_values`` and ``false_values`` for nullable ``boolean`` dtype (:issue:`34655`)
- Bug in :func:`read_json` when ``orient="split"`` does not maintain numeric string index (:issue:`28556`)
- :meth:`read_sql` returned an empty generator if ``chunksize`` was no-zero and the query returned no results. Now returns a generator with a single empty dataframe (:issue:`34411`)
+- Bug in :func:`read_hdf` returning unexpected records when filtering on categorical string columns using ``where`` parameter (:issue:`39189`)
Period
^^^^^^
diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py
index db2385de06e93..6a3b95186d666 100644
--- a/pandas/core/computation/pytables.py
+++ b/pandas/core/computation/pytables.py
@@ -210,12 +210,10 @@ def stringify(value):
return TermValue(int(v), v, kind)
elif meta == "category":
metadata = extract_array(self.metadata, extract_numpy=True)
- result = metadata.searchsorted(v, side="left")
-
- # result returns 0 if v is first element or if v is not in metadata
- # check that metadata contains v
- if not result and v not in metadata:
+ if v not in metadata:
result = -1
+ else:
+ result = metadata.searchsorted(v, side="left")
return TermValue(result, result, "integer")
elif kind == "integer":
v = int(float(v))
diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py
index 67209c2bc0d57..b873811de616c 100644
--- a/pandas/tests/io/pytables/test_categorical.py
+++ b/pandas/tests/io/pytables/test_categorical.py
@@ -184,3 +184,25 @@ def test_categorical_nan_only_columns(setup_path):
df.to_hdf(path, "df", format="table", data_columns=True)
result = read_hdf(path, "df")
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "where, df, expected",
+ [
+ ('col=="q"', DataFrame({"col": ["a", "b", "s"]}), DataFrame({"col": []})),
+ ('col=="a"', DataFrame({"col": ["a", "b", "s"]}), DataFrame({"col": ["a"]})),
+ ],
+)
+def test_convert_value(setup_path, where: str, df: DataFrame, expected: DataFrame):
+ # GH39420
+ # Check that read_hdf with categorical columns can filter by where condition.
+ df.col = df.col.astype("category")
+ max_widths = {"col": 1}
+ categorical_values = sorted(df.col.unique())
+ expected.col = expected.col.astype("category")
+ expected.col.cat.set_categories(categorical_values, inplace=True)
+
+ with ensure_clean_path(setup_path) as path:
+ df.to_hdf(path, "df", format="table", min_itemsize=max_widths)
+ result = read_hdf(path, where=where)
+ tm.assert_frame_equal(result, expected)
| - [V] closes #39189
- [V] tests added / passed
- [V] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [V] whatsnew entry
This bug happens when filtering on categorical string columns and choose a value which doesn't exist in the column.
Instead of returning an empty dataframe, we get some records.
It happens because of the usage in numpy `searchsorted(v, side="left")` that find indices where elements should be inserted to maintain order (and not 0 in case that the value doesn't exist), like was assumed in the code.
I changed it to first the for the value, and use `searchsorted` only if value exists, I also added a test for this specific use case.
I think in the long run, maybe we should refactor this area in the code since one function covers multiple use cases which makes it more complex to test.
In addition, I moved the logic to a new method to keep the single-responsibility principle and to make it easier to test. | https://api.github.com/repos/pandas-dev/pandas/pulls/39420 | 2021-01-26T21:01:58Z | 2021-01-30T20:46:15Z | 2021-01-30T20:46:14Z | 2021-01-31T06:26:55Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.