Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

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

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)]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...