python dataframe格式化输出
时间: 2025-05-18 07:06:57 浏览: 15
### Python Pandas DataFrame 格式化输出
在数据分析和处理的过程中,Pandas 是一种非常强大的工具。为了更好地呈现数据,通常需要对 `DataFrame` 进行格式化的输出操作。以下是几种常见的格式化方式及其具体实现。
#### 1. 使用 `round()` 方法控制浮点数精度
如果 `DataFrame` 中包含浮点数类型的列,则可以通过调用 `.round(n)` 来指定保留的小数位数[^3]。
```python
import pandas as pd
data = {'得分': [22.1234, 24.5678, 26.9012],
'篮板数': [12.3456, 14.7890, 13.1234]}
df = pd.DataFrame(data)
# 控制小数点后两位显示
formatted_df = df.round(2)
print(formatted_df)
```
#### 2. 自定义格式化函数
对于更复杂的格式需求,可以使用 `applymap()` 函数来应用自定义的格式化逻辑到整个 `DataFrame` 上[^1]。
```python
def custom_formatter(x):
if isinstance(x, float): # 如果是浮点数则四舍五入并转为字符串
return f"{x:.2f}"
elif isinstance(x, int): # 整型保持不变
return str(x)
else: # 默认返回原值作为字符串
return str(x)
formatted_df = df.applymap(custom_formatter)
print(formatted_df)
```
#### 3. 将 DataFrame 转换为 HTML 表格
有时需要将 `DataFrame` 嵌入网页或者导出成 HTML 文件,在这种情况下可利用 `.to_html()` 方法完成转换[^5]。
```python
html_output = formatted_df.to_html(index=False)
with open("output.html", "w", encoding="utf-8") as file:
file.write(html_output)
```
#### 4. 导出至 CSV 并设置编码与分隔符
当希望保存格式化后的结果到本地磁盘上时,可以选择通过 `.to_csv()` 方法指定额外参数如编码类型以及字段间的分割符号。
```python
csv_path = "output_formatted.csv"
formatted_df.to_csv(csv_path, index=False, sep=",", encoding="utf-8")
```
以上就是关于如何以不同方式进行 Python Pandas DataFrame 的格式化输出的一些示例说明。
阅读全文
相关推荐


















