如何通过列名称中的 'str' 过滤 pandas 中的数据框?
How to filter dataframe in pandas by 'str' in columns name?
关注 this recipe。我试图通过包含字符串“+”的列名来过滤数据框。这是示例:
B = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
columns=['A', '+B', '+C'], index=[1, 2, 3, 4, 5])
所以我想要一个只有“+B”和“+C”列的数据框 C。
C = B.filter(regex='+')
但是我收到错误:
File "c:\users\hernan\anaconda\lib\site-packages\pandas\core\generic.py", line 1888, in filter
matcher = re.compile(regex)
File "c:\users\hernan\anaconda\lib\re.py", line 190, in compile
return _compile(pattern, flags)
File "c:\users\hernan\anaconda\lib\re.py", line 244, in _compile
raise error, v # invalid expression
error: nothing to repeat
菜谱上说是Python3.我用的是python2.7。但是,我认为这不是这里的问题。
埃尔南
+
在正则表达式中有特殊含义(参见 here)。你可以使用 \
:
来逃避它
>>> C = B.filter(regex='\+')
>>> C
+B +C
1 5 2
2 4 4
3 3 1
4 2 2
5 1 4
或者,由于您只关心 +
的存在,您可以改用 like
参数:
>>> C = B.filter(like="+")
>>> C
+B +C
1 5 2
2 4 4
3 3 1
4 2 2
5 1 4
关注 this recipe。我试图通过包含字符串“+”的列名来过滤数据框。这是示例:
B = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
columns=['A', '+B', '+C'], index=[1, 2, 3, 4, 5])
所以我想要一个只有“+B”和“+C”列的数据框 C。
C = B.filter(regex='+')
但是我收到错误:
File "c:\users\hernan\anaconda\lib\site-packages\pandas\core\generic.py", line 1888, in filter
matcher = re.compile(regex)
File "c:\users\hernan\anaconda\lib\re.py", line 190, in compile
return _compile(pattern, flags)
File "c:\users\hernan\anaconda\lib\re.py", line 244, in _compile
raise error, v # invalid expression
error: nothing to repeat
菜谱上说是Python3.我用的是python2.7。但是,我认为这不是这里的问题。
埃尔南
+
在正则表达式中有特殊含义(参见 here)。你可以使用 \
:
>>> C = B.filter(regex='\+')
>>> C
+B +C
1 5 2
2 4 4
3 3 1
4 2 2
5 1 4
或者,由于您只关心 +
的存在,您可以改用 like
参数:
>>> C = B.filter(like="+")
>>> C
+B +C
1 5 2
2 4 4
3 3 1
4 2 2
5 1 4