python - 索引具有多个条件的 Python Pandas 数据框 SQL like where 语句

标签 python sql indexing pandas

我在 R 方面经验丰富,但对 Python Pandas 不熟悉。我正在尝试索引一个 DataFrame 以检索满足一组几个逻辑条件的行——很像 SQL 的“where”语句。

我知道如何在 R 中使用数据框(以及 R 的 data.table 包,它更像是 Pandas DataFrame 而不是 R 的 native 数据框)执行此操作。

下面是一些构建 DataFrame 的示例代码以及我希望如何对其进行索引的描述。有没有简单的方法可以做到这一点?

import pandas as pd
import numpy as np

# generate some data
mult = 10000
fruits = ['Apple', 'Banana', 'Kiwi', 'Grape', 'Orange', 'Strawberry']*mult
vegetables = ['Asparagus', 'Broccoli', 'Carrot', 'Lettuce', 'Rutabaga', 'Spinach']*mult
animals = ['Dog', 'Cat', 'Bird', 'Fish', 'Lion', 'Mouse']*mult
xValues = np.random.normal(loc=80, scale=2, size=6*mult)
yValues = np.random.normal(loc=79, scale=2, size=6*mult)

data = {'Fruit': fruits,
        'Vegetable': vegetables, 
        'Animal': animals, 
        'xValue': xValues,
        'yValue': yValues,}

df = pd.DataFrame(data)

# shuffle the columns to break structure of repeating fruits, vegetables, animals
np.random.shuffle(df.Fruit)
np.random.shuffle(df.Vegetable)
np.random.shuffle(df.Animal)

df.head(30)

# filter sets
fruitsInclude = ['Apple', 'Banana', 'Grape']
vegetablesExclude = ['Asparagus', 'Broccoli']

# subset1:  All rows and columns where:
#   (fruit in fruitsInclude) AND (Vegetable not in vegetablesExlude)

# subset2:  All rows and columns where:
#   (fruit in fruitsInclude) AND [(Vegetable not in vegetablesExlude) OR (Animal == 'Dog')]

# subset3:  All rows and specific columns where above logical conditions are true.

欢迎并高度赞赏所有帮助和意见!

谢谢, 兰德尔

最佳答案

# subset1:  All rows and columns where:
#   (fruit in fruitsInclude) AND (Vegetable not in vegetablesExlude)
df.ix[df['Fruit'].isin(fruitsInclude) & ~df['Vegetable'].isin(vegetablesExclude)]

# subset2:  All rows and columns where:
#   (fruit in fruitsInclude) AND [(Vegetable not in vegetablesExlude) OR (Animal == 'Dog')]
df.ix[df['Fruit'].isin(fruitsInclude) & (~df['Vegetable'].isin(vegetablesExclude) | (df['Animal']=='Dog'))]

# subset3:  All rows and specific columns where above logical conditions are true.
df.ix[df['Fruit'].isin(fruitsInclude) & ~df['Vegetable'].isin(vegetablesExclude) & (df['Animal']=='Dog')]

关于python - 索引具有多个条件的 Python Pandas 数据框 SQL like where 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17396898/

相关文章:

SQL 日期范围查询 - 表比较

当第二个表添加到查询时,MySQL 日期范围索引被忽略

SQL NOT IN 语句不使用索引检索数据

sql - Postgres - 使用 where 子句的慢速简单连接

python - 如何更改数组中元素的索引

python - 如何解决我的音乐游戏中的这个问题?

python - pipenv shell在虚拟环境中启动子shell… 'powershell.exe'无法识别为内部或外部命令,可操作程序或

Python 将自定义属性/元数据添加到文件

python - Django 表单、jquery 和 Balanced Payments API 如何交互以创建买家帐户?

sql - 无法获取有关 Windows NT 组用户的信息