Repository: pandas-dev/pandas

Issue:
pivot_table margins=True default aggfunc='mean' does integer division
#### Code Sample, a copy-pastable example if possible

Code
```
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6,10,3,11]},index=['one','two','three','four'])
pd.pivot_table(df,index='State',margins=True)
```
Output
```
	a	b
State		
Florida	2.00	7
Texas	4.50	8
All	3.25	7
```
#### Problem description

The margin value for the `b` column is 7 (calculated from default aggfunc mean of 7+8) when i expect 7.5. 

This issue seems to be opposite of issue #17013 which complains of integers becoming floats 

#### Expected Output
P.s I changed 6 to 6.0 in to create desired output.
Code
```
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6.0,10,3,11]},index=['one','two','three','four'])
pd.pivot_table(df,index='State',margins=True)
```
Desired Output (For the margin value only, i don't necessarily require 7, 8 to become 7.0, 8.0)
```
	a	b
State		
Florida	2.00	7.0
Texas	4.50	8.0
All	3.25	7.5

```
#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.7.0.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.23.4
pytest: 3.8.0
pip: 18.1
setuptools: 40.2.0
Cython: 0.28.5
numpy: 1.15.4
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.5.0
sphinx: 1.7.9
patsy: 0.5.0
dateutil: 2.7.3
pytz: 2018.5
blosc: None
bottleneck: 1.2.1
tables: 3.4.4
numexpr: 2.6.8
feather: None
matplotlib: 3.0.2
openpyxl: 2.5.6
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 1.1.0
lxml: 4.2.5
bs4: 4.6.3
html5lib: 1.0.1
sqlalchemy: 1.2.11
pymysql: None
psycopg2: 2.7.6.1 (dt dec pq3 ext lo64)
jinja2: 2.9.5
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 0.7.0
</details>

pivot_table margins=True default aggfunc='mean' does integer division
#### Code Sample, a copy-pastable example if possible

Code
```
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6,10,3,11]},index=['one','two','three','four'])
pd.pivot_table(df,index='State',margins=True)
```
Output
```
	a	b
State		
Florida	2.00	7
Texas	4.50	8
All	3.25	7
```
#### Problem description

The margin value for the `b` column is 7 (calculated from default aggfunc mean of 7+8) when i expect 7.5. 

This issue seems to be opposite of issue #17013 which complains of integers becoming floats 

#### Expected Output
P.s I changed 6 to 6.0 in to create desired output.
Code
```
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6.0,10,3,11]},index=['one','two','three','four'])
pd.pivot_table(df,index='State',margins=True)
```
Desired Output (For the margin value only, i don't necessarily require 7, 8 to become 7.0, 8.0)
```
	a	b
State		
Florida	2.00	7.0
Texas	4.50	8.0
All	3.25	7.5

```
#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.7.0.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.23.4
pytest: 3.8.0
pip: 18.1
setuptools: 40.2.0
Cython: 0.28.5
numpy: 1.15.4
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.5.0
sphinx: 1.7.9
patsy: 0.5.0
dateutil: 2.7.3
pytz: 2018.5
blosc: None
bottleneck: 1.2.1
tables: 3.4.4
numexpr: 2.6.8
feather: None
matplotlib: 3.0.2
openpyxl: 2.5.6
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 1.1.0
lxml: 4.2.5
bs4: 4.6.3
html5lib: 1.0.1
sqlalchemy: 1.2.11
pymysql: None
psycopg2: 2.7.6.1 (dt dec pq3 ext lo64)
jinja2: 2.9.5
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 0.7.0
</details>



Discussion:

Resolving patch:
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -261,9 +261,12 @@ def _add_margins(
 
     row_names = result.index.names
     try:
+        # check the result column and leave floats
         for dtype in set(result.dtypes):
             cols = result.select_dtypes([dtype]).columns
-            margin_dummy[cols] = margin_dummy[cols].astype(dtype)
+            margin_dummy[cols] = margin_dummy[cols].apply(
+                maybe_downcast_to_dtype, args=(dtype,)
+            )
         result = result.append(margin_dummy)
     except TypeError:
 


Test patch:
diff --git a/pandas/tests/reshape/merge/test_pivot_old.py b/pandas/tests/reshape/merge/test_pivot_old.py
new file mode 100644
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -1656,6 +1656,24 @@ def test_categorical_margins_category(self, observed):
         table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
         tm.assert_frame_equal(table, expected)
 
+    def test_margins_casted_to_float(self, observed):
+        # GH 24893
+        df = pd.DataFrame(
+            {
+                "A": [2, 4, 6, 8],
+                "B": [1, 4, 5, 8],
+                "C": [1, 3, 4, 6],
+                "D": ["X", "X", "Y", "Y"],
+            }
+        )
+
+        result = pd.pivot_table(df, index="D", margins=True)
+        expected = pd.DataFrame(
+            {"A": [3, 7, 5], "B": [2.5, 6.5, 4.5], "C": [2, 5, 3.5]},
+            index=pd.Index(["X", "Y", "All"], name="D"),
+        )
+        tm.assert_frame_equal(result, expected)
+
     def test_pivot_with_categorical(self, observed, ordered_fixture):
         # gh-21370
         idx = [np.nan, "low", "high", "low", np.nan]