简体   繁体   English

Python Dataframe:根据条件为列分配值?

[英]Python Dataframe: Assign values to a column based on condition?

I have a df with name and status with present and absent as values.我有一个带有namestatus的 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.

相关问题 Python dataframe 基于另一列有条件的赋值 - Python dataframe assign values based on another column with condition 根据条件将一个 dataframe 列的值分配给另一个 dataframe 列 - assign values of one dataframe column to another dataframe column based on condition Python Dataframe:根据其他列将值分配给列? - Python Dataframe: Assign Values to a column based on other column? 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python 基于另一列在 dataframe 列中分配值 - Assign values in a dataframe column based on another column 根据另一个 dataframe 中的列分配值列 - Assign values column based on a column in another dataframe Python Dataframe如何根据条件创建新的列值 - Python Dataframe how to create a new column values based on a condition 根据 python dataframe 中的特定条件减去特定列的行值 - Subtracting values of a row for a specific column based on a specific condition in python dataframe 根据条件使用字典替换 python dataframe 中的列值 - Replace column values in python dataframe using dictionary based on condition 如何根据 Python 中的条件将来自另一个 dataframe 的值分配给当前 dataframe? - How to assign values from another dataframe to current dataframe based on a condition in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM