gurudesh/pytracebugs huggingface dataset:
# Buggy code
def floor(self, freq):
    return self._round(freq, np.floor)


# Traceback (pytz.exceptions.AmbiguousTimeError)
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
result = method(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 118, in floor
return self._round(freq, np.floor)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 110, in _round
self._shallow_copy(result, **attribs))
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)/venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def floor(self, freq, ambiguous="raise"):
    return self._round(freq, np.floor, ambiguous)
# Buggy code
def ceil(self, freq):
    return self._round(freq, np.ceil)


# Traceback (pytz.exceptions.AmbiguousTimeError)
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
result = method(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 118, in floor
return self._round(freq, np.floor)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 110, in _round
self._shallow_copy(result, **attribs))
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)/venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
def ceil(self, freq, ambiguous="raise"):
    return self._round(freq, np.ceil, ambiguous)
# Buggy code
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
    """

    # reconvert to local tz
    if getattr(self, "tz", None) is not None:
        if not isinstance(result, ABCIndexClass):
            result = self._simple_new(result)
        result = result.tz_localize(self.tz)
    return result


# Traceback (pytz.exceptions.AmbiguousTimeError)
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
result = method(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 118, in floor
return self._round(freq, np.floor)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 110, in _round
self._shallow_copy(result, **attribs))
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimelike.py", line 230, in _ensure_localized
result = result.tz_localize(self.tz)
File "(...)/venv/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "(...)/venv/lib/python3.6/site-packages/pandas/core/indexes/datetimes.py", line 1858, in tz_localize
errors=errors)
File "pandas/_libs/tslib.pyx", line 3593, in pandas._libs.tslib.tz_localize_to_utc
pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the 'ambiguous' argument

# Fixed code
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, or bool-ndarray
        default 'raise'

    Returns
    -------
    localized DTI
    """

    # reconvert to local tz
    if getattr(self, "tz", None) is not None:
        if not isinstance(result, ABCIndexClass):
            result = self._simple_new(result)
        result = result.tz_localize(self.tz, ambiguous=ambiguous)
    return result
# Buggy code
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)
        categories = ensure_object(categories)

    (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)
    (_, _), cats = _get_data_algo(categories, _hashtables)
    t = hash_klass(len(cats))
    t.map_locations(cats)
    return coerce_indexer_dtype(t.lookup(vals), cats)


# Traceback (ValueError)
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/pandas/pandas/core/arrays/categorical.py in __init__(self, values, categories, ordered, dtype, fastpath)
426
427         else:
--> 428             codes = _get_codes_for_values(values, dtype.categories)
429
430         if null_mask.any():

~/sandbox/pandas/pandas/core/arrays/categorical.py in _get_codes_for_values(values, categories)
2449     (_, _), cats = _get_data_algo(categories, _hashtables)
2450     t = hash_klass(len(cats))
-> 2451     t.map_locations(cats)
2452     return coerce_indexer_dtype(t.lookup(vals), cats)
2453

~/sandbox/pandas/pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.map_locations()
1330             raise KeyError(key)
1331
-> 1332     def map_locations(self, ndarray[object] values):
1333         cdef:
1334             Py_ssize_t i, n = len(values)

ValueError: Buffer dtype mismatch, expected 'Python object' but got 'unsigned long'

# Fixed code
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_data_algo, retrieve
        # the underlying numpy array. gh-22702
        values = getattr(values, "values", values)
        categories = getattr(categories, "values", categories)
    else:
        values = ensure_object(values)
        categories = ensure_object(categories)

    (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)
    (_, _), cats = _get_data_algo(categories, _hashtables)
    t = hash_klass(len(cats))
    t.map_locations(cats)
    return coerce_indexer_dtype(t.lookup(vals), cats)
# Buggy code
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)  # when would this be hit?
            else:
                x = ensure_object(x)
                y = ensure_object(y)
                result = libops.vec_binop(x, y, op)
        else:
            # let null fall thru
            if not isna(y):
                y = bool(y)
            try:
                result = libops.scalar_binop(x, y, op)
            except:
                raise TypeError(
                    "cannot compare a dtyped [{dtype}] array "
                    "with a scalar of type [{typ}]".format(
                        dtype=x.dtype, typ=type(y).__name__
                    )
                )

    return result


# Traceback (ValueError)
ser &amp; 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 a.any() or a.all()

