Python 熊猫:更改列中的数据类型,然后将两列相乘
我已经导入了两个文件作为数据帧,并希望将“新价格”与“12个月订购数量”相乘。我认为我已经成功地将列从字符串更改为数字,以便能够将这两列相乘。看来我做错了什么 我想更改数据类型,以便将这两列相乘,然后将这两列添加到数据帧的末尾 然后我想得到乘以价格的总和 这是我失败的代码Python 熊猫:更改列中的数据类型,然后将两列相乘,python,pandas,Python,Pandas,我已经导入了两个文件作为数据帧,并希望将“新价格”与“12个月订购数量”相乘。我认为我已经成功地将列从字符串更改为数字,以便能够将这两列相乘。看来我做错了什么 我想更改数据类型,以便将这两列相乘,然后将这两列添加到数据帧的末尾 然后我想得到乘以价格的总和 这是我失败的代码 Comparisonfile[['newprice']]。转换对象(convert\u numeric=True) Comparisonfile['12个月订购数量']]。转换对象(转换数值=True) Comparisonf
Comparisonfile[['newprice']]。转换对象(convert\u numeric=True)
Comparisonfile['12个月订购数量']]。转换对象(转换数值=True)
Comparisonfile[['12个月订购数量]].转换\u对象(convert\u numeric=True)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1比较文件['拟定外部价格]]=比较文件['新
价格']*Comparisonfile['12个月订购数量']
包装中的C:\Anaconda2\lib\site packages\pandas\core\series.pyc(self,other,name)
162如果自索引等于(其他索引):
163名称=\u可能匹配\u名称(自身、其他)
-->164返回序列(换行结果(na_op(左值,右值)),
165 index=self.index,name=name,dtype=dtype)
166
C:\Anaconda2\lib\site packages\pandas\core\series.pyc在na_op(x,y)中
72如果存在(y,pa.阵列):
73掩码=非空(x)和非空(y)
--->74结果[mask]=op(x[mask],y[mask])
75其他:
76掩码=notnull(x)
TypeError:无法将序列与“float”类型的非int相乘
我以为我已经更改了列的值…convert函数不保留转换后的数据,而是返回它。如果需要,必须将其保存回旧数据
Comparisonfile['New Price'] = Comparisonfile['New Price'].convert_objects(convert_numeric =True)
Comparisonfile['12 Month Quantity Ordered'] = Comparisonfile['12 Month Quantity Ordered'].convert_objects(convert_numeric =True)
熊猫的许多功能都是这样的。有些人有一个
inplace
选项,尽管convert\u objects
似乎不是其中之一。您需要将转换后的对象指定给某些东西(它不是inplace)!谢谢。
Comparisonfile['New Price'] = Comparisonfile['New Price'].convert_objects(convert_numeric =True)
Comparisonfile['12 Month Quantity Ordered'] = Comparisonfile['12 Month Quantity Ordered'].convert_objects(convert_numeric =True)