0

I'm having a hard time finding a way to sum a dataframe column and then compare the sum to make sure it's greater than zero. I'm trying to do this with the index location because my dataframe has duplicate header names.

My block:

for i, each in enumerate(headers):
    if df.iloc[:, i].sum() > 0:
        header_mod_list.append(i)

print(header_mod_list) 

When I run this, I get an error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

Also, some of my columns do contains string values and others are float values since these are budget files.

Any thoughts? Thank you!

Mike Mann
  • 528
  • 4
  • 18
  • You can't sum mixed data types. What does the fact that it's a budget file have to do with anything? You need to clean and standardize your data if you want to do calculations on it. – MattDMo Aug 05 '22 at 23:35
  • @MattDMo sorry, let me clarify. I'm only interested in summing the column with floats and making sure it's greater than zero. When I test this on a numbers column, I'm getting the same error. – Mike Mann Aug 05 '22 at 23:40
  • Please see [How to make good reproducible Pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and the other information [here](https://stackoverflow.com/tags/pandas/info), then post a [mre] of your data and the code you've tried. Please also post the [*full text* of any errors or tracebacks](https://meta.stackoverflow.com/q/359146) you are getting. – MattDMo Aug 05 '22 at 23:48
  • @MattDMo thanks anyways. in case you're wondering you can sum a column with mixed data types using pd.to_numeric – Mike Mann Aug 06 '22 at 00:03

1 Answers1

0

Here's how I solved this one in case anyone is curious:

for i, each in enumerate(headers):
    if pd.to_numeric(df.iloc[:, i], errors='coerce').sum() > 0:
        header_mod_list.append(i)

print(header_mod_list) 

If I understand it correctly, this forced pandas to read only the integers, similar to how excel ignores strings in a sum function.

Mike Mann
  • 528
  • 4
  • 18