# Fixed code
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 = op(x, y)  # when would this be hit?
            else:
                x = ensure_object(x)
                y = ensure_object(y)
                result = libops.vec_binop(x, y, op)
        else:
            # let null fall thru
            if not isna(y):
                y = bool(y)
            try:
                result = libops.scalar_binop(x, y, op)
            except:
                raise TypeError(
                    "cannot compare a dtyped [{dtype}] array "
                    "with a scalar of type [{typ}]".format(
                        dtype=x.dtype, typ=type(y).__name__
                    )
                )

    return result
# Buggy code
def _apply_index_days(self, i, roll):
    i += (roll % 2) * Timedelta(days=self.day_of_month).value
    return i + Timedelta(days=-1)


# Traceback (TypeError)
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:59:59.999999999',
'2016-01-01 23:59:59.999999998',
'2016-01-02 23:59:59.999999997'],
dtype='datetime64[ns]', freq='86399999999999N')

arr + dti
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'DatetimeIndex'

tdi + arr
TimedeltaIndex(['1 days 00:00:00.000000', '2 days 00:00:00.000000',
'3 days 00:00:00.000000'],
dtype='timedelta64[ns]', freq='86400000000001N')

arr + tdi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'TimedeltaIndex'

tdi - arr
TimedeltaIndex(['0 days 23:59:59.999999', '1 days 23:59:59.999999',
'2 days 23:59:59.999999'],
dtype='timedelta64[ns]', freq='86399999999999N')

arr - tdi
TimedeltaIndex(['-1 days +00:00:00.000000', '-2 days +00:00:00.000000',
'-3 days +00:00:00.000000'],
dtype='timedelta64[ns]', freq='-86399999999999N')

# Fixed code
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("timedelta64[ns]")
    return i + Timedelta(days=-1)
# Buggy code
def _apply_index_days(self, i, roll):
    return i + (roll % 2) * Timedelta(days=self.day_of_month - 1).value


# Traceback (TypeError)
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:59:59.999999999',
'2016-01-01 23:59:59.999999998',
'2016-01-02 23:59:59.999999997'],
dtype='datetime64[ns]', freq='86399999999999N')

arr + dti
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'DatetimeIndex'

tdi + arr
TimedeltaIndex(['1 days 00:00:00.000000', '2 days 00:00:00.000000',
'3 days 00:00:00.000000'],
dtype='timedelta64[ns]', freq='86400000000001N')

arr + tdi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'TimedeltaIndex'

tdi - arr
TimedeltaIndex(['0 days 23:59:59.999999', '1 days 23:59:59.999999',
'2 days 23:59:59.999999'],
dtype='timedelta64[ns]', freq='86399999999999N')

arr - tdi
TimedeltaIndex(['-1 days +00:00:00.000000', '-2 days +00:00:00.000000',
'-3 days +00:00:00.000000'],
dtype='timedelta64[ns]', freq='-86399999999999N')

# Fixed code
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 + nanos.astype("timedelta64[ns]")
# Buggy code
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)


# Traceback (TypeError)
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:59:59.999999999',
'2016-01-01 23:59:59.999999998',
'2016-01-02 23:59:59.999999997'],
dtype='datetime64[ns]', freq='86399999999999N')

arr + dti
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'DatetimeIndex'

tdi + arr
TimedeltaIndex(['1 days 00:00:00.000000', '2 days 00:00:00.000000',
'3 days 00:00:00.000000'],
dtype='timedelta64[ns]', freq='86400000000001N')

arr + tdi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'TimedeltaIndex'

tdi - arr
TimedeltaIndex(['0 days 23:59:59.999999', '1 days 23:59:59.999999',
'2 days 23:59:59.999999'],
dtype='timedelta64[ns]', freq='86399999999999N')

arr - tdi
TimedeltaIndex(['-1 days +00:00:00.000000', '-2 days +00:00:00.000000',
'-3 days +00:00:00.000000'],
dtype='timedelta64[ns]', freq='-86399999999999N')

# Fixed code
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)
# Buggy code
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 must be 0<=day<=6, got {day}".format(day=self.weekday))
    if self.week < 0 or self.week > 3:
        raise ValueError("Week must be 0<=week<=3, got {week}".format(week=self.week))

    self.kwds = {"weekday": weekday, "week": week}


# Traceback (TypeError)
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:59:59.999999999',
'2016-01-01 23:59:59.999999998',
'2016-01-02 23:59:59.999999997'],
dtype='datetime64[ns]', freq='86399999999999N')

