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

如何用Python的csv模块及Pandas移除CSV中__mv开头的列

移除CSV中以__mv开头的列的两种实现方法

一、用Python内置csv模块实现

当然可以用csv模块搞定,思路就是先筛选出需要保留的列,再逐行提取对应数据写入新文件:

import csv

# 替换成你的输入输出文件路径
input_file = "your_input.csv"
output_file = "filtered_output.csv"

with open(input_file, 'r', newline='', encoding='utf-8') as infile, \
     open(output_file, 'w', newline='', encoding='utf-8') as outfile:
    
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    
    # 读取表头,筛选出不以__mv开头的列
    header = next(reader)
    keep_columns = [col for col in header if not col.startswith('__mv')]
    # 记录这些列的索引,方便后续提取数据
    keep_indices = [i for i, col in enumerate(header) if col in keep_columns]
    
    # 写入筛选后的表头
    writer.writerow(keep_columns)
    
    # 遍历每一行,只保留需要的列数据
    for row in reader:
        filtered_row = [row[i] for i in keep_indices]
        writer.writerow(filtered_row)

二、用Pandas的df.filter方法实现

用df.filter(regex='')的话,正则表达式写^(?!__mv)就行。这个正则的意思是:^匹配列名的开头,(?!__mv)是负向前瞻断言,确保列名开头不是__mv。

代码示例:

import pandas as pd

df = pd.read_csv("your_input.csv")
# 筛选出不以__mv开头的列
filtered_df = df.filter(regex=r'^(?!__mv)')
# 保存到新文件
filtered_df.to_csv("filtered_output.csv", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:46:13