USING LIKE inside pandas.query()

后端 未结 6 566
庸人自扰
庸人自扰 2020-12-13 18:22

I have been using Pandas for more than 3 months and I have an fair idea about the dataframes accessing and querying etc.

I have got an requirement wherein I wanted t

6条回答
  •  囚心锁ツ
    2020-12-13 18:42

    Not using query(), but this will give you what you're looking for:

    df[df.col_name.str.startswith('abc')]
    
    
    df
    Out[93]: 
      col_name
    0     this
    1     that
    2     abcd
    
    df[df.col_name.str.startswith('abc')]
    Out[94]: 
      col_name
    2     abcd
    

    Query uses the pandas eval() and is limited in what you can use within it. If you want to use pure SQL you could consider pandasql where the following statement would work for you:

    sqldf("select col_name from df where col_name like 'abc%';", locals())
    

    Or alternately if your problem with the pandas str methods was that your column wasn't entirely of string type you could do the following:

    df[df.col_name.str.startswith('abc').fillna(False)]
    

提交回复
热议问题