Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataFrame: How to toggle a cell value base on another cell of the row?

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.

like image 379
ebosi Avatar asked Dec 17 '22 23:12

ebosi


2 Answers

Toggle 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

Explanation

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.

like image 65
piRSquared Avatar answered May 10 '23 22:05

piRSquared


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
like image 28
jpp Avatar answered May 10 '23 22:05

jpp