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

如何在Jupyter Notebook中将DataFrame转为层级结构TXT并保存至下载目录?

解决DataFrame转层级结构TXT文件的方法

实现代码

import pandas as pd
import os
from IPython.display import FileLink

# 你的DataFrame(示例)
df = pd.DataFrame({'Parent': ['Stay home', "Stay home","Stay home", 'Go outside', "Go outside"], 
                   'Child' : ['Severe weather', "raining", "Windy", 'Sunny', "Good weather"],
                   'Child1': ['', "some rain", "extreme windy", "very hot", ""]})

# 获取系统Downloads文件夹路径(跨平台兼容)
downloads_dir = os.path.expanduser("~/Downloads")
output_file_path = os.path.join(downloads_dir, "hierarchy_result.txt")

# 构建层级文本内容
result_text = ""
# 按Parent分组,避免重复输出父节点
for parent_name, group in df.groupby('Parent'):
    result_text += f"{parent_name}\n"
    # 遍历每组内的子节点行
    for _, row in group.iterrows():
        # 输出子节点,缩进5个空格
        result_text += f"     {row['Child']}\n"
        # 若子子节点非空,输出并增加缩进(额外3个空格,共8个)
        child1_content = row['Child1'].strip()
        if child1_content:
            result_text += f"       {child1_content}\n"

# 将内容写入TXT文件
with open(output_file_path, 'w', encoding='utf-8') as f:
    f.write(result_text)

# 在Jupyter Notebook中生成下载链接
display(FileLink(output_file_path))

代码说明

  1. 跨平台路径处理:用os.path.expanduser("~/Downloads")自动识别Windows/Mac/Linux的下载文件夹,无需手动写路径。
  2. 分组去重父节点:通过groupby('Parent')确保每个父节点只输出一次,避免重复。
  3. 层级缩进控制:父节点无缩进,子节点用5个空格缩进,子子节点再额外加3个空格,完全匹配你要的格式。
  4. 空白内容过滤:用strip()过滤Child1中的空白字符,避免输出空行。
  5. Jupyter下载支持:通过FileLink生成直接下载链接,无需手动去文件夹找文件。

这个方法适合处理大量行数据,逐行构建文本内容,内存占用低,格式完全可控。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:45:35