如何选择包含大于阈值的所有行? [英] How to select all rows which contain values greater than a threshold?

查看:106
本文介绍了如何选择包含大于阈值的所有行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求很简单:我想选择所有包含大于阈值的行。

The request is simple: I want to select all rows which contain a value greater than a threshold.

如果我这样做,则:

df[(df > threshold)]

我得到了这些行,但是低于该阈值的值只是 NaN 。如何避免选择这些行?

I get these rows, but values below that threshold are simply NaN. How do I avoid selecting these rows?

推荐答案

绝对不需要双重转置-您可以简单地调用 any 沿布尔矩阵上的列索引(提供1或'columns')。

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

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

示例

>>> 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 self-answer does is just an unnecessary performance hit.

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

这篇关于如何选择包含大于阈值的所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