after_merge stringlengths 28 79.6k | before_merge stringlengths 20 79.6k | url stringlengths 38 71 | full_traceback stringlengths 43 922k | traceback_type stringclasses 555
values |
|---|---|---|---|---|
def _ensure_data(values, dtype=None):
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
- datetime64tz -> i8 (in local tz)
... | def _ensure_data(values, dtype=None):
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
- datetime64tz -> i8 (in local tz)
... | https://github.com/pandas-dev/pandas/issues/17128 | Traceback (most recent call last):
File "run.py", line 9, in <module>
df = pd.read_csv(data, na_values=na_values, index_col=index_col)
File "/home/liauys/Code/pandas/pandas/io/parsers.py", line 660, in parser_f
return _read(filepath_or_buffer, kwds)
File "/home/liauys/Code/pandas/pandas/io/parsers.py", line 416, in _re... | OverflowError |
def isin(comps, values):
"""
Compute the isin boolean array
Parameters
----------
comps: array-like
values: array-like
Returns
-------
boolean array same length as comps
"""
if not is_list_like(comps):
raise TypeError(
"only list-like objects are allowe... | def isin(comps, values):
"""
Compute the isin boolean array
Parameters
----------
comps: array-like
values: array-like
Returns
-------
boolean array same length as comps
"""
if not is_list_like(comps):
raise TypeError(
"only list-like objects are allowe... | https://github.com/pandas-dev/pandas/issues/17128 | Traceback (most recent call last):
File "run.py", line 9, in <module>
df = pd.read_csv(data, na_values=na_values, index_col=index_col)
File "/home/liauys/Code/pandas/pandas/io/parsers.py", line 660, in parser_f
return _read(filepath_or_buffer, kwds)
File "/home/liauys/Code/pandas/pandas/io/parsers.py", line 416, in _re... | OverflowError |
def mask(
self,
cond,
other=np.nan,
inplace=False,
axis=None,
level=None,
errors="raise",
try_cast=False,
raise_on_error=None,
):
if raise_on_error is not None:
warnings.warn(
"raise_on_error is deprecated in favor of errors='raise|ignore'",
Future... | def mask(
self,
cond,
other=np.nan,
inplace=False,
axis=None,
level=None,
errors="raise",
try_cast=False,
raise_on_error=None,
):
if raise_on_error is not None:
warnings.warn(
"raise_on_error is deprecated in favor of errors='raise|ignore'",
Future... | https://github.com/pandas-dev/pandas/issues/21891 | pd.Series([1, 2]).where([True, False])
# 0 1.0
# 1 NaN
# dtype: float64
pd.Series([1, 2]).mask([True, False])
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/usr/local/lib/python3.7/site-packages/pandas/core/generic.py", line 7792, in mask
# return self.where(~cond, oth... | TypeError |
def _aggregate_multiple_funcs(self, arg, _level):
if isinstance(arg, dict):
# show the deprecation, but only if we
# have not shown a higher level one
# GH 15931
if isinstance(self._selected_obj, Series) and _level <= 1:
warnings.warn(
(
... | def _aggregate_multiple_funcs(self, arg, _level):
if isinstance(arg, dict):
# show the deprecation, but only if we
# have not shown a higher level one
# GH 15931
if isinstance(self._selected_obj, Series) and _level <= 1:
warnings.warn(
(
... | https://github.com/pandas-dev/pandas/issues/21716 | In [12]: np.random.seed(1234)
In [13]: df = pd.DataFrame(np.random.rand(10, 1),
index=pd.date_range(start='2018-01-01', freq='5H', periods=10))
# This call works fine
In [14]: df.groupby(pd.Grouper(freq='D')).agg(['ohlc', 'sum'])
Out[14]:
0
ohlc sum
open high low clos... | ValueError |
def json_normalize(
data,
record_path=None,
meta=None,
meta_prefix=None,
record_prefix=None,
errors="raise",
sep=".",
):
"""
"Normalize" semi-structured JSON data into a flat table
Parameters
----------
data : dict or list of dicts
Unserialized JSON objects
r... | def json_normalize(
data,
record_path=None,
meta=None,
meta_prefix=None,
record_prefix=None,
errors="raise",
sep=".",
):
"""
"Normalize" semi-structured JSON data into a flat table
Parameters
----------
data : dict or list of dicts
Unserialized JSON objects
r... | https://github.com/pandas-dev/pandas/issues/21536 | Traceback (most recent call last):
File "c:\Users\levu\Desktop\tmp\json_normalize\main.py", line 3, in <module>
df = json_normalize({'A': [1, 2]}, 'A', record_prefix='Prefix.')
File "C:\Python36\lib\site-packages\pandas\io\json\normalize.py", line 262, in json_normalize
result.rename(columns=lambda x: record_prefix + x... | TypeError |
def _get_empty_meta(columns, index_col, index_names, dtype=None):
columns = list(columns)
# Convert `dtype` to a defaultdict of some kind.
# This will enable us to write `dtype[col_name]`
# without worrying about KeyError issues later on.
if not isinstance(dtype, dict):
# if dtype == None, ... | def _get_empty_meta(columns, index_col, index_names, dtype=None):
columns = list(columns)
# Convert `dtype` to a defaultdict of some kind.
# This will enable us to write `dtype[col_name]`
# without worrying about KeyError issues later on.
if not isinstance(dtype, dict):
# if dtype == None, ... | https://github.com/pandas-dev/pandas/issues/21141 | Traceback (most recent call last):
File "/home/peter/workspace/ray_env/lib/python3.6/site-packages/pandas/io/parsers.py", line 1848, in read
data = self._reader.read(nrows)
File "pandas/_libs/parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read
File "pandas/_libs/parsers.pyx", line 916, in pandas._libs.parse... | TypeError |
def _consensus_name_attr(objs):
name = objs[0].name
for obj in objs[1:]:
try:
if obj.name != name:
name = None
except ValueError:
name = None
return name
| def _consensus_name_attr(objs):
name = objs[0].name
for obj in objs[1:]:
if obj.name != name:
return None
return name
| https://github.com/pandas-dev/pandas/issues/21015 | In [2]: s1 = pd.Series({'a': 1.5}, name=np.int64(190))
In [3]: s2 = pd.Series([], name=(43, 0))
In [4]: pd.concat([s1, s2])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-5f754290d56c> in <module>... | ValueError |
def _convert_to_indexer(self, obj, axis=None, is_setter=False):
"""
Convert indexing key into something we can use to do actual fancy
indexing on an ndarray
Examples
ix[:5] -> slice(0, 5)
ix[[1,2,3]] -> [1,2,3]
ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz)
Going by ... | def _convert_to_indexer(self, obj, axis=None, is_setter=False):
"""
Convert indexing key into something we can use to do actual fancy
indexing on an ndarray
Examples
ix[:5] -> slice(0, 5)
ix[[1,2,3]] -> [1,2,3]
ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz)
Going by ... | https://github.com/pandas-dev/pandas/issues/17105 | ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-b0e70145e9a6> in <module>()
----> 1 df.loc[trange[bool_idx], "A"] += 1
/usr/local/lib/python3.6/site-packages/pandas/core/indexing.py in __setitem__(... | AttributeError |
def _searchsorted_monotonic(self, label, side, exclude_label=False):
if not self.is_non_overlapping_monotonic:
raise KeyError(
"can only get slices from an IntervalIndex if "
"bounds are non-overlapping and all monotonic "
"increasing or decreasing"
)
if isin... | def _searchsorted_monotonic(self, label, side, exclude_label=False):
if not self.is_non_overlapping_monotonic:
raise KeyError(
"can only get slices from an IntervalIndex if "
"bounds are non-overlapping and all monotonic "
"increasing or decreasing"
)
if isin... | https://github.com/pandas-dev/pandas/issues/20921 | import pandas as pd
pd.IntervalIndex.from_tuples([(1,100)]).get_loc(50)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/imre/code/pandas/pandas/core/indexes/interval.py", line 1049, in get_loc
raise KeyError(original_key)
KeyError: 50 | KeyError |
def _ensure_index(index_like, copy=False):
"""
Ensure that we have an index from some index-like object
Parameters
----------
index : sequence
An Index or other sequence
copy : bool
Returns
-------
index : Index or MultiIndex
Examples
--------
>>> _ensure_index... | def _ensure_index(index_like, copy=False):
"""
Ensure that we have an index from some index-like object
Parameters
----------
index : sequence
An Index or other sequence
copy : bool
Returns
-------
index : Index or MultiIndex
Examples
--------
>>> _ensure_index... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _has_valid_tuple(self, key):
"""check the key for valid keys across my indexer"""
for i, k in enumerate(key):
if i >= self.obj.ndim:
raise IndexingError("Too many indexers")
try:
self._validate_key(k, i)
except ValueError:
raise ValueError(
... | def _has_valid_tuple(self, key):
"""check the key for valid keys across my indexer"""
for i, k in enumerate(key):
if i >= self.obj.ndim:
raise IndexingError("Too many indexers")
if not self._has_valid_type(k, i):
raise ValueError(
"Location based indexing ... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _multi_take(self, tup):
"""create the reindex map for our objects, raise the _exception if we
can't create the indexer
"""
try:
o = self.obj
d = {}
for key, axis in zip(tup, o._AXIS_ORDERS):
ax = o._get_axis(axis)
# Have the index compute an indexer or... | def _multi_take(self, tup):
"""create the reindex map for our objects, raise the _exception if we
can't create the indexer
"""
try:
o = self.obj
d = {
a: self._convert_for_reindex(t, axis=o._get_axis_number(a))
for t, a in zip(tup, o._AXIS_ORDERS)
}
... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _convert_for_reindex(self, key, axis=None):
return key
| def _convert_for_reindex(self, key, axis=None):
if axis is None:
axis = self.axis or 0
labels = self.obj._get_axis(axis)
if com.is_bool_indexer(key):
key = check_bool_indexer(labels, key)
return labels[key]
else:
if isinstance(key, Index):
keyarr = labels._co... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if is_iterator(key):
key = list(key)
self._validate_key(key, axis)
labels = self.obj._get_axis(axis)
if isinstance(key, slice):
return self._get_slice_axis(key, axis=axis)
elif is_list_like_... | def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if self._should_validate_iterable(axis):
self._has_valid_type(key, axis)
labels = self.obj._get_axis(axis)
if isinstance(key, slice):
return self._get_slice_axis(key, axis=axis)
elif is_list_lik... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _getitem_iterable(self, key, axis=None):
if axis is None:
axis = self.axis or 0
self._validate_key(key, axis)
labels = self.obj._get_axis(axis)
if com.is_bool_indexer(key):
key = check_bool_indexer(labels, key)
(inds,) = key.nonzero()
return self.obj._take(inds, ax... | def _getitem_iterable(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if self._should_validate_iterable(axis):
self._has_valid_type(key, axis)
labels = self.obj._get_axis(axis)
if com.is_bool_indexer(key):
key = check_bool_indexer(labels, key)
(inds,) = k... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if is_iterator(key):
key = list(key)
labels = self.obj._get_axis(axis)
key = self._get_partial_string_timestamp_match_key(key, labels)
if isinstance(key, slice):
self._validate_key(key, axis)
... | def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
labels = self.obj._get_axis(axis)
key = self._get_partial_string_timestamp_match_key(key, labels)
if isinstance(key, slice):
self._has_valid_type(key, axis)
return self._get_slice_axis(key, axis=axi... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if isinstance(key, slice):
return self._get_slice_axis(key, axis=axis)
if isinstance(key, list):
key = np.asarray(key)
if com.is_bool_indexer(key):
self._validate_key(key, axis)
ret... | def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if isinstance(key, slice):
self._has_valid_type(key, axis)
return self._get_slice_axis(key, axis=axis)
if isinstance(key, list):
try:
key = np.asarray(key)
except TypeError: ... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _convert_to_indexer(self, obj, axis=None, is_setter=False):
"""much simpler as we only have to deal with our valid types"""
if axis is None:
axis = self.axis or 0
# make need to convert a float key
if isinstance(obj, slice):
return self._convert_slice_indexer(obj, axis)
elif is... | def _convert_to_indexer(self, obj, axis=None, is_setter=False):
"""much simpler as we only have to deal with our valid types"""
if axis is None:
axis = self.axis or 0
# make need to convert a float key
if isinstance(obj, slice):
return self._convert_slice_indexer(obj, axis)
elif is... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def _reindex_with_indexers(
self,
reindexers,
method=None,
fill_value=None,
limit=None,
copy=False,
allow_dups=False,
):
if method is not None or limit is not None:
raise NotImplementedError("cannot reindex with a method or limit with sparse")
if fill_value is None:
... | def _reindex_with_indexers(
self,
reindexers,
method=None,
fill_value=None,
limit=None,
copy=False,
allow_dups=False,
):
if method is not None or limit is not None:
raise NotImplementedError("cannot reindex with a method or limit with sparse")
if fill_value is None:
... | https://github.com/pandas-dev/pandas/issues/20753 | In [2]: pd.Series(range(3)).ix[5]
/usr/bin/ipython3:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
#! /bin/sh
-----------------------------... | KeyError |
def write_result(self, buf):
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
"""
# string representation of the columns
if len(self.frame.columns) == 0 or len(self.frame.index) == 0:
info_line = u("Empty {name}\nColumns: {col}\nIndex: {idx}").format(
name... | def write_result(self, buf):
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
"""
# string representation of the columns
if len(self.frame.columns) == 0 or len(self.frame.index) == 0:
info_line = u("Empty {name}\nColumns: {col}\nIndex: {idx}").format(
name... | https://github.com/pandas-dev/pandas/issues/14249 | test.set_index(['robustness', 'value']).to_latex()
Traceback (most recent call last):
File "/usr/local/anaconda2/envs/myenv2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-35-901bbd119ed6>", line 1, in <module>... | IndexError |
def str_get(arr, i):
"""
Extract element from lists, tuples, or strings in each element in the
Series/Index.
Parameters
----------
i : int
Integer index (location)
Returns
-------
items : Series/Index of objects
"""
def f(x):
if isinstance(x, dict):
... | def str_get(arr, i):
"""
Extract element from lists, tuples, or strings in each element in the
Series/Index.
Parameters
----------
i : int
Integer index (location)
Returns
-------
items : Series/Index of objects
"""
f = lambda x: x[i] if len(x) > i >= -len(x) else n... | https://github.com/pandas-dev/pandas/issues/20671 | s = pandas.Series([{0: 'a', 1: 'b'}])
s
0 {0: 'a', 1: 'b'}
dtype: object
s.str.get(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 1556, in get
result = str_get(self._data, i)
File "/home/mgarcia/.anac... | KeyError |
def f(x):
if isinstance(x, dict):
return x.get(i)
elif len(x) > i >= -len(x):
return x[i]
return np.nan
| def f(x):
if x[start:stop] == "":
local_stop = start
else:
local_stop = stop
y = ""
if start is not None:
y += x[:start]
y += repl
if stop is not None:
y += x[local_stop:]
return y
| https://github.com/pandas-dev/pandas/issues/20671 | s = pandas.Series([{0: 'a', 1: 'b'}])
s
0 {0: 'a', 1: 'b'}
dtype: object
s.str.get(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 1556, in get
result = str_get(self._data, i)
File "/home/mgarcia/.anac... | KeyError |
def groups(self):
"""return a list of all the top-level nodes (that are not themselves a
pandas storage object)
"""
_tables()
self._check_if_open()
return [
g
for g in self._handle.walk_nodes()
if (
not isinstance(g, _table_mod.link.Link)
and (
... | def groups(self):
"""return a list of all the top-level nodes (that are not themselves a
pandas storage object)
"""
_tables()
self._check_if_open()
return [
g
for g in self._handle.walk_nodes()
if (
getattr(g._v_attrs, "pandas_type", None)
or getat... | https://github.com/pandas-dev/pandas/issues/20523 | #! /path/to/python3.6
import pandas as pd
df = pd.DataFrame({ "a": [1], "b": [2] })
print(df.to_string())
hdf = pd.HDFStore("/tmp/test.hdf", mode="w")
hdf.put("/test/key", df)
#Brittle
hdf._handle.create_soft_link(hdf._handle.root.test, "symlink", "/test/key")
hdf.close()
print("Successful write")
hdf = pd.HDFStor... | KeyError |
def _shallow_copy(self, values=None, **kwargs):
if values is not None:
names = kwargs.pop("names", kwargs.pop("name", self.names))
# discards freq
kwargs.pop("freq", None)
return MultiIndex.from_tuples(values, names=names, **kwargs)
return self.view()
| def _shallow_copy(self, values=None, **kwargs):
if values is not None:
if "name" in kwargs:
kwargs["names"] = kwargs.pop("name", None)
# discards freq
kwargs.pop("freq", None)
return MultiIndex.from_tuples(values, **kwargs)
return self.view()
| https://github.com/pandas-dev/pandas/issues/20308 | import pandas as pd
import numpy as np
x = pd.MultiIndex.from_tuples([(1, 2), (3, 4)], names=['a', 'b'])
y = x[np.array([False, False])] # multiindex y is now empty
y.unique()
-->
---------------------------------------------------------------------------
TypeError Traceback (most recen... | TypeError |
def _sanitize_array(data, index, dtype=None, copy=False, raise_cast_failure=False):
"""sanitize input data to an ndarray, copy if specified, coerce to the
dtype if specified
"""
if dtype is not None:
dtype = pandas_dtype(dtype)
if isinstance(data, ma.MaskedArray):
mask = ma.getmask... | def _sanitize_array(data, index, dtype=None, copy=False, raise_cast_failure=False):
"""sanitize input data to an ndarray, copy if specified, coerce to the
dtype if specified
"""
if dtype is not None:
dtype = pandas_dtype(dtype)
if isinstance(data, ma.MaskedArray):
mask = ma.getmask... | https://github.com/pandas-dev/pandas/issues/19853 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\series.py", line 266, in __init__
data = SingleBlockManager(data, index, fastpath=True)
File "C:\Users\james\AppData\Local\Programs\Python\Python36-32\lib\s... | ValueError |
def melt(
frame,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
):
# TODO: what about the existing index?
if id_vars is not None:
if not is_list_like(id_vars):
id_vars = [id_vars]
elif isinstance(frame.columns, ABCMultiIndex)... | def melt(
frame,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
):
# TODO: what about the existing index?
if id_vars is not None:
if not is_list_like(id_vars):
id_vars = [id_vars]
elif isinstance(frame.columns, ABCMultiIndex)... | https://github.com/pandas-dev/pandas/issues/15785 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 140, in __setitem__
indexer = self._get_setitem_indexer(key)
File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 127, in _get_setitem_indexer
return ... | KeyError |
def encode(obj):
"""
Data encoder
"""
tobj = type(obj)
if isinstance(obj, Index):
if isinstance(obj, RangeIndex):
return {
"typ": "range_index",
"klass": u(obj.__class__.__name__),
"name": getattr(obj, "name", None),
... | def encode(obj):
"""
Data encoder
"""
tobj = type(obj)
if isinstance(obj, Index):
if isinstance(obj, RangeIndex):
return {
"typ": "range_index",
"klass": u(obj.__class__.__name__),
"name": getattr(obj, "name", None),
... | https://github.com/pandas-dev/pandas/issues/13463 | import pandas as pd
pd.DataFrame({'C': pd.period_range('2015-01-01', periods=3)}).to_msgpack()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-65-8e5ad9cd6036> in <module>()
----> 1 pd.DataFrame({'C': ... | TypeError |
def decode(obj):
"""
Decoder for deserializing numpy data types.
"""
typ = obj.get("typ")
if typ is None:
return obj
elif typ == "timestamp":
freq = obj["freq"] if "freq" in obj else obj["offset"]
return Timestamp(obj["value"], tz=obj["tz"], freq=freq)
elif typ == "n... | def decode(obj):
"""
Decoder for deserializing numpy data types.
"""
typ = obj.get("typ")
if typ is None:
return obj
elif typ == "timestamp":
freq = obj["freq"] if "freq" in obj else obj["offset"]
return Timestamp(obj["value"], tz=obj["tz"], freq=freq)
elif typ == "n... | https://github.com/pandas-dev/pandas/issues/13463 | import pandas as pd
pd.DataFrame({'C': pd.period_range('2015-01-01', periods=3)}).to_msgpack()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-65-8e5ad9cd6036> in <module>()
----> 1 pd.DataFrame({'C': ... | TypeError |
def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta type,
this method converts it to numeric so that cut method can
handle it
"""
dtype = None
if is_timedelta64_dtype(x):
x = to_timedelta(x)
dtype = np.timedelta64
elif is_datetime64_dtype(x):
... | def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta type,
this method converts it to integer so that cut method can
handle it
"""
dtype = None
if is_timedelta64_dtype(x):
x = to_timedelta(x).view(np.int64)
dtype = np.timedelta64
elif is_datetime64_dty... | https://github.com/pandas-dev/pandas/issues/19768 | Traceback (most recent call last):
File "mve.py", line 26, in <module>
pd.qcut(df["Date"], 2)
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/reshape/tile.py", line 208, in qcut
dtype=dtype, duplicates=duplicates)
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/reshape/tile.py", line 251, in _bi... | ValueError |
def to_stata(
self,
fname,
convert_dates=None,
write_index=True,
encoding="latin-1",
byteorder=None,
time_stamp=None,
data_label=None,
variable_labels=None,
):
"""
A class for writing Stata binary dta files from array-like objects
Parameters
----------
fname : st... | def to_stata(
self,
fname,
convert_dates=None,
write_index=True,
encoding="latin-1",
byteorder=None,
time_stamp=None,
data_label=None,
variable_labels=None,
):
"""
A class for writing Stata binary dta files from array-like objects
Parameters
----------
fname : st... | https://github.com/pandas-dev/pandas/issues/19817 | import pandas as pd
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
df.to_stata('test.dta', dataset_label='data label')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: to_stata() got an unexpected keyword argument 'dataset_label'
df.to_stata('test.dta', data_label='data label') | TypeError |
def __init__(
self,
data=None,
index=None,
columns=None,
default_kind=None,
default_fill_value=None,
dtype=None,
copy=False,
):
# pick up the defaults from the Sparse structures
if isinstance(data, SparseDataFrame):
if index is None:
index = data.index
... | def __init__(
self,
data=None,
index=None,
columns=None,
default_kind=None,
default_fill_value=None,
dtype=None,
copy=False,
):
# pick up the defaults from the Sparse structures
if isinstance(data, SparseDataFrame):
if index is None:
index = data.index
... | https://github.com/pandas-dev/pandas/issues/19374 | ---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-6-b9708ff05a7c> in <module>()
1 import pandas
2
----> 3 pandas.SparseDataFrame(pandas.Series())
~/anaconda3/lib/python3.6/site-packages/pandas/core/spar... | UnboundLocalError |
def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
):
"""
Return new object with labels in requested axis removed.
Parameters
----------
labels : single label or list-like
Index or column labels to drop.
... | def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
):
"""
Return new object with labels in requested axis removed.
Parameters
----------
labels : single label or list-like
Index or column labels to drop.
... | https://github.com/pandas-dev/pandas/issues/19186 | items.drop('abcd',axis=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", line 2530, in drop
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", l... | ValueError |
def _drop_axis(self, labels, axis, level=None, errors="raise"):
"""
Drop labels from specified axis. Used in the ``drop`` method
internally.
Parameters
----------
labels : single label or list-like
axis : int or axis name
level : int or level name, default None
For MultiIndex
... | def _drop_axis(self, labels, axis, level=None, errors="raise"):
"""
Drop labels from specified axis. Used in the ``drop`` method
internally.
Parameters
----------
labels : single label or list-like
axis : int or axis name
level : int or level name, default None
For MultiIndex
... | https://github.com/pandas-dev/pandas/issues/19186 | items.drop('abcd',axis=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", line 2530, in drop
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", l... | ValueError |
def drop(self, labels, errors="raise"):
"""
Make new Index with passed list of labels deleted
Parameters
----------
labels : array-like
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
Returns
-------
dropped : Index... | def drop(self, labels, errors="raise"):
"""
Make new Index with passed list of labels deleted
Parameters
----------
labels : array-like
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
Returns
-------
dropped : Index... | https://github.com/pandas-dev/pandas/issues/19186 | items.drop('abcd',axis=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", line 2530, in drop
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", l... | ValueError |
def pivot_table(
data,
values=None,
index=None,
columns=None,
aggfunc="mean",
fill_value=None,
margins=False,
dropna=True,
margins_name="All",
):
index = _convert_by(index)
columns = _convert_by(columns)
if isinstance(aggfunc, list):
pieces = []
keys = []... | def pivot_table(
data,
values=None,
index=None,
columns=None,
aggfunc="mean",
fill_value=None,
margins=False,
dropna=True,
margins_name="All",
):
index = _convert_by(index)
columns = _convert_by(columns)
if isinstance(aggfunc, list):
pieces = []
keys = []... | https://github.com/pandas-dev/pandas/issues/19186 | items.drop('abcd',axis=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", line 2530, in drop
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", l... | ValueError |
def __init__(
self, values, index, level=-1, value_columns=None, fill_value=None, constructor=None
):
self.is_categorical = None
self.is_sparse = is_sparse(values)
if values.ndim == 1:
if isinstance(values, Categorical):
self.is_categorical = values
values = np.array(valu... | def __init__(
self, values, index, level=-1, value_columns=None, fill_value=None, constructor=None
):
self.is_categorical = None
self.is_sparse = is_sparse(values)
if values.ndim == 1:
if isinstance(values, Categorical):
self.is_categorical = values
values = np.array(valu... | https://github.com/pandas-dev/pandas/issues/18562 | In [2]: df = pd.DataFrame([[2009, 1, 15, 'City1', 'Housing'],
...: [2010, 2, np.nan, 'City2', 'Housing']],
...: columns=['year', 'month', 'day', 'city', 'sector'])
...:
In [3]: df['day'] = 15
...: df['date'] = pd.to_datetime(df[['year', 'month', 'day']])
...:
In [4]: ind = df.set_... | AssertionError |
def get_result(self):
values, _ = self.get_new_values()
columns = self.get_new_columns()
index = self.get_new_index()
# may need to coerce categoricals here
if self.is_categorical is not None:
categories = self.is_categorical.categories
ordered = self.is_categorical.ordered
... | def get_result(self):
# TODO: find a better way than this masking business
values, value_mask = self.get_new_values()
columns = self.get_new_columns()
index = self.get_new_index()
# filter out missing levels
if values.shape[1] > 0:
col_inds, obs_ids = compress_group_index(self.sorted_l... | https://github.com/pandas-dev/pandas/issues/18562 | In [2]: df = pd.DataFrame([[2009, 1, 15, 'City1', 'Housing'],
...: [2010, 2, np.nan, 'City2', 'Housing']],
...: columns=['year', 'month', 'day', 'city', 'sector'])
...:
In [3]: df['day'] = 15
...: df['date'] = pd.to_datetime(df[['year', 'month', 'day']])
...:
In [4]: ind = df.set_... | AssertionError |
def get_new_columns(self):
if self.value_columns is None:
if self.lift == 0:
return self.removed_level
lev = self.removed_level
return lev.insert(0, _get_na_value(lev.dtype.type))
stride = len(self.removed_level) + self.lift
width = len(self.value_columns)
propagato... | def get_new_columns(self):
if self.value_columns is None:
if self.lift == 0:
return self.removed_level
lev = self.removed_level
return lev.insert(0, _get_na_value(lev.dtype.type))
stride = len(self.removed_level) + self.lift
width = len(self.value_columns)
propagato... | https://github.com/pandas-dev/pandas/issues/18562 | In [2]: df = pd.DataFrame([[2009, 1, 15, 'City1', 'Housing'],
...: [2010, 2, np.nan, 'City2', 'Housing']],
...: columns=['year', 'month', 'day', 'city', 'sector'])
...:
In [3]: df['day'] = 15
...: df['date'] = pd.to_datetime(df[['year', 'month', 'day']])
...:
In [4]: ind = df.set_... | AssertionError |
def _dt_index_cmp(opname, cls, nat_result=False):
"""
Wrap comparison operations to convert datetime-like to datetime64
"""
def wrapper(self, other):
func = getattr(super(DatetimeIndex, self), opname)
if isinstance(other, (datetime, compat.string_types)):
if isinstance(othe... | def _dt_index_cmp(opname, cls, nat_result=False):
"""
Wrap comparison operations to convert datetime-like to datetime64
"""
def wrapper(self, other):
func = getattr(super(DatetimeIndex, self), opname)
if isinstance(other, datetime) or isinstance(other, compat.string_types):
... | https://github.com/pandas-dev/pandas/issues/18162 | dr = pd.date_range('2016-01-01', periods=6)
dz = dr.tz_localize('US/Pacific')
dr < dz
array([ True, True, True, True, True, True], dtype=bool)
dr[0] < dz[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/_libs/tslib.pyx", line 1169, in pandas._libs.tslib._Timestamp.__richcmp__
... | TypeError |
def wrapper(self, other):
func = getattr(super(DatetimeIndex, self), opname)
if isinstance(other, (datetime, compat.string_types)):
if isinstance(other, datetime):
# GH#18435 strings get a pass from tzawareness compat
self._assert_tzawareness_compat(other)
other = _to_m... | def wrapper(self, other):
func = getattr(super(DatetimeIndex, self), opname)
if isinstance(other, datetime) or isinstance(other, compat.string_types):
other = _to_m8(other, tz=self.tz)
result = func(other)
if isna(other):
result.fill(nat_result)
else:
if isinstanc... | https://github.com/pandas-dev/pandas/issues/18162 | dr = pd.date_range('2016-01-01', periods=6)
dz = dr.tz_localize('US/Pacific')
dr < dz
array([ True, True, True, True, True, True], dtype=bool)
dr[0] < dz[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/_libs/tslib.pyx", line 1169, in pandas._libs.tslib._Timestamp.__richcmp__
... | TypeError |
def _add_datetimelike_methods(cls):
"""
add in the datetimelike methods (as we may have to override the
superclass)
"""
def __add__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import ... | def _add_datetimelike_methods(cls):
"""
add in the datetimelike methods (as we may have to override the
superclass)
"""
def __add__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import ... | https://github.com/pandas-dev/pandas/issues/19012 | dti + one
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/indexes/datetimelike.py", line 685, in __add__
elif is_offsetlike(other):
File "pandas/core/dtypes/common.py", line 294, in is_offsetlike
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
TypeError: len() of unsized ... | TypeError |
def __add__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import DateOffset
other = lib.item_from_zerodim(other)
if is_timedelta64_dtype(other):
return self._add_delta(other)
elif isinstance(self, ... | def __add__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import DateOffset
if is_timedelta64_dtype(other):
return self._add_delta(other)
elif isinstance(self, TimedeltaIndex) and isinstance(other, Ind... | https://github.com/pandas-dev/pandas/issues/19012 | dti + one
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/indexes/datetimelike.py", line 685, in __add__
elif is_offsetlike(other):
File "pandas/core/dtypes/common.py", line 294, in is_offsetlike
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
TypeError: len() of unsized ... | TypeError |
def __sub__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import DateOffset
other = lib.item_from_zerodim(other)
if is_timedelta64_dtype(other):
... | def __sub__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import DateOffset
if is_timedelta64_dtype(other):
return self._add_delta(-other)
el... | https://github.com/pandas-dev/pandas/issues/19012 | dti + one
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/indexes/datetimelike.py", line 685, in __add__
elif is_offsetlike(other):
File "pandas/core/dtypes/common.py", line 294, in is_offsetlike
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
TypeError: len() of unsized ... | TypeError |
def _add_delta_td(self, other):
"""
Add a delta of a timedeltalike
return the i8 result view
"""
inc = delta_to_nanoseconds(other)
new_values = checked_add_with_arr(self.asi8, inc, arr_mask=self._isnan).view("i8")
if self.hasnans:
new_values[self._isnan] = iNaT
return new_values... | def _add_delta_td(self, other):
# add a delta of a timedeltalike
# return the i8 result view
inc = delta_to_nanoseconds(other)
new_values = checked_add_with_arr(self.asi8, inc, arr_mask=self._isnan).view("i8")
if self.hasnans:
new_values[self._isnan] = iNaT
return new_values.view("i8")
| https://github.com/pandas-dev/pandas/issues/19012 | dti + one
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/indexes/datetimelike.py", line 685, in __add__
elif is_offsetlike(other):
File "pandas/core/dtypes/common.py", line 294, in is_offsetlike
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
TypeError: len() of unsized ... | TypeError |
def _add_delta_tdi(self, other):
"""
Add a delta of a TimedeltaIndex
return the i8 result view
"""
# delta operation
if not len(self) == len(other):
raise ValueError("cannot add indices of unequal length")
self_i8 = self.asi8
other_i8 = other.asi8
new_values = checked_add_w... | def _add_delta_tdi(self, other):
# add a delta of a TimedeltaIndex
# return the i8 result view
# delta operation
if not len(self) == len(other):
raise ValueError("cannot add indices of unequal length")
self_i8 = self.asi8
other_i8 = other.asi8
new_values = checked_add_with_arr(
... | https://github.com/pandas-dev/pandas/issues/19012 | dti + one
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/indexes/datetimelike.py", line 685, in __add__
elif is_offsetlike(other):
File "pandas/core/dtypes/common.py", line 294, in is_offsetlike
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
TypeError: len() of unsized ... | TypeError |
def _sort_levels_monotonic(self):
"""
.. versionadded:: 0.20.0
This is an *internal* function.
create a new MultiIndex from the current to monotonically sorted
items IN the levels. This does not actually make the entire MultiIndex
monotonic, JUST the levels.
The resulting MultiIndex will ... | def _sort_levels_monotonic(self):
"""
.. versionadded:: 0.20.0
This is an *internal* function.
create a new MultiIndex from the current to monotonically sorted
items IN the levels. This does not actually make the entire MultiIndex
monotonic, JUST the levels.
The resulting MultiIndex will ... | https://github.com/pandas-dev/pandas/issues/18310 | In [2]: df = pd.DataFrame(1, index=range(3), columns=pd.MultiIndex.from_product([['a', 'b'], [1, 2]]))
In [3]: df['c'] = 2
In [4]: df.stack(0)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a43741... | TypeError |
def to_dict(self, orient="dict", into=dict):
"""Convert DataFrame to dictionary.
Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.
- dict (default) : dict like {column -> {index -> value}}
... | def to_dict(self, orient="dict", into=dict):
"""Convert DataFrame to dictionary.
Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.
- dict (default) : dict like {column -> {index -> value}}
... | https://github.com/pandas-dev/pandas/issues/18372 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-34cf441e3f50> in <module>()
----> 1 df.to_dict(orient='records')
/Users/bolke/Documents/dev/airflow_env/lib/python2.7/site-packages/pandas-0.21.0-py2... | TypeError |
def to_dict(self, orient="dict", into=dict):
"""Convert DataFrame to dictionary.
Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.
- dict (default) : dict like {column -> {index -> value}}
... | def to_dict(self, orient="dict", into=dict):
"""Convert DataFrame to dictionary.
Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.
- dict (default) : dict like {column -> {index -> value}}
... | https://github.com/pandas-dev/pandas/issues/18372 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-34cf441e3f50> in <module>()
----> 1 df.to_dict(orient='records')
/Users/bolke/Documents/dev/airflow_env/lib/python2.7/site-packages/pandas-0.21.0-py2... | TypeError |
def filter(self, items=None, like=None, regex=None, axis=None):
"""
Subset rows or columns of dataframe according to labels in
the specified index.
Note that this routine does not filter a dataframe on its
contents. The filter is applied to the labels of the index.
Parameters
----------
... | def filter(self, items=None, like=None, regex=None, axis=None):
"""
Subset rows or columns of dataframe according to labels in
the specified index.
Note that this routine does not filter a dataframe on its
contents. The filter is applied to the labels of the index.
Parameters
----------
... | https://github.com/pandas-dev/pandas/issues/13101 | ---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-10-9de5a19c260e> in <module>()
----> 1 df.filter(regex=u'a')
C:\Users\...\AppData\Local\Continuum\32bit\Anaconda\envs\test\lib\site-packages\pandas\core... | UnicodeEncodeError |
def f(x):
return matcher.search(to_str(x)) is not None
| def f(x):
if not isinstance(x, string_types):
x = str(x)
return like in x
| https://github.com/pandas-dev/pandas/issues/13101 | ---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-10-9de5a19c260e> in <module>()
----> 1 df.filter(regex=u'a')
C:\Users\...\AppData\Local\Continuum\32bit\Anaconda\envs\test\lib\site-packages\pandas\core... | UnicodeEncodeError |
def count(self):
"""Compute count of group, excluding missing values"""
from functools import partial
from pandas.core.dtypes.missing import _isna_ndarraylike as isna
data, _ = self._get_data_to_aggregate()
ids, _, ngroups = self.grouper.group_info
mask = ids != -1
val = ((mask & ~isna(np.... | def count(self):
"""Compute count of group, excluding missing values"""
from functools import partial
from pandas.core.dtypes.missing import _isna_ndarraylike as isna
data, _ = self._get_data_to_aggregate()
ids, _, ngroups = self.grouper.group_info
mask = ids != -1
val = ((mask & ~isna(blk... | https://github.com/pandas-dev/pandas/issues/13393 | ValueError Traceback (most recent call last)
<ipython-input-5-3119045de5b1> in <module>()
2 df = pd.DataFrame({'x': ['a', 'a', 'b'],
3 'y': [pd.Timestamp('2016-05-07 20:09:25+00:00'), pd.Timestamp('2016-05-07 20:09:29+00:00'), pd.Timestamp('2016-05-07 20:09:29+00:00')]}... | ValueError |
def _add_datetimelike_methods(cls):
"""
add in the datetimelike methods (as we may have to override the
superclass)
"""
def __add__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import ... | def _add_datetimelike_methods(cls):
"""
add in the datetimelike methods (as we may have to override the
superclass)
"""
def __add__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import ... | https://github.com/pandas-dev/pandas/issues/17991 | In [9]: pd.to_timedelta(['24658 days 11:15:00', 'NaT']) + pd.Timestamp('1950-01-01')
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-9-cc287bf4c401> in <module>()
----> 1 pd.to_timedelta(['24658 days 1... | OverflowError |
def __sub__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import DateOffset
if isinstance(other, TimedeltaIndex):
return self._add_delta(-other)
... | def __sub__(self, other):
from pandas.core.index import Index
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.tseries.offsets import DateOffset
if isinstance(other, TimedeltaIndex):
return self._add_delta(-other)
... | https://github.com/pandas-dev/pandas/issues/17991 | In [9]: pd.to_timedelta(['24658 days 11:15:00', 'NaT']) + pd.Timestamp('1950-01-01')
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-9-cc287bf4c401> in <module>()
----> 1 pd.to_timedelta(['24658 days 1... | OverflowError |
def _sub_datelike(self, other):
# subtract a datetime from myself, yielding a TimedeltaIndex
from pandas import TimedeltaIndex
if isinstance(other, DatetimeIndex):
# require tz compat
if not self._has_same_tz(other):
raise TypeError(
"DatetimeIndex subtraction mu... | def _sub_datelike(self, other):
# subtract a datetime from myself, yielding a TimedeltaIndex
from pandas import TimedeltaIndex
if isinstance(other, DatetimeIndex):
# require tz compat
if not self._has_same_tz(other):
raise TypeError(
"DatetimeIndex subtraction mu... | https://github.com/pandas-dev/pandas/issues/17991 | In [9]: pd.to_timedelta(['24658 days 11:15:00', 'NaT']) + pd.Timestamp('1950-01-01')
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-9-cc287bf4c401> in <module>()
----> 1 pd.to_timedelta(['24658 days 1... | OverflowError |
def _add_datelike(self, other):
# adding a timedeltaindex to a datetimelike
from pandas import Timestamp, DatetimeIndex
if other is NaT:
result = self._nat_new(box=False)
else:
other = Timestamp(other)
i8 = self.asi8
result = checked_add_with_arr(i8, other.value, arr_mas... | def _add_datelike(self, other):
# adding a timedeltaindex to a datetimelike
from pandas import Timestamp, DatetimeIndex
if other is NaT:
result = self._nat_new(box=False)
else:
other = Timestamp(other)
i8 = self.asi8
result = checked_add_with_arr(i8, other.value)
... | https://github.com/pandas-dev/pandas/issues/17991 | In [9]: pd.to_timedelta(['24658 days 11:15:00', 'NaT']) + pd.Timestamp('1950-01-01')
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-9-cc287bf4c401> in <module>()
----> 1 pd.to_timedelta(['24658 days 1... | OverflowError |
def __init__(self, src, **kwds):
self.kwds = kwds
kwds = kwds.copy()
ParserBase.__init__(self, kwds)
if kwds.get("compression") is None and "utf-16" in (kwds.get("encoding") or ""):
# if source is utf-16 plain text, convert source to utf-8
if isinstance(src, compat.string_types):
... | def __init__(self, src, **kwds):
self.kwds = kwds
kwds = kwds.copy()
ParserBase.__init__(self, kwds)
if "utf-16" in (kwds.get("encoding") or ""):
if isinstance(src, compat.string_types):
src = open(src, "rb")
self.handles.append(src)
src = UTF8Recoder(src, kwds[... | https://github.com/pandas-dev/pandas/issues/18071 | Traceback (most recent call last):
File "<ipython-input-4-6daea174e70a>", line 3, in <module>
encoding='utf-16')
File "/Users/Nick/anaconda/lib/python3.5/site-packages/pandas/io/parsers.py", line 705, in parser_f
return _read(filepath_or_buffer, kwds)
File "/Users/Nick/anaconda/lib/python3.5/site-packages/pandas/io/... | AttributeError |
def first_valid_index(self):
if len(self) == 0:
return None
valid_indices = self._get_valid_indices()
return valid_indices[0] if len(valid_indices) else None
| def first_valid_index(self):
"""
Return label for first non-NA/null value
"""
if len(self) == 0:
return None
return self.index[self.count(1) > 0][0]
| https://github.com/pandas-dev/pandas/issues/17400 | Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
df.first_valid_index()
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 3859, in first_valid_index
return self.index[self.count(1) > 0][0]
File "C:\Python27\lib\site-packages\pandas\indexes\base.py", line 1423, in __getitem__
ret... | IndexError |
def last_valid_index(self):
if len(self) == 0:
return None
valid_indices = self._get_valid_indices()
return valid_indices[-1] if len(valid_indices) else None
| def last_valid_index(self):
"""
Return label for last non-NA/null value
"""
if len(self) == 0:
return None
return self.index[self.count(1) > 0][-1]
| https://github.com/pandas-dev/pandas/issues/17400 | Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
df.first_valid_index()
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 3859, in first_valid_index
return self.index[self.count(1) > 0][0]
File "C:\Python27\lib\site-packages\pandas\indexes\base.py", line 1423, in __getitem__
ret... | IndexError |
def first_valid_index(self):
if len(self) == 0:
return None
mask = isna(self._values)
i = mask.argmin()
if mask[i]:
return None
else:
return self.index[i]
| def first_valid_index(self):
"""
Return label for first non-NA/null value
"""
if len(self) == 0:
return None
mask = isna(self._values)
i = mask.argmin()
if mask[i]:
return None
else:
return self.index[i]
| https://github.com/pandas-dev/pandas/issues/17400 | Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
df.first_valid_index()
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 3859, in first_valid_index
return self.index[self.count(1) > 0][0]
File "C:\Python27\lib\site-packages\pandas\indexes\base.py", line 1423, in __getitem__
ret... | IndexError |
def last_valid_index(self):
if len(self) == 0:
return None
mask = isna(self._values[::-1])
i = mask.argmin()
if mask[i]:
return None
else:
return self.index[len(self) - i - 1]
| def last_valid_index(self):
"""
Return label for last non-NA/null value
"""
if len(self) == 0:
return None
mask = isna(self._values[::-1])
i = mask.argmin()
if mask[i]:
return None
else:
return self.index[len(self) - i - 1]
| https://github.com/pandas-dev/pandas/issues/17400 | Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
df.first_valid_index()
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 3859, in first_valid_index
return self.index[self.count(1) > 0][0]
File "C:\Python27\lib\site-packages\pandas\indexes\base.py", line 1423, in __getitem__
ret... | IndexError |
def setup(self):
self.ts = Timestamp("2017-08-25 08:16:14")
self.ts_tz = Timestamp("2017-08-25 08:16:14", tz="US/Eastern")
dt = datetime.datetime(2016, 3, 27, 1)
self.tzinfo = pytz.timezone("CET").localize(dt, is_dst=False).tzinfo
self.ts2 = Timestamp(dt)
| def setup(self):
self.ts = Timestamp("2017-08-25 08:16:14")
| https://github.com/pandas-dev/pandas/issues/15683 | pytz.timezone('CET').localize(pd.Timestamp(datetime(2016, 3, 27, 1)), is_dst=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/localhome/stefan/emsconda/envs/popeye/lib/python3.6/site-packages/pytz/tzinfo.py", line 327, in localize
raise NonExistentTimeError(dt)
pytz.exceptions.NonExis... | pytz.exceptions.NonExistentTimeError |
def setitem(self, indexer, value, mgr=None):
"""set the value inplace; return a new block (of a possibly different
dtype)
indexer is a direct slice/positional indexer; value must be a
compatible shape
"""
# coerce None values, if appropriate
if value is None:
if self.is_numeric:
... | def setitem(self, indexer, value, mgr=None):
"""set the value inplace; return a new block (of a possibly different
dtype)
indexer is a direct slice/positional indexer; value must be a
compatible shape
"""
# coerce None values, if appropriate
if value is None:
if self.is_numeric:
... | https://github.com/pandas-dev/pandas/issues/17193 | s = pd.Series([1,2])
s.iloc[pd.Series([0])] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/indexing.py", line 198, in __setitem__
self._setitem_with_indexer(indexer, value)
File "pandas/core/indexing.py", line 619, in _setitem_with_indexer
value=value)
File "pandas/core/int... | IndexError |
def _maybe_coerce_merge_keys(self):
# we have valid mergees but we may have to further
# coerce these if they are originally incompatible types
#
# for example if these are categorical, but are not dtype_equal
# or if we have object and integer dtypes
for lk, rk, name in zip(self.left_join_keys... | def _maybe_coerce_merge_keys(self):
# we have valid mergee's but we may have to further
# coerce these if they are originally incompatible types
#
# for example if these are categorical, but are not dtype_equal
# or if we have object and integer dtypes
for lk, rk, name in zip(self.left_join_key... | https://github.com/pandas-dev/pandas/issues/16900 | Traceback (most recent call last):
File "blah.py", line 20, in <module>
df, df2, how='outer', on=['date']
File "/Users/dave/code/pandas/pandas/core/reshape/merge.py", line 57, in merge
return op.get_result()
File "/Users/dave/code/pandas/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(r... | TypeError |
def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
"""
Create index with target's values (move/add/delete values as necessary)
Returns
-------
new_index : pd.Index
Resulting index
indexer : np.ndarray or None
Indices of output values in original inde... | def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
"""
Create index with target's values (move/add/delete values as necessary)
Returns
-------
new_index : pd.Index
Resulting index
indexer : np.ndarray or None
Indices of output values in original inde... | https://github.com/pandas-dev/pandas/issues/16770 | import pandas as pd
index = pd.CategoricalIndex([], [0])
pd.Series(index=index).reindex(index=[0])
Traceback (most recent call last):
File "~/miniconda3/envs/pantheon/lib/python3.6/site-packages/pandas/core/frame.py", line 2733, in reindex
**kwargs)
File "~/miniconda3/envs/pantheon/lib/python3.6/site-packages/pandas/c... | IndexError |
def isin(comps, values):
"""
Compute the isin boolean array
Parameters
----------
comps: array-like
values: array-like
Returns
-------
boolean array same length as comps
"""
if not is_list_like(comps):
raise TypeError(
"only list-like objects are allowe... | def isin(comps, values):
"""
Compute the isin boolean array
Parameters
----------
comps: array-like
values: array-like
Returns
-------
boolean array same length as comps
"""
if not is_list_like(comps):
raise TypeError(
"only list-like objects are allowe... | https://github.com/pandas-dev/pandas/issues/16012 | In [2]: i = pd.Series(list('abcdefghijk'*10**5))
In [3]: alt = [-1, 'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR']*6
In [4]: res = i[:10**6].isin(alt)
In [5]: res = i[:10**6+1].isin(alt)
---------------------------------------------------------------------------
TypeError ... | TypeError |
def _join_non_unique(self, other, how="left", return_indexers=False):
from pandas.core.reshape.merge import _get_join_indexers
left_idx, right_idx = _get_join_indexers(
[self._values], [other._values], how=how, sort=True
)
left_idx = _ensure_platform_int(left_idx)
right_idx = _ensure_platf... | def _join_non_unique(self, other, how="left", return_indexers=False):
from pandas.core.reshape.merge import _get_join_indexers
left_idx, right_idx = _get_join_indexers(
[self.values], [other._values], how=how, sort=True
)
left_idx = _ensure_platform_int(left_idx)
right_idx = _ensure_platfo... | https://github.com/pandas-dev/pandas/issues/16871 | TypeError Traceback (most recent call last)
<ipython-input-2-c7c6bdf18c3f> in <module>()
3 index=perindex, columns=['pnum'])
4 df2 = pd.concat([perdf, perdf])
----> 5 perdf.merge(df2, left_index=True, right_index=True, how='outer')
C:\Anaconda3\envs\py36\lib\site-pa... | TypeError |
def _astype(
self,
dtype,
copy=False,
errors="raise",
values=None,
klass=None,
mgr=None,
raise_on_error=False,
**kwargs,
):
"""
Coerce to the new type (if copy=True, return a new copy)
raise on an except if raise == True
"""
errors_legal_values = ("raise", "ignore... | def _astype(
self, dtype, copy=False, errors="raise", values=None, klass=None, mgr=None, **kwargs
):
"""
Coerce to the new type (if copy=True, return a new copy)
raise on an except if raise == True
"""
errors_legal_values = ("raise", "ignore")
if errors not in errors_legal_values:
i... | https://github.com/pandas-dev/pandas/issues/16524 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-6c903a3f0db3> in <module>()
----> 1 pd.Series(pd.Series(['a', 'b', 'c']), dtype='category')
/Users/ttylec/.virtualenvs/zettafox/lib/python3.6/site-pa... | TypeError |
def _try_aggregate_string_function(self, arg, *args, **kwargs):
"""
if arg is a string, then try to operate on it:
- try to find a function (or attribute) on ourselves
- try to find a numpy function
- raise
"""
assert isinstance(arg, compat.string_types)
f = getattr(self, arg, None)
... | def _try_aggregate_string_function(self, arg, *args, **kwargs):
"""
if arg is a string, then try to operate on it:
- try to find a function on ourselves
- try to find a numpy function
- raise
"""
assert isinstance(arg, compat.string_types)
f = getattr(self, arg, None)
if f is not N... | https://github.com/pandas-dev/pandas/issues/16405 | pd.DataFrame({'g': [0, 0, 1], 'v': [1, 2, None]}).agg({'v': 'size'})
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-15-5fc5c38cdb5f> in <module>()
----> 1 pd.DataFrame({'g': [0, 0, 1], 'v': [1, 2, 3]}... | RecursionError |
def drop(self, labels, axis=0, level=None, inplace=False, errors="raise"):
"""
Return new object with labels in requested axis removed.
Parameters
----------
labels : single label or list-like
axis : int or axis name
level : int or level name, default None
For MultiIndex
inplace... | def drop(self, labels, axis=0, level=None, inplace=False, errors="raise"):
"""
Return new object with labels in requested axis removed.
Parameters
----------
labels : single label or list-like
axis : int or axis name
level : int or level name, default None
For MultiIndex
inplace... | https://github.com/pandas-dev/pandas/issues/16398 | In [2]: pd.DataFrame([[1,2], [3,4], [5,6]], index=['a','a','b']).drop(['a'])
Out[2]:
0 1
b 5 6
In [3]: pd.DataFrame([[1,2], [3,4], [5,6]], index=['a','a','b']).drop(['b'])
Out[3]:
0 1
a 1 2
a 3 4
In [4]: pd.DataFrame([[1,2], [3,4], [5,6]], index=['a','a','b']).drop([])
----------------------------------------... | ValueError |
def _translate(self):
"""
Convert the DataFrame in `self.data` and the attrs from `_build_styles`
into a dictionary of {head, body, uuid, cellstyle}
"""
table_styles = self.table_styles or []
caption = self.caption
ctx = self.ctx
precision = self.precision
uuid = self.uuid or str(uui... | def _translate(self):
"""
Convert the DataFrame in `self.data` and the attrs from `_build_styles`
into a dictionary of {head, body, uuid, cellstyle}
"""
table_styles = self.table_styles or []
caption = self.caption
ctx = self.ctx
precision = self.precision
uuid = self.uuid or str(uui... | https://github.com/pandas-dev/pandas/issues/15953 | In [6]: pd.DataFrame().style.render()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-345e1b37074e> in <module>()
----> 1 pd.DataFrame().style.render()
/Users/taugspurger/Envs/dask-dev/lib/python3.6... | IndexError |
def to_clipboard(self, excel=None, sep=None, **kwargs):
"""
Attempt to write text representation of object to the system clipboard
This can be pasted into Excel, for example.
Parameters
----------
excel : boolean, defaults to True
if True, use the provided separator, writing in a cs... | def to_clipboard(self, excel=None, sep=None, **kwargs):
"""
Attempt to write text representation of object to the system clipboard
This can be pasted into Excel, for example.
Parameters
----------
excel : boolean, defaults to True
if True, use the provided separator, writing in a cs... | https://github.com/pandas-dev/pandas/issues/16288 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/smiel/.venvs/foo/local/lib/python2.7/site-packages/pandas/__init__.py", line 58, in <module>
from pandas.io.api import *
File "/home/smiel/.venvs/foo/local/lib/python2.7/site-packages/pandas/io/api.py", line 8, in <module>
from pandas.io... | ImportError |
def reset_index(self, level=None, drop=False, inplace=False, col_level=0, col_fill=""):
"""
For DataFrame with multi-level index, return new DataFrame with
labeling information in the columns under the index names, defaulting
to 'level_0', 'level_1', etc. if any are None. For a standard index,
the i... | def reset_index(self, level=None, drop=False, inplace=False, col_level=0, col_fill=""):
"""
For DataFrame with multi-level index, return new DataFrame with
labeling information in the columns under the index names, defaulting
to 'level_0', 'level_1', etc. if any are None. For a standard index,
the i... | https://github.com/pandas-dev/pandas/issues/16164 | In [2]: df = pd.DataFrame([[1, 2]], columns=pd.MultiIndex.from_product([['A'], ['a', 'b']]))
In [3]: reind = df.set_index([('A', 'a')])
In [4]: reind.reset_index()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/h... | TypeError |
def _ipython_display_(self):
try:
from IPython.display import display
except ImportError:
return None
# Series doesn't define _repr_html_ or _repr_latex_
latex = self._repr_latex_() if hasattr(self, "_repr_latex_") else None
html = self._repr_html_() if hasattr(self, "_repr_html_") ... | def _ipython_display_(self):
try:
from IPython.display import display
except ImportError:
return None
# Series doesn't define _repr_html_ or _repr_latex_
latex = self._repr_latex_() if hasattr(self, "_repr_latex_") else None
html = self._repr_html_() if hasattr(self, "_repr_html_") ... | https://github.com/pandas-dev/pandas/issues/15996 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/kylek/code/src/github.com/pandas-dev/pandas/pandas/indexes/multi.py in _convert_can_do_setop(self, other)
2513 try:
-> 2514 o... | TypeError |
def __init__(
self,
obj,
orient,
date_format,
double_precision,
ensure_ascii,
date_unit,
default_handler=None,
):
"""
Adds a `schema` attribut with the Table Schema, resets
the index (can't do in caller, because the schema inference needs
to know what the index is, forces... | def __init__(
self,
obj,
orient,
date_format,
double_precision,
ensure_ascii,
date_unit,
default_handler=None,
):
"""
Adds a `schema` attribut with the Table Schema, resets
the index (can't do in caller, because the schema inference needs
to know what the index is, forces... | https://github.com/pandas-dev/pandas/issues/15996 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/kylek/code/src/github.com/pandas-dev/pandas/pandas/indexes/multi.py in _convert_can_do_setop(self, other)
2513 try:
-> 2514 o... | TypeError |
def insert(self, loc, item, value, allow_duplicates=False):
"""
Insert item at selected position.
Parameters
----------
loc : int
item : hashable
value : array_like
allow_duplicates: bool
If False, trying to insert non-unique item will raise
"""
if not allow_duplicates ... | def insert(self, loc, item, value, allow_duplicates=False):
"""
Insert item at selected position.
Parameters
----------
loc : int
item : hashable
value : array_like
allow_duplicates: bool
If False, trying to insert non-unique item will raise
"""
if not allow_duplicates ... | https://github.com/pandas-dev/pandas/issues/16120 | In [2]: df = pd.DataFrame(index=range(2), columns=pd.MultiIndex.from_tuples([['A', 'a'], ['B', '']]))
In [3]: df.index.name = 'B'
In [4]: df.reset_index()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-in... | TypeError |
def _get_labels_for_sorting(self):
"""
we categorizing our labels by using the
available catgories (all, not just observed)
excluding any missing ones (-1); this is in preparation
for sorting, where we need to disambiguate that -1 is not
a valid valid
"""
from pandas.core.categorical imp... | def _get_labels_for_sorting(self):
"""
we categorizing our labels by using the
available catgories (all, not just observed)
excluding any missing ones (-1); this is in preparation
for sorting, where we need to disambiguate that -1 is not
a valid valid
"""
from pandas.core.categorical imp... | https://github.com/pandas-dev/pandas/issues/16064 | import pandas as pd
df = pd.DataFrame(index=[0], columns=['a', 'b', 'c'])
df.groupby('a').nth(10)
Empty DataFrame
Columns: [b, c]
Index: []
df.groupby(['a', 'b']).nth(10)
Traceback (most recent call last):
File "<ipython-input-3-ae8299c3984e>", line 1, in <module>
df.groupby(['a', 'b']).nth(10)
File "~/anaconda3/lib... | ValueError |
def sort_index(
self,
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
by=None,
):
# TODO: this can be combined with Series.sort_index impl as
# almost identical
inplace = validate_bool_kwarg(inplace, "inplace"... | def sort_index(
self,
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
by=None,
):
inplace = validate_bool_kwarg(inplace, "inplace")
# 10726
if by is not None:
warnings.warn(
"by argument to ... | https://github.com/pandas-dev/pandas/issues/13431 | df2.sort_index().loc['b':'d']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
# a lot of lines omitted here.
/Users/yimengzh/miniconda/envs/cafferc3/lib/python2.7/site-packages/pandas/indexes/multi.py in _partial_t... | KeyError |
def _aggregate_series_fast(self, obj, func):
func = self._is_builtin_func(func)
if obj.index._has_complex_internals:
raise TypeError("Incompatible index for Cython grouper")
group_index, _, ngroups = self.group_info
# avoids object / Series creation overhead
dummy = obj._get_values(slice(... | def _aggregate_series_fast(self, obj, func):
func = self._is_builtin_func(func)
if obj.index._has_complex_internals:
raise TypeError("Incompatible index for Cython grouper")
group_index, _, ngroups = self.group_info
# avoids object / Series creation overhead
dummy = obj._get_values(slice(... | https://github.com/pandas-dev/pandas/issues/13431 | df2.sort_index().loc['b':'d']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
# a lot of lines omitted here.
/Users/yimengzh/miniconda/envs/cafferc3/lib/python2.7/site-packages/pandas/indexes/multi.py in _partial_t... | KeyError |
def sort_index(
self,
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
):
# TODO: this can be combined with DataFrame.sort_index impl as
# almost identical
inplace = validate_bool_kwarg(inplace, "inplace")
axis ... | def sort_index(
self,
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
):
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
index = self.index
if level is not None:
new... | https://github.com/pandas-dev/pandas/issues/13431 | df2.sort_index().loc['b':'d']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
# a lot of lines omitted here.
/Users/yimengzh/miniconda/envs/cafferc3/lib/python2.7/site-packages/pandas/indexes/multi.py in _partial_t... | KeyError |
def from_product(cls, iterables, sortorder=None, names=None):
"""
Make a MultiIndex from the cartesian product of multiple iterables
Parameters
----------
iterables : list / sequence of iterables
Each iterable has unique labels for each level of the index.
sortorder : int or None
... | def from_product(cls, iterables, sortorder=None, names=None):
"""
Make a MultiIndex from the cartesian product of multiple iterables
Parameters
----------
iterables : list / sequence of iterables
Each iterable has unique labels for each level of the index.
sortorder : int or None
... | https://github.com/pandas-dev/pandas/issues/13431 | df2.sort_index().loc['b':'d']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
# a lot of lines omitted here.
/Users/yimengzh/miniconda/envs/cafferc3/lib/python2.7/site-packages/pandas/indexes/multi.py in _partial_t... | KeyError |
def _partial_tup_index(self, tup, side="left"):
if len(tup) > self.lexsort_depth:
raise UnsortedIndexError(
"Key length (%d) was greater than MultiIndex"
" lexsort depth (%d)" % (len(tup), self.lexsort_depth)
)
n = len(tup)
start, end = 0, len(self)
zipped = zip(... | def _partial_tup_index(self, tup, side="left"):
if len(tup) > self.lexsort_depth:
raise KeyError(
"Key length (%d) was greater than MultiIndex"
" lexsort depth (%d)" % (len(tup), self.lexsort_depth)
)
n = len(tup)
start, end = 0, len(self)
zipped = zip(tup, self.... | https://github.com/pandas-dev/pandas/issues/13431 | df2.sort_index().loc['b':'d']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
# a lot of lines omitted here.
/Users/yimengzh/miniconda/envs/cafferc3/lib/python2.7/site-packages/pandas/indexes/multi.py in _partial_t... | KeyError |
def _next_line(self):
if isinstance(self.data, list):
while self.skipfunc(self.pos):
self.pos += 1
while True:
try:
line = self._check_comments([self.data[self.pos]])[0]
self.pos += 1
# either uncommented or blank to begin with... | def _next_line(self):
if isinstance(self.data, list):
while self.skipfunc(self.pos):
self.pos += 1
while True:
try:
line = self._check_comments([self.data[self.pos]])[0]
self.pos += 1
# either uncommented or blank to begin with... | https://github.com/pandas-dev/pandas/issues/15910 | from pandas.compat import StringIO
pd.read_csv(StringIO('''Date,Value
1/1/2012,100.00
1/2/2012,102.00
"a quoted junk row"morejunk'''), skipfooter=1)
Out[21]
ERROR:root:An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line str... | ValueError |
def _get_lines(self, rows=None):
lines = self.buf
new_rows = None
# already fetched some number
if rows is not None:
# we already have the lines in the buffer
if len(self.buf) >= rows:
new_rows, self.buf = self.buf[:rows], self.buf[rows:]
# need some lines
e... | def _get_lines(self, rows=None):
source = self.data
lines = self.buf
new_rows = None
# already fetched some number
if rows is not None:
# we already have the lines in the buffer
if len(self.buf) >= rows:
new_rows, self.buf = self.buf[:rows], self.buf[rows:]
# ne... | https://github.com/pandas-dev/pandas/issues/15910 | from pandas.compat import StringIO
pd.read_csv(StringIO('''Date,Value
1/1/2012,100.00
1/2/2012,102.00
"a quoted junk row"morejunk'''), skipfooter=1)
Out[21]
ERROR:root:An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line str... | ValueError |
def scatter_matrix(
frame,
alpha=0.5,
figsize=None,
ax=None,
grid=False,
diagonal="hist",
marker=".",
density_kwds=None,
hist_kwds=None,
range_padding=0.05,
**kwds,
):
"""
Draw a matrix of scatter plots.
Parameters
----------
frame : DataFrame
alpha :... | def scatter_matrix(
frame,
alpha=0.5,
figsize=None,
ax=None,
grid=False,
diagonal="hist",
marker=".",
density_kwds=None,
hist_kwds=None,
range_padding=0.05,
**kwds,
):
"""
Draw a matrix of scatter plots.
Parameters
----------
frame : DataFrame
alpha :... | https://github.com/pandas-dev/pandas/issues/14855 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-f3d30057e124> in <module>()
14 columns=iris.feature_names)
15 scatterplot = pd.scatter_matrix(dataframe, alpha=0.3,
---> 16 figsize=(10, 10), diagonal=... | ValueError |
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs):
"""
Make a scatter plot from two DataFrame columns
Parameters
----------
data : DataFrame
x : Column name for the x-axis values
y : Column name for the y-axis values
ax : Matplotlib axis object
figsi... | def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs):
"""
Make a scatter plot from two DataFrame columns
Parameters
----------
data : DataFrame
x : Column name for the x-axis values
y : Column name for the y-axis values
ax : Matplotlib axis object
figsi... | https://github.com/pandas-dev/pandas/issues/14855 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-f3d30057e124> in <module>()
14 columns=iris.feature_names)
15 scatterplot = pd.scatter_matrix(dataframe, alpha=0.3,
---> 16 figsize=(10, 10), diagonal=... | ValueError |
def _clean_na_values(na_values, keep_default_na=True):
if na_values is None:
if keep_default_na:
na_values = _NA_VALUES
else:
na_values = set()
na_fvalues = set()
elif isinstance(na_values, dict):
na_values = na_values.copy() # Prevent aliasing.
i... | def _clean_na_values(na_values, keep_default_na=True):
if na_values is None:
if keep_default_na:
na_values = _NA_VALUES
else:
na_values = []
na_fvalues = set()
elif isinstance(na_values, dict):
na_values = na_values.copy() # Prevent aliasing.
if k... | https://github.com/pandas-dev/pandas/issues/15835 | Traceback (most recent call last):
File "/home/alexey.lisicyn/testPand.py", line 22, in <module>
header_v = read_excel(file, **pre_kwargs).columns.values
File "/tmp/opt/linux-CentOS_4.4-x64/P7/python-2.7.7-dbg/lib/python2.7/site-packages/pandas/io/excel.py", line 170, in read_excel
skip_footer=skip_footer, converters=c... | TypeError |
def asof(self, where, subset=None):
"""
The last row without any NaN is taken (or the last row without
NaN considering only the subset of columns in the case of a DataFrame)
.. versionadded:: 0.19.0 For DataFrame
If there is no good value, NaN is returned for a Series
a Series of NaN values fo... | def asof(self, where, subset=None):
"""
The last row without any NaN is taken (or the last row without
NaN considering only the subset of columns in the case of a DataFrame)
.. versionadded:: 0.19.0 For DataFrame
If there is no good value, NaN is returned for a Series
a Series of NaN values fo... | https://github.com/pandas-dev/pandas/issues/15713 | import pandas as pd
import numpy as np
pd.Series([np.nan]).asof([0])
Traceback (most recent call last):
File "<ipython-input-268-2b0f8084a393>", line 1, in <module>
pd.Series([np.nan]).asof([0])
File "~/anaconda3/lib/python3.5/site-packages/pandas/core/generic.py", line 3985, in asof
locs = self.index.asof_locs(where, ... | IndexError |
def cut(
x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False
):
"""
Return indices of half-open bins to which each value of `x` belongs.
Parameters
----------
x : array-like
Input array to be binned. It has to be 1-dimensional.
bins : int or sequence o... | def cut(
x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False
):
"""
Return indices of half-open bins to which each value of `x` belongs.
Parameters
----------
x : array-like
Input array to be binned. It has to be 1-dimensional.
bins : int or sequence o... | https://github.com/pandas-dev/pandas/issues/15428 | import pandas as pd
pd.__version__
u'0.19.2'
s = pd.Series([0,0,0])
pd.cut(s, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/luca/.local/lib/python2.7/site-packages/pandas/tools/tile.py", line 119, in cut
include_lowest=include_lowest)
File "/home/luca/.local/lib/python2.7/site-p... | ValueError |
def _bins_to_cuts(
x,
bins,
right=True,
labels=None,
precision=3,
include_lowest=False,
dtype=None,
duplicates="raise",
):
if duplicates not in ["raise", "drop"]:
raise ValueError(
"invalid value for 'duplicates' parameter, valid options are: raise, drop"
... | def _bins_to_cuts(
x,
bins,
right=True,
labels=None,
precision=3,
include_lowest=False,
dtype=None,
duplicates="raise",
):
if duplicates not in ["raise", "drop"]:
raise ValueError(
"invalid value for 'duplicates' parameter, valid options are: raise, drop"
... | https://github.com/pandas-dev/pandas/issues/15428 | import pandas as pd
pd.__version__
u'0.19.2'
s = pd.Series([0,0,0])
pd.cut(s, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/luca/.local/lib/python2.7/site-packages/pandas/tools/tile.py", line 119, in cut
include_lowest=include_lowest)
File "/home/luca/.local/lib/python2.7/site-p... | ValueError |
def cummin(self, axis=0, **kwargs):
"""Cumulative min for each group"""
if axis != 0:
return self.apply(lambda x: np.minimum.accumulate(x, axis))
return self._cython_transform("cummin", numeric_only=False)
| def cummin(self, axis=0, **kwargs):
"""Cumulative min for each group"""
if axis != 0:
return self.apply(lambda x: np.minimum.accumulate(x, axis))
return self._cython_transform("cummin", **kwargs)
| https://github.com/pandas-dev/pandas/issues/15561 | import pandas as pd
x = pd.DataFrame(dict(a=[1], b=pd.to_datetime(['2001'])))
x.groupby('a').b.cummax()
Traceback (most recent call last):
File "<ipython-input-9-316257648d5f>", line 1, in <module>
x.groupby('a').b.cummax()
File "~/anaconda3/lib/python3.5/site-packages/pandas/core/groupby.py", line 1454, in cummax
ret... | DataError |
def cummax(self, axis=0, **kwargs):
"""Cumulative max for each group"""
if axis != 0:
return self.apply(lambda x: np.maximum.accumulate(x, axis))
return self._cython_transform("cummax", numeric_only=False)
| def cummax(self, axis=0, **kwargs):
"""Cumulative max for each group"""
if axis != 0:
return self.apply(lambda x: np.maximum.accumulate(x, axis))
return self._cython_transform("cummax", **kwargs)
| https://github.com/pandas-dev/pandas/issues/15561 | import pandas as pd
x = pd.DataFrame(dict(a=[1], b=pd.to_datetime(['2001'])))
x.groupby('a').b.cummax()
Traceback (most recent call last):
File "<ipython-input-9-316257648d5f>", line 1, in <module>
x.groupby('a').b.cummax()
File "~/anaconda3/lib/python3.5/site-packages/pandas/core/groupby.py", line 1454, in cummax
ret... | DataError |
def json_normalize(
data,
record_path=None,
meta=None,
meta_prefix=None,
record_prefix=None,
errors="raise",
):
"""
"Normalize" semi-structured JSON data into a flat table
Parameters
----------
data : dict or list of dicts
Unserialized JSON objects
record_path : ... | def json_normalize(
data,
record_path=None,
meta=None,
meta_prefix=None,
record_prefix=None,
errors="raise",
):
"""
"Normalize" semi-structured JSON data into a flat table
Parameters
----------
data : dict or list of dicts
Unserialized JSON objects
record_path : ... | https://github.com/pandas-dev/pandas/issues/15534 | In[21]: pandas.io.json.json_normalize([])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-21-1bd834af8a9b> in <module>()
----> 1 pandas.io.json.json_normalize([])
/usr/local/lib/python3.6/site-package... | IndexError |
def to_records(self, index=True, convert_datetime64=True):
"""
Convert DataFrame to record array. Index will be put in the
'index' field of the record array if requested
Parameters
----------
index : boolean, default True
Include index in resulting record array, stored in 'index' field
... | def to_records(self, index=True, convert_datetime64=True):
"""
Convert DataFrame to record array. Index will be put in the
'index' field of the record array if requested
Parameters
----------
index : boolean, default True
Include index in resulting record array, stored in 'index' field
... | https://github.com/pandas-dev/pandas/issues/11879 | In [322]: df = pandas.DataFrame({u'c/\u03c3':[1,2,3]})
In [323]: df
Out[323]:
c/σ
0 1
1 2
2 3
In [324]: df.to_records()
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-324-6d3142e97d2d> in <... | UnicodeEncodeError |
def _getitem_axis(self, key, axis=0):
labels = self.obj._get_axis(axis)
key = self._get_partial_string_timestamp_match_key(key, labels)
if isinstance(key, slice):
self._has_valid_type(key, axis)
return self._get_slice_axis(key, axis=axis)
elif is_bool_indexer(key):
return self._... | def _getitem_axis(self, key, axis=0):
labels = self.obj._get_axis(axis)
key = self._get_partial_string_timestamp_match_key(key, labels)
if isinstance(key, slice):
self._has_valid_type(key, axis)
return self._get_slice_axis(key, axis=axis)
elif is_bool_indexer(key):
return self._... | https://github.com/pandas-dev/pandas/issues/15424 | In [2]: d = pd.DataFrame([[1, 1, 3],
...: [1, 2, 4],
...: [2, 2, 5]], columns=['a', 'b', 'c'])
In [3]: d.set_index(['a', 'b']).loc[pd.Series([1, 2])]
Out[3]:
c
a b
1 1 3
2 4
2 2 5
In [4]: d.set_index(['a', 'b']).loc[pd.Series([1, 2], index=[2,0])]
Out[4]:
c
a b
1 1 3
2 4
2 2 ... | KeyError |
def _cython_operation(self, kind, values, how, axis):
assert kind in ["transform", "aggregate"]
# can we do this operation with our cython functions
# if not raise NotImplementedError
# we raise NotImplemented if this is an invalid operation
# entirely, e.g. adding datetimes
# categoricals ar... | def _cython_operation(self, kind, values, how, axis):
assert kind in ["transform", "aggregate"]
# can we do this operation with our cython functions
# if not raise NotImplementedError
# we raise NotImplemented if this is an invalid operation
# entirely, e.g. adding datetimes
# categoricals ar... | https://github.com/pandas-dev/pandas/issues/15109 | (pandas) bash-3.2$ nosetests pandas/tests/groupby/test_groupby.py -s -m cummin_cummax
F
======================================================================
FAIL: test_cummin_cummax (test_groupby.TestGroupBy)
----------------------------------------------------------------------
Traceback (most recent call last):
Fi... | AssertionError |
def _aggregate(
self, result, counts, values, comp_ids, agg_func, is_numeric, is_datetimelike
):
if values.ndim > 3:
# punting for now
raise NotImplementedError("number of dimensions is currently limited to 3")
elif values.ndim > 2:
for i, chunk in enumerate(values.transpose(2, 0, 1)... | def _aggregate(self, result, counts, values, comp_ids, agg_func, is_numeric):
if values.ndim > 3:
# punting for now
raise NotImplementedError("number of dimensions is currently limited to 3")
elif values.ndim > 2:
for i, chunk in enumerate(values.transpose(2, 0, 1)):
chunk = ... | https://github.com/pandas-dev/pandas/issues/15109 | (pandas) bash-3.2$ nosetests pandas/tests/groupby/test_groupby.py -s -m cummin_cummax
F
======================================================================
FAIL: test_cummin_cummax (test_groupby.TestGroupBy)
----------------------------------------------------------------------
Traceback (most recent call last):
Fi... | AssertionError |
def _transform(
self, result, values, comp_ids, transform_func, is_numeric, is_datetimelike
):
comp_ids, _, ngroups = self.group_info
if values.ndim > 3:
# punting for now
raise NotImplementedError("number of dimensions is currently limited to 3")
elif values.ndim > 2:
for i, chu... | def _transform(self, result, accum, values, comp_ids, transform_func, is_numeric):
comp_ids, _, ngroups = self.group_info
if values.ndim > 3:
# punting for now
raise NotImplementedError("number of dimensions is currently limited to 3")
elif values.ndim > 2:
for i, chunk in enumerate(... | https://github.com/pandas-dev/pandas/issues/15109 | (pandas) bash-3.2$ nosetests pandas/tests/groupby/test_groupby.py -s -m cummin_cummax
F
======================================================================
FAIL: test_cummin_cummax (test_groupby.TestGroupBy)
----------------------------------------------------------------------
Traceback (most recent call last):
Fi... | AssertionError |
def _map(f, arr, na_mask=False, na_value=np.nan, dtype=object):
if not len(arr):
return np.ndarray(0, dtype=dtype)
if isinstance(arr, ABCSeries):
arr = arr.values
if not isinstance(arr, np.ndarray):
arr = np.asarray(arr, dtype=object)
if na_mask:
mask = isnull(arr)
... | def _map(f, arr, na_mask=False, na_value=np.nan, dtype=object):
if not len(arr):
return np.ndarray(0, dtype=dtype)
if isinstance(arr, ABCSeries):
arr = arr.values
if not isinstance(arr, np.ndarray):
arr = np.asarray(arr, dtype=object)
if na_mask:
mask = isnull(arr)
... | https://github.com/pandas-dev/pandas/issues/15055 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-bc58c5c60bd2> in <module>()
----> 1 s.str.replace(r'[aeiou]', lambda m: m.group().upper())
/anaconda3/lib/python3.4/site-packages/pandas/core/strings... | TypeError |
def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
"""
Replace occurrences of pattern/regex in the Series/Index with
some other string. Equivalent to :meth:`str.replace` or
:func:`re.sub`.
Parameters
----------
pat : string
Character sequence or regular expression
repl :... | def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
"""
Replace occurrences of pattern/regex in the Series/Index with
some other string. Equivalent to :meth:`str.replace` or
:func:`re.sub`.
Parameters
----------
pat : string
Character sequence or regular expression
repl :... | https://github.com/pandas-dev/pandas/issues/15055 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-bc58c5c60bd2> in <module>()
----> 1 s.str.replace(r'[aeiou]', lambda m: m.group().upper())
/anaconda3/lib/python3.4/site-packages/pandas/core/strings... | TypeError |
def validate(self):
super(Rolling, self).validate()
# we allow rolling on a datetimelike index
if self.is_datetimelike and isinstance(
self.window, (compat.string_types, DateOffset)
):
self._validate_monotonic()
freq = self._validate_freq()
# we don't allow center
... | def validate(self):
super(Rolling, self).validate()
# we allow rolling on a datetimelike index
if self.is_datetimelike and isinstance(
self.window, (compat.string_types, DateOffset)
):
# must be monotonic for on
if not self._on.is_monotonic:
formatted = self.on or "i... | https://github.com/pandas-dev/pandas/issues/15130 | In [7]: dates_df.groupby('name').rolling('180D', on='date')['amount'].sum()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-8896cb99a66a> in <module>()
----> 1 dates_df.groupby('name').rolling('180D'... | ValueError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.