简体   繁体   English

从 df.query() 字符串获取左右边界

[英]Getting left and right bounds from df.query() string

I'm trying to get some extra info from strings that I feed into df.query()我正在尝试从输入df.query() 的字符串中获取一些额外信息

Currently I'm doing data cleaning with:目前我正在做数据清理:

df = pd.DataFrame({'A': range(1, 6),
                   'B': range(10, 0, -2),
                   'C': range(10, 5, -1)})

query_string = "6 <= B <= 8"

df.query(query_string)

df >>
   A   B    C
1  2   8    9
2  3   6    8

I'm wondering if it would be possible to somehow get the bounds for the query, something like this:我想知道是否有可能以某种方式获得查询的边界,如下所示:

query_string = "6 <= B <= 8"
bounds = some_get_bounds_function(query_string)

bounds >>
(6, 8)

Tried looking around for any ideas better than just parsing the strings myself.尝试四处寻找任何想法,而不仅仅是自己解析字符串。

Thanks!谢谢!

You can split and return the part of the string before the first and after the last space and create a tuple by separating the two with a comma and enclosing with parentheses:您可以split并返回第一个空格之前和最后一个空格之后的字符串部分,并通过用逗号分隔两者并用括号括起来来创建tuple

bounds = (int(query_string.split()[0]), int(query_string.split()[-1]))
bounds
(6, 8)

Or better, per your comment:或者更好,根据您的评论:

bounds = (df['B'].min(), df['B'].max())
bounds
(6, 8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM