internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pandas-dev/pandas

Issue:
unexpected join behavior for datetime indexes with integers
I can't tell if this is bug or not. I think object indices should stay as object indices if they are originally mixed, but currently an index join converts something date-ish to dates...

```
In [9]: df = mkdf(10, 10, data_gen_f=lambda*args:randn(), r_idx_type='i', c_idx_type='dt')

In [10]: df.columns.join(df.index, how='outer').join(df.columns)
Out[10]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2000-01-03 00:00:00, ..., 1970-01-01 00:00:00.000000009]
Length: 20, Freq: None, Timezone: None
```

this could be an edge case, but it's a problem when trying to join indexes in a general way for upcoming `pandas.eval`...i.e., i can't just call `align`.



Discussion:

Resolving patch:
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -910,7 +910,8 @@ def join(self, other, how='left', level=None, return_indexers=False):
         """
         See Index.join
         """
-        if not isinstance(other, DatetimeIndex) and len(other) > 0:
+        if (not isinstance(other, DatetimeIndex) and len(other) > 0 and
+            other.inferred_type != 'mixed-integer'):
             try:
                 other = DatetimeIndex(other)
             except TypeError:


Test patch:
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -18,7 +18,6 @@
 import pandas.core.datetools as datetools
 import pandas.tseries.offsets as offsets
 import pandas.tseries.frequencies as fmod
-from pandas.tseries.index import TimeSeriesError
 import pandas as pd
 
 from pandas.util.testing import assert_series_equal, assert_almost_equal
@@ -1853,6 +1852,14 @@ def test_date(self):
         expected = [t.date() for t in rng]
         self.assert_((result == expected).all())
 
+    def test_does_not_convert_mixed_integer(self):
+        df = tm.makeCustomDataframe(10, 10, data_gen_f=lambda *args, **kwargs:
+                                    randn(), r_idx_type='i', c_idx_type='dt')
+        cols = df.columns.join(df.index, how='outer')
+        joined = cols.join(df.columns)
+        self.assertEqual(cols.dtype, np.dtype('O'))
+        self.assertEqual(cols.dtype, joined.dtype)
+        self.assert_(np.array_equal(cols.values, joined.values))
 
 class TestLegacySupport(unittest.TestCase):
     _multiprocess_can_split_ = True
Repository: pandas-dev/pandas

Issue:
itertuples() fails after selecting a column twice
The following code gives incorrect result (using pandas 0.11):

``` python
import pandas
df = pandas.DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
print df[["a", "a"]].values # works
print list(df[["a", "a"]].itertuples()) # FAILS!
```

The last lines prints [(0, 'a', 'a'), (1, 'a', 'a')] instead of [(0, 1, 1), (1, 2, 2), (2, 3, 3)].



Discussion:
i can repro this...prolly a bug.


Resolving patch:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -818,7 +818,9 @@ def itertuples(self, index=True):
         arrays = []
         if index:
             arrays.append(self.index)
-        arrays.extend(self[k] for k in self.columns)
+
+        # use integer indexing because of possible duplicate column names
+        arrays.extend(self.iloc[:, k] for k in xrange(len(self.columns)))
         return izip(*arrays)
 
     iterkv = iteritems


Test patch:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -3951,6 +3951,10 @@ def test_itertuples(self):
         for tup in df.itertuples(index=False):
             self.assert_(isinstance(tup[1], np.integer))
 
+        df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
+        dfaa = df[['a', 'a']]
+        self.assertEqual(list(dfaa.itertuples()), [(0, 1, 1), (1, 2, 2), (2, 3, 3)])
+
     def test_len(self):
         self.assertEqual(len(self.frame), len(self.frame.index))
Repository: pandas-dev/pandas

Issue:
Setup.py should define setup_requires=
We have trouble combining pandas with <a href="http://buildout.org">buildout</a>. It looks like pandas depends on numpy during the setup phase, but it doesn't it declare the `setup_requires` (<a href="http://pythonhosted.org/distribute/setuptools.html">ref</a>) directive in setup.py. Any reason why this feature remains unused, or shall I submit a pull request? Because I see the matplotlib and numexpr don't use it as well.



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -34,9 +34,9 @@
     _have_setuptools = False
 
 setuptools_kwargs = {}
+min_numpy_ver = '1.6'
 if sys.version_info[0] >= 3:
 
-    min_numpy_ver = 1.6
     if sys.version_info[1] >= 3:  # 3.3 needs numpy 1.7+
         min_numpy_ver = "1.7.0b2"
 
