【问题标题】:Python- replace negative numbers shown as a string with parentheses into a floatPython-将显示为带括号的字符串的负数替换为浮点数
【发布时间】:2019-02-26 13:32:48
【问题描述】:

我有一个数据集,其中一些负数以 (3.4) 格式显示,一些负数显示为 -3.4。我正在尝试将所有括号调整为浮点格式。

下面的公式给我一个错误

replace() 参数 1 必须是 str,而不是 list

Total['Rate']=Total['Rate'].apply(lambda x:x.replace(['(',')'],['-','']))

Old Format
(.35)
1.2
-2


Final Format
-.35
1.2
-2

有人建议 Total['Rate'] = Total['Rate'].apply(lambda x: float(x) if '(' not in x else float('-'+x[x.find("(")+1: x.find(")")]))

这给出了错误 TypeError: 'float' 类型的参数不可迭代

【问题讨论】:

  • 您可以发布示例数据和预期输出吗?

标签: python pandas dataframe


【解决方案1】:

你也可以试试:

Total['rate'] = Total['rate'].astype(str).str.replace('\((.*)\)', '-\\1')

【讨论】:

  • AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
  • Total['rate'] = Total['rate'].astype(str).str.replace('\((.*)\)', '-\\1') 呢?
【解决方案2】:

看看How to use replace method 只需连接 replace() 方法:

Total['Rate']=Total['Rate'].apply(lambda x:x.replace('(',')').replace('-',''))

【讨论】:

  • 我得到错误 'float' 对象没有属性 'replace' 我假设它是因为并非所有值都采用 () 格式
  • 完全替换方法只适用于字符串对象。
【解决方案3】:

看起来你需要。

演示:

import pandas as pd

df = pd.DataFrame({"Rate": ["(.35)", "1.2", "-2"]})
print(df["Rate"].str.replace("(", "-").str.rstrip(")").astype(float))

输出:

0   -0.35
1    1.20
2   -2.00
Name: Rate, dtype: float64

【讨论】:

  • 我得到错误 AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
  • print(df["Rate"].astype(str).str.replace("(", "-").str.rstrip(")").astype(float))
猜你喜欢
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
相关资源
最近更新 更多