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

如何用Python从文本文件提取指定列生成DataFrame/表格/列表

解决方案:提取指定列数据

这里提供两种Python实现方式,按需选择:

方法一:纯Python标准库(无第三方依赖)

直接通过文件读取和字符串处理提取目标列,适合不想安装额外库的场景:

# 替换为你的文件路径
file_path = "your_data_file.txt"

# 读取文件并过滤注释行
with open(file_path, 'r') as f:
    # 去除空行和注释行,同时去掉每行首尾空格
    valid_lines = [line.strip() for line in f if line.strip() and not line.startswith('#')]

# 解析表头,确定目标列的索引
header_parts = valid_lines[0].split()
volume_col_idx = header_parts.index('Volume_mm3')
struct_col_idx = header_parts.index('StructName')

# 提取数据,存储为字典列表(也可根据需求改成二维列表)
target_data = []
for line in valid_lines[1:]:
    line_parts = line.split()
    # 提取对应列的值,Volume转成浮点数,StructName保留字符串
    volume = float(line_parts[volume_col_idx])
    struct_name = line_parts[struct_col_idx]
    target_data.append({
        'StructName': struct_name,
        'Volume_mm3': volume
    })

# 查看结果示例
print(target_data[:3])

输出示例:

[
    {'StructName': 'Left-Lateral-Ventricle', 'Volume_mm3': 7260.4},
    {'StructName': 'Left-Inf-Lat-Vent', 'Volume_mm3': 328.8},
    {'StructName': 'Left-Cerebellum-White-Matter', 'Volume_mm3': 15593.6}
]

方法二:使用Pandas(简洁高效)

如果经常处理表格数据,推荐用Pandas,代码更简洁:

import pandas as pd

# 读取文件,自动跳过注释行,按空格分隔列
df = pd.read_csv(
    "your_data_file.txt",
    comment='#',  # 跳过以#开头的行
    delim_whitespace=True,  # 处理空格分隔的表格
    engine='python'
)

# 只保留需要的两列
target_df = df[['StructName', 'Volume_mm3']]

# 查看结果
print(target_df.head())

# 如果需要转成列表格式
target_list = target_df.to_dict('records')

输出示例:

StructName  Volume_mm3
0      Left-Lateral-Ventricle      7260.4
1       Left-Inf-Lat-Vent       328.8
2  Left-Cerebellum-White-Matter     15593.6
3    Left-Cerebellum-Cortex       60538.4
4      Left-Thalamus-Proper        8080.4

关键说明

  • 两种方法都会自动跳过所有以#开头的注释行,只保留表头和数据行
  • 你的示例数据中StructName均为连字符连接,split()可以正确识别;若后续出现带空格的结构名,纯Python方法需调整分割逻辑
  • Pandas方法自动处理各种分隔情况,适合复杂表格场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:10:39