@@ -45,6 +45,7 @@
                          'install_requires': ['python-dateutil >= 2',
                                               'pytz',
                                               'numpy >= %s' % min_numpy_ver],
+                         'setup_requires': ['numpy >= %s' % min_numpy_ver],
                          'use_2to3_exclude_fixers': ['lib2to3.fixes.fix_next',
                                                      ],
                          }
@@ -53,10 +54,12 @@
                  "\n$ pip install distribute")
 
 else:
+    min_numpy_ver = '1.6.1'
     setuptools_kwargs = {
         'install_requires': ['python-dateutil',
                              'pytz',
-                             'numpy >= 1.6.1'],
+                             'numpy >= %s' % min_numpy_ver],
+        'setup_requires': ['numpy >= %s' % min_numpy_ver],
         'zip_safe': False,
     }
 


Test patch:
Repository: pandas-dev/pandas

Issue:
Bad grammar in exception message: "If use all scalar values, must pass index"
I found this little gem here:

```
File ".....lib/python2.7/site-packages/pandas/core/frame.py" in extract_index
5366.             raise ValueError('If use all scalar values, must pass index')

Exception Type: ValueError at /reporting/reports/7/preview
Exception Value: If use all scalar values, must pass index
```

Just wanted to point that out. It's not urgent or very grave.



Discussion:

Resolving patch:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5713,7 +5713,8 @@ def extract_index(data):
                 raw_lengths.append(len(v))
 
         if not indexes and not raw_lengths:
-            raise ValueError('If use all scalar values, must pass index')
+            raise ValueError('If using all scalar values, you must must pass'
+                             ' an index')
 
         if have_series or have_dicts:
             index = _union_indexes(indexes)


Test patch:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -2245,8 +2245,9 @@ def test_constructor_error_msgs(self):
         try:
             DataFrame({'a': False, 'b': True})
         except (Exception), detail:
+            msg = 'If using all scalar values, you must must pass an index'
             self.assert_(type(detail) == ValueError)
-            self.assert_("If use all scalar values, must pass index" in str(detail))
+            self.assert_(msg in str(detail))
 
     def test_constructor_subclass_dict(self):
         # Test for passing dict subclass to constructor
Repository: pandas-dev/pandas

Issue:
Problem with Series.clip with Timestamp threshold
```
>>> import pandas as pd
>>> s = pd.Series(pd.date_range('2013-05-01', '2013-05-03'))
>>> s
0   2013-05-01 00:00:00
1   2013-05-02 00:00:00
2   2013-05-03 00:00:00
dtype: datetime64[ns]

>>> s.clip_lower(s[1])
0    2013-05-02 00:00:00
1    1367452800000000000
2    1367539200000000000
dtype: object

>>> s.clip_lower(s[1].value)
0   2013-05-02 00:00:00
1   2013-05-02 00:00:00
2   2013-05-03 00:00:00
dtype: datetime64[ns]

>>> print pd.__version__
0.11.1.dev-f1a3226
```

Any reason not to implement clip_lower and clip_upper with Series.where rather than np.where? It solves this problem.



Discussion:
yes....`Serise.where` knows how to deal with `datetime64[ns]` and `NaT` so that would be a good change

if you want to do a PR, pls add a test for this (and see that existing tests pass)

thanks!


Resolving patch:
diff --git a/pandas/core/series.py b/pandas/core/series.py
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1984,7 +1984,10 @@ def clip_upper(self, threshold):
         -------
         clipped : Series
         """
-        return pa.where(self > threshold, threshold, self)
+        if isnull(threshold):
+            raise ValueError("Cannot use an NA value as a clip threshold")
+
+        return self.where((self <= threshold) | isnull(self), threshold)
 
     def clip_lower(self, threshold):
         """
@@ -1998,7 +2001,10 @@ def clip_lower(self, threshold):
         -------
         clipped : Series
         """
-        return pa.where(self < threshold, threshold, self)
+        if isnull(threshold):
+            raise ValueError("Cannot use an NA value as a clip threshold")
+
+        return self.where((self >= threshold) | isnull(self), threshold)
 
     def dot(self, other):
         """


Test patch:
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -2840,6 +2840,21 @@ def test_clip(self):
         assert_series_equal(result, expected)
         self.assert_(isinstance(expected, Series))
 
