Skip to content

Commit dc6ed74

Browse files
committed
broadcast should preserve like-columns
1 parent 1363c03 commit dc6ed74

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pandas/core/apply.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ def apply_broadcast(self, target):
187187
# axis which we want to compare compliance
188188
result_compare = target.shape[0]
189189

190-
index = target.index
190+
index = None
191191
for i, col in enumerate(target.columns):
192192
res = self.f(target[col])
193193
ares = np. asarray(res).ndim
@@ -208,6 +208,11 @@ def apply_broadcast(self, target):
208208

209209
result_values[:, i] = res
210210

211+
# if we are returning a list-like
212+
# then preserve the original index
213+
if index is None:
214+
index = target.index
215+
211216
result = self.obj._constructor(result_values, index=index,
212217
columns=target.columns)
213218
return result

pandas/tests/frame/test_apply.py

+18
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,24 @@ def test_apply_broadcast(self):
163163
index=self.frame.index)
164164
tm.assert_frame_equal(result, expected)
165165

166+
# preserve columns
167+
df = DataFrame(np.tile(np.arange(3), 6).reshape(6, -1) + 1,
168+
columns=list('ABC'))
169+
result = df.apply(lambda x: [1, 2, 3],
170+
axis=1,
171+
result_type='broadcast')
172+
tm.assert_frame_equal(result, df)
173+
174+
# columms come from the returned Series
175+
df = DataFrame(np.tile(np.arange(3), 6).reshape(6, -1) + 1,
176+
columns=list('ABC'))
177+
result = df.apply(lambda x: Series([1, 2, 3], index=list('abc')),
178+
axis=1,
179+
result_type='broadcast')
180+
expected = df.copy()
181+
expected.columns = list('abc')
182+
tm.assert_frame_equal(result, expected)
183+
166184
def test_apply_broadcast_error(self):
167185
df = DataFrame(
168186
np.tile(np.arange(3, dtype='int64'), 6).reshape(6, -1) + 1,

0 commit comments

Comments
 (0)