Skip to content

Commit a8bc986

Browse files
committed
Merge pull request #6130 from jreback/append_bug
BUG: DataFrame.append when appending a row with different columns (GH6129)
2 parents ef55e60 + 67e710c commit a8bc986

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

doc/source/release.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ Bug Fixes
162162
- Bug in propogating _ref_locs during construction of a DataFrame with dups
163163
index/columns (:issue:`6121`)
164164
- Bug in ``DataFrame.apply`` when using mixed datelike reductions (:issue:`6125`)
165-
165+
- Bug in ``DataFrame.append`` when appending a row with different columns (:issue:`6129`)
166166

167167
pandas 0.13.0
168168
-------------

pandas/core/frame.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3513,9 +3513,12 @@ def append(self, other, ignore_index=False, verify_integrity=False):
35133513
'ignore_index=True')
35143514

35153515
index = None if other.name is None else [other.name]
3516-
other = other.reindex(self.columns, copy=False)
3516+
combined_columns = self.columns.tolist() + ((self.columns | other.index) - self.columns).tolist()
3517+
other = other.reindex(combined_columns, copy=False)
35173518
other = DataFrame(other.values.reshape((1, len(other))),
3518-
index=index, columns=self.columns).convert_objects()
3519+
index=index, columns=combined_columns).convert_objects()
3520+
if not self.columns.equals(combined_columns):
3521+
self = self.reindex(columns=combined_columns)
35193522
elif isinstance(other, list) and not isinstance(other[0], DataFrame):
35203523
other = DataFrame(other)
35213524
if (self.columns.get_indexer(other.columns) >= 0).all():

pandas/tools/tests/test_merge.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,14 @@ def test_append(self):
11631163
self.assertRaises(ValueError, self.frame.append, self.frame,
11641164
verify_integrity=True)
11651165

1166+
# new columns
1167+
# GH 6129
1168+
df = DataFrame({'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}})
1169+
row = Series([5, 6, 7], index=['a', 'b', 'c'], name='z')
1170+
expected = DataFrame({'a': {'x': 1, 'y': 2, 'z': 5}, 'b': {'x': 3, 'y': 4, 'z': 6}, 'c' : {'z' : 7}})
1171+
result = df.append(row)
1172+
assert_frame_equal(result, expected)
1173+
11661174
def test_append_length0_frame(self):
11671175
df = DataFrame(columns=['A', 'B', 'C'])
11681176
df3 = DataFrame(index=[0, 1], columns=['A', 'B'])

0 commit comments

Comments
 (0)