python - 选择列大于系列中的值的 DataFrame 行

标签 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]

最佳答案

这是一种方法-

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

sample 运行-

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')]

关于python - 选择列大于系列中的值的 DataFrame 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619935/

相关文章:

pandas - 从格式为 d-m-yyyy(Pyspark 或 Pandans)的字符串中创建 Unix 时间戳

python - 如何获取 Pandas 中某些特定日期之前和之后的日期时间?

python - Python中的OpenCV2使用inRange抛出错误

python - 如何让不同的变量引用相同的值,同时仍然允许直接操作?

python - 根据当前日期添加和计算行的非零值

python - 如何在 Pandas Dataframe 中的 groupby 之后使用 assign 函数

python - 配置单元查询插入问题

python - 为什么我的 geopy 循环总是以 Killed : 9? 结束

python - Flask 蓝图将对象传递到另一个文件

python-3.x - 使用 df ['C' ] 与 df.loc[ :, 'C' ] 在 Pandas 数据框中分配新列