Unable to query a local variable in pandas 0.14.0

前端 未结 2 1670
北荒
北荒 2020-12-10 12:57

I can query an explicit value:

fills.query(\'Symbol==\"BUD US\"\')

Now I want to query a variable:

In [40]: my_symbol
Out[4         


        
相关标签:
2条回答
  • 2020-12-10 13:26

    Seems a bug in 0.14, specifically with strings (works eg with ints). I filed an issue here: https://github.com/pydata/pandas/issues/7300.
    As a workaround for now, you can wrap it in a list:

    In [40]: fills
    Out[40]: 
        Price  Symbol
    0  109.70  BUD US
    1  109.72  BUD US
    2  183.30  IBM US
    3  183.35  IBM US
    
    In [41]: my_symbol = ['BUD US']
    
    In [42]: fills.query('Symbol==@my_symbol')
    Out[42]: 
        Price  Symbol
    0  109.70  BUD US
    1  109.72  BUD US
    
    0 讨论(0)
  • 2020-12-10 13:34

    The above answer is pretty much right on, but wanted to mention another workaround that I've used in this situation. Basically, just treat the query string like you would any other string where you'd want to insert a variable.

    my_symbol = 'BUD US'
    fills.query("Symbol=='{0}'".format(my_symbol))
    

    edit: fixed per your comment

    0 讨论(0)
提交回复
热议问题