我正在尝试从熊猫数据框的以下“引擎”列中删除CC
,并将此引擎转换为浮点型值。
我已经尝试了很多可以在互联网上找到的东西,但对我没有任何帮助。stackoverflow here上也存在类似的问题,但这给了我以下错误:
dtype
中的car_data['Engine']
被显示为对象。我非常需要。在这种情况下请有人帮助我。
Edit1:
ValueError Traceback (most recent call last)
<ipython-input-147-237a92589206> in <module>
----> 1 car_data['Power']=car_data["Power"].str.strip(" bhp").astype(np.float64)
F:\Users\lenovo\Anaconda3\lib\site-packages\pandas\core\generic.py in astype(self, dtype, copy, errors, **kwargs)
5689 # else, only a single dtype is given
5690 new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,
-> 5691 **kwargs)
5692 return self._constructor(new_data).__finalize__(self)
5693
F:\Users\lenovo\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in astype(self, dtype, **kwargs)
529
530 def astype(self, dtype, **kwargs):
--> 531 return self.apply('astype', dtype=dtype, **kwargs)
532
533 def convert(self, **kwargs):
F:\Users\lenovo\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs)
393 copy=align_copy)
394
--> 395 applied = getattr(b, f)(**kwargs)
396 result_blocks = _extend_blocks(applied, result_blocks)
397
F:\Users\lenovo\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in astype(self, dtype, copy, errors, values, **kwargs)
532 def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs):
533 return self._astype(dtype, copy=copy, errors=errors, values=values,
--> 534 **kwargs)
535
536 def _astype(self, dtype, copy=False, errors='raise', values=None,
F:\Users\lenovo\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in _astype(self, dtype, copy, errors, values, **kwargs)
631
632 # _astype_nansafe works fine with 1-d only
--> 633 values = astype_nansafe(values.ravel(), dtype, copy=True)
634
635 # TODO(extension)
F:\Users\lenovo\Anaconda3\lib\site-packages\pandas\core\dtypes\cast.py in astype_nansafe(arr, dtype, copy, skipna)
700 if copy or is_object_dtype(arr) or is_object_dtype(dtype):
701 # Explicit copy, or required since NumPy can't view from / to object.
--> 702 return arr.astype(dtype, copy=True)
703
704 return arr.view(dtype)
ValueError: could not convert string to float: 'null'
我将Power
属性转换为float时,也遇到了以上错误。请帮忙。
答案 0 :(得分:1)
为什么不先执行以下代码:
car_data["Engine"] = car_data["Engine"].str.strip(" CC").astype(float)
或者:
car_data["Engine"] = car_data["Engine"].str[:-3].astype(float)