arr + dti
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'DatetimeIndex'

tdi + arr
TimedeltaIndex(['1 days 00:00:00.000000', '2 days 00:00:00.000000',
'3 days 00:00:00.000000'],
dtype='timedelta64[ns]', freq='86400000000001N')

arr + tdi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'TimedeltaIndex'

tdi - arr
TimedeltaIndex(['0 days 23:59:59.999999', '1 days 23:59:59.999999',
'2 days 23:59:59.999999'],
dtype='timedelta64[ns]', freq='86399999999999N')

arr - tdi
TimedeltaIndex(['-1 days +00:00:00.000000', '-2 days +00:00:00.000000',
'-3 days +00:00:00.000000'],
dtype='timedelta64[ns]', freq='-86399999999999N')

# Fixed code
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 0<=day<=6, got {day}".format(day=self.weekday))
    if self.week < 0 or self.week > 3:
        raise ValueError("Week must be 0<=week<=3, got {week}".format(week=self.week))

    self.kwds = {"weekday": weekday, "week": week}
# Buggy code
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}".format(day=self.weekday))

    self.kwds = {"weekday": weekday}


# Traceback (TypeError)
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:59:59.999999999',
'2016-01-01 23:59:59.999999998',
'2016-01-02 23:59:59.999999997'],
dtype='datetime64[ns]', freq='86399999999999N')

arr + dti
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'DatetimeIndex'

tdi + arr
TimedeltaIndex(['1 days 00:00:00.000000', '2 days 00:00:00.000000',
'3 days 00:00:00.000000'],
dtype='timedelta64[ns]', freq='86400000000001N')

arr + tdi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'TimedeltaIndex'

tdi - arr
TimedeltaIndex(['0 days 23:59:59.999999', '1 days 23:59:59.999999',
'2 days 23:59:59.999999'],
dtype='timedelta64[ns]', freq='86399999999999N')

arr - tdi
TimedeltaIndex(['-1 days +00:00:00.000000', '-2 days +00:00:00.000000',
'-3 days +00:00:00.000000'],
dtype='timedelta64[ns]', freq='-86399999999999N')

# Fixed code
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(day=self.weekday))

    self.kwds = {"weekday": weekday}
# Buggy code
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 duplicates, by
        default use all of the columns
    keep : {'first', 'last', False}, default 'first'
        - ``first`` : Drop duplicates except for the first occurrence.
        - ``last`` : Drop duplicates except for the last occurrence.
        - False : Drop all duplicates.
    inplace : boolean, default False
        Whether to drop duplicates in place or to return a copy

    Returns
    -------
    deduplicated : DataFrame
    """
    inplace = validate_bool_kwarg(inplace, "inplace")
    duplicated = self.duplicated(subset, keep=keep)

    if inplace:
        (inds,) = (-duplicated).nonzero()
        new_data = self._data.take(inds)
        self._update_inplace(new_data)
    else:
        return self[-duplicated]


# Traceback (ValueError)
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/python3.6/site-packages/pandas/core/frame.py", line 3144, in duplicated
labels, shape = map(list, zip(*map(f, vals)))
ValueError: not enough values to unpack (expected 2, got 0)

# Fixed code
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 duplicates, by
        default use all of the columns
    keep : {'first', 'last', False}, default 'first'
        - ``first`` : Drop duplicates except for the first occurrence.
        - ``last`` : Drop duplicates except for the last occurrence.
        - False : Drop all duplicates.
    inplace : boolean, default False
        Whether to drop duplicates in place or to return a copy

    Returns
    -------
    deduplicated : DataFrame
    """
    if self.empty:
        return self.copy()

    inplace = validate_bool_kwarg(inplace, "inplace")
    duplicated = self.duplicated(subset, keep=keep)

    if inplace:
        (inds,) = (-duplicated).nonzero()
        new_data = self._data.take(inds)
        self._update_inplace(new_data)
    else:
        return self[-duplicated]
# Buggy code
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'",
            FutureWarning,
            stacklevel=2,
        )

        if raise_on_error:
            errors = "raise"
        else:
            errors = "ignore"

    inplace = validate_bool_kwarg(inplace, "inplace")
    cond = com._apply_if_callable(cond, self)

    return self.where(
        ~cond,
        other=other,
        inplace=inplace,
        axis=axis,
        level=level,
        try_cast=try_cast,
        errors=errors,
    )


