代码之家  ›  专栏  ›  技术社区  ›  Oalvinegro

如何在pandas中添加带有countif的行

  •  1
  • Oalvinegro  · 技术社区  · 6 年前

    我有一个值为1和2的数据帧。
    COUNTIF(A:A,1) 并拖动到excel中的所有列

    我试过类似的东西 df.loc['lastrow']=df.count()[1] ,但结果不正确。
    我怎么做,这个功能是什么( count()[1] )是吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   BENY    6 年前

    你能行 append 之后 sum

    df.append(df.eq(1).sum(),ignore_index=True )
    
        2
  •  2
  •   willeM_ Van Onsem    6 年前

    您可以将数据帧与感兴趣的值进行比较( 1

    >>> df
       0  1  2  3  4
    0  2  2  2  1  2
    1  2  2  2  2  2
    2  2  1  2  1  1
    3  1  2  2  1  1
    4  2  2  1  2  1
    5  2  2  2  2  2
    6  1  1  1  1  2
    7  2  2  1  1  1
    8  1  1  1  2  1
    9  2  2  1  2  1
    >>> (df == 1).sum()
    0    3
    1    3
    2    5
    3    5
    4    6
    dtype: int64
    

    你可以这样做 追加 那一排,比如:

    >>> df.append((df == 1).sum(), ignore_index=True)
        0  1  2  3  4
    0   2  2  2  1  2
    1   2  2  2  2  2
    2   2  1  2  1  1
    3   1  2  2  1  1
    4   2  2  1  2  1
    5   2  2  2  2  2
    6   1  1  1  1  2
    7   2  2  1  1  1
    8   1  1  1  2  1
    9   2  2  1  2  1
    10  3  3  5  5  6
    

    因此,这里的最后一行包含 1. 上一行的s。