在 pandas 中的特定行之后查找满足条件的下一个第一行

2024-03-03

我有一个像这样的熊猫数据框:

    first   second
0   True    False
1   False   True
2   True    True
3   False   False
4   False   True
5   False   True
6   True    False
7   False   False

可以使用以下代码创建:

import pandas as pd

df = pd.DataFrame(
    {
        'first': [True, False, True, False, False, False, True, False], 
        'second': [False, True, True, False, True, True, False, False]
    }
)

对于任何具有True值在first列,我想找到下一行中的第一行,其中值second列是True.

所以输出应该是:

    first   second
1   False   True
4   False   True

另外,我的首要任务是不使用任何 for 循环。

你对此有什么想法吗?


您可以使用:

g = df['first'].ne(df['first'].shift()).cumsum().loc[~df['first']]
# or
# g = df['first'].cumsum()[~df['first']]

out = df[df['second']].groupby(g).head(1)

Output:

   first  second
1  False    True
4  False    True

中石斑鱼g:

1    2
3    4
4    4
5    4
7    6
Name: first, dtype: int64
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 pandas 中的特定行之后查找满足条件的下一个第一行 的相关文章

随机推荐