Python 使用pandas查询具有多词标题的列

Python 使用pandas查询具有多词标题的列,python,pandas,dataframe,Python,Pandas,Dataframe,如果使用此代码,则可以在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当我使用这个代

如果使用此代码,则可以在
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当我使用这个代码时,我希望在
一个东西中得到所有带有
条的行,但是我得到了一个错误

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+您可以使用反勾号:

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

以前的版本-您不能随心所欲-您必须坚持使用有效的Python文本名称来在查询中使用。

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

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()})
pandas使用python内置的eval()对其进行求值。 因此,为了更好、更清晰地理解这一点,请参见本文

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

假设我写的是“myname='joker'”,而不是“myname='joker'”,在这种情况下,第一条语句肯定会出错。python编译器不接受这种语法,因为变量名中有空格

键命令也是一个变量,因此不接受中间的空格。
如果您有更多疑问,请评论此帖子。我会进一步解释。

这是一个非常有用的答案。我正在从CSV中读取数据-有没有办法自动将空格转换为下划线?@Abijah一旦阅读完毕-手动更新列名?类似于:
df.columns=df.columns.str.replace(“\s+”,“"”)
a='app le' 
apple='ball'
print(eval(a)) // ERROR:unexpected EOF while parsing