I have a list of friends attending my party:
import pandas as pd
d = {'name': ['Alice', 'Bob', 'Charlie'], 'is_here': [True, True, False]}
df = pd.DataFrame(data=d)
Question: How can I toggle the is_here
boolean based on a given name? (e.g. how to make toggle('Charlie')
turns the False
into True
in my DataFrame?)
I can get one's status as a boolean using df[df['name'] == 'Charlie'].iloc[0]['is_here']
, but I struggle changing the value in df
.
Charlie
with xor
df.loc[df.name.eq('Charlie'), 'is_here'] ^= True
df
is_here name
0 True Alice
1 True Bob
2 True Charlie
Only one can be True
Truth Table for xor
x y x ^ y
0 True True False
1 True False True
2 False True True
3 False False False
So:
if x = True
, x ^ True
evaluates to False
if x = False
, x ^ True
evaluates to True
Using ^=
on the loc
, we take the xor
with True
for all elements represented with the slice and assign the results in place.
To update your mapping
df = df.set_index('name')
df.loc['Charlie', 'is_here'] = ~df.loc['Charlie', 'is_here']
print(df.reset_index())
# name is_here
# 0 Alice True
# 1 Bob True
# 2 Charlie True
To query your mapping
From your dataframe:
ishere = df.set_index('name')['is_here'].get
print(ishere('Alice')) # True
From your original dictionary:
ishere = dict(zip(d['name'], d['is_here'])).get
print(ishere('Alice')) # True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With