【问题标题】:Using pandas to select rows using two different columns from dataframe?使用 pandas 使用数据框中的两个不同列选择行?
【发布时间】:2012-12-18 16:11:22
【问题描述】:

Q 与此类似: use a list of values to select rows from a pandas dataframe

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你几乎拥有它,但你必须使用 "bitwise or" 运算符:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2023-04-05
      • 2017-08-10
      • 2015-01-22
      • 2022-10-13
      • 2021-05-09
      • 2021-09-29
      相关资源
      最近更新 更多