You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python DataFrame按指定格式对齐输出至TXT文件?

实现代码

以下是符合要求的Python代码,可将指定DataFrame转换为目标格式的TXT文件:

import pandas as pd

# 示例DataFrame(可替换为用户实际的DataFrame)
data = {
    'ID': [16069518, 15907047, 1890070, 10978227, 13968376],
    'party': ['Australia', 'India', 'Canada', 'America', 'Italy'],
    'test': [4538, 7595, 3481, 7595, 6310],
    'MRK': [4508329.38, -24646.59, 21556268.87, -258747.70, 146648.45],
    'Bundle': ['', '', '', '', ''],
    'Entity': ['abc', 'cbd', 'xyz', 'yac', 'gbc']
}
df = pd.DataFrame(data)

# 根据列位置规则定义格式化字符串
# 各字段宽度计算:
# - ID左对齐,占据前33位(party列末尾在42位,party内容最大宽度9,42-9=33)
# - party右对齐,宽度9(42-33=9)
# - test右对齐,宽度51(93-42=51)
# - MRK右对齐,宽度21(114-93=21)
# - Bundle ID右对齐,宽度20(134-114=20)
# - Entity右对齐,宽度17(151-134=17)
header_format = "{:<33}{:>9}{:>51}{:>21}{:>20}{:>17}"
row_format = "{:<33}{:>9}{:>51}{:>21}{:>20}{:>17}"

# 生成表头行
header = header_format.format('ID', 'party', 'test', 'MRK', 'Bundle ID', 'Entity')

# 生成数据行
data_rows = []
for _, row in df.iterrows():
    # 确保MRK保留两位小数,与示例格式一致
    formatted_row = row_format.format(
        str(row['ID']),
        row['party'],
        str(row['test']),
        f"{row['MRK']:.2f}",
        row['Bundle'],
        row['Entity']
    )
    data_rows.append(formatted_row)

# 拼接所有内容并写入文件
full_content = '\n'.join([header] + data_rows)
with open('formatted_output.txt', 'w', encoding='utf-8') as file:
    file.write(full_content)

代码说明

  1. 格式规则匹配:严格按照要求的列结束位置计算各字段的占位宽度,确保每列末尾落在指定位置
  2. 对齐方式:ID列使用左对齐符号<,其余列使用右对齐符号>
  3. 数值格式化:对MRK字段强制保留两位小数,与示例输出格式一致
  4. 文件写入:将表头和所有数据行拼接后写入UTF-8编码的TXT文件

内容的提问来源于stack exchange,提问作者SGC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 14:24:19