将两列中的值相乘:TypeError:不能将序列乘以非类型&int的浮点数' float'

时间:2017-07-05 18:13:28

标签: python pandas numpy

我试图将两个单独的列中的值相乘

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

第二列的内容为'float'

当我这样做时

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

我得到了

  

' TypeError:不能将序列乘以非int类型' float'

我真的不明白为什么我不能将numpy.float64float的值相乘。 Aren他们彼此相似并且可以互相增加吗?

2 个答案:

答案 0 :(得分: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'

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

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'

答案 1 :(得分:0)

您可以尝试不安全的投射:

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