我注意到从{0.25版本开始,使用pandas.DataFrame.query
时,列名中允许使用空格,即,这些列名应使用反引号引起来。例如:
import pandas as pd
df = pd.DataFrame({'a b':[1,0,1,1,0,0],
'c d':[1,0,1,1,0,0],
'e f':[0,0,0,0,1,0]})
print(df)
a b c d e f
0 1 1 0
1 0 0 0
2 1 1 0
3 1 1 0
4 0 0 1
5 0 0 0
q = "(`a b` == 1) | (`c d` == 1) | (`e f` == 1)"
df = df.query(q)
print (df)
a b c d e f
0 1 1 0
2 1 1 0
3 1 1 0
4 0 0 1
它可以正常工作,但我的列中可能包含“&”号,加号或其他特殊字符。目前似乎不支持他们:
df2 = pd.DataFrame({'a b+':[1,0,1,1,0,0],
'c | d':[1,0,1,1,0,0],
'e & f':[0,0,0,0,1,0]})
print(df2)
a b+ c | d e & f
0 1 1 0
1 0 0 0
2 1 1 0
3 1 1 0
4 0 0 1
5 0 0 0
q = "(`a b+` == 1) | (`c | d` == 1) | (`e & f` == 1)"
df2 = df2.query(q)
print (df2)
上次打印给我一个错误:
Traceback (most recent call last):
File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\computation\scope.py", line 188, in resolve
return self.resolvers[key]
File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\collections\__init__.py", line 914, in __getitem__
return self.__missing__(key) # support subclasses that define __missing__
File "C:\Users\XXX\AppData\Local\Programs\Python\Python37\lib\collections\__init__.py", line 906, in __missing__
raise KeyError(key)
KeyError: 'a_b_'
对于此方法或为数据框建立过滤条件,是否有其他解决方法?我想定义一个将动态过滤器返回为字符串的函数。
答案 0 :(得分:0)
实际上pandas在列名中支持unicode符号,它应该可以工作。 请尝试这种方法:
set1 = df2['a b+'] == 1
set2 df2['c | d'] == 1
print(df2[set1 | set2])
根据您的测试数据为我工作