【问题标题】:How to delete columns containing all zeros from a csv file in python?如何从python中的csv文件中删除包含全零的列?
【发布时间】:2021-02-09 20:44:34
【问题描述】:

我想从包含全零的 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

【问题讨论】:

标签: python python-3.x csv


【解决方案1】:

csv 库可以使用以下方法:

  1. 读入标题
  2. 读取行
  3. 将行列表转换为列列表(使用zip
  4. 使用集合删除所有仅包含0 的列
  5. 写出新的标题
  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]))

【讨论】:

  • 当有四列(一起)包含全零时,它不起作用。列号(从 1 开始)19、20、21 和 22 包含全零,脚本对此不起作用。你能帮忙吗?
  • 您能否发布有问题的文件的链接?例如使用类似 pastebin 的东西
猜你喜欢
  • 2014-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
相关资源
最近更新 更多