![](/img/trans.png)
[英]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.