【问题标题】:python/pandas: using regular expressions remove anything in square brackets in stringpython/pandas:使用正则表达式删除字符串中方括号中的任何内容
【发布时间】:2018-07-14 23:27:44
【问题描述】:

使用 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'[[^]]*\)','')

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为你需要:

    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.

    【讨论】:

    • @user3483203 对,你的建议也很有道理
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    相关资源
    最近更新 更多