![](/img/trans.png)
[英]Open a csv file, delete columns containing a word in their name, save in a new csv Pandas, Python
[英]How to delete columns containing all zeros from a csv file in python?
我想從包含全零的 csv 文件中刪除列,例如列 f、g、h、k、l。 有問題的 csv 文件填充了腳本,因此無法對列進行硬編碼。 如果您能提供幫助,我將不勝感激。
File.csv
a,b,c,d,e,f,g,h,i,j,k,l
1,5,4,4,5,0,0,0,6,3,0,0
2,5,3,4,1,0,0,0,7,1,0,0
1,2,6,4,1,0,0,0,9,2,0,0
5,7,3,4,2,0,0,0,2,2,0,0
7,2,9,4,3,0,0,0,1,1,0,0
預期結果
File.csv
a,b,c,d,e,i,j
1,5,4,4,5,6,3
2,5,3,4,1,7,1
1,2,6,4,1,9,2
5,7,3,4,2,2,2
7,2,9,4,3,1,1
以下方法可用於csv
庫:
zip
)0
的列例如:
import csv
with open('file.csv', newline='') as f_input:
csv_input = csv.reader(f_input)
header = next(csv_input) # read header
columns = zip(*list(csv_input)) # read rows and transpose to columns
data = [(h, c) for h, c in zip(header, columns) if set(c) != set('0')]
with open('file2.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(h for h, c in data) # write the new header
csv_output.writerows(zip(*[c for h, c in data]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.