pandas中DataFrame列与float浮点数相乘报错的解决方法
Pandas DataFrame数值列与浮点数相乘报错解决方案
问题背景
现有DataFramedf部分数据如下:
carrera cinta1 cinta2 0 0.61 499.556 611.029 1 0.876 499.556 611.029 2 1.082 499.556 611.029 3 1.167 499.556 611.029 4 1.337 0.045 611.029
需要对carrera列执行与浮点数0.2的乘法运算。
原始代码
从列表生成DataFrame的代码
def calculo(self, datos): df2 = pd.DataFrame(datos) df2.columns = ['carrera', 'cinta1', 'cinta2'] print(df2.dtypes)
列相乘运算代码
df1 = df2['carrera']*0.2 print(df1)
报错信息
运行时报错:can't multiply sequence by non-int of type 'float'
解决方法
问题原因
从列表生成DataFrame时未指定数据类型,导致carrera列数据为object类型,无法直接与浮点数做算术运算。
修复方案
创建DataFrame时添加dtype=float参数指定数据类型即可,修改后的代码如下:
df2 = pd.DataFrame(datos, dtype=float)
内容的提问来源于stack exchange,提问作者Teresa
相关产品推荐
相关产品推荐

