2015-02-24 119 views
1

正在關注this recipe。我試圖通過包含字符串'+'的列名稱來過濾數據框。這裏的例子:如何通過列名稱中的'str'過濾pandas中的數據框?

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 

配方說,這是Python 3下我使用Python 2.7。但是,我認爲這不是問題。

埃爾南

回答

2

+在正則表達式有特殊意義(參見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 
+0

謝謝!相關的,是否有可能做類似C = B.filter(like =「+」或like =「 - 」)? – hernanavella 2015-02-24 18:36:57

+1

@hernanavella:不用''like',但是可以使用'regex',像'B.filter(regex =「\ + | - 」)'(其中'|'表示「或」)。但坦白地說,在那一點上,我不打算聰明,我只是寫'B [[如果在col中爲「+」或在col中爲「 - 」則在col中輸入col)]。 – DSM 2015-02-24 18:39:46

相關問題