简体   繁体   中英

Comparing and removing rows of CSV file in python?

I have a csv file that looks something similar to this.

"title","keep","get_rid","keep","rubbish"
"hello_world",1,0,0,0
"goodbye_world",0,0,1,0
"to_string",1,0,1,0
"not_so_smart",1,0,0,0

The goal is to remove the columns of which do not contain an instance of 1. So in this example, "get-rid" and "rubbish" will be removed - leaving us with something like...

"title","keep", "keep"
"hello_world",1,0
"goodbye_world",0,1
"to_string",1,1
"not_so_smart",1,0

However, I have somehow struggled to perform what seemed to be initially a simple problem.

My failed solution currently looks like this...

with open("filename.csv", "rb") as file:
reader = csv.reader(file)
header = next(reader)
for i, columns in enumerate(reader):
    for j, rows in enumerate(columns):
        if "1" not in rows[1:]:

Which isn't working as expected. Can anyone point me in the right direction?

1应该是str类型,而不是int类型。

if '1' not in columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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