简体   繁体   English

在 pandas df 中查找 A 列中的 True 值是否是自 B 列中最后一个 True 以来他的第一次出现

[英]In pandas df find if the True value in column A is his first occurrence since last True in column B

I'm searching for the most efficient way to find if True value in column A is the first occurrence since last True value in column B .我正在寻找最有效的方法来查找column A中的True值是否是自column B中的最后一个True值以来的第一次出现。 In this example the result would be column C .在此示例中,结果将是column C

df = pd.DataFrame({
    'A': [False, False, True, False, True, False, True, False, True],
    'B': [True, False, False, False, False, True, False, False, False],
    'C': [False, False, True, False, False, False, True, False, False]
})
A一个 B C C
0 0 False错误的 True真的 False错误的
1 1 False错误的 False错误的 False错误的
2 2 True真的 False错误的 True真的
3 3 False错误的 False错误的 False错误的
4 4 True真的 False错误的 False错误的
5 5 False错误的 True真的 False错误的
6 6 True真的 False错误的 True真的
7 7 False错误的 False错误的 False错误的
8 8 True真的 False错误的 False错误的

You can use a groupby operation on the cumulative sum of column "B" to group your dataframe how you described.您可以对“B”列的累积总和使用groupby操作,按照您的描述对 dataframe 进行分组。 Then you can use idxmax to get the index where each of those first occurrences exist within column "A".然后,您可以使用idxmax来获取每个第一次出现在“A”列中的索引。 Once you have those indices, you can create your new column "C".一旦你有了这些索引,你就可以创建你的新列“C”。

Using idxmax is a little trick because we're not actually interested in the maximum value since column "A" only ever has True and False as its values.使用idxmax是一个小技巧,因为我们实际上对最大值并不感兴趣,因为“A”列只有TrueFalse作为其值。 idxmax will return the index of the first occurrence of the maximum (in this case, the first occurrence of True within each group), which is what we're specifically interested in. idxmax将返回最大值第一次出现的索引(在这种情况下,每个组中第一次出现True ),这是我们特别感兴趣的。

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

indices = df["A"].groupby(df["B"].cumsum()).idxmax()
df["C"] = False
df.loc[indices, "C"] = True

print(df)
       A      B      C
0  False   True  False
1  False  False  False
2   True  False   True
3  False  False  False
4   True  False  False
5  False   True  False
6   True  False   True
7  False  False  False
8   True  False  False

What I've tried until now is:到目前为止我尝试过的是:

is_occurred = False
def is_first_occurrence_since(column_to_check, column_occurence):
    global is_occurred
    if is_occurred and column_to_check == True:
        is_occurred = False
        return True
    elif not is_occurred and column_occurence == True:
        is_occurred = True
    return False
df.apply(lambda row: is_first_occurrence_since(row['A'], row['B']), axis=1)

Is there a better way?有没有更好的办法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM