当前位置:首页python > 正文

python提取csv指定列

作者:野牛程序员:2023-07-12 19:43:04python阅读 2741

要提取CSV文件的指定列,可以使用Python的csv模块。下面是一个示例代码,展示了如何提取指定列的数据:

import csv

def extract_columns(csv_file, columns):
    extracted_data = []

    with open(csv_file, 'r') as file:
        reader = csv.reader(file)
        header = next(reader)  # 读取标题行

        # 确定要提取的列的索引
        column_indices = [header.index(column) for column in columns]

        # 逐行读取数据
        for row in reader:
            extracted_row = [row[index] for index in column_indices]
            extracted_data.append(extracted_row)

    return extracted_data

# 示例用法
csv_file = 'data.csv'  # 替换CSV文件路径
columns_to_extract = ['列1', '列2']  # 替换要提取的列的名称

extracted_data = extract_columns(csv_file, columns_to_extract)

# 打印提取的数据
for row in extracted_data:
    print(row)

在上面的示例中,extract_columns函数接受两个参数:CSV文件的路径和要提取的列的名称列表。它首先打开CSV文件,然后使用csv.reader函数创建一个读取器对象。然后,它读取标题行并确定要提取的列的索引。接下来,它逐行读取数据,并根据列的索引提取相应的数据。最后,它返回一个包含提取的数据的列表。

需要将csv_file变量替换为你自己的CSV文件路径,并将columns_to_extract变量替换为你想要提取的列的名称列表。运行代码后,提取的数据将被打印出来。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击