Skip to main content
 首页 » 编程设计

python之删除csv文件中无用的列和行并使用python保存

2025年01月19日11pengyingh

这是一个示例 csv 文件;

out_gate,uless_col,in_gate,n_con 
p,x,x,1 
p,x,y,1 
p,x,z,1 
a_a,u,b,1 
a_a,s,b,3 
a_b,e,a,2 
a_b,l,c,4 
a_c,e,a,5 
a_c,s,b,5 
a_c,s,b,3 
a_c,c,a,4 
a_d,o,c,2 
a_d,l,c,3 
a_d,m,b,2 
p,y,x,1 
p,y,y,1 
p,y,z,3 

我想删除无用的列(第二列)和无用的行(前三行和后三行)并创建一个新的 csv 文件,然后保存这个新文件。以及如何处理包含 10 个以上无用列和无用行的 csv 文件?

(假设无用的行只位于顶部或底部的行没有散布在中间)

(我还假设我们要使用的所有行的第一个元素名称都以“a_”开头)

我是否也可以在不使用 numpys 或 pandas 的情况下获得解决方案?谢谢!

请您参考如下方法:

假设您有一个或多个不需要的列并且需要的行以“a_”开头。

import csv 
with open('filename.csv') as infile: 
    reader = csv.reader(infile) 
    header = next(reader) 
    data = list(reader) 
 
useless = set(['uless_col', 'n_con']) # Let's say there are 2 useless columns 
mask, new_header = zip(*[(i,name) for i,name in enumerate(header)  
                          if name not in useless]) 
#(0,2) - column mask 
#('out_gate', 'in_gate') - new column headers 
 
new_data = [[row[i] for i in mask] for row in data] # Remove unwanted columns 
new_data = [row for row in new_data if row[0].startswith("a_")] # Remove unwanted rows 
 
with open('filename.csv', 'w') as outfile: 
    writer = csv.writer(outfile) 
    writer.writerow(new_header) 
    writer.writerows(new_data)