Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas dataframe selecting with index and condition on a column

I am trying for a while to solve this problem:

I have a daraframe like this:

import pandas as pd
df=pd.DataFrame(np.array([['A', 2, 3], ['B', 5, 6], ['C', 8, 9]]),columns=['a', 'b', 'c'])
j=[0,2]

But then when i try to select just a part of it filtering by a list of index and a condition on a column I get error…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df[df.loc[j]['a']=='A']

There is somenting wrong, but i don’t get what is the problem here. Can you help me?

This is the error message:

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

>Solution :

There is filtered DataFrame compared by original, so indices are different, so error is raised.

You need compare filtered DataFrame:

df1 = df.loc[j]
print (df1)
   a  b  c
0  A  2  3
2  C  8  9

out = df1[df1['a']=='A']
print(out)
   a  b  c
0  A  2  3

Your solution is possible use with convert ndices of filtered mask by original indices by Series.reindex:

out = df[(df.loc[j, 'a']=='A').reindex(df.index, fill_value=False)]
print(out)
   a  b  c
0  A  2  3

Or nicer solution:

out = df[(df['a'] == 'A') & (df.index.isin(j))]
print(out)
   a  b  c
0  A  2  3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading