[英]Using complex operations in query method of pandas
Let say I have below code,假设我有以下代码,
import pandas as pd
dat = pd.DataFrame({'col1' : [1,2,3,4,5,6,7,8,9,10], 'col2' : ['A', 'X', 'D', 'Y', 'A', 'D', 'Y', 'X', 'D', 'A']})
dat1 = pd.DataFrame({'col1' : [1,2,3,4,5,6,7,8,9,10], 'col2' : ['A', 'X', 'D', 'Y', 'A', 'D', 'Y', 'X', 'D', 'A']})
number = dat['col1'].values[dat.shape[0] - 3]
dat1.query("col1 == @number")
now instead of using @number
in the last line, I want pass entire calculation dat['col1'].values[dat.shape[0] - 3]
in the query
method.现在我不想在最后一行使用
@number
,而是想在query
方法中传递整个计算dat['col1'].values[dat.shape[0] - 3]
。
Is there any way to achieve this?有什么办法可以做到这一点?
What exactly is your use case?你的用例到底是什么?
query
does not support such complex expression. query
不支持这种复杂的表达式。
You can however use loc
with a callable, which enables you to use a dynamic expression in a pipeline:但是,您可以将
loc
与可调用对象一起使用,这使您能够在管道中使用动态表达式:
dat1.loc[lambda d: d['col1'].eq(d['col1'].values[d.shape[0] - 3])]
output:输出:
col1 col2
7 8 X
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.