# Traceback (TypeError)
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, other=other, inplace=inplace, axis=axis,
# TypeError: bad operand type for unary ~: 'list'

# Fixed code
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'",
            FutureWarning,
            stacklevel=2,
        )

        if raise_on_error:
            errors = "raise"
        else:
            errors = "ignore"

    inplace = validate_bool_kwarg(inplace, "inplace")
    cond = com._apply_if_callable(cond, self)

    # see gh-21891
    if not hasattr(cond, "__invert__"):
        cond = np.array(cond)

    return self.where(
        ~cond,
        other=other,
        inplace=inplace,
        axis=axis,
        level=level,
        try_cast=try_cast,
        errors=errors,
    )
# Buggy code
def _consensus_name_attr(objs):
    name = objs[0].name
    for obj in objs[1:]:
        if obj.name != name:
            return None
    return name


# Traceback (ValueError)
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>()
----> 1 pd.concat([s1, s2])

~/scipy/pandas/pandas/core/reshape/concat.py in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, sort, copy)
224                        verify_integrity=verify_integrity,
225                        copy=copy, sort=sort)
--> 226     return op.get_result()
227
228

~/scipy/pandas/pandas/core/reshape/concat.py in get_result(self)
385             # stack blocks
386             if self.axis == 0:
--> 387                 name = com._consensus_name_attr(self.objs)
388
389                 mgr = self.objs[0]._data.concat([x._data for x in self.objs],

~/scipy/pandas/pandas/core/common.py in _consensus_name_attr(objs)
56     name = objs[0].name
57     for obj in objs[1:]:
---> 58         if obj.name != name:
59             return None
60     return name

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Fixed code
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
# Buggy code
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 isinstance(label, IntervalMixin):
        raise NotImplementedError

    if (side == "left" and self.left.is_monotonic_increasing) or (
        side == "right" and self.left.is_monotonic_decreasing
    ):
        sub_idx = self.right
        if self.open_right or exclude_label:
            label = _get_next_label(label)
    else:
        sub_idx = self.left
        if self.open_left or exclude_label:
            label = _get_prev_label(label)

    return sub_idx._searchsorted_monotonic(label, side)


# Traceback (KeyError)
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

# Fixed code
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 isinstance(label, IntervalMixin):
        raise NotImplementedError

    # GH 20921: "not is_monotonic_increasing" for the second condition
    # instead of "is_monotonic_decreasing" to account for single element
    # indexes being both increasing and decreasing
    if (side == "left" and self.left.is_monotonic_increasing) or (
        side == "right" and not self.left.is_monotonic_increasing
    ):
        sub_idx = self.right
        if self.open_right or exclude_label:
            label = _get_next_label(label)
    else:
        sub_idx = self.left
        if self.open_left or exclude_label:
            label = _get_prev_label(label)

    return sub_idx._searchsorted_monotonic(label, side)
# Buggy code
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 np.nan
    return _na_map(f, arr)


# Traceback (KeyError)
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/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 1264, in str_get
return _na_map(f, arr)
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 156, in _na_map
return _map(f, arr, na_mask=True, na_value=na_result, dtype=dtype)
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 171, in _map
result = lib.map_infer_mask(arr, f, mask.view(np.uint8), convert)
File "pandas/_libs/src/inference.pyx", line 1482, in pandas._libs.lib.map_infer_mask
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 1263, in <lambda>
f = lambda x: x[i] if len(x) > i >= -len(x) else np.nan
KeyError: -1

# Fixed code
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):
            return x.get(i)
        elif len(x) > i >= -len(x):
            return x[i]
        return np.nan

    return _na_map(f, arr)
# Buggy code
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


# Traceback (KeyError)
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/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 1264, in str_get
return _na_map(f, arr)
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 156, in _na_map
return _map(f, arr, na_mask=True, na_value=na_result, dtype=dtype)
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 171, in _map
result = lib.map_infer_mask(arr, f, mask.view(np.uint8), convert)
File "pandas/_libs/src/inference.pyx", line 1482, in pandas._libs.lib.map_infer_mask
File "/home/mgarcia/.anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 1263, in <lambda>
f = lambda x: x[i] if len(x) > i >= -len(x) else np.nan
KeyError: -1

# Fixed code
def f(x):
    if isinstance(x, dict):
        return x.get(i)
    elif len(x) > i >= -len(x):
        return x[i]
    return np.nan
