简体   繁体   English

带双引号的熊猫查询 python

[英]panda query with double quotation python

I want pandas query with text possibly have a double quote.我想要 pandas 查询文本可能有双引号。 This text variable is passed in as a parameter.此文本变量作为参数传入。

text = 'this is "dave"'

df.query(r'index != "text"')

Here, theres an error这里,有一个错误

SyntaxError: Python keyword not valid identifier in numexpr query

Therefore, I changed the text to escape double quote因此,我更改了文本以转义双引号

text = text.replace('"','\"')

But the issue persists.但问题仍然存在。

How do I fix this我该如何解决

Use @ for pass variable to DataFrame.query :使用@将变量传递给DataFrame.query

df = pd.DataFrame({
        'A':list('abc'),
         'B':[4,5,6]

}, index=['this is "dave"','aa','bb'])

print (df)

                A  B
this is "dave"  a  4
aa              b  5
bb              c  6

text = 'this is "dave"'
print (df.query(r'index != @text'))
    A  B
aa  b  5
bb  c  6

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

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