我想为 Python 数据框中的每个观察更改基于其他布尔变量的布尔变量

I want to change a boolean variable based on other boolean variables for every observation in a Python data frame

从数据框中看,数据摘要如下所示。这仅显示了多个 A、B 和 C 变量为 True 的子集。我只希望其中之一是真实的。我创建了 Multiples 变量 select 要更改的变量,摘要如下所示 table.

     A        B      C     Multiples
ID              
197 True    True    False   True
215 True    True    False   True
225 True    False   True    True
234 True    True    False   True
265 True    True    False   True
321 False   True    True    True

这是改进后的数据的示例。在每一行中,只有 A、B 或 C 中的一个为真,并且是最右边的一个。我需要知道如何在 Python 中进行更改。不要担心 Multiples 变量。当我重新计算时,A、B 和 C 如下所示,所有倍数都将为假。我已经有了执行此操作的代码。

 A        B      C     Multiples

ID
197 假 真 假 假
215 假 真 假 假
225 假 假 真 假
234 假 真 假 假
265 假 真 假 假
321 假 假 真 假

我搜索了网络和这个网站,但找不到任何有用的东西,至少我知道。

这是我当前的 Python 代码:

for index, item in enumerate(df['A']):
    if ((df['Multiples'] == True) & (df['C'] == True | df['B'] == True)):
        df['Multiples'] = False

如果只有一列为 True,您希望 Multiples 为 True:

import pandas as pd

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

df['Multiples'] = 0+df['A']+df['B']+df['C'] == 1

print(df)

那将输出:

       A      B      C  Multiples
0   True   True   True      False
1   True   True  False      False
2   True  False  False       True
3  False  False  False      False

要检查多个 True 列,请使用 > 1 而不是 == 1

我自己用下面的代码解决了这个问题:


def clear_redundant(row):
    # no need to change rows with only one True value
    if not row['Multiples']:
        return
    # if the last column is true, both earlier should be false
    if row['C']:
        row['A'] = False
        row['B'] = False
    # if the middle column is true, the first should be false
    elif row['B']:
        row['A'] = False

df.apply(clear_redundant, axis="columns")