|
15 | 15 | )
|
16 | 16 | from pandas.core.dtypes.generic import ABCMultiIndex, ABCSeries
|
17 | 17 |
|
| 18 | +from pandas.core.construction import create_series_with_explicit_dtype |
| 19 | + |
18 | 20 | if TYPE_CHECKING:
|
19 | 21 | from pandas import DataFrame, Series, Index
|
20 | 22 |
|
@@ -203,15 +205,15 @@ def apply_empty_result(self):
|
203 | 205 |
|
204 | 206 | if not should_reduce:
|
205 | 207 | try:
|
206 |
| - r = self.f(Series([])) |
| 208 | + r = self.f(Series([], dtype=np.float64)) |
207 | 209 | except Exception:
|
208 | 210 | pass
|
209 | 211 | else:
|
210 | 212 | should_reduce = not isinstance(r, Series)
|
211 | 213 |
|
212 | 214 | if should_reduce:
|
213 | 215 | if len(self.agg_axis):
|
214 |
| - r = self.f(Series([])) |
| 216 | + r = self.f(Series([], dtype=np.float64)) |
215 | 217 | else:
|
216 | 218 | r = np.nan
|
217 | 219 |
|
@@ -346,14 +348,25 @@ def apply_series_generator(self) -> Tuple[ResType, "Index"]:
|
346 | 348 | def wrap_results(
|
347 | 349 | self, results: ResType, res_index: "Index"
|
348 | 350 | ) -> Union["Series", "DataFrame"]:
|
| 351 | + from pandas import Series |
349 | 352 |
|
350 | 353 | # see if we can infer the results
|
351 | 354 | if len(results) > 0 and 0 in results and is_sequence(results[0]):
|
352 | 355 |
|
353 | 356 | return self.wrap_results_for_axis(results, res_index)
|
354 | 357 |
|
355 | 358 | # dict of scalars
|
356 |
| - result = self.obj._constructor_sliced(results) |
| 359 | + |
| 360 | + # the default dtype of an empty Series will be `object`, but this |
| 361 | + # code can be hit by df.mean() where the result should have dtype |
| 362 | + # float64 even if it's an empty Series. |
| 363 | + constructor_sliced = self.obj._constructor_sliced |
| 364 | + if constructor_sliced is Series: |
| 365 | + result = create_series_with_explicit_dtype( |
| 366 | + results, dtype_if_empty=np.float64 |
| 367 | + ) |
| 368 | + else: |
| 369 | + result = constructor_sliced(results) |
357 | 370 | result.index = res_index
|
358 | 371 |
|
359 | 372 | return result
|
|
0 commit comments