python变量如何作为sql的where条件_索引具有多个条件的Python Pandas数据帧SQL where where语句...

我在R和Python Pandas的新手中很有经验.我试图索引一个DataFrame来检索满足一组几个逻辑条件的行 – 很像SQL的“where”语句.

我知道如何在R中使用数据帧(以及使用R的data.table包,这更像是Pandas DataFrame而不是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.

欢迎所有帮助和投入,并高度赞赏!

谢谢,

兰德尔

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值