pandas 使用熊猫从数据框中使用两个不同的列选择行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13937022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:32:52  来源:igfitidea点击:

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

pythonpandas

提问by Merlin

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

Q 与此类似: 使用值列表从 Pandas 数据框中选择行

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

如果两列中的任何一个值都在列表中,我想要数据框。返回两列(组合 #1 和 #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)]

回答by Andy Hayden

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