简体   繁体   English

根据两个条件在python中的数据框中选择行

[英]select rows in a dataframe in python based on two criteria

Based on the dataframe (1) below, I wish to create a dataframe (2) where either y or z is equal to 2. Is there a way to do this conveniently? 基于下面的数据帧(1),我希望创建一个数据帧(2),其中y或z等于2.有没有办法方便地做到这一点?

And if I were to create a dataframe (3) that only contains rows from dataframe (1) but not dataframe (2), how should I approach it? 如果我要创建一个只包含来自dataframe(1)但不包含dataframe(2)的行的数据帧(3),我应该如何处理它?

    id  x  y  z 
    0 324  1  2
    1 213  1  1
    2 529  2  1
    3 347  3  2
    4 109  2  2

... ...

df[df[['y','z']].eq(2).any(1)]
Out[1205]: 
   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2

You can create df2 easily enough using a condition: 您可以使用条件轻松创建df2

df2 = df1[df1.y.eq(2) | df1.z.eq(2)]

df2
      x  y  z
id           
0   324  1  2
2   529  2  1
3   347  3  2
4   109  2  2

Given df2 and df1 , you can perform a set difference operation on the index, like this: 给定df2df1 ,您可以对索引执行设置差异操作,如下所示:

df3 = df1.iloc[df1.index.difference(df2.index)]

df3 
      x  y  z
id           
1   213  1  1

You can do the following: 您可以执行以下操作:

import pandas as pd

df = pd.read_csv('data.csv')
df2 = df[(df.y == 2) | (df.z == 2)]

print(df2)

Results: 结果:

   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据Python中的另一个数据框选择数据框的行 - Select rows of a dataframe based on another dataframe in Python select dataframe 行如何根据索引值和列值判断? - How to select dataframe rows based on index value and columns value criteria? 根据多个条件从 Pandas DataFrame 中随机选择行 - Randomly select rows from Pandas DataFrame based on multiple criteria 按条件过滤行和 select 多列来自 dataframe 和 python Z3A43B4F88325D94022C0EFA9 - Filter rows by criteria and select multiple columns from a dataframe with python pandas 删除基于索引的行熊猫数据框(多个条件)(Python 3.5.1) - Delete rows pandas Dataframe based on index (multiple criteria) (Python 3.5.1) 如何使用Python根据另一个DataFrame中的行选择DataFrame中的行 - How to select rows in a DataFrame based on rows in another DataFrame using Python 使用 Python 删除满足两个特定条件(值)的数据帧行 - Drop dataframe rows that meet two specific criteria (values) using Python Python DataFrame - 根据另一个数据帧中的值选择数据帧行 - Python DataFrame - Select dataframe rows based on values in another dataframe 为什么不能根据多个或条件在 python pandas 数据框中选择数据 - Why not able to select data in python pandas dataframe based on multiple or criteria Python DataFrame - Select dataframe rows based on values in a column of same dataframe - Python DataFrame - Select dataframe rows based on values in a column of same dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM