【问题标题】:How can convert number given in parenthesis with negative number in python?python - 如何将括号中给出的数字与python中的负数转换?
【发布时间】:2020-03-23 09:06:16
【问题描述】:

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

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

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

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

输入损失是 (20) 转换为 -20

第二行也一样

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

【问题讨论】:

  • 显示你尝试了什么?
  • 我尝试过使用正则表达式,但发现模式只会与转换任务 Details["Column"].str.replace(r"(\d+)", "-\d+") 混淆
  • str.replace 将仅用预定义的输入替换我的发现
  • 您想要整数或字符串类型的关闭和丢失值吗?
  • 所有东西都将与括号内的任何数字一样,将其转换为负数。示例 (23) 将是 -23。

标签: python pandas


【解决方案1】:

试试:

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)

分辨率:

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

【讨论】:

  • 感谢您的回答。我也在研究 re.sub 模块来完成任务。我必须循环传递我们的数据框并应用这种逻辑来获得答案。如果您知道如何在不使用循环的情况下传递我的所有这些行都具有字符串值的数据框列,请提出建议。
  • 你将使用df[column name].apply(your_function)
  • 检查编辑后的答案。如果任何答案有帮助,请关闭问题。
  • 我也实现了同样的逻辑 def conver(words): new_words = [] for word in words: word = str(word) new_word = re.sub(r"((\d+)) ", r"-\1", word) new_words.append(new_word) return new_words
  • 您遇到任何错误?没有循环解决方案将使用 apply
猜你喜欢
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
相关资源
最近更新 更多