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

筛选Pandas数据帧时出现问题

  •  0
  • user1245262  · 技术社区  · 1 年前

    我试图从Pandas数据帧中筛选值,但在谷歌上搜索和ChatGPT都无济于事:

    为什么

    x1 = df[df!=True]
    x2 = df[df==True]
    

    导致2个数据帧,每个数据帧的形状与原始数据帧的相同?如何将此数据帧筛选为True和非True的部分。?

    最终,我想在一个有几列的数据帧上进行过滤,所以我真正想做的是更多的lke:

    x1 = df[df['col1']!=True]
    x2 = df[df['col1']==True]
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Mark    1 年前

    举一个这样的例子:

    df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
    >>> df
       A  B
    0  1  4
    1  2  5
    2  3  6
    
    # df!=True checks for each value in the DataFrame if the value is equal to True (it matches on 1 because 1 is equivalent to True (and False equivalent to 0) when using "==" and "!="
    >>> df!=True 
           A     B
    0  False  True
    1   True  True
    2   True  True
    
    # df[df!=True] gets the values which are True in df!=True, and doesn't get anything for the ones which are false (hence A0 being NaN)
    >>> df[df!=True]
         A  B
    0  NaN  4
    1  2.0  5
    2  3.0  6
    
    # this is similar to example #1, but only looks at column 'A'
    >>> df['A']!=True
    0    False
    1     True
    2     True
    Name: A, dtype: bool
    

    筛选到列“A”==为True的行

    >>> df[df['A']!=True]
       A  B
    1  2  5
    2  3  6
    

    Pandas会在您想要筛选行时插入它,因此它会采用上一个示例中的值,并将行筛选为返回True的行。如果您只想要实际为True的值(即不匹配 1 s) ,您可以使用 is ,如

    1 is True # False