gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:06:49 30 4
gpt4 key购买 nike

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

    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值的任何行,我想在接下来的行中找到该值的第一行第二列的值为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)

输出:

   first  second
1 False True
4 False True

中石斑鱼g:

1    2
3 4
4 4
5 4
7 6
Name: first, dtype: int64

关于python - 在 pandas 中的特定行之后查找满足条件的下一个第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73057952/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com