Pandas 真假匹配

标签 pandas dataframe boolean calculated-columns

对于此表:
enter image description here
我想生成“desired_output”列。实现这一目标的一种方法可能是:

  • col_1 中的所有 True 值都直接传输到所需的输出(红色箭头)
  • 在 desired_output 中,将 True 值置于任何现有 True 值(绿色箭头)之上

  • 我试过的代码:
    df['desired_output']=df.col_1.apply(lambda x: True if x.shift()==True else False)
    
    谢谢

    最佳答案

    您可以通过 | 链接按位 OR原始值偏移 Series.shift :

    d = {"col1":[False,True,True,True,False,True,False,False,True,False,False,False]}
    df = pd.DataFrame(d)
    
    df['new'] = df.col1 | df.col1.shift(-1)
    print (df)
         col1    new
    0   False   True
    1    True   True
    2    True   True
    3    True   True
    4   False   True
    5    True   True
    6   False  False
    7   False   True
    8    True   True
    9   False  False
    10  False  False
    11  False  False
    

    关于 Pandas 真假匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63440200/

    相关文章:

    excel - 简单的 boolean 值和表达式

    python - 如何从 Pandas 数据框中的列表中删除值?

    python - Pandas ,选择一个列,其中第二列具有 NaN 值

    python - 如何在 streamlit 中使用 pandas.style

    python - Pandas 滚动最大与 groupby

    java - 如何在java中返回一个 boolean 方法?

    python - 使用 MultiIndex 和多列从 DataFrame 中绘制和注释

    python - 将单索引 DataFrame 复制到 MultiIndex DataFrame

    python - isin、str.contains 和 if 条件的区别?

    java - 使用 3 个 boolean 值的 If 语句