繁体   English   中英

如何删除包含所有零值的行但不使用非零值的零

[英]How to drop rows with ALL zero values but not zeros WITH non zero values

我有一个带有这些值的csv文件:

0,0,0,0,October 29 2018 16:35:04
0,1,2,0,October 30 2018 11:40:04
0,0,0,0,November 25 2018 04:20:13

我想在前4列中删除零值的行:

0,0,0,0,October 29 2018 16:35:04 #remove this
0,1,2,0,October 30 2018 11:40:04 #this should stay
0,0,0,0,November 25 2018 04:20:13 #remove this

IIUC使用df[...]

print(df[~(df[df.columns[:4]]==0).all(1)])

稍微好一点(感谢@jpp),使用iloc

print((df.iloc[:, :4] == 0).all(1))

两个输出:

   0  1  2  3                         4
1  0  1  2  0  October 30 2018 11:40:04

输出列可能不正确,因为我不知道实际的列。

有很多方法可以做你想要的,但你有几个任务:

  • 读一个.csv,你可以用csv.reader做到这csv.reader
  • 浏览所有内容,您可以通过简单的for循环来完成
  • 检查一些条件,你需要检查整数值是否为0, int(row[col]) == 0
  • 将符合条件的行写入新的.csv,您可以使用csv.writer执行此操作

这是一个可以完成这些工作的工作脚本,除了标准的csv之外,不需要外部库:

from csv import reader, writer

with open('input.csv', 'r') as input_file:
    with open('output.csv', 'w', newline='') as output_file:
        csv_in = reader(input_file)
        csv_out = writer(output_file)
        for row in csv_in:
            if not all([int(row[col]) == 0 for col in range(0, 4)]):
                csv_out.writerow(row)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM