Home > front end >  In Python, check for zeros in each row, if row has 3 or more zeros, remove the row. Current code doe
In Python, check for zeros in each row, if row has 3 or more zeros, remove the row. Current code doe

Time:04-19

I'm looking to count the amount of zeros in a row. If it has three or more zeros, remove the row. Once all rows with three or more zeros are removed, export the new file.

CSV:

Year 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
Person_A $10.00 $20.00 $20.00 $50.00 $0.00 $10.00 $0.00 $0.00 $50.00 $0.00 $10.00 $0.00 $1.00
Person_B $100.00 $150.00 $1.00 $50.00 $0.25 $100.00 $0.00 $50.00 $60.00 $50.00 $0.00 $0.00 $1000.00

Desired result:

Year 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
Person_B $100.00 $150.00 $1.00 $50.00 $0.25 $100.00 $0.00 $50.00 $60.00 $50.00 $0.00 $0.00 $1000.00

Current Code does nothing to the file. I have what I think is count zeros, if more than 3 drop the row, but the row count for File.csv and NewFile.csv are the same:

import pandas as pd

df = pd.read_csv("C:/Users/File.CSV" , encoding = "ISO-8859-1") # import csv as DataFrame

df_new = df.loc[df.eq(0).sum(1).le(3),] # Look for zeros, if more than 3, remove row

df_new.to_csv( "C:/Users/Folder/NewFile.CSV", index=False ) # Export new file

I have also attempted this, but again makes no changes to File:


df = pd.read_csv("C:/Users/File.CSV" , encoding = "ISO-8859-1") # import csv as DataFrame

df_new = df[df.eq('$0.00').sum(1) <= 3] # Look for zeros, if more than 3 remove row

df_new.to_csv( "C:/Users/Folder/NewFile.CSV", index=False ) # Export new file

CodePudding user response:

Update

df = pd.read_csv('GiftYearTotal.csv', encoding='ISO-8859-1')
df = df.apply(lambda x: x.str.strip())
out = df[df.eq('$0.00').sum(1) <= 3]

Old answer

You can use:

out = df[df.eq('$0.00').sum(1) <= 3]
print(out)

# Output
       Year     2010     2011   2012    2013   2014     2015   2016    2017    2018    2019   2020   2021      2022
1  Person_B  $100.00  $150.00  $1.00  $50.00  $0.25  $100.00  $0.00  $50.00  $60.00  $50.00  $0.00  $0.00  $1000.00
  • Related