If you use this code, you can get all rows with bar
in 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 when I use this code, I expect to get all rows with bar
in A thing
but I get an error.
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"') )
有没有一种方法可以处理列名称中的空格?
对于0.25+的熊猫,您可以使用反引号:
先前的版本-您无法做您想做的-您必须坚持使用在查询中使用的有效Python文字名称。
您需要在变量名称中使用下划线而不是空格
pandas使用内置的python eval()对其进行评估。 因此请参阅此内容,以更好地理解。
但
假设我写“我的名字='小丑'”,而不是如果“我的名字='小丑'”,则在这种情况下对于第一条语句肯定存在错误。且python编译器不接受语法,其中变量名称中有空格。
密钥字典也是一个变量,因此它们之间不接受空格。 如果您有更多疑问,请对此线程发表评论。病再解释。