# Buggy code
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 getattr(g, "table", None)
            or (isinstance(g, _table_mod.table.Table) and g._v_name != u("table"))
        )
    ]


# Traceback (KeyError)
#! /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.HDFStore("/tmp/test.hdf", mode="r")
'''
Traceback (most recent call last):
File "snippet.py", line 31, in <module>
print(hdf.keys())
File "python3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 529, in keys
return [n._v_pathname for n in self.groups()]
File "python3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 1077, in groups
g for g in self._handle.walk_nodes()
File "python3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 1078, in <listcomp>
if (getattr(g._v_attrs, 'pandas_type', None) or
File "python3.6.3/lib/python3.6/site-packages/tables/link.py", line 79, in __getattr__
"`%s` instance" % self.__class__.__name__)
KeyError: 'you cannot get attributes from this `NoAttrs` instance'
'''
print(hdf.keys()) #causes exception
hdf.close()

print("Successful read")

# Fixed code
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 (
                getattr(g._v_attrs, "pandas_type", None)
                or getattr(g, "table", None)
                or (isinstance(g, _table_mod.table.Table) and g._v_name != u("table"))
            )
        )
    ]
# Buggy code
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()


# Traceback (TypeError)
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 recent call last)
<ipython-input-1-290d71fd5bc3> in <module>()
3 x = pd.MultiIndex.from_tuples([(1, 2), (3, 4)]. names=['a', 'b'])
4 y = x[np.array([False, False])]
----> 5 y.unique()

C:\projects\pandas-dk\pandas\core\indexes\multi.py in unique(self, level)
1072
1073         if level is None:
-> 1074             return super(MultiIndex, self).unique()
1075         else:
1076             level = self._get_level_number(level)

C:\projects\pandas-dk\pandas\core\indexes\base.py in unique(self, level)
3971             self._validate_index_level(level)
3972         result = super(Index, self).unique()
-> 3973         return self._shallow_copy(result)
3974
3975     @Appender(base._shared_docs['drop_duplicates'] % _index_doc_kwargs)

C:\projects\pandas-dk\pandas\core\indexes\multi.py in _shallow_copy(self, values, **kwargs)
559             # discards freq
560             kwargs.pop('freq', None)
--> 561             return MultiIndex.from_tuples(values, **kwargs)
562         return self.view()
563

C:\projects\pandas-dk\pandas\core\indexes\multi.py in from_tuples(cls, tuples, sortorder, names)
1316             if names is None:
1317                 msg = 'Cannot infer number of levels from empty list'
-> 1318                 raise TypeError(msg)
1319             arrays = [[]] * len(names)
1320         elif isinstance(tuples, (np.ndarray, Index)):

TypeError: Cannot infer number of levels from empty list

# Fixed code
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()
# Buggy code
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_dtype(x):
        x = to_datetime(x).view(np.int64)
        dtype = np.datetime64

    return x, dtype


# Traceback (ValueError)
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 _bins_to_cuts
dtype=dtype)
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/reshape/tile.py", line 344, in _format_labels
labels = IntervalIndex.from_breaks(breaks, closed=closed)
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/indexes/interval.py", line 370, in from_breaks
name=name, copy=copy)
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/indexes/interval.py", line 411, in from_arrays
copy=copy, verify_integrity=True)
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/indexes/interval.py", line 225, in _simple_new
result._validate()
File "/tmp/test/env/lib/python3.5/site-packages/pandas/core/indexes/interval.py", line 265, in _validate
raise ValueError('missing values must be missing in the same '
ValueError: missing values must be missing in the same location both left and right sides

# Fixed code
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):
        x = to_datetime(x)
        dtype = np.datetime64

    if dtype is not None:
        # GH 19768: force NaT to NaN during integer conversion
        x = np.where(x.notna(), x.view(np.int64), np.nan)

    return x, dtype
# Buggy code
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
    """
    arr_dtype = "object" if self.dtype == "object" else None
    labels = _index_labels_to_array(labels, dtype=arr_dtype)
    indexer = self.get_indexer(labels)
    mask = indexer == -1
    if mask.any():
        if errors != "ignore":
            raise ValueError("labels %s not contained in axis" % labels[mask])
        indexer = indexer[~mask]
    return self.delete(indexer)


# Traceback (ValueError)
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", line 2562, in _drop_axis
new_axis = axis.drop(labels, errors=errors)
File "/usr/local/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3744, in drop
labels[mask])
ValueError: labels ['abcd'] not contained in axis

# Fixed code
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

    Raises
    ------
    KeyError
        If none of the labels are found in the selected axis
    """
    arr_dtype = "object" if self.dtype == "object" else None
    labels = _index_labels_to_array(labels, dtype=arr_dtype)
    indexer = self.get_indexer(labels)
    mask = indexer == -1
    if mask.any():
        if errors != "ignore":
            raise KeyError("labels %s not contained in axis" % labels[mask])
        indexer = indexer[~mask]
    return self.delete(indexer)
