Need count of negative values in a dataframe

Viewed 27862

I need total count of negative values in a dataframe. i am able to get for an array but unable to find for DataFrame. for array i am using below code can any one suggest me how to get the count for below DataFrame.

sum(n<0 for n in numbers)

Below is my dataframe and expected result is 4

  a  b  c  d
   -3 -2 -1  1
   -2  2  3  4
    4  5  7  8
5 Answers

I am using the following. Might not be the best way to go about it.

negatives = len(df.loc[(df.a < 0)]) + len(df.loc[(df.b < 0)] + 
            len(df.loc[(df.c < 0)] + len(df.loc[(df.d < 0)]

EdChum's solution is very good, but I'd like to add another simple and acceptable solution that uses the pd.DataFrame.agg method, which is very commonly used and should therefore be easy to remember:

# Set up dataframe
import pandas as pd
df = pd.DataFrame({'a': [-3, -2, 4],
                   'b': [-2, 2, 5],
                   'c': [-1, 3, 7],
                   'd': [1, 4, 8]})

The pd.DataFrame.agg method to aggregate each row or column (columns by default) into a Series object. Then you can aggregate the series to get a scalar:

# Count all negative values in a dataframe.
df.agg(lambda x: sum(x < 0)).sum()

Output:

>>> 4
Related