+    def test_clip_types_and_nulls(self):
+
+        sers = [Series([np.nan, 1.0, 2.0, 3.0]),
+                Series([None, 'a', 'b', 'c']),
+                Series(pd.to_datetime([np.nan, 1, 2, 3], unit='D'))]
+
+        for s in sers:
+            thresh = s[2]
+            l = s.clip_lower(thresh)
+            u = s.clip_upper(thresh)
+            self.assertEqual(l[notnull(l)].min(), thresh)
+            self.assertEqual(u[notnull(u)].max(), thresh)
+            self.assertEqual(list(isnull(s)), list(isnull(l)))
+            self.assertEqual(list(isnull(s)), list(isnull(u)))
+
     def test_valid(self):
         ts = self.ts.copy()
         ts[::2] = np.NaN
Repository: pandas-dev/pandas

Issue:
Dropna=False is ignored for MultiIndex stack.
```

>>> df = pd.DataFrame({'A': ['a1', 'a2'], 'B': ['b1', 'b2'], 'C': [1, 1]})
>>> df
    A   B  C
0  a1  b1  1
1  a2  b2  1

# Unstack introduces some NaNs
>>> df.set_index(['A', 'B']).unstack()
     C    
B   b1  b2
A         
a1   1 NaN
a2 NaN   1

# Stack with dropna=False should keep the NaNs, but doesn't.
>>> df.set_index(['A', 'B']).unstack().stack(dropna=False)
       C
A  B    
a1 b1  1
a2 b2  1

# This is what I expected to get
>>> df.set_index(['A', 'B']).unstack().stack(dropna=False)
        C
A  B     
a1 b1   1
   b2 NaN
a2 b1 NaN
   b2   1
```

The problem seems to be with reshape.py, line 495 with forces dropna=True.

```
if isinstance(frame.columns, MultiIndex):
    return _stack_multi_columns(frame, level=level, dropna=True)
```



Discussion:

Resolving patch:
diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py
--- a/pandas/core/reshape.py
+++ b/pandas/core/reshape.py
@@ -492,7 +492,7 @@ def stack(frame, level=-1, dropna=True):
     level = frame.columns._get_level_number(level)
 
     if isinstance(frame.columns, MultiIndex):
-        return _stack_multi_columns(frame, level=level, dropna=True)
+        return _stack_multi_columns(frame, level=level, dropna=dropna)
     elif isinstance(frame.index, MultiIndex):
         new_levels = list(frame.index.levels)
         new_levels.append(frame.columns)


Test patch:
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -948,6 +948,19 @@ def test_stack_multiple_bug(self):
         xp.columns.name = 'Params'
         assert_frame_equal(rs, xp)
 
