|
14 | 14 | from pandas.core.categorical import Categorical |
15 | 15 | from pandas.core.frame import DataFrame |
16 | 16 | from pandas.core.generic import NDFrame |
17 | | -from pandas.core.index import Index, MultiIndex, _ensure_index |
| 17 | +from pandas.core.index import Index, MultiIndex, _ensure_index, _union_indexes |
18 | 18 | from pandas.core.internals import BlockManager, make_block |
19 | 19 | from pandas.core.series import Series |
20 | 20 | from pandas.core.panel import Panel |
@@ -425,7 +425,7 @@ def convert(key, s): |
425 | 425 | return Timestamp(key).asm8 |
426 | 426 | return key |
427 | 427 |
|
428 | | - sample = list(self.indices)[0] |
| 428 | + sample = next(iter(self.indices)) |
429 | 429 | if isinstance(sample, tuple): |
430 | 430 | if not isinstance(name, tuple): |
431 | 431 | raise ValueError("must supply a tuple to get_group with multiple grouping keys") |
@@ -2193,33 +2193,37 @@ def transform(self, func, *args, **kwargs): |
2193 | 2193 | ------- |
2194 | 2194 | transformed : Series |
2195 | 2195 | """ |
2196 | | - result = self._selected_obj.copy() |
2197 | | - if hasattr(result, 'values'): |
2198 | | - result = result.values |
2199 | | - dtype = result.dtype |
| 2196 | + dtype = self._selected_obj.dtype |
2200 | 2197 |
|
2201 | 2198 | if isinstance(func, compat.string_types): |
2202 | 2199 | wrapper = lambda x: getattr(x, func)(*args, **kwargs) |
2203 | 2200 | else: |
2204 | 2201 | wrapper = lambda x: func(x, *args, **kwargs) |
2205 | 2202 |
|
2206 | | - for name, group in self: |
| 2203 | + result = self._selected_obj.values.copy() |
| 2204 | + for i, (name, group) in enumerate(self): |
2207 | 2205 |
|
2208 | 2206 | object.__setattr__(group, 'name', name) |
2209 | 2207 | res = wrapper(group) |
| 2208 | + |
2210 | 2209 | if hasattr(res, 'values'): |
2211 | 2210 | res = res.values |
2212 | 2211 |
|
2213 | | - # need to do a safe put here, as the dtype may be different |
2214 | | - # this needs to be an ndarray |
2215 | | - result = Series(result) |
2216 | | - result.iloc[self._get_index(name)] = res |
2217 | | - result = result.values |
| 2212 | + # may need to astype |
| 2213 | + try: |
| 2214 | + common_type = np.common_type(np.array(res), result) |
| 2215 | + if common_type != result.dtype: |
| 2216 | + result = result.astype(common_type) |
| 2217 | + except: |
| 2218 | + pass |
| 2219 | + |
| 2220 | + indexer = self._get_index(name) |
| 2221 | + result[indexer] = res |
2218 | 2222 |
|
2219 | | - # downcast if we can (and need) |
2220 | 2223 | result = _possibly_downcast_to_dtype(result, dtype) |
2221 | | - return self._selected_obj.__class__(result, index=self._selected_obj.index, |
2222 | | - name=self._selected_obj.name) |
| 2224 | + return self._selected_obj.__class__(result, |
| 2225 | + index=self._selected_obj.index, |
| 2226 | + name=self._selected_obj.name) |
2223 | 2227 |
|
2224 | 2228 | def filter(self, func, dropna=True, *args, **kwargs): |
2225 | 2229 | """ |
|
0 commit comments