使用熊猫查询具有多个单词标题的列

时间:2020-05-23 21:44:44

标签: python pandas dataframe

如果使用此代码,则可以在bar中获得所有带有A的行

import pandas as pd
 df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split()})
 print(df)
print("=============")
print( df.query('A== "bar"') )

WSo使用此代码时,我希望在bar中获得所有带有A thing的行,但会出现错误。

import pandas as pd
 df = pd.DataFrame({'A thing': 'foo bar foo bar foo bar foo foo'.split(),
                   'B thing': 'one one two three two two one three'.split()})
 print(df)
print("=============")
print( df.query('A thing== "bar"') )

有没有一种方法可以处理列名中的空格?

2 个答案:

答案 0 :(得分:3)

对于0.25+的熊猫,您可以使用反引号:

df.query('`A thing` == "bar"')

以前的版本-您无法做您想做的-您必须坚持使用有效的Python文字名称在查询中使用。

答案 1 :(得分:1)

您需要在变量名中使用下划线而不是空格

php artisan config:cache

pandas使用内置的python eval()对其进行评估。 因此,请参阅此内容以获得更好,更清晰的理解。

df = pd.DataFrame({'A_thing': 'foo bar foo bar foo bar foo foo'.split(),
                   'B_thing': 'one one two three two two one three'.split()})

但是

a='apple' 
apple='ball'
print(eval(a)) // Will give ball as output

假设我写“ my name ='joker'”代替,如果“ myname ='joker'”在这种情况下对于第一条语句肯定是错误的。并且变量名中有空格的python编译器不接受该语法。

关键字典也是一个变量,因此它们之间不接受空格。 如果您有更多疑问,请对此线程发表评论。请进一步解释。

相关问题