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

Python如何从.csv文件加载指定列并存储为2D数组

CSV指定列提取实现方案

你可以按照以下方式修改代码实现需求:

import csv

def loadVsCSV(path):
    data = []
    with open(path, 'r', encoding='utf-8') as file:
        # 若你的CSV为逗号分隔,删除delimiter和skipinitialspace参数即可
        rows = csv.reader(file, delimiter=' ', skipinitialspace=True)
        # 读取表头定位目标列索引
        header = next(rows)
        target_index = [header.index(col) for col in ['Name', 'Lat', 'Lng']]
        # 逐行提取指定列
        for row in rows:
            if not row:
                continue
            # 如需保留字符串格式,可删除float()转换逻辑
            res_row = []
            for idx in target_index:
                val = row[idx]
                if idx in (target_index[1], target_index[2]):
                    val = float(val)
                res_row.append(val)
            data.append(res_row)
    return data

调用该函数后返回的二维数组就是你需要的格式。

补充说明:如果你的CSV文件是标准逗号分隔格式,只需要把csv.reader的参数改为默认的csv.reader(file)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:24:02