How to select all rows containing values ​​that exceed a threshold value?

The query is simple: I want to select all rows that contain a value that exceeds a threshold value.

If I do it like this:

df[(df > threshold)]

I get these lines, but values ​​below this threshold are simple NaN. How to avoid selecting these lines?

+4
source share
2 answers

There is absolutely no need for double transposition - you can simply call anyalong the column index (with delivery 1 or 'columns') on your Boolean matrix.

df[(df > threshold).any(1)]

Example

>>> df = pd.DataFrame(np.random.randint(0, 100, 50).reshape(5, 10))

>>> df

    0   1   2   3   4   5   6   7   8   9
0  45  53  89  63  62  96  29  56  42   6
1   0  74  41  97  45  46  38  39   0  49
2  37   2  55  68  16  14  93  14  71  84
3  67  45  79  75  27  94  46  43   7  40
4  61  65  73  60  67  83  32  77  33  96

>>> df[(df > 95).any(1)]

    0   1   2   3   4   5   6   7   8   9
0  45  53  89  63  62  96  29  56  42   6
1   0  74  41  97  45  46  38  39   0  49
4  61  65  73  60  67  83  32  77  33  96

Transposing, as your own answer, is simply an extra blow to productivity.

df = pd.DataFrame(np.random.randint(0, 100, 10**8).reshape(10**4, 10**4))

# standard way
%timeit df[(df > 95).any(1)]
1 loop, best of 3: 8.48 s per loop

# transposing
%timeit df[df.T[(df.T > 95)].any()]
1 loop, best of 3: 13 s per loop
+5
source

:

df[df.T[(df.T > 0.33)].any()]
0

Source: https://habr.com/ru/post/1671539/


All Articles