选择DataFrame行,其中列大于Series中的值

时间:2017-01-12 17:58:48

标签: python pandas

我有一个值数据框,

df1 = pd.DataFrame(np.random.rand(5*4).reshape(5,4),columns=['a','b','c','d'])
         a        b        c        d 
0 0.346137 0.537688 0.984077 0.809581
1 0.644753 0.363966 0.617507 0.114848
2 0.495147 0.014281 0.780733 0.579303
3 0.393447 0.108278 0.255716 0.318466
4 0.718629 0.789863 0.217532 0.891606

和一系列最大值。

s = pd.Series(np.random.rand(4),index=['a','b','c','d'])

a    0.005678
b    0.419059
c    0.511721
d    0.322693

我正在尝试识别df1中df1列中的值大于s中对应值的所有行。

我有办法一次做一个这样的专栏,但是想一次完成。

df1[df1.a > s.a].index,df1[df1.b > s.b].index,df1[df1.c > s.c].index,df1[df1.d > s.d].index

(Int64Index([0, 1, 2, 3, 4], dtype='int64'),
 Int64Index([0, 4], dtype='int64'),
 Int64Index([0, 1, 2], dtype='int64'),
 Int64Index([0, 2, 4], dtype='int64'))

最后,我希望结果为[0,1,2,3,4]

2 个答案:

答案 0 :(得分:3)

这是一种方法 -

r,c = np.where((df1 > s).T)
out = np.split(df1.index[c], np.flatnonzero(r[1:] > r[:-1])+1 )

示例运行 -

In [141]: df1
Out[141]: 
          a         b         c         d
0  0.346137  0.537688  0.984077  0.809581
1  0.644753  0.363966  0.617507  0.114848
2  0.495147  0.014281  0.780733  0.579303
3  0.393447  0.108278  0.255716  0.318466
4  0.718629  0.789863  0.217532  0.891606

In [142]: s
Out[142]: 
a    0.005678
b    0.419059
c    0.511721
d    0.322693
dtype: float64

In [143]: r,c = np.where((df1 > s).T)

In [144]: np.split(df1.index[c], np.flatnonzero(r[1:] > r[:-1])+1 )
Out[144]: 
[Int64Index([0, 1, 2, 3, 4], dtype='int64'),
 Int64Index([0, 4], dtype='int64'),
 Int64Index([0, 1, 2], dtype='int64'),
 Int64Index([0, 2, 4], dtype='int64')]

答案 1 :(得分:1)

我找到了

df1.loc[(df1 > s).any(axis=1) == True].index.tolist()

正常工作,简洁明了。

相关问题