[英]How do i lookup a row on one dataframe based on the column cell value and append that to a row on another dataframe?
[英]DataFrame: How to toggle a cell value base on another cell of the row?
我有參加聚會的朋友名單:
import pandas as pd
d = {'name': ['Alice', 'Bob', 'Charlie'], 'is_here': [True, True, False]}
df = pd.DataFrame(data=d)
問題:如何根據給定名稱切換is_here
布爾值? (例如,如何進行toggle('Charlie')
在我的DataFrame中將False
變為True
?)
我可以使用df[df['name'] == 'Charlie'].iloc[0]['is_here']
來獲得一個布爾狀態df[df['name'] == 'Charlie'].iloc[0]['is_here']
,但我很難改變df
的值。
xor
切換Charlie
df.loc[df.name.eq('Charlie'), 'is_here'] ^= True
df
is_here name
0 True Alice
1 True Bob
2 True Charlie
只有一個可以是真的
xor
真值表
x y x ^ y
0 True True False
1 True False True
2 False True True
3 False False False
所以:
如果x = True
,則x ^ True
計算為False
如果x = False
,則x ^ True
計算結果為True
在loc
上使用^=
,對於用切片表示的所有元素,我們將xor
與True
一起使用,並將結果分配到位。
您可以使用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
要更新映射
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
查詢您的映射
從您的數據框:
ishere = df.set_index('name')['is_here'].get
print(ishere('Alice')) # True
從你原來的字典:
ishere = dict(zip(d['name'], d['is_here'])).get
print(ishere('Alice')) # True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.