Skip to content
Advertisement

Turn cell into False based another row/column Pandas

I have the following table of boolean values:

df = pd.DataFrame(data={'val1': [True, False, False, True], 
                        'val2': [False, True, False, True], 
                        'val3': [True, True, False, True], 
                        'val4': [True, False, True, False], 
                        'val5': [True, True, False, False],
                        'val6': [False, False, True, True]},
                        index=pd.Series([1, 2, 3, 4], name='index'))
index val1 val2 val3 val4 val5 val6
1 True False True True True False
2 False True True False True False
3 False False False True False True
4 True True True False False True

I also have the following dictionary:

dict = {'val1': ['val2', 'val3'], 'val4': ['val5', 'val6']}

How do I change the table so for every key column in dict, if that row has a True value, the value columns turn to False?

index val1 val2 val3 val4 val5 val6
1 True False False True False False
2 False True True False True False
3 False False False True False False
4 True False False False False True

For example, since val1 is True at index 1, val2 and val3 turned to False

I’m doing something like this:

for k, v in dict.items():
    if df[k] == True:
        df[v] = False

but I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Advertisement

Answer

You can’t use if with Series, which is only meant for scalar boolean check. Use conditional update with boolean indexing instead:

for k, v in dict.items():
    df.loc[df[k], v] = False  # update columns v where df[k] is True

df
        val1   val2   val3   val4   val5   val6
index                                          
1       True  False  False   True  False  False
2      False   True   True  False   True  False
3      False  False  False   True  False  False
4       True  False  False  False  False   True
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement