我今天有一个谎言
userlabel|country
SZ5GZTD_[56][13631808]|russia
YZ5GZTC-3_[51][13680735]|uk
XZ5GZTA_12-[51][13574893]|usa
testYZ5GZWC_11-[51][13632101]|cuba
我使用pandas
读取此csv,我想添加一个新列ci
,其值来自userlabel
,并且必须满足以下条件:
代码如下所示:
(df['userlabel'].str.lower()).str.extract(r"(test)?([a-z]+).*", expand=True)[1]
当它匹配时,ci
是第一个“-or u”和第二个“-or”之间的数字
伪代码如下所示:
ci = (userlabel,r'.*(\_|\-)(\d+)(\_|\-).*',2)
最后,结果是这样的
userlabel ci country
SZ5GZTD_[56][13631808] russia
YZ5GZTC-3_[51][13680735] 3 uk
XZ5GZTA_12-[51][13574893] usa
testYZ5GZWC_11-[51][13632101] 11 cuba
你可以用
请参阅regex demo。
正则表达式详细信息:
(?i)
-使模式不区分大小写(无需使用str.lower()
)^
-字符串的开头(?:yz|testyz)
-与yz
或testyz
匹配的非捕获组[^_-]*
-除_
和-
之外的零个或多个字符[_-]
-第一个{(\d+)
-group1(由于Series.str.extract
只返回这个捕获的子字符串,所以它需要一个捕获组):一个或多个数字[-_]
-a-
或_
李>相关问题 更多 >
编程相关推荐