12

I am relatively new to Python/Pandas and am struggling with extracting the correct data from a pd.Dataframe. What I actually have is a Dataframe with 3 columns:

data =

Position Letter Value
1        a      TRUE
2        f      FALSE
3        c      TRUE
4        d      TRUE
5        k      FALSE

What I want to do is put all of the TRUE rows into a new Dataframe so that the answer would be:

answer = 

Position Letter Value
1        a      TRUE
3        c      TRUE
4        d      TRUE

I know that you can access a particular column using

data['Value']

but how do I extract all of the TRUE rows?

Thanks for any help and advice,

Alex

1

2 Answers 2

23

You can test which Values are True:

In [11]: data['Value'] == True
Out[11]:
0     True
1    False
2     True
3     True
4    False
Name: Value, dtype: bool

and then use fancy indexing to pull out those rows:

In [12]: data[data['Value'] == True]
Out[12]:
   Position Letter Value
0         1      a  True
2         3      c  True
3         4      d  True

*Note: if the values are actually the strings 'TRUE' and 'FALSE' (they probably shouldn't be!) then use:

data['Value'] == 'TRUE'
Sign up to request clarification or add additional context in comments.

Comments

0

You can wrap your value/values in a list and do the following:

new_df = df.loc[df['yourColumnName'].isin(['your', 'list', 'items'])]

This will return a new dataframe consisting of rows where your list items match your column name in df.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.