I have a column with rows having a string like:
{"Manufacture":"1920","Comapany":"(BMW)","Loss":"(20)","price":"93"}
{"Manufacture":"1911","price":"20","shutdown":"(13)"}
I want to convert (number) entry with -number for example in first-row entry output will be
{"Manufacture":"1920","Comapany":"(BMW)","Loss":"-20","price":"93"}
Entry for loss is (20) which is converted to -20
same goes for second row entry
{"Manufacture":"1911","price":"20","shutdown":"-13"}
Try:
re.sub(r"\((\d+)\)", r"-\1", s)
Example:
s = str({"Manufacture":"1920","Comapany":"(BMW)","Loss":"(20)","price":"93"})
st = str({"Manufacture":"1911","price":"20","shutdown":"(13)"})
res = re.sub(r"\((\d+)\)", r"-\1", s)
res:
"{'Manufacture': '1920', 'Comapany': '(BMW)', 'Loss': '-20', 'price': '93'}"
result = re.sub(r"\((\d+)\)", r"-\1", st)
result:
"{'Manufacture': '1911', 'price': '20', 'shutdown': '-13'}"
Let say your df is:
0
0 {"Manufacture":"1920","Comapany":"(BMW)","Loss":"(20)","price":"93"}
1 {"Manufacture":"1911","price":"20","shutdown":"(13)"}
def num2neg(row):
return re.sub(r"\((\d+)\)", r"-\1", row)
df[0] = df[0].apply(num2neg)
df:
0
0 {"Manufacture":"1920","Comapany":"(BMW)","Loss":"-20","price":"93"}
1 {"Manufacture":"1911","price":"20","shutdown":"-13"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.