pandas 查询功能不适用于列名称中的空格 [英] Pandas query function not working with spaces in column names
本文介绍了 pandas 查询功能不适用于列名称中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,其列名中带有空格.我正在尝试使用query
方法来获取结果.可以在"c"列中正常工作,但会出现"a b"错误
I have a dataframe with spaces in column names. I am trying to use query
method to get the results. It is working fine with 'c' column but getting error for 'a b'
import pandas as pd
a = pd.DataFrame(columns=["a b", "c"])
a["a b"] = [1,2,3,4]
a["c"] = [5,6,7,8]
a.query('a b==5')
为此,我收到此错误:
a b ==5
^
SyntaxError: invalid syntax
我不想用'_'等其他字符填充空间.
I don't want to fill up space with other characters like '_' etc.
有一种黑客使用pandasql将变量名放在方括号内,例如: [a b]
There is one hack using pandasql to put variable name inside brackets example: [a b]
推荐答案
从熊猫0.25
开始,您将能够使用反引号对列名进行转义,从而可以
From pandas 0.25
onward you will be able to escape column names with backticks so you can do
a.query('`a b` == 5')
这篇关于 pandas 查询功能不适用于列名称中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文