[英]Python Dataframe: Assign values to a column based on condition?
I have a df with name
and status
with present and absent as values.我有一个带有name
和status
的 df,其中存在和不存在作为值。
name status
0 anthony present
1 anthony absent
2 mason present
3 donny present
4 donny absent
5 donny absent
6 paul present
7 paul present
I'm trying to put status - True or False
for each name.我正在尝试为每个名称设置状态 - True or False
。
If one of the name
has absent
their status will be False如果其中一个name
absent
其状态将为 False
Expected Output:预期输出:
name output
0 anthony False
1 mason True
2 donny False
3 paul True
You can compare status
to 'present'
then get the mininum by name
:您可以将status
与'present'
进行比较,然后按name
获取最小值:
# or `all()` instead of `min()`
df['status'].eq('present').groupby(df['name']).min()
Output:输出:
name
anthony False
donny False
mason True
paul True
Name: status, dtype: bool
Another way is to groupby name and find if a name has present as the only status.另一种方法是按名称分组并查找名称是否作为唯一状态存在。
df.groupby('name')['status'].apply(lambda x: (x=='present').all())
name
anthony False
donny False
mason True
paul True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.