【问题标题】:DataFrame: How to toggle a cell value base on another cell of the row?DataFrame:如何根据行的另一个单元格切换单元格值?
【发布时间】:2018-04-13 00:59:17
【问题描述】:

我有一份参加聚会的朋友名单:

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 中的值。

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    切换Charliexor

    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 = Truex ^ True 计算为False
    如果x = Falsex ^ True 计算结果为True

    loc 上使用^=,我们将xorTrue 用于切片表示的所有元素,并将结果分配到位。

    【讨论】:

      【解决方案2】:

      更新您的地图

      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
      

      【讨论】:

        【解决方案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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-01
          • 2019-06-16
          • 1970-01-01
          • 2012-05-15
          • 1970-01-01
          相关资源
          最近更新 更多