Reputation: 2591
I know the topic is very well documented but I did not find a solution good enough. I have a boolean pandas series, myboolseries. I have a dataframe df. I want to filter df according to myboolseries (the index where the value is True).
myboolseries = pd.Series(data = [True, False, True], index = [2,5,8])
mydic = {"Age" : [14,12,55,22,98], "Name" : ["Pierre", "Mike", "Selena", "Victor", "Jesus"], "index" : [2,14,5,99,8]}
df = pd.DataFrame.from_dict(mydic).set_index("index")
Here is my solution (it does work), but I'm lookin for a more elegant way :
myboolseries = myboolseries[myboolseries].index
df[myboolseries]
Upvotes: 2
Views: 295
Reputation: 153460
You can try this:
df.reindex(myboolseries.loc[lambda x: x].index)
Output:
Age Name
2 14 Pierre
8 98 Jesus
Upvotes: 1
Reputation: 86
if your Boolean series is the same length of your DataFrame you can just :
df = df[boolseries]
thats it.
Upvotes: 1
Reputation: 75080
Try:
df.loc[df.index.isin(myboolseries.index)][myboolseries]
Age Name
index
2 14 Pierre
8 98 Jesus
Upvotes: 1