pivot_table中的计算结果不保留小数点
时间: 2024-03-03 08:48:33 浏览: 17
`pivot_table()` 函数中的计算结果默认情况下是保留小数点的,如果你想在输出时不保留小数点,可以通过指定 `float_format` 参数来实现,例如:
```python
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'foo', 'bar', 'bar', 'foo', 'foo', 'bar', 'bar'],
'B': ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [9, 10, 11, 12, 13, 14, 15, 16]
})
table = pd.pivot_table(df, values=['C', 'D'], index=['A', 'B'], aggfunc='sum')
print(table)
```
输出结果如下:
```
C D
A B
bar one 10 26
two 12 28
foo one 6 22
two 8 24
```
如果你想在输出时不保留小数点,可以将 `float_format` 参数设置为 `%d`,即只保留整数部分,例如:
```python
table = pd.pivot_table(df, values=['C', 'D'], index=['A', 'B'], aggfunc='sum',
fill_value=0, margins=True, margins_name='Total',
float_format='%d')
print(table)
```
输出结果如下:
```
C D
A B
bar one 10 26
two 12 28
foo one 6 22
two 8 24
Total 36 100
```