Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pandas to select rows using two different columns from dataframe?

Tags:

python

pandas

Q is similar to this: use a list of values to select rows from a pandas dataframe

I want to dataframe if either value in two columns are in a list. Return both columns (combine results of #1 and #4.

import numpy as np
from pandas import *


d = {'one' : [1., 2., 3., 4] ,'two' : [5., 6., 7., 8.],'three' : [9., 16., 17., 18.]}

df = DataFrame(d)
print df

checkList = [1,7]

print df[df.one == 1 ]#1
print df[df.one == 7 ]#2
print df[df.two == 1 ]#3
print df[df.two == 7 ]#4

#print df[df.one == 1 or df.two ==7]
print df[df.one.isin(checkList)]
like image 932
Merlin Avatar asked Dec 18 '12 16:12

Merlin


People also ask

How do I select specific rows and columns from a DataFrame?

To select a single value from the DataFrame, you can do the following. You can use slicing to select a particular column. To select rows and columns simultaneously, you need to understand the use of comma in the square brackets.


1 Answers

You nearly had it, but you have to use the "bitwise or" operator:

In [6]: df[(df.one == 1) | (df.two == 7)]
Out[6]: 
   one  three  two
0    1      9    5
2    3     17    7

In [7]: df[(df.one.isin(checkList)) | (df.two.isin(checkList))]
Out[7]: 
   one  three  two
0    1      9    5
2    3     17    7
like image 83
Andy Hayden Avatar answered Oct 12 '22 09:10

Andy Hayden