Pandas - Induce an opening/closing bracket or induce a Negative sign before the number

后端 未结 1 1017
暗喜
暗喜 2021-01-21 19:17

I have a column which has data with circular braces missing at times: The output required is to either remove the braces and induce a negative sign before the number or add star

相关标签:
1条回答
  • 2021-01-21 19:41

    You want to add a - before any number that is enclosed with at least one parenthesis on either left, or right, or on both sides.

    Use an alternation-based regex:

    df['testz'].str.replace(r'\(?\s*(\d+(?:,\d+)?)\s*\)|\(\s*(\d+(?:,\d+)?)\s*\)?', r'-\1\2')
    

    See the regex demo

    Details

    • \(?\s*(\d+(?:,\d+)?)\s*\) - an optional (, 0+ whitespaces, Group 1: 1+ digits followed with an optional sequence of , and 1+ digits; then 0+ whitespaces and a ) char
    • | - or
    • \(\s*(\d+(?:,\d+)?)\s*\)? - a ( char, 0+ whitespaces, Group 1: 1+ digits followed with an optional sequence of , and 1+ digits; then 0+ whitespaces and an optional ) char
    0 讨论(0)
提交回复
热议问题