Skip to content

Commit 84fa2ef

Browse files
Chris Bertinatojreback
Chris Bertinato
authored andcommitted
BUG: Replace internal use of loc with reindex in append (#26022)
1 parent 55abdc5 commit 84fa2ef

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ Indexing
331331
^^^^^^^^
332332

333333
- Improved exception message when calling :meth:`DataFrame.iloc` with a list of non-numeric objects (:issue:`25753`).
334-
-
334+
- Bug in which :meth:`DataFrame.append` produced an erroneous warning indicating that a ``KeyError`` will be thrown in the future when the data to be appended contains new columns (:issue:`22252`).
335335
-
336336

337337

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6720,7 +6720,7 @@ def append(self, other, ignore_index=False,
67206720
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
67216721
other = DataFrame(other)
67226722
if (self.columns.get_indexer(other.columns) >= 0).all():
6723-
other = other.loc[:, self.columns]
6723+
other = other.reindex(columns=self.columns)
67246724

67256725
from pandas.core.reshape.concat import concat
67266726
if isinstance(other, (list, tuple)):

pandas/tests/frame/test_combine_concat.py

+15
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,21 @@ def test_append_list_of_series_dicts(self):
167167
expected = df.append(DataFrame(dicts), ignore_index=True, sort=True)
168168
assert_frame_equal(result, expected)
169169

170+
def test_append_missing_cols(self):
171+
# GH22252
172+
# exercise the conditional branch in append method where the data
173+
# to be appended is a list and does not contain all columns that are in
174+
# the target DataFrame
175+
df = DataFrame(np.random.randn(5, 4),
176+
columns=['foo', 'bar', 'baz', 'qux'])
177+
178+
dicts = [{'foo': 9}, {'bar': 10}]
179+
with tm.assert_produces_warning(None):
180+
result = df.append(dicts, ignore_index=True, sort=True)
181+
182+
expected = df.append(DataFrame(dicts), ignore_index=True, sort=True)
183+
assert_frame_equal(result, expected)
184+
170185
def test_append_empty_dataframe(self):
171186

172187
# Empty df append empty df

0 commit comments

Comments
 (0)