Skip to content

Commit f050f5f

Browse files
author
Chris Bertinato
committed
BUG: Replace internal use of loc with reindex in append
1 parent 6c613c8 commit f050f5f

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ Indexing
325325
^^^^^^^^
326326

327327
- Improved exception message when calling :meth:`DataFrame.iloc` with a list of non-numeric objects (:issue:`25753`).
328-
-
328+
- 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`).
329329
-
330330

331331

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6731,7 +6731,7 @@ def append(self, other, ignore_index=False,
67316731
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
67326732
other = DataFrame(other)
67336733
if (self.columns.get_indexer(other.columns) >= 0).all():
6734-
other = other.loc[:, self.columns]
6734+
other = other.reindex(columns=self.columns)
67356735

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

pandas/tests/frame/test_combine_concat.py

+13
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,19 @@ 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+
result = df.append(dicts, ignore_index=True, sort=True)
180+
expected = df.append(DataFrame(dicts), ignore_index=True, sort=True)
181+
assert_frame_equal(result, expected)
182+
170183
def test_append_empty_dataframe(self):
171184

172185
# Empty df append empty df

0 commit comments

Comments
 (0)