在python中,如何将括号中的数字转换为负数?

2024-09-19 23:51:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列,其中的行具有如下字符串:

{"Manufacture":"1920","Comapany":"(BMW)","Loss":"(20)","price":"93"}
{"Manufacture":"1911","price":"20","shutdown":"(13)"}

我想将(数字)条目转换为-number 例如,在第一行输入输出将是

{"Manufacture":"1920","Comapany":"(BMW)","Loss":"-20","price":"93"}

损失分录为(20),转换为-20

第二行条目也是如此

{"Manufacture":"1911","price":"20","shutdown":"-13"}

Tags: 字符串number条目数字price损失输入输出loss
1条回答
网友
1楼 · 发布于 2024-09-19 23:51:53

试试看:

re.sub(r"\((\d+)\)", r"-\1", s)

示例:

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)

结果:

"{'Manufacture': '1911', 'price': '20', 'shutdown': '-13'}"

编辑:

假设您的df为:

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

相关问题 更多 >