代码之家  ›  专栏  ›  技术社区  ›  KubiK888

如何将用户字符串输入转换为要作为参数传递给Python Pandas的drop函数的条件?

  •  -2
  • KubiK888  · 技术社区  · 7 年前

    在pandas中,如果要根据条件删除某些行,可以执行以下操作:

    df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
    

    主要变化部分如下,表示条件:

    (df.score < 50) & (df.score > 20)
    

    我正试图在此基础上创建自己的函数。

    def drop_condition(df, cond_in_str):
        df.drop(df[cond_in_str].index, inplace=True)
    

    这样称呼:

    drop_condition(df, 'df.score < 50')
    KeyError: 'df.score < 50'
    

    如何将条件字符串转换为Pandas drop函数将识别的参数条件?

    3 回复  |  直到 7 年前
        1
  •  0
  •   sundance    7 年前

    您可以按原样使用函数,只需不加引号:

    drop_condition(df, df.score < 50)
    
        2
  •  0
  •   user96564    7 年前

    创建另一个变量并分配给它怎么样?然后在函数中使用

    check_val = df.score > 50
    (drop_condition(df, check_val))
    
        3
  •  0
  •   harvpan    7 年前

    你需要使用 pandas.DataFrame.query() 它将表达式作为 string .

    def drop_condition(df, cond_in_str):
          df.drop(df.query(cond_in_str).index)