代码之家  ›  专栏  ›  技术社区  ›  Josh Friedlander

在熊猫数据框中的任意位置搜索值

  •  1
  • Josh Friedlander  · 技术社区  · 6 年前

    这似乎是一个简单的问题,但我以前找不到它( this this 很接近,但答案不太好)。

    问题是:如果我想搜索一个值 在某处 在我的df中(我不知道它在哪个列中),返回所有匹配的行。

    最泛泛的方法是什么?有什么比这更好的吗?

    for col in list(df):
        try:    
            df[col] == var
            return df[df[col] == var]
        except TypeError:
            continue 
    

    ?

    2 回复  |  直到 6 年前
        1
  •  2
  •   cs95 abhishek58g    6 年前

    可以对整个数据帧执行相等比较:

    df[df.eq(var1).any(1)]
    

    另一个选择是使用 numpy 比较:

    df[(df.values.ravel() == var1).reshape(df.shape).any(1)]
    
        2
  •  2
  •   BENY    6 年前

    你应该用 isin ,这是返回列,是要行检查冷'答案:-)

    df.isin(['bal1']).any()
    A        False
    B         True
    C        False
    CLASS    False
    dtype: bool
    

    df[df.isin(['bal1'])].stack() # level 0 index is row index , level 1 index is columns which contain that value 
    0  B    bal1
    1  B    bal1
    dtype: object