Return dataframe subset based on a list of boolean values

前端 未结 6 2241
星月不相逢
星月不相逢 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条回答
  •  别那么骄傲
    2021-02-13 05:26

    Selecting using a list of Booleans is something itertools.compress does well.

    Given

    >>> df = pd.DataFrame(np.random.randint(10, size=(10, 2)))
    >>> selectors = [0, 1, 0, 0, 1, 1, 0, 0, 0, 1]
    

    Code

    >>> selected_idxs = list(itertools.compress(df.index, selectors))   # [1, 4, 5, 9]
    >>> df.iloc[selected_idxs, :]
       0  1
    1  1  9
    4  3  4
    5  4  1
    9  8  9
    

提交回复
热议问题