pandas:如何根据 X 列数是否大于一个数字来选择行? [英] pandas: How do I select rows based on if X number of columns is greater than a number?

查看:278
本文介绍了pandas:如何根据 X 列数是否大于一个数字来选择行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 data[data[data >10].any(1)] 选择任何列大于 10 的行.如果我想选择任何 5 列大于 10 的行怎么办?

I can use data[data[data > 10].any(1)] to select rows where any of the columns are greater than 10. What if I wanted to select rows where any 5 columns are greater than 10?

推荐答案

以下内容应该适合您:

data[data[data > 10].count(axis=1) > 5]

示例:

In [66]:

df = pd.DataFrame({'a':randn(10), 'b':randn(10), 'c':randn(10), 'd':randn(10), 'e':randn(10), 'f':randn(10), 'g':randn(10)})
df
Out[66]:
          a         b         c         d         e         f         g
0 -2.617089 -0.882830  0.678067 -0.517271  0.451493  1.233842  2.039522
1 -0.099578  0.316943  0.707360  0.408488 -0.127735  0.587747 -0.472138
2 -0.717133  0.804504  1.290014  0.091469 -0.311926  0.493378  0.337818
3  0.443820  1.148113  0.437646  0.098209 -0.072878  1.741442  1.954516
4  1.674700 -1.155307 -0.464377 -1.403315 -2.009475 -0.358216  0.430474
5 -0.243898  0.457013 -1.303361 -0.259384 -0.618927 -0.115834  0.062917
6 -1.731918  0.582375  0.007224 -0.336893 -0.092084  0.724403  0.622719
7  0.377062 -0.475285 -1.343725  0.572877  0.613228  0.573816  0.854494
8  0.063625 -0.484536  0.093442 -1.015500  1.062488 -1.818364 -1.139001
9 -0.349160  0.731415  0.418029 -0.341685 -0.421163  0.105534  0.642873

[10 rows x 7 columns]
In [85]:

df[df > 1.0]
Out[85]:
        a         b         c   d         e         f         g
0     NaN       NaN       NaN NaN       NaN  1.233842  2.039522
1     NaN       NaN       NaN NaN       NaN       NaN       NaN
2     NaN       NaN  1.290014 NaN       NaN       NaN       NaN
3     NaN  1.148113       NaN NaN       NaN  1.741442  1.954516
4  1.6747       NaN       NaN NaN       NaN       NaN       NaN
5     NaN       NaN       NaN NaN       NaN       NaN       NaN
6     NaN       NaN       NaN NaN       NaN       NaN       NaN
7     NaN       NaN       NaN NaN       NaN       NaN       NaN
8     NaN       NaN       NaN NaN  1.062488       NaN       NaN
9     NaN       NaN       NaN NaN       NaN       NaN       NaN

[10 rows x 7 columns]
In [86]:

df[df[df > 1.0].count(axis=1) > 2]

Out[86]:
         a         b         c         d         e         f         g
3  0.44382  1.148113  0.437646  0.098209 -0.072878  1.741442  1.954516

[1 rows x 7 columns]

这篇关于pandas:如何根据 X 列数是否大于一个数字来选择行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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