【问题标题】:Find next first row meeting a condition after a specific row in pandas在熊猫中的特定行之后找到满足条件的下一个第一行
【发布时间】:2023-01-31 14:01:32
【问题描述】:

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

    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 循环。

你知道吗?

【问题讨论】:

  • 它应该在每个第一个 True 上重置吗?例如,如果 1/second 为 False,那么 2 是否应该匹配?
  • 是的,它应该重置。因此,如果 1/second 是 False,则 2 不在输出中。

标签: python pandas dataframe


【解决方案1】:

您可以使用:

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

【讨论】:

  • 感谢您的回答。不要问一个新问题,如果它应该在每个第一个 True 上重置怎么办?例如,如果 1/second 是 False,则 2 应该匹配。 (正是你的问题:))
  • @mozway 你能解释一下这段代码的逻辑吗?谢谢
  • @GopalChitalia 当然,让组从“第一”的每个 True 开始(请参阅我的回答中的g),对于这些组中的每一个,只保留“第二”中有 True 的行并获得第一行团体。您实际上可以使它更简单一些,请参阅编辑。
【解决方案2】:

没有groupby的另一种方式:

out = (df.loc[df.loc[df.any(axis=1), 'first'].shift(fill_value=False)
         .loc[lambda x: x].index])
print(out)

# Output
   first  second
1  False    True
4  False    True

注意:它之所以有效,是因为 first 列的两个真值之间总是有一个 second 列的真值。

【讨论】:

    【解决方案3】:

    另一种方法:

    first_true_idx = df.loc[df['first']].index
    second_true_idx = df.loc[df['second']].index
    df = df.loc[second_true_idx[list(filter(
         lambda x:x>=0, [(second_true_idx  > e).tolist().index(True) 
                    if (second_true_idx > e).any() else -1 for e in first_true_idx]))]]
    

    打印(df):

    first  second
    1  False    True
    4  False    True
    

    我相信它应该适用于真实值处于“第二”的任何位置 基本上,我尝试为第一个真实索引中的每个索引在第二个真实索引中寻找第一个更大的索引。这正是你要问的。

    【讨论】:

      猜你喜欢
      • 2023-02-06
      • 1970-01-01
      • 2016-08-22
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多