【问题标题】:index a Python Pandas dataframe with multiple conditions SQL like where statement索引具有多个条件 SQL 的 Python Pandas 数据帧,例如 where 语句
【发布时间】:2013-06-28 03:03:08
【问题描述】:

我在 R 方面经验丰富,并且对 Python Pandas 很陌生。我正在尝试索引 DataFrame 以检索满足一组多个逻辑条件的行 - 很像 SQL 的“where”语句。

我知道如何在 R 中使用数据框(以及使用 R 的 data.table 包,它更像是 Pandas 数据框而不是 R 的本机数据框)。

这里有一些构建 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.

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

谢谢, 兰德尔

【问题讨论】:

  • 哇。正是我需要的。感谢您快速直接的回答。请注意,我拼写错误的蔬菜排除...应该是蔬菜排除(带 c)。在上面的代码中更正了它,因此应该复制并粘贴以进行测试。再次感谢。兰德尔。

标签: python sql indexing pandas


【解决方案1】:
# 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')]

【讨论】:

  • 也勉强打败我吧!这与我提出的 +1 完全相同的解决方案
  • 如果我想要的只是索引,有没有比这更短的方法:df.ix[df['Fruit'].isin(fruitsInclude).index
  • @Zhubarb: df.index[df['Fruit'].isin(fruitsInclude)]df.ix[df['Fruit'].isin(fruitsInclude)].index 更短并且(在我的机器上~33%)快。
猜你喜欢
  • 2020-12-13
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 2013-06-28
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
相关资源
最近更新 更多