user2293224
user2293224

Reputation: 2220

Python Pandas: filtering dataframe based on mask list throwing error

I have a list that contains True/False values. Index of the list is the id. List looks like as follow:

mask:

0000003555CE050     True
0000484541CE90D     True
0000486629CE4AA     True
0000012748DE8FB     True
0000047030DE4E4     True 
0000510518CEA7C    False
0000510762DE9AC    False
0000510486CEF04    False
0000202438DEE9C    False
0000510534CE437    False

I have a dataframe which also contains the id column. I want to keep values of those id that has True from the list. I am trying to filter the data frame using following command:

df.loc[:,mask]

However, I got TypeError which is as follows:

    TypeError: '(slice(None, None, None), 0000003555CE050     True
0000484541CE90D     True
0000486629CE4AA     True
0000012748DE8FB     True
0000047030DE4E4     True
                   ...  
0000510518CEA7C    False
0000510762DE9AC    False
0000510486CEF04    False
0000202438DEE9C    False
0000510534CE437    False
Name: ICP, Length: 92245, dtype: bool)' is an invalid key

I am not sure where am I making the mistake. Could anyone point out where am I making the mistake?

Upvotes: 0

Views: 280

Answers (1)

BENY
BENY

Reputation: 323226

Let us try get_level_values, you need know which level it is , for id column

df = df[df.columns.get_level_values(level=0).isin(mask.index[mask])]

Upvotes: 1

Related Questions