python / pandas:使用正则表达式删除字符串中方括号中的所有内容

时间:2018-07-14 15:09:11

标签: python pandas

从pandas数据框开始尝试将列从$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'[[^]]*\)','')

对于某些开发人员来说,这是微不足道的,但我并没有真正经常使用正则表达式来了解这一点,并且我还检查了上述表达式,并从一个类似的堆栈示例中进行了检查。

1 个答案:

答案 0 :(得分:3)

我认为您需要:

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

相关问题