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 __new__(
cls,
data=None,
freq=None,
tz=None,
normalize=False,
closed=None,
ambiguous="raise",
dayfirst=False,
yearfirst=False,
dtype=None,
copy=False,
name=None,
):
if is_scalar(data):
raise TypeError(
f"{cls.__name__}() must be called with a "... | def __new__(
cls,
data=None,
freq=None,
tz=None,
normalize=False,
closed=None,
ambiguous="raise",
dayfirst=False,
yearfirst=False,
dtype=None,
copy=False,
name=None,
):
if is_scalar(data):
raise TypeError(
f"{cls.__name__}() must be called with a "... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def __new__(
cls,
data,
closed=None,
dtype=None,
copy: bool = False,
name=None,
verify_integrity: bool = True,
):
name = maybe_extract_name(name, data, cls)
with rewrite_exception("IntervalArray", cls.__name__):
array = IntervalArray(
data,
closed=clo... | def __new__(
cls,
data,
closed=None,
dtype=None,
copy: bool = False,
name=None,
verify_integrity: bool = True,
):
if name is None and hasattr(data, "name"):
name = data.name
with rewrite_exception("IntervalArray", cls.__name__):
array = IntervalArray(
dat... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def __new__(cls, data=None, dtype=None, copy=False, name=None):
cls._validate_dtype(dtype)
# Coerce to ndarray if not already ndarray or Index
if not isinstance(data, (np.ndarray, Index)):
if is_scalar(data):
raise cls._scalar_data_error(data)
# other iterable of some kind
... | def __new__(cls, data=None, dtype=None, copy=False, name=None):
cls._validate_dtype(dtype)
# Coerce to ndarray if not already ndarray or Index
if not isinstance(data, (np.ndarray, Index)):
if is_scalar(data):
raise cls._scalar_data_error(data)
# other iterable of some kind
... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def __new__(
cls,
data=None,
ordinal=None,
freq=None,
tz=None,
dtype=None,
copy=False,
name=None,
**fields,
):
valid_field_set = {
"year",
"month",
"day",
"quarter",
"hour",
"minute",
"second",
}
if not set(fields).... | def __new__(
cls,
data=None,
ordinal=None,
freq=None,
tz=None,
dtype=None,
copy=False,
name=None,
**fields,
):
valid_field_set = {
"year",
"month",
"day",
"quarter",
"hour",
"minute",
"second",
}
if not set(fields).... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def __new__(
cls,
start=None,
stop=None,
step=None,
dtype=None,
copy=False,
name=None,
):
cls._validate_dtype(dtype)
name = maybe_extract_name(name, start, cls)
# RangeIndex
if isinstance(start, RangeIndex):
start = start._range
return cls._simple_new(start, ... | def __new__(
cls,
start=None,
stop=None,
step=None,
dtype=None,
copy=False,
name=None,
):
cls._validate_dtype(dtype)
# RangeIndex
if isinstance(start, RangeIndex):
name = start.name if name is None else name
start = start._range
return cls._simple_new(sta... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def __new__(
cls,
data=None,
unit=None,
freq=None,
closed=None,
dtype=_TD_DTYPE,
copy=False,
name=None,
):
name = maybe_extract_name(name, data, cls)
if is_scalar(data):
raise TypeError(
f"{cls.__name__}() must be called with a "
f"collection of s... | def __new__(
cls,
data=None,
unit=None,
freq=None,
closed=None,
dtype=_TD_DTYPE,
copy=False,
name=None,
):
if is_scalar(data):
raise TypeError(
f"{cls.__name__}() must be called with a "
f"collection of some kind, {repr(data)} was passed"
)
... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
# `dtype` is passed by _shallow_copy in corner cases, should always
# be timedelta64[ns] if present
if not isinstance(values, TimedeltaArray):
values = TimedeltaArray._simple_new(values, dtype=dtype, freq=freq)
else:
i... | def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
# `dtype` is passed by _shallow_copy in corner cases, should always
# be timedelta64[ns] if present
if not isinstance(values, TimedeltaArray):
values = TimedeltaArray._simple_new(values, dtype=dtype, freq=freq)
else:
i... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def __init__(
self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False
):
# we are called internally, so short-circuit
if fastpath:
# data is an ndarray, index is defined
if not isinstance(data, SingleBlockManager):
data = SingleBlockManager(data, index, fas... | def __init__(
self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False
):
# we are called internally, so short-circuit
if fastpath:
# data is an ndarray, index is defined
if not isinstance(data, SingleBlockManager):
data = SingleBlockManager(data, index, fas... | https://github.com/pandas-dev/pandas/issues/29069 | In [5]: pd.Series([], name=[])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-2c73ddde103e> in <module>
----> 1 pd.Series([], name=[])
~/sandbox/pandas/pandas/core/series.py in __init__(self, data,... | TypeError |
def _attempt_YYYYMMDD(arg, errors):
"""
try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,
arg is a passed in as an object dtype, but could really be ints/strings
with nan-like/or floats (e.g. with nan)
Parameters
----------
arg : passed value
errors : 'raise','ignore',... | def _attempt_YYYYMMDD(arg, errors):
"""
try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,
arg is a passed in as an object dtype, but could really be ints/strings
with nan-like/or floats (e.g. with nan)
Parameters
----------
arg : passed value
errors : 'raise','ignore',... | https://github.com/pandas-dev/pandas/issues/30011 | Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/pandas/core/tools/datetimes.py", line 448, in _convert_listlike_datetimes
values, tz = conversion.datetime_to_datetime64(arg)
File "pandas/_libs/tslibs/conversion.pyx", line 200, in pandas._libs.tslibs.conversion.datetime_to_datetime64
Type... | TypeError |
def melt(
frame: DataFrame,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
) -> DataFrame:
# TODO: what about the existing index?
# If multiindex, gather names of columns on all level for checking presence
# of `id_vars` and `value_vars`
if isin... | def melt(
frame: DataFrame,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
) -> DataFrame:
# TODO: what about the existing index?
# If multiindex, gather names of columns on all level for checking presence
# of `id_vars` and `value_vars`
if isin... | https://github.com/pandas-dev/pandas/issues/29718 | Traceback (most recent call last):
File "test.py", line 5, in <module>
pd.melt(df, id_vars=[1, "string"])
File "/home/nils/projects/tsfresh/venv/lib/python3.6/site-packages/pandas/core/reshape/melt.py", line 52, in melt
"".format(missing=list(missing))
KeyError: "The following 'id_vars' are not present in the DataFrame... | KeyError |
def append(self, other, ignore_index=False, verify_integrity=False, sort=None):
"""
Append rows of `other` to the end of caller, returning a new object.
Columns in `other` that are not in the caller are added as new columns.
Parameters
----------
other : DataFrame or Series/dict-like object, o... | def append(self, other, ignore_index=False, verify_integrity=False, sort=None):
"""
Append rows of `other` to the end of caller, returning a new object.
Columns in `other` that are not in the caller are added as new columns.
Parameters
----------
other : DataFrame or Series/dict-like object, o... | https://github.com/pandas-dev/pandas/issues/28769 | import pandas
pandas.DataFrame().append([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".env\lib\site-packages\pandas\core\frame.py", line 7108, in append
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
IndexError: list index out of range
pandas.__version__
'0.25.1... | IndexError |
def recons_codes(self):
# get unique result indices, and prepend 0 as groupby starts from the first
return [np.r_[0, np.flatnonzero(self.bins[1:] != self.bins[:-1]) + 1]]
| def recons_codes(self):
comp_ids, obs_ids, _ = self.group_info
codes = (ping.codes for ping in self.groupings)
return decons_obs_group_ids(comp_ids, obs_ids, self.shape, codes, xnull=True)
| https://github.com/pandas-dev/pandas/issues/28479 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-543-5efc1c882109> in <module>
14 [print(g) for g in dfg]
15 print('This will cause crash:')
---> 16 display(dfg['Food'].value_counts())
~/anaconda3/lib/... | ValueError |
def _setitem_with_indexer(self, indexer, value):
self._has_valid_setitem_indexer(indexer)
# also has the side effect of consolidating in-place
from pandas import Panel, DataFrame, Series
info_axis = self.obj._info_axis_number
# maybe partial set
take_split_path = self.obj._is_mixed_type
... | def _setitem_with_indexer(self, indexer, value):
self._has_valid_setitem_indexer(indexer)
# also has the side effect of consolidating in-place
from pandas import Panel, DataFrame, Series
# maybe partial set
take_split_path = self.obj._is_mixed_type
# if there is only one block/type, still hav... | https://github.com/pandas-dev/pandas/issues/10360 | In [1]: import pandas as pd
In [29]: panel1 = pd.Panel([[[0., 0.]], [[0., 0.]]], items=['A', 'B'], minor_axis=['x', 'y'])
In [30]: panel2 = pd.Panel([[[0., 0.]], [['o', 'o']]], items=['A', 'B'], minor_axis=['x', 'y'])
In [33]: panel1['C'] = 0.
In [34]: panel2['C'] = 0.
In [35]: panel1.dtypes
Out[35]:
A float64
... | ValueError |
def boxplot(
data,
column=None,
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
figsize=None,
layout=None,
return_type=None,
**kwds,
):
import matplotlib.pyplot as plt
# validate return_type:
if return_type not in BoxPlot._valid_return_types:
raise Val... | def boxplot(
data,
column=None,
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
figsize=None,
layout=None,
return_type=None,
**kwds,
):
import matplotlib.pyplot as plt
# validate return_type:
if return_type not in BoxPlot._valid_return_types:
raise Val... | https://github.com/pandas-dev/pandas/issues/26214 | Traceback (most recent call last):
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 33, in <module>
comparative_results()
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 26, in comparative_results
ax = draw_plot(ax, df1, 'k')
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 22, in d... | TypeError |
def _get_colors():
# num_colors=3 is required as method maybe_color_bp takes the colors
# in positions 0 and 2.
# if colors not provided, use same defaults as DataFrame.plot.box
result = _get_standard_colors(num_colors=3)
result = np.take(result, [0, 0, 2])
result = np.append(result, "k")
... | def _get_colors():
# num_colors=3 is required as method maybe_color_bp takes the colors
# in positions 0 and 2.
return _get_standard_colors(color=kwds.get("color"), num_colors=3)
| https://github.com/pandas-dev/pandas/issues/26214 | Traceback (most recent call last):
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 33, in <module>
comparative_results()
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 26, in comparative_results
ax = draw_plot(ax, df1, 'k')
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 22, in d... | TypeError |
def maybe_color_bp(bp):
setp(bp["boxes"], color=colors[0], alpha=1)
setp(bp["whiskers"], color=colors[1], alpha=1)
setp(bp["medians"], color=colors[2], alpha=1)
setp(bp["caps"], color=colors[3], alpha=1)
| def maybe_color_bp(bp):
if "color" not in kwds:
setp(bp["boxes"], color=colors[0], alpha=1)
setp(bp["whiskers"], color=colors[0], alpha=1)
setp(bp["medians"], color=colors[2], alpha=1)
| https://github.com/pandas-dev/pandas/issues/26214 | Traceback (most recent call last):
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 33, in <module>
comparative_results()
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 26, in comparative_results
ax = draw_plot(ax, df1, 'k')
File "/Users/BNL28/Code/DataPerformance/bug_report.py", line 22, in d... | TypeError |
def __setitem__(self, key, value):
value = extract_array(value, extract_numpy=True)
if not lib.is_scalar(key) and is_list_like(key):
key = np.asarray(key)
if not lib.is_scalar(value):
value = np.asarray(value)
value = np.asarray(value, dtype=self._ndarray.dtype)
self._ndarray[key]... | def __setitem__(self, key, value):
value = extract_array(value, extract_numpy=True)
if not lib.is_scalar(key) and is_list_like(key):
key = np.asarray(key)
if not lib.is_scalar(value):
value = np.asarray(value)
values = self._ndarray
t = np.result_type(value, values)
if t != se... | https://github.com/pandas-dev/pandas/issues/28118 | In [3]: t = pd.array(['a', 'b', 'c'])
In [4]: t[0] = 't'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-7d1c8d6d2e6a> in <module>
----> 1 t[0] = 't'
~/sandbox/pandas/pandas/core/arrays/numpy_.py i... | TypeError |
def aggregate(self, func, *args, **kwargs):
_level = kwargs.pop("_level", None)
relabeling = func is None and _is_multi_agg_with_relabel(**kwargs)
if relabeling:
func, columns, order = _normalize_keyword_aggregation(kwargs)
kwargs = {}
elif func is None:
# nicer error message
... | def aggregate(self, func, *args, **kwargs):
_level = kwargs.pop("_level", None)
relabeling = func is None and _is_multi_agg_with_relabel(**kwargs)
if relabeling:
func, columns, order = _normalize_keyword_aggregation(kwargs)
kwargs = {}
elif func is None:
# nicer error message
... | https://github.com/pandas-dev/pandas/issues/27519 | ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-58-5b7e2c8bacf8> in <module>
3 df = pd.DataFrame({"A": [1, 2]})
4
----> 5 df.groupby([1, 1]).agg(foo=('A', lambda x: x.max()), bar=("A", lambda x: x.min(... | KeyError |
def _normalize_keyword_aggregation(kwargs):
"""
Normalize user-provided "named aggregation" kwargs.
Transforms from the new ``Dict[str, NamedAgg]`` style kwargs
to the old OrderedDict[str, List[scalar]]].
Parameters
----------
kwargs : dict
Returns
-------
aggspec : dict
... | def _normalize_keyword_aggregation(kwargs):
"""
Normalize user-provided "named aggregation" kwargs.
Transforms from the new ``Dict[str, NamedAgg]`` style kwargs
to the old OrderedDict[str, List[scalar]]].
Parameters
----------
kwargs : dict
Returns
-------
aggspec : dict
... | https://github.com/pandas-dev/pandas/issues/27519 | ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-58-5b7e2c8bacf8> in <module>
3 df = pd.DataFrame({"A": [1, 2]})
4
----> 5 df.groupby([1, 1]).agg(foo=('A', lambda x: x.max()), bar=("A", lambda x: x.min(... | KeyError |
def length_of_indexer(indexer, target=None) -> int:
"""
return the length of a single non-tuple indexer which could be a slice
"""
if target is not None and isinstance(indexer, slice):
target_len = len(target)
start = indexer.start
stop = indexer.stop
step = indexer.step
... | def length_of_indexer(indexer, target=None) -> int:
"""
return the length of a single non-tuple indexer which could be a slice
"""
if target is not None and isinstance(indexer, slice):
target_len = len(target)
start = indexer.start
stop = indexer.stop
step = indexer.step
... | https://github.com/pandas-dev/pandas/issues/26939 | import pandas as pd
s = pd.Series(index=range(2010, 2020))
s.loc[2015:2010:-1] = [6, 5, 4, 3, 2, 1]
Traceback (most recent call last):
[...]
ValueError: cannot set using a slice indexer with a different length than the value | ValueError |
def rename(self, index=None, **kwargs):
"""
Alter Series index labels or name.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
Alternatively, change ``Series.name`` with a scalar value.
S... | def rename(self, index=None, **kwargs):
"""
Alter Series index labels or name.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
Alternatively, change ``Series.name`` with a scalar value.
S... | https://github.com/pandas-dev/pandas/issues/27813 | Traceback (most recent call last):
File "test.py", line 8, in <module>
s.rename(i1) # raises error
File "/usr/local/lib/python3.6/dist-packages/pandas/core/series.py", line 3736, in rename
return super(Series, self).rename(index=index, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py", line... | TypeError |
def _isna_new(obj):
if is_scalar(obj):
return libmissing.checknull(obj)
# hack (for now) because MI registers as ndarray
elif isinstance(obj, ABCMultiIndex):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstan... | def _isna_new(obj):
if is_scalar(obj):
return libmissing.checknull(obj)
# hack (for now) because MI registers as ndarray
elif isinstance(obj, ABCMultiIndex):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(
obj,
(
ABCSeries,
... | https://github.com/pandas-dev/pandas/issues/27482 | import pandas as pd
x = pd.Series([1,2,3,4])
xt = type(x)
pd.isnull(xt)
## Traceback (most recent call last):
## File "<input>", line 1, in <module>
## File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 122, in isna
## return _isna(obj)
## File "/home/bbassett/venv37... | AttributeError |
def _isna_old(obj):
"""Detect missing values. Treat None, NaN, INF, -INF as null.
Parameters
----------
arr: ndarray or object value
Returns
-------
boolean ndarray or boolean
"""
if is_scalar(obj):
return libmissing.checknull_old(obj)
# hack (for now) because MI regist... | def _isna_old(obj):
"""Detect missing values. Treat None, NaN, INF, -INF as null.
Parameters
----------
arr: ndarray or object value
Returns
-------
boolean ndarray or boolean
"""
if is_scalar(obj):
return libmissing.checknull_old(obj)
# hack (for now) because MI regist... | https://github.com/pandas-dev/pandas/issues/27482 | import pandas as pd
x = pd.Series([1,2,3,4])
xt = type(x)
pd.isnull(xt)
## Traceback (most recent call last):
## File "<input>", line 1, in <module>
## File "/home/bbassett/venv37/lib/python3.7/site-packages/pandas/core/dtypes/missing.py", line 122, in isna
## return _isna(obj)
## File "/home/bbassett/venv37... | AttributeError |
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
out = kwargs.get("out", ())
for x in inputs + out:
if not isinstance(x, self._HANDLED_TYPES + (SparseArray,)):
return NotImplemented
# for binary ops, use our custom dunder methods
result = ops.maybe_dispatch_ufunc_to_dun... | def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
out = kwargs.get("out", ())
for x in inputs + out:
if not isinstance(x, self._HANDLED_TYPES + (SparseArray,)):
return NotImplemented
# for binary ops, use our custom dunder methods
result = ops.maybe_dispatch_ufunc_to_dun... | https://github.com/pandas-dev/pandas/issues/27080 | In [2]: a = pd.SparseArray([0, 10, 1])
In [3]: np.maximum.reduce(a)
Out[3]: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/Envs/pandas-dev/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, ... | TypeError |
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
"""
Return values at the given quantile over requested axis.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.
axis : {0, 1, 'inde... | def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
"""
Return values at the given quantile over requested axis.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.
axis : {0, 1, 'inde... | https://github.com/pandas-dev/pandas/issues/23925 | In [18]: pd.DataFrame(pd.date_range('1/1/18', periods=5)).quantile()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-18-68ffc067f6f0> in <module>
----> 1 pd.DataFrame(pd.date_range('1/1/18', periods=5)... | ValueError |
def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
indexer = self.index._convert_slice_indexer(key, kind="getitem")
return self._set_values(indexer, value)
else:
if isinstance(key, tuple):
try:
self._set_values(... | def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
indexer = self.index._convert_slice_indexer(key, kind="getitem")
return self._set_values(indexer, value)
else:
if isinstance(key, tuple):
try:
self._set_values(... | https://github.com/pandas-dev/pandas/issues/12862 | ValueError Traceback (most recent call last)
<ipython-input-24-cc1ab78086e5> in <module>()
1 x = pd.Series()
2 x['foo'] = pd.to_datetime(42).tz_localize('UTC')
----> 3 x['bar'] = pd.to_datetime(666).tz_localize('UTC')
/usr/lib/python3.5/site-packages/pandas/core/series.py in __setitem__(... | ValueError |
def _get_join_indexers(self):
"""return the join indexers"""
def flip(xs):
"""unlike np.transpose, this returns an array of tuples"""
xs = [x if not is_extension_array_dtype(x) else x._ndarray_values for x in xs]
labels = list(string.ascii_lowercase[: len(xs)])
dtypes = [x.dtype... | def _get_join_indexers(self):
"""return the join indexers"""
def flip(xs):
"""unlike np.transpose, this returns an array of tuples"""
labels = list(string.ascii_lowercase[: len(xs)])
dtypes = [x.dtype for x in xs]
labeled_dtypes = list(zip(labels, dtypes))
return np.arra... | https://github.com/pandas-dev/pandas/issues/26649 | Traceback (most recent call last):
File "test.py", line 13, in <module>
pd.merge_asof(left, right, by=['by_col1', 'by_col2'], on='on_col')
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 462, in merge_asof
return op.get_result()
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/mer... | SystemError |
def flip(xs):
"""unlike np.transpose, this returns an array of tuples"""
xs = [x if not is_extension_array_dtype(x) else x._ndarray_values for x in xs]
labels = list(string.ascii_lowercase[: len(xs)])
dtypes = [x.dtype for x in xs]
labeled_dtypes = list(zip(labels, dtypes))
return np.array(list(... | def flip(xs):
"""unlike np.transpose, this returns an array of tuples"""
labels = list(string.ascii_lowercase[: len(xs)])
dtypes = [x.dtype for x in xs]
labeled_dtypes = list(zip(labels, dtypes))
return np.array(list(zip(*xs)), labeled_dtypes)
| https://github.com/pandas-dev/pandas/issues/26649 | Traceback (most recent call last):
File "test.py", line 13, in <module>
pd.merge_asof(left, right, by=['by_col1', 'by_col2'], on='on_col')
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 462, in merge_asof
return op.get_result()
File "myenv/lib/python3.6/site-packages/pandas/core/reshape/mer... | SystemError |
def _format_value(self, val):
if is_scalar(val) and missing.isna(val):
val = self.na_rep
elif is_float(val):
if missing.isposinf_scalar(val):
val = self.inf_rep
elif missing.isneginf_scalar(val):
val = "-{inf}".format(inf=self.inf_rep)
elif self.float_form... | def _format_value(self, val):
if is_scalar(val) and missing.isna(val):
val = self.na_rep
elif is_float(val):
if missing.isposinf_scalar(val):
val = self.inf_rep
elif missing.isneginf_scalar(val):
val = "-{inf}".format(inf=self.inf_rep)
elif self.float_form... | https://github.com/pandas-dev/pandas/issues/7056 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-4e18a4be2a71> in <module>()
----> 1 df.to_excel('test.xlsx')
/home/silvio/prod34/lib/python3.4/site-packages/pandas/core/frame.py in to_excel(self, ex... | TypeError |
def _wrap_applied_output(self, keys, values, not_indexed_same=False):
from pandas.core.index import _all_indexes_same
if len(keys) == 0:
return DataFrame(index=keys)
key_names = self.grouper.names
# GH12824.
def first_not_none(values):
try:
return next(com._not_none(*v... | def _wrap_applied_output(self, keys, values, not_indexed_same=False):
from pandas.core.index import _all_indexes_same
from pandas.core.tools.numeric import to_numeric
if len(keys) == 0:
return DataFrame(index=keys)
key_names = self.grouper.names
# GH12824.
def first_not_none(values):
... | https://github.com/pandas-dev/pandas/issues/13287 | Traceback (most recent call last):
File "/Users/jkelleher/anaconda/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-46-ae20c6b6248f>", line 1, in <module>
pd.DataFrame(ts_array)
File "/Users/jkelleher/anaconda/li... | AssertionError |
def init_ndarray(values, index, columns, dtype=None, copy=False):
# input must be a ndarray, list, Series, index
if isinstance(values, ABCSeries):
if columns is None:
if values.name is not None:
columns = [values.name]
if index is None:
index = values.ind... | def init_ndarray(values, index, columns, dtype=None, copy=False):
# input must be a ndarray, list, Series, index
if isinstance(values, ABCSeries):
if columns is None:
if values.name is not None:
columns = [values.name]
if index is None:
index = values.ind... | https://github.com/pandas-dev/pandas/issues/13287 | Traceback (most recent call last):
File "/Users/jkelleher/anaconda/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-46-ae20c6b6248f>", line 1, in <module>
pd.DataFrame(ts_array)
File "/Users/jkelleher/anaconda/li... | AssertionError |
def _get_value(self, index, col, takeable=False):
if takeable:
series = self._iget_item_cache(col)
return com.maybe_box_datetimelike(series._values[index])
series = self._get_item_cache(col)
engine = self.index._engine
try:
return engine.get_value(series._values, index)
exc... | def _get_value(self, index, col, takeable=False):
if takeable:
series = self._iget_item_cache(col)
return com.maybe_box_datetimelike(series._values[index])
series = self._get_item_cache(col)
engine = self.index._engine
try:
return engine.get_value(series._values, index)
exc... | https://github.com/pandas-dev/pandas/issues/20629 | Python 3.6.3 (default, Oct 3 2017, 21:45:48)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import pandas as pd
x = pd.Series([1, 2, 3], index=pd.CategoricalIndex(["A", "B", "C"]))
x.loc["A"]
1
x.at["A"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>... | AttributeError |
def get_value(self, series: AnyArrayLike, key: Any):
"""
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
Parameters
----------
series : Series, ExtensionArray, Index, or ndarray
1-dimensional array to take values from
key: : scalar
... | def get_value(self, series, key):
"""
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
try:
k = com.values_from_object(key)
k = self._convert_scalar_indexer(k, kind="getitem")
indexer = self.get_loc(k)
return series.iloc... | https://github.com/pandas-dev/pandas/issues/20629 | Python 3.6.3 (default, Oct 3 2017, 21:45:48)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import pandas as pd
x = pd.Series([1, 2, 3], index=pd.CategoricalIndex(["A", "B", "C"]))
x.loc["A"]
1
x.at["A"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>... | AttributeError |
def coerce_to_array(values, dtype, mask=None, copy=False):
"""
Coerce the input values array to numpy arrays with a mask
Parameters
----------
values : 1D list-like
dtype : integer dtype
mask : boolean 1D array, optional
copy : boolean, default False
if True, copy the input
... | def coerce_to_array(values, dtype, mask=None, copy=False):
"""
Coerce the input values array to numpy arrays with a mask
Parameters
----------
values : 1D list-like
dtype : integer dtype
mask : boolean 1D array, optional
copy : boolean, default False
if True, copy the input
... | https://github.com/pandas-dev/pandas/issues/25211 | In [1]: import pandas as pd, numpy as np
# expected behaviour with ordinary dtype
In [2]: pd.Series([True, False], dtype=int)
Out[2]:
0 1
1 0
dtype: int64
# broken
In [3]: pd.Series([True, False], dtype=pd.Int64Dtype())
---------------------------------------------------------------------------
TypeError ... | TypeError |
def apply_index(self, i):
"""
Vectorized apply of DateOffset to DatetimeIndex,
raises NotImplentedError for offsets without a
vectorized implementation.
Parameters
----------
i : DatetimeIndex
Returns
-------
y : DatetimeIndex
"""
if type(self) is not DateOffset:
... | def apply_index(self, i):
"""
Vectorized apply of DateOffset to DatetimeIndex,
raises NotImplentedError for offsets without a
vectorized implementation.
Parameters
----------
i : DatetimeIndex
Returns
-------
y : DatetimeIndex
"""
if type(self) is not DateOffset:
... | https://github.com/pandas-dev/pandas/issues/26258 | Traceback (most recent call last):
File "C:\mma\local\Anaconda3\envs\pd24\lib\site-packages\pandas\core\arrays\datetimelike.py", line 884, in _validate_frequency
raise ValueError
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, i... | ValueError |
def _construct_result(left, result, index, name, dtype=None):
"""
If the raw op result has a non-None name (e.g. it is an Index object) and
the name argument is None, then passing name to the constructor will
not be enough; we still need to override the name attribute.
"""
out = left._constructo... | def _construct_result(left, result, index, name, dtype=None):
"""
If the raw op result has a non-None name (e.g. it is an Index object) and
the name argument is None, then passing name to the constructor will
not be enough; we still need to override the name attribute.
"""
out = left._constructo... | https://github.com/pandas-dev/pandas/issues/25557 | a.divmod(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/danlaw/Projects/pandas/pandas/core/ops.py", line 1892, in flex_wrapper
return self._binop(other, op, level=level, fill_value=fill_value)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 2522, in _binop
result... | ValueError |
def _construct_divmod_result(left, result, index, name, dtype=None):
"""divmod returns a tuple of like indexed series instead of a single series."""
return (
_construct_result(left, result[0], index=index, name=name, dtype=dtype),
_construct_result(left, result[1], index=index, name=name, dtype=... | def _construct_divmod_result(left, result, index, name, dtype=None):
"""divmod returns a tuple of like indexed series instead of a single series."""
constructor = left._constructor
return (
constructor(result[0], index=index, name=name, dtype=dtype),
constructor(result[1], index=index, name=... | https://github.com/pandas-dev/pandas/issues/25557 | a.divmod(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/danlaw/Projects/pandas/pandas/core/ops.py", line 1892, in flex_wrapper
return self._binop(other, op, level=level, fill_value=fill_value)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 2522, in _binop
result... | ValueError |
def _binop(self, other, func, level=None, fill_value=None):
"""
Perform generic binary operation with optional fill value.
Parameters
----------
other : Series
func : binary operator
fill_value : float or object
Value to substitute for NA/null values. If both Series are NA in a
... | def _binop(self, other, func, level=None, fill_value=None):
"""
Perform generic binary operation with optional fill value.
Parameters
----------
other : Series
func : binary operator
fill_value : float or object
Value to substitute for NA/null values. If both Series are NA in a
... | https://github.com/pandas-dev/pandas/issues/25557 | a.divmod(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/danlaw/Projects/pandas/pandas/core/ops.py", line 1892, in flex_wrapper
return self._binop(other, op, level=level, fill_value=fill_value)
File "/Users/danlaw/Projects/pandas/pandas/core/series.py", line 2522, in _binop
result... | ValueError |
def _try_cast(self, result, obj, numeric_only=False):
"""
Try to cast the result to our obj original type,
we may have roundtripped through object in the mean-time.
If numeric_only is True, then only try to cast numerics
and not datetimelikes.
"""
if obj.ndim > 1:
dtype = obj._valu... | def _try_cast(self, result, obj, numeric_only=False):
"""
Try to cast the result to our obj original type,
we may have roundtripped through object in the mean-time.
If numeric_only is True, then only try to cast numerics
and not datetimelikes.
"""
if obj.ndim > 1:
dtype = obj._valu... | https://github.com/pandas-dev/pandas/issues/23683 | Traceback (most recent call last):
File "~/.pyenv/versions/anaconda3-5.3.0/lib/python3.7/site-packages/pandas/core/groupby/groupby.py", line 2670, in agg_series
return self._aggregate_series_fast(obj, func)
File "~/.pyenv/versions/anaconda3-5.3.0/lib/python3.7/site-packages/pandas/core/groupby/groupby.py", line 2689, i... | ValueError |
def nunique(self, dropna=True):
"""
Return DataFrame with number of distinct observations per group for
each column.
.. versionadded:: 0.20.0
Parameters
----------
dropna : boolean, default True
Don't include NaN in the counts.
Returns
-------
nunique: DataFrame
E... | def nunique(self, dropna=True):
"""
Return DataFrame with number of distinct observations per group for
each column.
.. versionadded:: 0.20.0
Parameters
----------
dropna : boolean, default True
Don't include NaN in the counts.
Returns
-------
nunique: DataFrame
E... | https://github.com/pandas-dev/pandas/issues/23222 | import pandas as pd
pd.show_versions()
Backend TkAgg is interactive backend. Turning interactive mode on.
Matplotlib support failed
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\183.3647.8\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 23, in do_imp... | KeyError |
def read_sas(
filepath_or_buffer,
format=None,
index=None,
encoding=None,
chunksize=None,
iterator=False,
):
"""
Read SAS files stored as either XPORT or SAS7BDAT format files.
Parameters
----------
filepath_or_buffer : string or file-like object
Path to the SAS file... | def read_sas(
filepath_or_buffer,
format=None,
index=None,
encoding=None,
chunksize=None,
iterator=False,
):
"""
Read SAS files stored as either XPORT or SAS7BDAT format files.
Parameters
----------
filepath_or_buffer : string or file-like object
Path to the SAS file... | https://github.com/pandas-dev/pandas/issues/24548 | ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-de3f5c15fb71> in <module>
1 import pandas as pd
----> 2 pd.read_sas('/tmp/foo')
~/.virtualenvs/pandas/lib/python3.7/site-packages/pandas/io/sas/sasre... | AttributeError |
def _write_col_header(self, indent):
truncate_h = self.fmt.truncate_h
if isinstance(self.columns, ABCMultiIndex):
template = 'colspan="{span:d}" halign="left"'
if self.fmt.sparsify:
# GH3547
sentinel = com.sentinel_factory()
else:
sentinel = False
... | def _write_col_header(self, indent):
truncate_h = self.fmt.truncate_h
if isinstance(self.columns, ABCMultiIndex):
template = 'colspan="{span:d}" halign="left"'
if self.fmt.sparsify:
# GH3547
sentinel = com.sentinel_factory()
else:
sentinel = None
... | https://github.com/pandas-dev/pandas/issues/22887 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-59e289592884> in <module>()
3 ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
4 df = pd.DataFrame(index=arrays, columns=arrays)
--... | TypeError |
def _write_hierarchical_rows(self, fmt_values, indent):
template = 'rowspan="{span}" valign="top"'
truncate_h = self.fmt.truncate_h
truncate_v = self.fmt.truncate_v
frame = self.fmt.tr_frame
nrows = len(frame)
idx_values = frame.index.format(sparsify=False, adjoin=False, names=False)
idx_v... | def _write_hierarchical_rows(self, fmt_values, indent):
template = 'rowspan="{span}" valign="top"'
truncate_h = self.fmt.truncate_h
truncate_v = self.fmt.truncate_v
frame = self.fmt.tr_frame
nrows = len(frame)
# TODO: after gh-22887 fixed, refactor to use class property
# in place of row_le... | https://github.com/pandas-dev/pandas/issues/22887 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-59e289592884> in <module>()
3 ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
4 df = pd.DataFrame(index=arrays, columns=arrays)
--... | TypeError |
def _non_reducing_slice(slice_):
"""
Ensurse that a slice doesn't reduce to a Series or Scalar.
Any user-paseed `subset` should have this called on it
to make sure we're always working with DataFrames.
"""
# default to column slice, like DataFrame
# ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
... | def _non_reducing_slice(slice_):
"""
Ensurse that a slice doesn't reduce to a Series or Scalar.
Any user-paseed `subset` should have this called on it
to make sure we're always working with DataFrames.
"""
# default to column slice, like DataFrame
# ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
... | https://github.com/pandas-dev/pandas/issues/19861 | Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 434, in render
self._compute()
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\styl... | AttributeError |
def pred(part):
# 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
)
| def pred(part):
# true when slice does *not* reduce
return isinstance(part, slice) or is_list_like(part)
| https://github.com/pandas-dev/pandas/issues/19861 | Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\style.py", line 434, in render
self._compute()
File "c:\Users\user\AppData\Local\Continuum\Miniconda3\envs\lg\lib\site-packages\pandas\io\formats\styl... | AttributeError |
def _has_bool_dtype(x):
try:
if isinstance(x, ABCDataFrame):
return "bool" in x.dtypes
else:
return x.dtype == bool
except AttributeError:
return isinstance(x, (bool, np.bool_))
| def _has_bool_dtype(x):
try:
return x.dtype == bool
except AttributeError:
try:
return "bool" in x.dtypes
except AttributeError:
return isinstance(x, (bool, np.bool_))
| https://github.com/pandas-dev/pandas/issues/22383 | In [8]: df.loc[:, ['a','dtype']].ne(df.loc[:, ['a', 'dtype']])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-a0710f18822f> in <module>()
----> 1 df.loc[:, ['a','dtype']].ne(df.loc[:, ['a', 'dtype']... | ValueError |
def _ensure_datetimelike_to_i8(other, to_utc=False):
"""
Helper for coercing an input scalar or array to i8.
Parameters
----------
other : 1d array
to_utc : bool, default False
If True, convert the values to UTC before extracting the i8 values
If False, extract the i8 values dir... | def _ensure_datetimelike_to_i8(other, to_utc=False):
"""
Helper for coercing an input scalar or array to i8.
Parameters
----------
other : 1d array
to_utc : bool, default False
If True, convert the values to UTC before extracting the i8 values
If False, extract the i8 values dir... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _dt_array_cmp(cls, op):
"""
Wrap comparison operations to convert datetime-like to datetime64
"""
opname = "__{name}__".format(name=op.__name__)
nat_result = True if opname == "__ne__" else False
def wrapper(self, other):
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
o... | def _dt_array_cmp(cls, op):
"""
Wrap comparison operations to convert datetime-like to datetime64
"""
opname = "__{name}__".format(name=op.__name__)
nat_result = True if opname == "__ne__" else False
def wrapper(self, other):
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
i... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def wrapper(self, other):
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
other = lib.item_from_zerodim(other)
if isinstance(other, (datetime, np.datetime64, compat.string_types)):
if isinstance(other, (datetime, np.datetime64)):
# GH#18435 strings get a pass from tzawareness compat... | def wrapper(self, other):
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
if isinstance(other, (datetime, np.datetime64, compat.string_types)):
if isinstance(other, (datetime, np.datetime64)):
# GH#18435 strings get a pass from tzawareness compat
self._assert_tzawareness_comp... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _period_array_cmp(cls, op):
"""
Wrap comparison operations to convert Period-like to PeriodDtype
"""
opname = "__{name}__".format(name=op.__name__)
nat_result = True if opname == "__ne__" else False
def wrapper(self, other):
op = getattr(self.asi8, opname)
# We want to event... | def _period_array_cmp(cls, op):
"""
Wrap comparison operations to convert Period-like to PeriodDtype
"""
opname = "__{name}__".format(name=op.__name__)
nat_result = True if opname == "__ne__" else False
def wrapper(self, other):
op = getattr(self.asi8, opname)
# We want to event... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def wrapper(self, other):
op = getattr(self.asi8, opname)
# We want to eventually defer to the Series or PeriodIndex (which will
# return here with an unboxed PeriodArray). But before we do that,
# we do a bit of validation on type (Period) and freq, so that our
# error messages are sensible
if ... | def wrapper(self, other):
op = getattr(self.asi8, opname)
# We want to eventually defer to the Series or PeriodIndex (which will
# return here with an unboxed PeriodArray). But before we do that,
# we do a bit of validation on type (Period) and freq, so that our
# error messages are sensible
not... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _td_array_cmp(cls, op):
"""
Wrap comparison operations to convert timedelta-like to timedelta64
"""
opname = "__{name}__".format(name=op.__name__)
nat_result = True if opname == "__ne__" else False
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
def wrapper(self, other):
if ... | def _td_array_cmp(cls, op):
"""
Wrap comparison operations to convert timedelta-like to timedelta64
"""
opname = "__{name}__".format(name=op.__name__)
nat_result = True if opname == "__ne__" else False
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
def wrapper(self, other):
if ... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def wrapper(self, other):
if _is_convertible_to_td(other) or other is NaT:
try:
other = _to_m8(other)
except ValueError:
# failed to parse as timedelta
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
if isna(other):
... | def wrapper(self, other):
if _is_convertible_to_td(other) or other is NaT:
try:
other = _to_m8(other)
except ValueError:
# failed to parse as timedelta
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
if isna(other):
... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _add_numeric_methods_unary(cls):
"""
Add in numeric unary methods.
"""
def _make_evaluate_unary(op, opstr):
def _evaluate_numeric_unary(self):
self._validate_for_numeric_unaryop(op, opstr)
attrs = self._get_attributes_dict()
attrs = self._maybe_update_att... | def _add_numeric_methods_unary(cls):
"""
Add in numeric unary methods.
"""
def _make_evaluate_unary(op, opstr):
def _evaluate_numeric_unary(self):
self._validate_for_numeric_unaryop(op, opstr)
attrs = self._get_attributes_dict()
attrs = self._maybe_update_att... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _make_evaluate_unary(op, opstr):
def _evaluate_numeric_unary(self):
self._validate_for_numeric_unaryop(op, opstr)
attrs = self._get_attributes_dict()
attrs = self._maybe_update_attributes(attrs)
return Index(op(self.values), **attrs)
_evaluate_numeric_unary.__name__ = opstr
... | def _make_evaluate_unary(op, opstr):
def _evaluate_numeric_unary(self):
self._validate_for_numeric_unaryop(op, opstr)
attrs = self._get_attributes_dict()
attrs = self._maybe_update_attributes(attrs)
return Index(op(self.values), **attrs)
return _evaluate_numeric_unary
| https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def add_special_arithmetic_methods(cls):
"""
Adds the full suite of special arithmetic methods (``__add__``,
``__sub__``, etc.) to the class.
Parameters
----------
cls : class
special methods will be defined and pinned to this class
"""
_, _, arith_method, comp_method, bool_meth... | def add_special_arithmetic_methods(cls):
"""
Adds the full suite of special arithmetic methods (``__add__``,
``__sub__``, etc.) to the class.
Parameters
----------
cls : class
special methods will be defined and pinned to this class
"""
_, _, arith_method, comp_method, bool_meth... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _wrap_inplace_method(method):
"""
return an inplace wrapper for this method
"""
def f(self, other):
result = method(self, other)
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace(
... | def _wrap_inplace_method(method):
"""
return an inplace wrapper for this method
"""
def f(self, other):
result = method(self, other)
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace(
... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
str_rep = _get_opstr(op, cls)
op_name = _get_op_name(op, special)
eval_kwargs = _gen_eval_kwargs(op_name)
fill_zeros = _gen_fill_zeros(op_name)
construct_... | def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
str_rep = _get_opstr(op, cls)
op_name = _get_op_name(op, special)
eval_kwargs = _gen_eval_kwargs(op_name)
fill_zeros = _gen_fill_zeros(op_name)
construct_... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _comp_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
masker = _gen_eval_kwargs(op_name).get("masker", False)
def na_op(x, y):
# TODO:
# should have guarantess on w... | def _comp_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
masker = _gen_eval_kwargs(op_name).get("masker", False)
def na_op(x, y):
# TODO:
# should have guarantess on w... | https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _coerce_method(converter):
"""
Install the scalar coercion methods.
"""
def wrapper(self):
if len(self) == 1:
return converter(self.iloc[0])
raise TypeError("cannot convert the series to {0}".format(str(converter)))
wrapper.__name__ = "__{name}__".format(name=conver... | def _coerce_method(converter):
"""
Install the scalar coercion methods.
"""
def wrapper(self):
if len(self) == 1:
return converter(self.iloc[0])
raise TypeError("cannot convert the series to {0}".format(str(converter)))
return wrapper
| https://github.com/pandas-dev/pandas/issues/23078 | ---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-8a2a887e6efd> in <module>
----> 1 idx <= idx[[0]]
~/sandbox/pandas/pandas/core/indexes/datetimes.py in wrapper(self, other)
90
91 def wrapper(self... | ValueError |
def _factorize_keys(lk, rk, sort=True):
# Some pre-processing for non-ndarray lk / rk
if is_datetime64tz_dtype(lk) and is_datetime64tz_dtype(rk):
lk = lk.values
rk = rk.values
elif (
is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk)
):
if lk... | def _factorize_keys(lk, rk, sort=True):
if is_datetime64tz_dtype(lk) and is_datetime64tz_dtype(rk):
lk = lk.values
rk = rk.values
# if we exactly match in categories, allow us to factorize on codes
if is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk):
k... | https://github.com/pandas-dev/pandas/issues/23020 | In [4]: pd.merge(df, df, on='A').dtypes
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-e77608ca3973> in <module>()
----> 1 pd.merge(df, df, on='A').dtypes
~/pandas/pandas/core/reshape/merge.py in m... | ValueError |
def _simple_new(cls, values, name=None, freq=None, **kwargs):
"""
Create a new PeriodIndex.
Parameters
----------
values : PeriodArray, PeriodIndex, Index[int64], ndarray[int64]
Values that can be converted to a PeriodArray without inference
or coercion.
"""
# TODO: raising... | def _simple_new(cls, values, name=None, freq=None, **kwargs):
"""
Create a new PeriodIndex.
Parameters
----------
values : PeriodArray, PeriodIndex, Index[int64], ndarray[int64]
Values that can be converted to a PeriodArray without inference
or coercion.
"""
# TODO: raising... | https://github.com/pandas-dev/pandas/issues/24135 | In [18]: s = pd.Series(np.random.rand(5), index=pd.date_range('20130101', periods=5))
In [19]: s
Out[19]:
2013-01-01 0.130706
2013-01-02 0.232104
2013-01-03 0.506547
2013-01-04 0.155568
2013-01-05 0.873604
Freq: D, dtype: float64
In [20]: s.to_msgpack('test.msg')
In [22]: s2 = pd.read_msgpack('test.ms... | AttributeError |
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/24135 | In [18]: s = pd.Series(np.random.rand(5), index=pd.date_range('20130101', periods=5))
In [19]: s
Out[19]:
2013-01-01 0.130706
2013-01-02 0.232104
2013-01-03 0.506547
2013-01-04 0.155568
2013-01-05 0.873604
Freq: D, dtype: float64
In [20]: s.to_msgpack('test.msg')
In [22]: s2 = pd.read_msgpack('test.ms... | AttributeError |
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
re... | 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
re... | https://github.com/pandas-dev/pandas/issues/22706 | Traceback (most recent call last):
File ".\test.py", line 15, in <module>
json_normalize(d, record_path = ["info", "phones"])
File "C:\Python36\lib\site-packages\pandas\io\json\normalize.py", line 262, in json_normalize
_recursive_extract(data, record_path, {}, level=0)
File "C:\Python36\lib\site-packages\pandas\io\jso... | TypeError |
def _recursive_extract(data, path, seen_meta, level=0):
if isinstance(data, dict):
data = [data]
if len(path) > 1:
for obj in data:
for val, key in zip(meta, meta_keys):
if level + 1 == len(val):
seen_meta[key] = _pull_field(obj, val[-1])
... | def _recursive_extract(data, path, seen_meta, level=0):
if len(path) > 1:
for obj in data:
for val, key in zip(meta, meta_keys):
if level + 1 == len(val):
seen_meta[key] = _pull_field(obj, val[-1])
_recursive_extract(obj[path[0]], path[1:], seen_m... | https://github.com/pandas-dev/pandas/issues/22706 | Traceback (most recent call last):
File ".\test.py", line 15, in <module>
json_normalize(d, record_path = ["info", "phones"])
File "C:\Python36\lib\site-packages\pandas\io\json\normalize.py", line 262, in json_normalize
_recursive_extract(data, record_path, {}, level=0)
File "C:\Python36\lib\site-packages\pandas\io\jso... | TypeError |
def str_extractall(arr, pat, flags=0):
r"""
For each subject string in the Series, extract groups from all
matches of regular expression pat. When each subject string in the
Series has exactly one match, extractall(pat).xs(0, level='match')
is the same as extract(pat).
.. versionadded:: 0.18.0
... | def str_extractall(arr, pat, flags=0):
r"""
For each subject string in the Series, extract groups from all
matches of regular expression pat. When each subject string in the
Series has exactly one match, extractall(pat).xs(0, level='match')
is the same as extract(pat).
.. versionadded:: 0.18.0
... | https://github.com/pandas-dev/pandas/issues/23556 | import pandas as pd
pd.Index(['a', 'b', 'aa'], dtype='category').str.replace('a', 'c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\ProgramData\Miniconda3\envs\pandas-dev\lib\site-packages\pandas\core\strings.py", line 2430, in replace
return self._wrap_result(result)
File "C:\Program... | AttributeError |
def _wrap_result(
self, result, use_codes=True, name=None, expand=None, fill_value=np.nan
):
from pandas import Index, Series, MultiIndex
# for category, we do the stuff on the categories, so blow it up
# to the full series again
# But for some operations, we have to do the stuff on the full values... | def _wrap_result(
self, result, use_codes=True, name=None, expand=None, fill_value=np.nan
):
from pandas.core.index import Index, MultiIndex
# for category, we do the stuff on the categories, so blow it up
# to the full series again
# But for some operations, we have to do the stuff on the full val... | https://github.com/pandas-dev/pandas/issues/23556 | import pandas as pd
pd.Index(['a', 'b', 'aa'], dtype='category').str.replace('a', 'c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\ProgramData\Miniconda3\envs\pandas-dev\lib\site-packages\pandas\core\strings.py", line 2430, in replace
return self._wrap_result(result)
File "C:\Program... | AttributeError |
def _print_as_set(s):
return "{" + "{arg}".format(arg=", ".join(pprint_thing(el) for el in s)) + "}"
| def _print_as_set(s):
return "{{arg}}".format(arg=", ".join(pprint_thing(el) for el in s))
| https://github.com/pandas-dev/pandas/issues/23549 | import pandas as pd
df_list = pd.read_html('https://google.com', flavor='unknown')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/achabot/envs/tmp-b79b7181308bb9c1/lib/python3.7/site-packages/pandas/io/html.py", line 987, in read_html
displayed_only=displayed_only)
File "/Users/acha... | ValueError |
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period):
if value.freq != self.freq:
msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr)
raise IncompatibleFrequency(msg)
value = value.ordinal
elif isinstance(value, compat.string_ty... | def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period):
if value.freq != self.freq:
msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr)
raise IncompatibleFrequency(msg)
value = value.ordinal
elif isinstance(value, compat.string_ty... | https://github.com/pandas-dev/pandas/issues/22803 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
TypeErr... | TypeError |
def get_loc(self, key, method=None, tolerance=None):
"""
Get integer location for requested label
Returns
-------
loc : int
"""
try:
return self._engine.get_loc(key)
except KeyError:
if is_integer(key):
raise
try:
asdt, parsed, reso = par... | def get_loc(self, key, method=None, tolerance=None):
"""
Get integer location for requested label
Returns
-------
loc : int
"""
try:
return self._engine.get_loc(key)
except KeyError:
if is_integer(key):
raise
try:
asdt, parsed, reso = par... | https://github.com/pandas-dev/pandas/issues/22803 | ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
TypeErr... | TypeError |
def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
indexer = self.index._convert_slice_indexer(key, kind="getitem")
return self._set_values(indexer, value)
else:
if isinstance(key, tuple):
try:
self._set_values(... | def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
indexer = self.index._convert_slice_indexer(key, kind="getitem")
return self._set_values(indexer, value)
else:
if isinstance(key, tuple):
try:
self._set_values(... | https://github.com/pandas-dev/pandas/issues/23451 | import pandas
x = pandas.Series([1,2,3], index=['Date','b','other'])
x
Date 1
b 2
other 3
dtype: int64
from datetime import date
x.Date = date.today()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python37\lib\site-packages\pandas\core\generic.py", line 4405, in __setatt... | ValueError |
def _convert_string_array(data, encoding, errors, itemsize=None):
"""
we take a string-like that is object dtype and coerce to a fixed size
string type
Parameters
----------
data : a numpy array of object dtype
encoding : None or string-encoding
errors : handler for encoding errors
... | def _convert_string_array(data, encoding, errors, itemsize=None):
"""
we take a string-like that is object dtype and coerce to a fixed size
string type
Parameters
----------
data : a numpy array of object dtype
encoding : None or string-encoding
errors : handler for encoding errors
... | https://github.com/pandas-dev/pandas/issues/12242 | In [3]: store = pd.HDFStore('teststore.h5', 'w')
In [4]: chunk = pd.DataFrame({'V1':['a','b','c','d','e'], 'data':np.arange(5)})
In [5]: store.append('df', chunk, min_itemsize={'V1': 4})
In [6]: chunk = pd.DataFrame({'V1':['', ''], 'data': [3, 5]})
In [7]: store.append('df', chunk, min_itemsize={'V1': 4})
---------... | ValueError |
def astype(self, dtype, copy=True, errors="raise", **kwargs):
"""
Cast a pandas object to a specified dtype ``dtype``.
Parameters
----------
dtype : data type, or dict of column name -> data type
Use a numpy.dtype or Python type to cast entire pandas object to
the same type. Alterna... | def astype(self, dtype, copy=True, errors="raise", **kwargs):
"""
Cast a pandas object to a specified dtype ``dtype``.
Parameters
----------
dtype : data type, or dict of column name -> data type
Use a numpy.dtype or Python type to cast entire pandas object to
the same type. Alterna... | https://github.com/pandas-dev/pandas/issues/22578 | In [8]: df = pd.DataFrame([[1., 2.], [3., 4.], [5., 6.]], columns=['a', 'b'])
In [9]: df
Out[9]:
a b
0 1.0 2.0
1 3.0 4.0
2 5.0 6.0
In [10]: df.astype('Int64')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last... | AttributeError |
def _astype(
self, dtype, copy=False, errors="raise", values=None, klass=None, mgr=None, **kwargs
):
"""Coerce to the new type
Parameters
----------
dtype : str, dtype convertible
copy : boolean, default False
copy if indicated
errors : str, {'raise', 'ignore'}, default 'ignore'
... | def _astype(
self, dtype, copy=False, errors="raise", values=None, klass=None, mgr=None, **kwargs
):
"""Coerce to the new type
Parameters
----------
dtype : str, dtype convertible
copy : boolean, default False
copy if indicated
errors : str, {'raise', 'ignore'}, default 'ignore'
... | https://github.com/pandas-dev/pandas/issues/22578 | In [8]: df = pd.DataFrame([[1., 2.], [3., 4.], [5., 6.]], columns=['a', 'b'])
In [9]: df
Out[9]:
a b
0 1.0 2.0
1 3.0 4.0
2 5.0 6.0
In [10]: df.astype('Int64')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last... | AttributeError |
def get_reindexed_values(self, empty_dtype, upcasted_na):
if upcasted_na is None:
# No upcasting is necessary
fill_value = self.block.fill_value
values = self.block.get_values()
else:
fill_value = upcasted_na
if self.is_na:
if getattr(self.block, "is_object",... | def get_reindexed_values(self, empty_dtype, upcasted_na):
if upcasted_na is None:
# No upcasting is necessary
fill_value = self.block.fill_value
values = self.block.get_values()
else:
fill_value = upcasted_na
if self.is_na:
if getattr(self.block, "is_object",... | https://github.com/pandas-dev/pandas/issues/22796 | ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-42-457226d62f27> in <module>()
1 a = pd.DataFrame([[1, 2]], dtype='datetime64[ns, UTC]')
2 b = pd.DataFrame([[3]], dtype='datetime64[ns, UTC]')
----> 3 p... | AttributeError |
def dispatch_to_extension_op(op, left, right):
"""
Assume that left or right is a Series backed by an ExtensionArray,
apply the operator defined by op.
"""
# The op calls will raise TypeError if the op is not defined
# on the ExtensionArray
# TODO(jreback)
# we need to listify to avoid ... | def dispatch_to_extension_op(op, left, right):
"""
Assume that left or right is a Series backed by an ExtensionArray,
apply the operator defined by op.
"""
# The op calls will raise TypeError if the op is not defined
# on the ExtensionArray
# TODO(jreback)
# we need to listify to avoid ... | https://github.com/pandas-dev/pandas/issues/22478 | In [41]: s
Out[41]:
0 1
1 2
2 3
dtype: Int64
In [42]: s.values
Out[42]: IntegerArray([1, 2, 3], dtype='Int64')
In [43]: s + s.values
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-43-c3f015... | UnboundLocalError |
def _ensure_localized(self, arg, ambiguous="raise", from_utc=False):
"""
ensure that we are re-localized
This is for compat as we can then call this on all datetimelike
indexes generally (ignored for Period/Timedelta)
Parameters
----------
arg : DatetimeIndex / i8 ndarray
ambiguous : s... | def _ensure_localized(self, result, ambiguous="raise"):
"""
ensure that we are re-localized
This is for compat as we can then call this on all datetimelike
indexes generally (ignored for Period/Timedelta)
Parameters
----------
result : DatetimeIndex / i8 ndarray
ambiguous : str, bool, ... | https://github.com/pandas-dev/pandas/issues/18885 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 58, in merge
return op.get_result()
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(resul... | pytz.exceptions.AmbiguousTimeError |
def where(self, cond, other=None):
other = _ensure_datetimelike_to_i8(other, to_utc=True)
values = _ensure_datetimelike_to_i8(self, to_utc=True)
result = np.where(cond, values, other).astype("i8")
result = self._ensure_localized(result, from_utc=True)
return self._shallow_copy(result, **self._get_a... | def where(self, cond, other=None):
other = _ensure_datetimelike_to_i8(other)
values = _ensure_datetimelike_to_i8(self)
result = np.where(cond, values, other).astype("i8")
result = self._ensure_localized(result)
return self._shallow_copy(result, **self._get_attributes_dict())
| https://github.com/pandas-dev/pandas/issues/18885 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 58, in merge
return op.get_result()
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(resul... | pytz.exceptions.AmbiguousTimeError |
def _ensure_datetimelike_to_i8(other, to_utc=False):
"""
helper for coercing an input scalar or array to i8
Parameters
----------
other : 1d array
to_utc : bool, default False
If True, convert the values to UTC before extracting the i8 values
If False, extract the i8 values dire... | def _ensure_datetimelike_to_i8(other):
"""helper for coercing an input scalar or array to i8"""
if is_scalar(other) and isna(other):
other = iNaT
elif isinstance(other, ABCIndexClass):
# convert tz if needed
if getattr(other, "tz", None) is not None:
other = other.tz_loca... | https://github.com/pandas-dev/pandas/issues/18885 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 58, in merge
return op.get_result()
File "(...)//venv/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 604, in get_result
self._maybe_add_join_keys(resul... | pytz.exceptions.AmbiguousTimeError |
def __getitem__(self, key):
if self._selection is not None:
raise IndexError(
"Column(s) {selection} already selected".format(selection=self._selection)
)
if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)):
if len(self.obj.columns.intersection(key)) != l... | def __getitem__(self, key):
if self._selection is not None:
raise Exception(
"Column(s) {selection} already selected".format(selection=self._selection)
)
if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)):
if len(self.obj.columns.intersection(key)) != le... | https://github.com/pandas-dev/pandas/issues/15072 | In [13]: df = pd.DataFrame({"A": pd.to_datetime(['2015', '2017']), "B": [1, 1]})
In [14]: df
Out[14]:
A B
0 2015-01-01 1
1 2017-01-01 1
In [15]: df.set_index("A").groupby([0, 0]).resample("AS")
Out[15]: DatetimeIndexResamplerGroupby [freq=<YearBegin: month=1>, axis=0, closed=left, label=left, convention=e, base=0]... | Exception |
def _gotitem(self, key, ndim, subset=None):
"""
sub-classes to define
return a sliced object
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on
"""
# create a new object to pr... | def _gotitem(self, key, ndim, subset=None):
"""
sub-classes to define
return a sliced object
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on
"""
# create a new object to pr... | https://github.com/pandas-dev/pandas/issues/15072 | In [13]: df = pd.DataFrame({"A": pd.to_datetime(['2015', '2017']), "B": [1, 1]})
In [14]: df
Out[14]:
A B
0 2015-01-01 1
1 2017-01-01 1
In [15]: df.set_index("A").groupby([0, 0]).resample("AS")
Out[15]: DatetimeIndexResamplerGroupby [freq=<YearBegin: month=1>, axis=0, closed=left, label=left, convention=e, base=0]... | Exception |
def _round(self, freq, rounder, ambiguous):
# round the local times
values = _ensure_datetimelike_to_i8(self)
result = round_ns(values, rounder, freq)
result = self._maybe_mask_results(result, fill_value=NaT)
attribs = self._get_attributes_dict()
if "freq" in attribs:
attribs["freq"] = ... | def _round(self, freq, rounder):
# round the local times
values = _ensure_datetimelike_to_i8(self)
result = round_ns(values, rounder, freq)
result = self._maybe_mask_results(result, fill_value=NaT)
attribs = self._get_attributes_dict()
if "freq" in attribs:
attribs["freq"] = None
if... | https://github.com/pandas-dev/pandas/issues/18946 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
r... | pytz.exceptions.AmbiguousTimeError |
def round(self, freq, ambiguous="raise"):
return self._round(freq, np.round, ambiguous)
| def round(self, freq, *args, **kwargs):
return self._round(freq, np.round)
| https://github.com/pandas-dev/pandas/issues/18946 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
r... | pytz.exceptions.AmbiguousTimeError |
def floor(self, freq, ambiguous="raise"):
return self._round(freq, np.floor, ambiguous)
| def floor(self, freq):
return self._round(freq, np.floor)
| https://github.com/pandas-dev/pandas/issues/18946 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
r... | pytz.exceptions.AmbiguousTimeError |
def ceil(self, freq, ambiguous="raise"):
return self._round(freq, np.ceil, ambiguous)
| def ceil(self, freq):
return self._round(freq, np.ceil)
| https://github.com/pandas-dev/pandas/issues/18946 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
r... | pytz.exceptions.AmbiguousTimeError |
def _ensure_localized(self, result, ambiguous="raise"):
"""
ensure that we are re-localized
This is for compat as we can then call this on all datetimelike
indexes generally (ignored for Period/Timedelta)
Parameters
----------
result : DatetimeIndex / i8 ndarray
ambiguous : str, bool, ... | def _ensure_localized(self, result):
"""
ensure that we are re-localized
This is for compat as we can then call this on all datetimelike
indexes generally (ignored for Period/Timedelta)
Parameters
----------
result : DatetimeIndex / i8 ndarray
Returns
-------
localized DTI
... | https://github.com/pandas-dev/pandas/issues/18946 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "(...)/venv/lib/python3.6/site-packages/pandas/core/accessor.py", line 115, in f
return self._delegate_method(name, *args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/accessors.py", line 131, in _delegate_method
r... | pytz.exceptions.AmbiguousTimeError |
def _get_time_bins(self, ax):
if not isinstance(ax, DatetimeIndex):
raise TypeError(
"axis must be a DatetimeIndex, but got "
"an instance of %r" % type(ax).__name__
)
if len(ax) == 0:
binner = labels = DatetimeIndex(data=[], freq=self.freq, name=ax.name)
... | def _get_time_bins(self, ax):
if not isinstance(ax, DatetimeIndex):
raise TypeError(
"axis must be a DatetimeIndex, but got "
"an instance of %r" % type(ax).__name__
)
if len(ax) == 0:
binner = labels = DatetimeIndex(data=[], freq=self.freq, name=ax.name)
... | https://github.com/pandas-dev/pandas/issues/10117 | In [27]: idx = pd.date_range("2014-10-25 22:00:00", "2014-10-26 00:30:00",
freq="30T", tz="Europe/London")
In [28]: series = pd.Series(np.random.randn(len(idx)), index=idx)
In [31]: series
Out[31]:
2014-10-25 22:00:00+01:00 -0.874014
2014-10-25 22:30:00+01:00 1.316258
2014-10-25 23:00:00+01:00 -1.334616
2014-1... | AmbiguousTimeError |
def _get_range_edges(first, last, offset, closed="left", base=0):
if isinstance(offset, Tick):
is_day = isinstance(offset, Day)
day_nanos = delta_to_nanoseconds(timedelta(1))
# #1165
if (is_day and day_nanos % offset.nanos == 0) or not is_day:
return _adjust_dates_anchor... | def _get_range_edges(first, last, offset, closed="left", base=0):
if isinstance(offset, compat.string_types):
offset = to_offset(offset)
if isinstance(offset, Tick):
is_day = isinstance(offset, Day)
day_nanos = delta_to_nanoseconds(timedelta(1))
# #1165
if (is_day and d... | https://github.com/pandas-dev/pandas/issues/10117 | In [27]: idx = pd.date_range("2014-10-25 22:00:00", "2014-10-26 00:30:00",
freq="30T", tz="Europe/London")
In [28]: series = pd.Series(np.random.randn(len(idx)), index=idx)
In [31]: series
Out[31]:
2014-10-25 22:00:00+01:00 -0.874014
2014-10-25 22:30:00+01:00 1.316258
2014-10-25 23:00:00+01:00 -1.334616
2014-1... | AmbiguousTimeError |
def _adjust_dates_anchored(first, last, offset, closed="right", base=0):
# First and last offsets should be calculated from the start day to fix an
# error cause by resampling across multiple days when a one day period is
# not a multiple of the frequency.
#
# See https://github.com/pandas-dev/panda... | def _adjust_dates_anchored(first, last, offset, closed="right", base=0):
# First and last offsets should be calculated from the start day to fix an
# error cause by resampling across multiple days when a one day period is
# not a multiple of the frequency.
#
# See https://github.com/pandas-dev/panda... | https://github.com/pandas-dev/pandas/issues/10117 | In [27]: idx = pd.date_range("2014-10-25 22:00:00", "2014-10-26 00:30:00",
freq="30T", tz="Europe/London")
In [28]: series = pd.Series(np.random.randn(len(idx)), index=idx)
In [31]: series
Out[31]:
2014-10-25 22:00:00+01:00 -0.874014
2014-10-25 22:30:00+01:00 1.316258
2014-10-25 23:00:00+01:00 -1.334616
2014-1... | AmbiguousTimeError |
def _get_codes_for_values(values, categories):
"""
utility routine to turn values into codes given the specified categories
"""
from pandas.core.algorithms import _get_data_algo, _hashtables
if is_dtype_equal(values.dtype, categories.dtype):
# To prevent erroneous dtype coercion in _get_dat... | def _get_codes_for_values(values, categories):
"""
utility routine to turn values into codes given the specified categories
"""
from pandas.core.algorithms import _get_data_algo, _hashtables
if not is_dtype_equal(values.dtype, categories.dtype):
values = ensure_object(values)
categ... | https://github.com/pandas-dev/pandas/issues/22702 | In [16]: pd.Categorical([], categories=[True, False])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-8e79cd310199> in <module>()
----> 1 pd.Categorical([], categories=[True, False])
~/sandbox/pand... | ValueError |
def _bool_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = construct_1d_object_array_fr... | def _bool_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = construct_1d_object_array_fr... | https://github.com/pandas-dev/pandas/issues/22092 | ser & idx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/ops.py", line 1481, in wrapper
res_values = na_op(self.values, other)
File "pandas/core/ops.py", line 1439, in na_op
if not isna(y):
ValueError: The truth value of an array with more than one element is ambiguous. Use... | ValueError |
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = construct_1d_object_array_from_listlike(y)
if isinstance(y, (np.ndarray, ABCSeries, ABCIndexClass)):
if is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype):
result... | def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = construct_1d_object_array_from_listlike(y)
if isinstance(y, (np.ndarray, ABCSeries)):
if is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype):
result = op(x, y) # ... | https://github.com/pandas-dev/pandas/issues/22092 | ser & idx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pandas/core/ops.py", line 1481, in wrapper
res_values = na_op(self.values, other)
File "pandas/core/ops.py", line 1439, in na_op
if not isna(y):
ValueError: The truth value of an array with more than one element is ambiguous. Use... | ValueError |
def _apply_index_days(self, i, roll):
"""Add days portion of offset to DatetimeIndex i
Parameters
----------
i : DatetimeIndex
roll : ndarray[int64_t]
Returns
-------
result : DatetimeIndex
"""
nanos = (roll % 2) * Timedelta(days=self.day_of_month).value
i += nanos.astype("... | def _apply_index_days(self, i, roll):
i += (roll % 2) * Timedelta(days=self.day_of_month).value
return i + Timedelta(days=-1)
| https://github.com/pandas-dev/pandas/issues/19123 | dti = pd.date_range('2016-01-01', periods=3, freq='D')
tdi = pd.TimedeltaIndex(['1 day', '2days', '3 days'], freq='D')
arr = np.array([1, 2, 3], dtype=np.int64)
dti + arr
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03'], dtype='datetime64[ns]', freq='86400000000001N')
dti - arr
DatetimeIndex(['2015-12-31 23:5... | TypeError |
def _apply_index_days(self, i, roll):
"""Add days portion of offset to DatetimeIndex i
Parameters
----------
i : DatetimeIndex
roll : ndarray[int64_t]
Returns
-------
result : DatetimeIndex
"""
nanos = (roll % 2) * Timedelta(days=self.day_of_month - 1).value
return i + nano... | def _apply_index_days(self, i, roll):
return i + (roll % 2) * Timedelta(days=self.day_of_month - 1).value
| https://github.com/pandas-dev/pandas/issues/19123 | dti = pd.date_range('2016-01-01', periods=3, freq='D')
tdi = pd.TimedeltaIndex(['1 day', '2days', '3 days'], freq='D')
arr = np.array([1, 2, 3], dtype=np.int64)
dti + arr
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03'], dtype='datetime64[ns]', freq='86400000000001N')
dti - arr
DatetimeIndex(['2015-12-31 23:5... | TypeError |
def apply_index(self, i):
if self.weekday is None:
return (i.to_period("W") + self.n).to_timestamp() + i.to_perioddelta("W")
else:
return self._end_apply_index(i)
| def apply_index(self, i):
if self.weekday is None:
return (i.to_period("W") + self.n).to_timestamp() + i.to_perioddelta("W")
else:
return self._end_apply_index(i, self.freqstr)
| https://github.com/pandas-dev/pandas/issues/19123 | dti = pd.date_range('2016-01-01', periods=3, freq='D')
tdi = pd.TimedeltaIndex(['1 day', '2days', '3 days'], freq='D')
arr = np.array([1, 2, 3], dtype=np.int64)
dti + arr
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03'], dtype='datetime64[ns]', freq='86400000000001N')
dti - arr
DatetimeIndex(['2015-12-31 23:5... | TypeError |
def __init__(self, n=1, normalize=False, week=0, weekday=0):
self.n = self._validate_n(n)
self.normalize = normalize
self.weekday = weekday
self.week = week
if self.n == 0:
raise ValueError("N cannot be 0")
if self.weekday < 0 or self.weekday > 6:
raise ValueError("Day must be ... | def __init__(self, n=1, normalize=False, week=None, weekday=None):
self.n = self._validate_n(n)
self.normalize = normalize
self.weekday = weekday
self.week = week
if self.n == 0:
raise ValueError("N cannot be 0")
if self.weekday < 0 or self.weekday > 6:
raise ValueError("Day mu... | https://github.com/pandas-dev/pandas/issues/19123 | dti = pd.date_range('2016-01-01', periods=3, freq='D')
tdi = pd.TimedeltaIndex(['1 day', '2days', '3 days'], freq='D')
arr = np.array([1, 2, 3], dtype=np.int64)
dti + arr
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03'], dtype='datetime64[ns]', freq='86400000000001N')
dti - arr
DatetimeIndex(['2015-12-31 23:5... | TypeError |
def __init__(self, n=1, normalize=False, weekday=0):
self.n = self._validate_n(n)
self.normalize = normalize
self.weekday = weekday
if self.n == 0:
raise ValueError("N cannot be 0")
if self.weekday < 0 or self.weekday > 6:
raise ValueError("Day must be 0<=day<=6, got {day}".format(... | def __init__(self, n=1, normalize=False, weekday=None):
self.n = self._validate_n(n)
self.normalize = normalize
self.weekday = weekday
if self.n == 0:
raise ValueError("N cannot be 0")
if self.weekday < 0 or self.weekday > 6:
raise ValueError("Day must be 0<=day<=6, got {day}".form... | https://github.com/pandas-dev/pandas/issues/19123 | dti = pd.date_range('2016-01-01', periods=3, freq='D')
tdi = pd.TimedeltaIndex(['1 day', '2days', '3 days'], freq='D')
arr = np.array([1, 2, 3], dtype=np.int64)
dti + arr
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03'], dtype='datetime64[ns]', freq='86400000000001N')
dti - arr
DatetimeIndex(['2015-12-31 23:5... | TypeError |
def drop_duplicates(self, subset=None, keep="first", inplace=False):
"""
Return DataFrame with duplicate rows removed, optionally only
considering certain columns
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying du... | def drop_duplicates(self, subset=None, keep="first", inplace=False):
"""
Return DataFrame with duplicate rows removed, optionally only
considering certain columns
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying du... | https://github.com/pandas-dev/pandas/issues/20516 | pd.DataFrame().drop_duplicates()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/analytical-monk/miniconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 3098, in drop_duplicates
duplicated = self.duplicated(subset, keep=keep)
File "/home/analytical-monk/miniconda3/lib/pytho... | ValueError |
def duplicated(self, subset=None, keep="first"):
"""
Return boolean Series denoting duplicate rows, optionally only
considering certain columns
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
... | def duplicated(self, subset=None, keep="first"):
"""
Return boolean Series denoting duplicate rows, optionally only
considering certain columns
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
... | https://github.com/pandas-dev/pandas/issues/20516 | pd.DataFrame().drop_duplicates()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/analytical-monk/miniconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 3098, in drop_duplicates
duplicated = self.duplicated(subset, keep=keep)
File "/home/analytical-monk/miniconda3/lib/pytho... | ValueError |
def __init__(
self, obj, func, broadcast, raw, reduce, result_type, ignore_failures, args, kwds
):
self.obj = obj
self.raw = raw
self.ignore_failures = ignore_failures
self.args = args or ()
self.kwds = kwds or {}
if result_type not in [None, "reduce", "broadcast", "expand"]:
raise ... | def __init__(
self, obj, func, broadcast, raw, reduce, result_type, ignore_failures, args, kwds
):
self.obj = obj
self.raw = raw
self.ignore_failures = ignore_failures
self.args = args or ()
self.kwds = kwds or {}
if result_type not in [None, "reduce", "broadcast", "expand"]:
raise ... | https://github.com/pandas-dev/pandas/issues/22376 | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<cut>/pandas/core/frame.py", line 6173, in apply
return op.get_result()
File "<cut>/pandas/core/apply.py", line 151, in get_result
return self.apply_standard()
File "<cut>/pandas/core/apply.py", line 257, in apply_standard
self.apply_series_ge... | TypeError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.