gpt4 book ai didi

python - 如何从Python对象中删除特定字符串?

转载 作者:行者123 更新时间:2023-12-01 07:37:56 25 4
gpt4 key购买 nike

我正在尝试从 pandas 数据帧的下面的 Engine 列中删除 CC 并将该引擎转换为浮点类型值。

Engine column in this Dataframe

我尝试了很多在互联网上可以找到的东西,但没有任何效果对我有用。stackoverflow here 上存在类似的问题但它给了我以下错误:

Error

car_data['Engine']dtype 显示为对象。我急需。请有人在这种情况下帮助我。

编辑1:

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 时,我也遇到了上述错误。请帮忙。

最佳答案

为什么不先执行以下代码然后再执行其余代码:

car_data["Engine"] = car_data["Engine"].str.strip(" CC").astype(float)

或者:

car_data["Engine"] = car_data["Engine"].str[:-3].astype(float)

关于python - 如何从Python对象中删除特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56884933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com