From 7265d29d3a8bf5d1750b8991c5588b4f3d7fd5ce Mon Sep 17 00:00:00 2001 From: gfyoung Date: Tue, 1 Mar 2016 02:05:28 +0000 Subject: [PATCH] BUG: Allow assignment by indexing with duplicate column names Closes gh-12344. --- doc/source/whatsnew/v0.18.0.txt | 1 + pandas/core/indexing.py | 2 +- pandas/tests/frame/test_nonunique_indexes.py | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v0.18.0.txt b/doc/source/whatsnew/v0.18.0.txt index 77c8a5a585b51..49e6945bf4700 100644 --- a/doc/source/whatsnew/v0.18.0.txt +++ b/doc/source/whatsnew/v0.18.0.txt @@ -1201,3 +1201,4 @@ Bug Fixes - Bug when initializing categorical series with a scalar value. (:issue:`12336`) - Bug when specifying a UTC ``DatetimeIndex`` by setting ``utc=True`` in ``.to_datetime`` (:issue:`11934`) - Bug when increasing the buffer size of CSV reader in ``read_csv`` (:issue:`12494`) +- Bug when setting columns of a ``DataFrame`` with duplicate column names (:issue:`12344`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index f0f5507bc3e85..03fa072db83da 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -541,7 +541,7 @@ def can_do_equal_len(): if (len(indexer) > info_axis and is_integer(indexer[info_axis]) and all(is_null_slice(idx) for i, idx in enumerate(indexer) - if i != info_axis)): + if i != info_axis) and item_labels.is_unique): self.obj[item_labels[indexer[info_axis]]] = value return diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 1b24e829088f2..77974718714f8 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -452,3 +452,19 @@ def test_as_matrix_duplicates(self): dtype=object) self.assertTrue(np.array_equal(result, expected)) + + def test_set_value_by_index(self): + # See gh-12344 + df = DataFrame(np.arange(9).reshape(3, 3).T) + df.columns = list('AAA') + expected = df.iloc[:, 2] + + df.iloc[:, 0] = 3 + assert_series_equal(df.iloc[:, 2], expected) + + df = DataFrame(np.arange(9).reshape(3, 3).T) + df.columns = [2, float(2), str(2)] + expected = df.iloc[:, 1] + + df.iloc[:, 0] = 3 + assert_series_equal(df.iloc[:, 1], expected)