![](/img/trans.png)
[英]Extract items delimited with square brackets using python regular expressions
[英]python/pandas: using regular expressions remove anything in square brackets in string
从pandas数据$12,342
工作,尝试将列从$12,342
到12342
,然后将列设置为int或float。 虽然找到了736[4]
一行,所以我必须删除方括号(包括方括号)中的所有内容。
到目前为止的代码
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace('$','')
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(',','')
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(' ','')
下面的行是处理和删除方括号的内容,它的内容也是有意的。
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(r'[[^]]*\)','')
对于某些开发人员来说,这是微不足道的,但是我并没有真正经常使用正则表达式来了解这一点,并且我还检查了上述示例中的一个堆栈示例。
我认为您需要:
df2 = pd.DataFrame({'Average Monthly Wage $': ['736[4]','7336[445]', '[4]345[5]']})
print (df2)
Average Monthly Wage $
0 736[4]
1 7336[445]
2 [4]345[5]
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(r'\[.*?\]','')
print (df2)
Average Monthly Wage $
0 736
1 7336
2 345
regex101
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.