2016-07-29 97 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就够了。