【问题标题】:Multiplying the values in two columns: TypeError: can't multiply sequence by non-int of type 'float'将两列中的值相乘:TypeError:不能将序列乘以“float”类型的非整数
【发布时间】:2017-12-09 12:54:55
【问题描述】:

我正在尝试将两个单独列中的值相乘

第一列元素的类型是'numpy.float64'

第二列是'float'

当我这样做时

new_column = df['first_column'] * df['second column']

我明白了

'TypeError: 不能将序列乘以'float'类型的非整数

我真的不明白为什么我不能将numpy.float64float 的值相乘。它们不是彼此相似且可乘的吗?

【问题讨论】:

  • 这个问题解释了如何将 numpy 类型转换为原生 python 类型:stackoverflow.com/questions/9452775/…
  • 您没有尝试将numpy.float64float 的值相乘,这就是问题所在。我猜第一组值是 list 而不是 numpy 数组?
  • 马克。第一组和第二组值的类型都是“pandas.core.series.Series”。
  • 您当然可以使用zip 来通过列表理解来遍历这两个系列,并分别将每个元素相乘。我对 pandas 不熟悉,所以不知道有没有其他选择。
  • 您能否提供一个重现错误的示例数据框。

标签: python pandas numpy


【解决方案1】:

我可以通过以下方式重现您的错误消息:

In [267]: [1,2,3]*3.43
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-267-fc9c3bc4b243> in <module>()
----> 1 [1,2,3]*3.43

TypeError: can't multiply sequence by non-int of type 'float'

在 Python(不是 numpy 或 pandas)中,列表或其他序列乘以整数会复制该序列:

In [268]: [1,2,3]*3
Out[268]: [1, 2, 3, 1, 2, 3, 1, 2, 3]

如果

df['first_column'] * df['second column']

正在产生错误,那么一个术语是一个序列(例如列表),另一个是浮点数。另一种可能性是一个对象 dtype 数组,并且包含一个或多个列表。

In [271]: np.array([(2,3),(3,)])*3
Out[271]: array([(2, 3, 2, 3, 2, 3), (3, 3, 3)], dtype=object)
In [272]: np.array([(2,3),(3,)])*3.34
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-272-c3152ad55f88> in <module>()
----> 1 np.array([(2,3),(3,)])*3.34

TypeError: can't multiply sequence by non-int of type 'float'

它甚至可以是浮点数和列表的混合体,对数字执行 number * 并在列表上进行复制。

In [283]: np.array([(2,3),(3,),12])*np.array([[3],[2]])
Out[283]: 
array([[(2, 3, 2, 3, 2, 3), (3, 3, 3), 36],
       [(2, 3, 2, 3), (3, 3), 24]], dtype=object)

更有可能是一个包含数字和字符串的对象数组(或数据系列):

In [287]: np.array(['astring',12],dtype=object)*np.array([[3]])
Out[287]: array([['astringastringastring', 36]], dtype=object)
In [288]: np.array(['astring',12],dtype=object)*np.array([[3.23]])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-288-5a02408d1a73> in <module>()
----> 1 np.array(['astring',12],dtype=object)*np.array([[3.23]])

TypeError: can't multiply sequence by non-int of type 'float'

【讨论】:

    【解决方案2】:

    你可以像这样尝试不安全的投射:

    numpy.multiply(A, B, out=A, casting='unsafe')
    

    【讨论】:

    • 我试过了,但我得到了同样的错误:TypeError: can't multiply sequence by non-int of type 'float'
    • casting 无法解决我发现的 Python 序列错误。
    猜你喜欢
    • 2010-12-30
    • 2012-10-09
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多