DataFrame: how to switch the base of cell values ​​to another cell in a 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 switch a is_hereboolean based on a given name? (for example, how to make toggle('Charlie')turns Falseinto Truein my DataFrame?)


I can get one status as a boolean using df[df['name'] == 'Charlie'].iloc[0]['is_here'], but I'm trying to change the value in df.

+4
source share
3 answers

Toggle Charliewithxor

df.loc[df.name.eq('Charlie'), 'is_here'] ^= True

df

   is_here     name
0     True    Alice
1     True      Bob
2     True  Charlie

Description

Only True 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 ^ Trueevaluated as False
if x = False, x ^ Trueevaluated asTrue

^= loc, xor True , , .

+5

set_index + .loc

df.set_index('name',inplace=True)
df.loc['Alice']
Out[164]: 
is_here    True
Name: Alice, dtype: bool

df.loc[df.name=='Charlie','is_here']=True
df
Out[176]: 
   is_here     name
0     True    Alice
1     True      Bob
2     True  Charlie

2

df.loc[df.name=='Charlie','is_here']=~df['is_here']
df
Out[185]: 
   is_here     name
0     True    Alice
1     True      Bob
2     True  Charlie
+3

To refresh the display

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 request your mapping

From your data frame:

ishere = df.set_index('name')['is_here'].get

print(ishere('Alice'))  # True

From the source dictionary:

ishere = dict(zip(d['name'], d['is_here'])).get

print(ishere('Alice'))  # True
+3
source

Source: https://habr.com/ru/post/1696137/


All Articles