我有参加聚会的朋友名单:
import pandas as pd
d = {'name': ['Alice', 'Bob', 'Charlie'], 'is_here': [True, True, False]}
df = pd.DataFrame(data=d)
问题:如何根据给定名称切换is_here
布尔值? (例如,如何toggle('Charlie')
将False
变为我的DataFrame中的True
?)
我可以使用df[df['name'] == 'Charlie'].iloc[0]['is_here']
获取一个布尔状态,但我很难改变df
中的值。
答案 0 :(得分:5)
Charlie
xor
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
一起用于切片所代表的所有元素并分配结果。
答案 1 :(得分:3)
您可以使用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
答案 2 :(得分:3)
更新地图
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