2016-07-29 84 views
2

我想提取從feccandid柱具有一個H或S作爲第一值的行:熊貓:選擇行從列使用正則表達式

cid  amount date catcode  feccandid 
0 N00031317 1000 2010 B2000 H0FL19080 
1 N00027464 5000 2009 B1000 H6IA01098 
2 N00024875 1000 2009 A5200 S2IL08088 
3 N00030957 2000 2010 J2200 S0TN04195 
4 N00026591 1000 2009 F3300 S4KY06072 
5 N00031317 1000 2010 B2000 P0FL19080 
6 N00027464 5000 2009 B1000 P6IA01098 
7 N00024875 1000 2009 A5200 S2IL08088 
8 N00030957 2000 2010 J2200 H0TN04195 
9 N00026591 1000 2009 F3300 H4KY06072 

我使用這個代碼:

campaign_contributions.loc[campaign_contributions['feccandid'].astype(str).str.extractall(r'^(?:S|H)')] 

返回錯誤: ValueError: pattern contains no capture groups

有沒有人有使用正則表達式的經驗知道我在做什麼錯?

回答

2

對於一些這個簡單,你可以繞過正則表達式:

relevant = campaign_contributions.feccandid.str.startswith('H') | \ 
    campaign_contributions.feccandid.str.startswith('S') 
campaign_contributions[relevant] 

但是,如果你想使用正則表達式,你可以改變這

relevant = ~campaign_contributions['feccandid'].str.extract(r'^(S|H)').isnull() 

注意,astype是多餘的,那extract就夠了。