簡體   English   中英

如何從 python 中的 csv 文件中刪除包含全零的列?

[英]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庫:

  1. 閱讀 header 中的
  2. 讀取中的行
  3. 將行列表轉置為列列表(使用zip
  4. 使用集合刪除所有僅包含0的列
  5. 寫出新的 header
  6. 將轉置的列列表寫為行列表。

例如:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM