首页  >  文章  >  后端开发  >  如何在整列中用减号替换下划线?

如何在整列中用减号替换下划线?

王林
王林转载
2024-02-12 17:03:04379浏览

如何在整列中用减号替换下划线?

问题内容

下图是我的列表,我想在其中编辑两个列以供将来在数据清理过程中进行分析:

运行代码 bike_share_data["start_lng"].dtypes 时,“start_lng”和“end_lng”列的内容为 dtype('o')

现在我想用减号(-)替换下划线(_)并使整个列的数据类型为浮点数。

我已经单独测试了代码,如下所示:

import pandas as pd
d =[ '_1.0', '_2.0', '_3.0']

d=[s.replace('_','-') for s in d]
print(d)

结果是['-1.0', '-2.0', '-3.0']。

但无法在 bike_share_data["start_lng"] 列上实现它。我该怎么做?


正确答案


您可以使用 str.replace() 方法执行替换,然后使用 astype() 更改数据类型。

# sample DataFrame with a "start_lng" column containing strings
data = {'start_lng': ['_1.0', '_2.0', '_3.0']}
Bike_share_data = pd.DataFrame(data)

# Replace underscores with minus signs & convert the column to float
Bike_share_data["start_lng"] = Bike_share_data["start_lng"].str.replace('_', '-').astype(float)

以上是如何在整列中用减号替换下划线?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除