Return dataframe subset based on a list of boolean values

前端 未结 6 2232
星月不相逢
星月不相逢 2021-02-13 04:38

I\'m trying to slice a dataframe based on list of values, how would I go about this?

Say I have an expression or a list l = [0,1,0,0,1,1,0,0,0,1]

Ho

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 05:36

    You can use masking here:

    df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]
    

    So we construct a boolean array with true and false. Every place where the array is True is a row we select.

    Mind that we do not filter inplace. In order to retrieve the result, you have to assign the result to an (optionally different) variable:

    df2 = df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]
    

提交回复
热议问题