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

如何用Python(pandas)高效导入UCI ML Repo文件夹下的所有CSV文件?

批量导入selfBACK数据集的高效方法

Python 实现

  • 用glob模块递归匹配所有CSV文件,结合pandas批量读取,可按需合并:
import pandas as pd
import glob

# 替换为你的selfBACK数据集根目录路径
root_path = "/path/to/selfBACK"
# 递归匹配所有子文件夹下的CSV文件
csv_files = glob.glob(f"{root_path}/**/*.csv", recursive=True)

# 批量读取所有CSV,存储为DataFrame列表
df_list = [pd.read_csv(file) for file in csv_files]

# 若所有CSV结构一致,合并为单个DataFrame
if df_list:
    combined_df = pd.concat(df_list, ignore_index=True)
# 若不同子文件夹的CSV结构不同,按文件夹分组处理
else:
    from collections import defaultdict
    folder_dfs = defaultdict(list)
    for file in csv_files:
        folder = file.split(root_path)[1].split("/")[1]
        folder_dfs[folder].append(pd.read_csv(file))
    # 每个文件夹内的CSV可单独合并
    folder_combined = {k: pd.concat(v, ignore_index=True) for k, v in folder_dfs.items()}

R 实现

  • 用list.files递归获取文件路径,结合tidyverse工具批量读取:
library(tidyverse)

# 替换为你的selfBACK数据集根目录路径
root_path <- "/path/to/selfBACK"
# 递归获取所有CSV文件的完整路径
csv_files <- list.files(path = root_path, pattern = "\\.csv$", recursive = TRUE, full.names = TRUE)

# 结构一致时,直接合并所有CSV
combined_df <- map_dfr(csv_files, read_csv)

# 结构不同时,按文件夹分组处理
folder_dfs <- csv_files %>%
  split(dirname(.)) %>%
  map(~map_dfr(., read_csv))

命令行快速合并(Linux/macOS)

如果所有CSV结构完全一致,可直接用命令行合并为单个文件,方便后续导入:

# 进入数据集根目录
cd /path/to/selfBACK
# 提取第一个文件的表头,再追加其他文件的内容(跳过表头)
head -n 1 $(find . -name "*.csv" | head -n 1) > combined.csv
find . -name "*.csv" -exec tail -n +2 {} >> combined.csv \;

Windows用户可使用PowerShell实现类似逻辑:

$rootPath = "C:\path\to\selfBACK"
$csvFiles = Get-ChildItem -Path $rootPath -Filter *.csv -Recurse -File
# 写入第一个文件的表头
Get-Content $csvFiles[0].FullName -Head 1 | Out-File combined.csv -Encoding utf8
# 追加其他文件内容(跳过表头)
foreach ($file in $csvFiles[1..$csvFiles.Count]) {
    Get-Content $file.FullName -Skip 1 | Out-File combined.csv -Encoding utf8 -Append
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:35:20