【问题标题】:Arithmetic operation on Array causes TypeError: unsupported operand type(s) for -: 'str' and 'str'Array 上的算术运算导致 TypeError: unsupported operand type(s) for -: 'str' and 'str'
【发布时间】:2020-09-08 08:07:42
【问题描述】:

我在 Array 中有数据集,如下所示。

P=array([['984.6'],
       ['983.9'],
       ['983.2'],
       ...,
       ['7.8'],
       ['7.8'],
       ['                  ']], dtype=object)

当我在做任何算术运算时,它给出了一个错误。例如我试过Sub = P - P然后

`TypeError: unsupported operand type(s) for -: 'str' and 'str'` 

请推荐相同的

【问题讨论】:

  • 您确定要在数组中添加 strings 吗?不是实际数值?
  • 错误信息几乎说明了一切。您的数组中没有数字。它们的值都是字符串。 '7.8' 是一个字符串。 7.8 是一个数字。他们不一样。你不能减去字符串。您需要将字符串转换为数字,例如float('7.8'),即7.8
  • @sushanth ValueError: could not convert string to float:
  • @TomKarzes 我也试过这个float(n) for n in s.split()] 但不行
  • 请尝试P=array([[984.6],[983.9],...),不要在数字周围加上单引号。

标签: python arrays string dtype


【解决方案1】:

你的数组是用字符串而不是浮点数填充的。它抛出了一个错误,因为您正试图对字符串变量执行算术运算。

【讨论】:

    【解决方案2】:

    显示错误是因为,你不能减去两个字符串,你首先需要使用 int(str) 将这些字符串类型转换为整数或使用 float(str) 进行浮点

    【讨论】:

    • 我试过int(P)eval(P)TypeError: only size-1 arrays can be converted to Python scalars
    【解决方案3】:

    @Addy

    您不能直接使用 int(p) 类型转换 2-d,您必须对其进行迭代 另一种对整个数组进行类型转换的方法是

    new_array =  P.astype(np.float)
    

    希望,这对你有用:)

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 2023-04-02
      • 2021-02-10
      • 2021-12-25
      • 2021-03-27
      • 2020-04-14
      • 1970-01-01
      • 2016-04-29
      相关资源
      最近更新 更多