dataframe.query() 筛选 tips

1、常规操作

要从一个 dataframe 中,筛选出某些列值符合要求的行数据,可以用类似以下的语句实现:

df[df[col] == x]

也可以用 .query() 实现:

df.query(col == x)
2、其他操作方法

1)筛选出 col 列中值不是 bool 类型的行

df.query(col not in (True, False))

2)筛选出 col 列中值为 nan、None 的值

df = pd.DataFrame({"value": [3,4,9,10,11,np.nan,12]})

# 方法1
# 利用 nan 不等于自身 的性质,筛选出非 nan、None 的行
df.query(value == value)

# 方法2
# 类似的还有 isnull, notnull,isnan 等
df.query(value.notna(), engine=python)

# 方法3
df.query(value != NaN")

以上结果都是

Out[28]: 
   value
0    3.0
1    4.0
2    9.0
3   10.0
4   11.0
6   12.0
# 筛选出不是 NaT 的行(提前使用外部函数,超纲了哈)
df.query(col not in [@pd.NaT])

3)在 query 中筛选时引用外部变量

# 1. 外部为普通变量
# 方法1
pi = 3.1415
df.query(value < 10 and value > @pi)

# 方法2
pi = 3.1415
df.query(fvalue < 10 and value > {pi})

# 2.外部变量为 list
cond = [4, 12]
df.query(@cond[0] < value < @cond[1])

# 3.外部变量为 dict,注意中括号中不能有引号,因此要取 dict 的值,需要用 dict.get() 的方式
cond = {dn_band: 4, up_band: 12}
df.query("@cond.get(dn_band) < value < @cond.get(up_band)")

# 4.外部为函数
num = [2, 6] 
def func(x):
	return x * 2
df.query(@func(@num[0]) < value < @func(@num[1]))

以上的结果都是

Out[30]: 
   value
3   10.0
4   11.0

参考资料: 1、 2、

经验分享 程序员 微信小程序 职场和发展