I have the following table of boolean values:
JavaScript
x
8
1
df = pd.DataFrame(data={'val1': [True, False, False, True],
2
'val2': [False, True, False, True],
3
'val3': [True, True, False, True],
4
'val4': [True, False, True, False],
5
'val5': [True, True, False, False],
6
'val6': [False, False, True, True]},
7
index=pd.Series([1, 2, 3, 4], name='index'))
8
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:
JavaScript
1
2
1
dict = {'val1': ['val2', 'val3'], 'val4': ['val5', 'val6']}
2
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:
JavaScript
1
4
1
for k, v in dict.items():
2
if df[k] == True:
3
df[v] = False
4
but I get the following error:
JavaScript
1
2
1
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
2
Advertisement
Answer
You can’t use if
with Series, which is only meant for scalar boolean check. Use conditional update with boolean indexing instead:
JavaScript
1
11
11
1
for k, v in dict.items():
2
df.loc[df[k], v] = False # update columns v where df[k] is True
3
4
df
5
val1 val2 val3 val4 val5 val6
6
index
7
1 True False False True False False
8
2 False True True False True False
9
3 False False False True False False
10
4 True False False False False True
11