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
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