+    def test_stack_dropna(self):
+        # GH #3997
+        df = pd.DataFrame({'A': ['a1', 'a2'], 
+                           'B': ['b1', 'b2'], 
+                           'C': [1, 1]})
+        df = df.set_index(['A', 'B'])
+
+        stacked = df.unstack().stack(dropna=False)
+        self.assertTrue(len(stacked) > len(stacked.dropna()))
+
+        stacked = df.unstack().stack(dropna=True)
+        assert_frame_equal(stacked, stacked.dropna())
+
     def test_unstack_multiple_hierarchical(self):
         df = DataFrame(index=[[0, 0, 0, 0, 1, 1, 1, 1],
                               [0, 0, 1, 1, 0, 0, 1, 1],
Repository: pandas-dev/pandas

Issue:
df.groupby() does not allow to use name of index at level 0 when not using a MultiIndex
``` python
In [24]: df = pd.DataFrame({
   ....:         'exp' : ['A']*3 + ['B']*3,
   ....:         'var1' : range(6),
   ....:         })

In [25]: df = df.set_index(['exp'])

In [26]: df.index.names
Out[27]: ['exp']


In [28]: df
Out[28]:
     var1
exp
A       0
A       1
A       2
B       3
B       4
B       5

In [29]: try:
   ....:             df.groupby(level='exp').size()
   ....: except ValueError as e:
   ....:             print('index can not be accessed by name')
   ....:             print(e)
   ....:
index can not be accessed by name
level > 0 only valid with MultiIndex
# at this point I would argue that the level 'exp' is level 0,
# and therefore this should work.

In [29]: df1 = df.groupby(level=0).size()

In [30]: df1
Out[30]:
exp
A      3
B      3
dtype: int64
```



Discussion:
Good find. I've put a fix together for this (coming shortly).

Note: although in python 2 'exp' > 0 in py3 this raises an error.


Resolving patch:
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1252,11 +1252,14 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True):
 
     if level is not None:
         if not isinstance(group_axis, MultiIndex):
-            if level > 0:
+            if isinstance(level, basestring):
+                if obj.index.name != level:
+                    raise ValueError('level name %s is not the name of the index' % level)
+            elif level > 0:
                 raise ValueError('level > 0 only valid with MultiIndex')
-            else:
-                level = None
-                key = group_axis
+            
+            level = None
+            key = group_axis
 
     if isinstance(key, CustomGrouper):
         gpr = key.get_grouper(obj)


Test patch:
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -1414,6 +1414,12 @@ def test_groupby_level(self):
         # raise exception for non-MultiIndex
         self.assertRaises(ValueError, self.df.groupby, level=1)
 
+    def test_groupby_level_index_names(self):
+        ## GH4014 this used to raise ValueError since 'exp'>1 (in py2)
+        df = DataFrame({'exp' : ['A']*3 + ['B']*3, 'var1' : range(6),}).set_index('exp')
+        df.groupby(level='exp')
+        self.assertRaises(ValueError, df.groupby, level='foo')
+
     def test_groupby_level_with_nas(self):
         index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],
                            labels=[[1, 1, 1, 1, 0, 0, 0, 0],
Repository: pandas-dev/pandas

Issue:
tox invocation is broken for python >= 3.2
invocation error due to pickle import. this happens after recreating the cache



Discussion:

Resolving patch:
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -1,8 +1,5 @@
-# XXX: HACK for NumPy 1.5.1 to suppress warnings
-try:
-    import cPickle as pickle
-except ImportError:  # pragma: no cover
-    import pickle
+import cPickle as pkl
+
 
 def to_pickle(obj, path):
     """
@@ -14,11 +11,9 @@ def to_pickle(obj, path):
     path : string
         File path
     """
-    f = open(path, 'wb')
-    try:
-        pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
-    finally:
-        f.close()
+    with open(path, 'wb') as f:
+        pkl.dump(obj, f, protocol=pkl.HIGHEST_PROTOCOL)
+
 
 def read_pickle(path):
     """
@@ -38,11 +33,11 @@ def read_pickle(path):
     unpickled : type of object stored in file
     """
     try:
-        with open(path,'rb') as fh:
-            return pickle.load(fh)
+        with open(path, 'rb') as fh:
+            return pkl.load(fh)
     except:
-        from pandas.util import py3compat
-        if not py3compat.PY3:
-            raise
-        with open(path,'rb') as fh:
-            return pickle.load(fh, encoding='latin1')
\ No newline at end of file
+        from pandas.util.py3compat import PY3
+        if PY3:
+            with open(path, 'rb') as fh:
+                return pkl.load(fh, encoding='latin1')
+        raise


Test patch:
Repository: pandas-dev/pandas

Issue:
BUG: AssertionError using mask on a dataframe with shape (1, n)
Using a DataFrame of bools to mask some values in another dataframe works great:

``` python
In [84]: pd.DataFrame([[1,2],[3,4]]).mask(pd.DataFrame([[True,False],[False, True]]))
Out[84]: 
    0   1
0 NaN   2
1   3 NaN
```

but not if we try on a dataframe with a single index:

``` python
In [85]: pd.DataFrame([[1,2],]).mask(pd.DataFrame([[True,False],]))
AssertionError: Number of Block dimensions (1) must equal number of axes (2)
```



Discussion:
what version are you using?

0.11.0

different error on latest master ... marked as a bug for 0.13


Resolving patch:
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -575,9 +575,10 @@ def func(c,v,o):
             return make_block(result, self.items, self.ref_items)
 
         # might need to separate out blocks
-        axis = cond.ndim-1
-        cond = cond.swapaxes(axis,0)
-        mask = np.array([ cond[i].all() for i in enumerate(range(cond.shape[0]))],dtype=bool)
+        axis = cond.ndim - 1
+        cond = cond.swapaxes(axis, 0)
+        mask = np.array([cond[i].all() for i in xrange(cond.shape[0])],
+                        dtype=bool)
 
         result_blocks = []
         for m in [mask, ~mask]:


Test patch:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -7675,6 +7675,13 @@ def test_mask(self):
         assert_frame_equal(rs, df.mask(df <= 0))
         assert_frame_equal(rs, df.mask(~cond))
 
+    def test_mask_edge_case_1xN_frame(self):
+        # GH4071
+        df = DataFrame([[1, 2]])
+        res = df.mask(DataFrame([[True, False]]))
+        expec = DataFrame([[nan, 2]])
+        assert_frame_equal(res, expec)
+
     #----------------------------------------------------------------------
     # Transposing
     def test_transpose(self):
Repository: pandas-dev/pandas

Issue:
more descriptive error message when assigning dataframe with different index shape to column
http://stackoverflow.com/questions/17432944/python-pandas-error-when-doing-groupby-counts

The below example doesn't make sense, but perhaps the error message could be clearer...

```
df = pd.DataFrame(np.random.randint(0,2,(4,4)),
                  columns=['a', 'b', 'c', 'd'])

In [11]: df
Out[11]:
   a  b  c  d  gr
0  0  1  1  0   1
1  1  1  1  0   1
2  0  1  1  0   1
3  1  1  0  1   0

In [12]: df.groupby(['b', 'c']).count()
Out[12]:
     a  b  c  d  gr
b c
1 0  1  1  1  1   1
  1  3  3  3  3   3

df['gr'] = df.groupby(['b', 'c']).count()
---------------------------------------------------------------------------
ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long'
```



Discussion:
`TypeError: incompatible index of inserted column with frame index`

better?


Resolving patch:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2190,7 +2190,13 @@ def _sanitize_column(self, key, value):
                     # copy the values
                     value = value.values.copy()
                 else:
-                    value = value.reindex(self.index).values
+
+                    # GH 4107
+                    try:
+                        value = value.reindex(self.index).values
+                    except:
+                        raise TypeError('incompatible index of inserted column '
+                                        'with frame index')
 
                 if is_frame:
                     value = value.T


Test patch:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -2250,6 +2250,19 @@ def test_constructor_error_msgs(self):
             self.assert_(type(detail) == ValueError)
             self.assert_(msg in str(detail))
 
+    def test_insert_error_msmgs(self):
+
+        # GH 4107, more descriptive error message
+        df = DataFrame(np.random.randint(0,2,(4,4)),
+                       columns=['a', 'b', 'c', 'd'])
+
+        try:
+            df['gr'] = df.groupby(['b', 'c']).count()
+        except (Exception), detail:
+            msg = 'incompatible index of inserted column with frame index'
+            self.assert_(type(detail) == TypeError)
+            self.assert_(msg in str(detail))
+
     def test_constructor_subclass_dict(self):
         # Test for passing dict subclass to constructor
         data = {'col1': tm.TestSubDict((x, 10.0 * x) for x in xrange(10)),
Repository: pandas-dev/pandas

Issue:
BUG: DataFrame.replace is broken in 0.12-dev
the `DataFrame.replace` seems to be broken in 0.12 development version

this code:

```
df = pd.DataFrame({'Type':['Q','T','Q','Q','T'], 'tmp':2})
print df
print df.replace({'Type': {'Q': 0, 'T': 1}})
```

Return correct result in 0.11.0:

```
  Type  tmp
0    Q    2
1    T    2
2    Q    2
3    Q    2
4    T    2
5    T    2
  Type  tmp
0    0    2
1    1    2
2    0    2
3    0    2
4    1    2
5    1    2
```

and in 0.12.0.dev-795004d it does not work:

```

  Type  tmp
0    Q    2
1    T    2
2    Q    2
3    Q    2
4    T    2
5    T    2
   Type  tmp
0     0    2
1     1    2
2     0    2
3     1    2
4     0    2
5     1    2
```

Series.replace it works well, so the workaround for this bug is the following:

```
df['Type'] = df['Type'].replace({'Q': 0, 'T': 1})
```



Discussion:
@cpcloud  take a look?

sure

while i'm fixing you can also do

```
df.replace({'Type': {'Q': 0}}).replace({'Type': {'T': 1}})
```

ah i remember this being a bit tricky. was the last change i made before submitting the original pr. @vfilimonov thanks for the report


Resolving patch:
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -756,7 +756,7 @@ def replace(self, to_replace, value, inplace=False, filter=None,
             blk = super(ObjectBlock, self).replace(to_replace, value,
                                                    inplace=inplace,
                                                    filter=filter, regex=regex)
-        elif both_lists and regex:
+        elif both_lists:
             for to_rep, v in itertools.izip(to_replace, value):
                 blk[0], = blk[0]._replace_single(to_rep, v, inplace=inplace,
                                                  filter=filter, regex=regex)


Test patch:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -6737,6 +6737,11 @@ def test_regex_replace_dict_nested(self):
         assert_frame_equal(res3, expec)
         assert_frame_equal(res4, expec)
 
+    def test_regex_replace_dict_nested_gh4115(self):
+        df = pd.DataFrame({'Type':['Q','T','Q','Q','T'], 'tmp':2})
+        expected = DataFrame({'Type': [0,1,0,0,1], 'tmp': 2})
+        assert_frame_equal(df.replace({'Type': {'Q':0,'T':1}}), expected)
+
     def test_regex_replace_list_to_scalar(self):
         mix = {'a': range(4), 'b': list('ab..'), 'c': ['a', 'b', nan, 'd']}
         df = DataFrame(mix)