【问题标题】:Filter Dataframe based on condition coming in request根据请求中的条件过滤数据框
【发布时间】:2023-01-10 16:02:44
【问题描述】:

我有一个数据框,我需要根据从 UI 请求中接收到的条件进行过滤。请求示例:

{
"table": "abc",
"condition": "A=98 and C=73 and D='rendom_char'"
} 

数据框示例:

A B C D
0 85 39 54 td
1 39 51 23 abc
2 98 17 73 def
3 98 52 73 def
4 85 52 21 rst
5 61 89 31 xvz

所以假设如果我从 UI 获得条件 "condition": "A=98 and C=73 and D='def'""condition": "A=98 and C=73" 输出应该是这样的:

A B C D
2 98 17 73 def
3 98 52 73 def

我面临的问题是如何将从 UI 获取的字符串条件转换为 python 形式,以便我可以在数据帧上应用过滤器。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用DataFrame.query替换=来加倍=

    d = {"condition": "A=98 and C=73 and D='def'"}
    print (df.query(d['condition'].replace('=','==')))
        A   B   C    D
    2  98  17  73  def
    3  98  52  73  def
    
    d = {"condition": "A=85 and C=21"}
    print (df.query(d['condition'].replace('=','==')))
    
        A   B   C    D
    4  85  52  21  rst
    

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2018-09-15
      相关资源
      最近更新 更多