【问题标题】:Pandas: Change datatype in columns and then multiply two columnsPandas:更改列中的数据类型,然后将两列相乘
【发布时间】:2013-10-19 19:30:09
【问题描述】:

我已将两个文件作为 DataFrames 导入,并希望将“新价格”乘以“12 个月订购数量”。我虽然已经成功地将列从字符串更改为数字,以便能够将这两列相乘。而且好像我做错了什么。

我想更改数据类型,以便将两列相乘,然后将这两列添加到 DataFrame 的末尾。

然后我想得到乘以价格的总和。

这是我失败的代码。

Comparisonfile[['New Price']].convert_objects(convert_numeric =True) Comparisonfile[['12 Month Quantity Ordered']].convert_objects(convert_numeric =True)

  Comparisonfile[['12 Month Quantity Ordered']].convert_objects(convert_numeric =True)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-e8d0f16b4286> in <module>()
----> 1 Comparisonfile['Proposed Ext. Price'] = Comparisonfile['New
     Price']*Comparisonfile['12 Month Quantity Ordered']

C:\Anaconda2\lib\site-packages\pandas\core\series.pyc in wrapper(self, other, name)
162             if self.index.equals(other.index):
163                 name = _maybe_match_name(self, other)
--> 164                 return Series(wrap_results(na_op(lvalues, rvalues)),
165                               index=self.index, name=name, dtype=dtype)
166 

C:\Anaconda2\lib\site-packages\pandas\core\series.pyc in na_op(x, y)
 72             if isinstance(y, pa.Array):
 73                 mask = notnull(x) & notnull(y)
---> 74                 result[mask] = op(x[mask], y[mask])
 75             else:
 76                 mask = notnull(x)

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

我以为我改变了列的值...

【问题讨论】:

  • 您需要将转换后的对象分配给某物(不是就地)

标签: python pandas


【解决方案1】:

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)

pandas 中的许多函数都以​​这种方式运行。有些有inplace 选项,尽管convert_objects 似乎不是其中之一。

【讨论】:

  • 太棒了!非常感谢。
猜你喜欢
  • 2021-08-07
  • 2019-06-18
  • 1970-01-01
  • 2017-08-27
  • 2020-07-24
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多