pandas: Boolean indexing with multi index

前端 未结 6 1651
再見小時候
再見小時候 2021-02-08 14:52

There are many questions here with similar titles, but I couldn\'t find one that\'s addressing this issue.

I have dataframes from many different origins, and I want to f

6条回答
  •  别跟我提以往
    2021-02-08 15:32

    Simply:

    df.where(
        filt.rename_axis('a').rename('c').to_frame()
    ).dropna().astype(int)
    

    Explanation:

    • .rename_axis('a') renames the index as a (the index we want to filter by)
    • .rename('c') renames the column as c (the column that stores the values)
    • .to_frame() converts this Series into a DataFrame, for compatibility with df
    • df.where(...) filters the rows, leaving missing values (NaN) where filter is False
    • .drop_na() removes the rows with missing values (in our case where a == 2)
    • .astype(int) converts from float back to int (not sure why float to begin with)

    By the way, it seems that df.where(...) and df[...] behave similarly here, so take your pick.

提交回复
热议问题