drop a series of true false in pandas removes first two lines

后端 未结 1 1879
孤街浪徒
孤街浪徒 2021-01-29 03:35

Handing the pandas.drop function a list of True and False statements drops the first two lines. Why? Is this a bug?

df = pd.DataFrame({         


        
相关标签:
1条回答
  • 2021-01-29 04:13

    Explanation why this happens

    No, this is not a bug, it is just a side-effect of that True and False are equal to 1 and 0

    This code:

    df = pd.DataFrame({"foo":[1,2,3]})
    df.drop([False, False, True])
    

    Is identical to this code:

    df = pd.DataFrame({"foo":[1,2,3]})
    df.drop([0, 0, 1])
    

    The pandas drop function takes a list of indicies to drop, not a mask.

    How to properly use the drop method

    The proper way of using masks to drop data is either to mask, then access the index and hand this to the drop function:

    df.drop(df[[False, False, True]].index)
       foo
    0    1
    1    2
    

    Or just by inverted masking:

    df[~pd.Series([False, False, True])]
       foo
    0    1
    1    2
    
    0 讨论(0)
提交回复
热议问题