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
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.