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

如何在Python中基于DataFrame的FilePath列生成层级与计数新列

基于文件路径生成层级、文件数和子目录数的实现方案

原始数据

给定包含FilePath列的DataFrame:

import pandas as pd

data = {
    'FilePath': [
        r"S:\\colab\a.csv",
        r"S:\\colab\b.csv",
        r"S:\\colab\c.csv",
        r"S:\\colab\apple\dog.txt",
        r"S:\\colab\apple\cat.pdf"
    ]
}
df = pd.DataFrame(data)

需求

需基于FilePath列生成三个新列:

  • Hierarchy列:移除路径前缀S:\\,将路径分隔符\替换为>,得到文件层级字符串;
  • FileCnt列:统计对应目录下的文件数量;
  • DirCnt列:统计对应目录下的子目录数量;

完整实现代码

1. 生成Hierarchy列

修正原代码的转义问题,同时提供两种实现方式:

import os

# 方式一:字符串快速处理(适配简单路径场景)
df['Hierarchy'] = df['FilePath'].str.lstrip('S:\\').str.replace('\\', ' > ')

# 方式二:os模块路径解析(更可靠,兼容复杂路径)
# df['Hierarchy'] = df['FilePath'].apply(
#     lambda x: ' > '.join(os.path.relpath(x, 'S:\\').split('\\')[:-1])
# )

2. 提取父目录并统计文件数

先获取每个文件的父目录,再统计该目录下的文件总数:

# 提取每个文件的父目录路径
df['ParentDir'] = df['FilePath'].apply(os.path.dirname)

# 统计每个父目录的文件数量并映射到原表
file_count_map = df['ParentDir'].value_counts().to_dict()
df['FileCnt'] = df['ParentDir'].map(file_count_map)

3. 统计子目录数量

遍历所有唯一目录,统计每个目录下的直接子目录数:

# 获取所有唯一的目录集合
all_unique_dirs = df['ParentDir'].unique()

# 构建目录到子目录数的映射
dir_count_map = {}
for current_dir in all_unique_dirs:
    # 统计当前目录下的直接子目录数量
    subdir_num = sum(1 for dir_path in all_unique_dirs if os.path.dirname(dir_path) == current_dir)
    dir_count_map[current_dir] = subdir_num

# 将映射结果赋值给DirCnt列
df['DirCnt'] = df['ParentDir'].map(dir_count_map)

4. 清理中间列(可选)

如果不需要保留ParentDir列,可执行删除:

df = df.drop('ParentDir', axis=1)

最终输出

执行上述代码后,DataFrame结果如下:

FilePath         Hierarchy  FileCnt  DirCnt
0        S:\\colab\a.csv            colab        3       1
1        S:\\colab\b.csv            colab        3       1
2        S:\\colab\c.csv            colab        3       1
3  S:\\colab\apple\dog.txt  colab > apple        2       0
4  S:\\colab\apple\cat.pdf  colab > apple        2       0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:30:41