# Buggy code
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 isinstance(other, list):
            other = DatetimeIndex(other)
        elif not isinstance(other, (np.ndarray, Index, ABCSeries)):
            other = _ensure_datetime64(other)
        result = func(np.asarray(other))
        result = _values_from_object(result)

        if isinstance(other, Index):
            o_mask = other.values.view("i8") == libts.iNaT
        else:
            o_mask = other.view("i8") == libts.iNaT

        if o_mask.any():
            result[o_mask] = nat_result

    if self.hasnans:
        result[self._isnan] = nat_result

    # support of bool dtype indexers
    if is_bool_dtype(result):
        return result
    return Index(result)


# Traceback (TypeError)
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__
File "pandas/_libs/tslib.pyx", line 1230, in pandas._libs.tslib._Timestamp._assert_tzawareness_compat
TypeError: Cannot compare tz-naive and tz-aware timestamps

# Fixed code
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_m8(other, tz=self.tz)
        result = func(other)
        if isna(other):
            result.fill(nat_result)
    else:
        if isinstance(other, list):
            other = DatetimeIndex(other)
        elif not isinstance(other, (np.ndarray, Index, ABCSeries)):
            other = _ensure_datetime64(other)

        if is_datetimelike(other):
            self._assert_tzawareness_compat(other)

        result = func(np.asarray(other))
        result = _values_from_object(result)

        if isinstance(other, Index):
            o_mask = other.values.view("i8") == libts.iNaT
        else:
            o_mask = other.view("i8") == libts.iNaT

        if o_mask.any():
            result[o_mask] = nat_result

    if self.hasnans:
        result[self._isnan] = nat_result

    # support of bool dtype indexers
    if is_bool_dtype(result):
        return result
    return Index(result)
# Buggy code
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, Index):
        if hasattr(other, "_add_delta"):
            return other._add_delta(self)
        raise TypeError("cannot add TimedeltaIndex and {typ}".format(typ=type(other)))
    elif isinstance(other, (DateOffset, timedelta)):
        return self._add_delta(other)
    elif is_integer(other):
        return self.shift(other)
    elif isinstance(other, (datetime, np.datetime64)):
        return self._add_datelike(other)
    elif is_offsetlike(other):
        # Array/Index of DateOffset objects
        return self._add_offset_array(other)
    elif isinstance(other, Index):
        return self._add_datelike(other)
    else:  # pragma: no cover
        return NotImplemented


# Traceback (TypeError)
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 object

# Fixed code
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, TimedeltaIndex) and isinstance(other, Index):
        if hasattr(other, "_add_delta"):
            return other._add_delta(self)
        raise TypeError("cannot add TimedeltaIndex and {typ}".format(typ=type(other)))
    elif isinstance(other, (DateOffset, timedelta)):
        return self._add_delta(other)
    elif is_integer(other):
        return self.shift(other)
    elif isinstance(other, (datetime, np.datetime64)):
        return self._add_datelike(other)
    elif is_offsetlike(other):
        # Array/Index of DateOffset objects
        return self._add_offset_array(other)
    elif isinstance(other, Index):
        return self._add_datelike(other)
    else:  # pragma: no cover
        return NotImplemented
# Buggy code
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")


# Traceback (TypeError)
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 object

# Fixed code
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")
# Buggy code
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(
        self_i8, other_i8, arr_mask=self._isnan, b_mask=other._isnan
    )
    if self.hasnans or other.hasnans:
        mask = (self._isnan) | (other._isnan)
        new_values[mask] = iNaT
    return new_values.view("i8")


# Traceback (TypeError)
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 object

# Fixed code
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(
        self_i8, other_i8, arr_mask=self._isnan, b_mask=other._isnan
    )
    if self.hasnans or other.hasnans:
        mask = (self._isnan) | (other._isnan)
        new_values[mask] = iNaT
    return new_values.view("i8")