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

问题描述 投票:0回答:1

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

“start_lng”和“end_lng”列的内容在运行代码时为

dtype('O')
Bike_share_data["start_lng"].dtypes

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

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

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"] 列上实现它。我该怎么做?

python pandas dataframe list data-analysis
1个回答
0
投票

使用

str.replace
并可选择使用
to_numeric
:

将字符串转换为数字
import pandas as pd

df = pd.DataFrame({'col': [ '_1.0', '_2.0', '_3.0']})

df['col'] = pd.to_numeric(df['col'].str.replace('_', '-'))

输出:

   col
0 -1.0
1 -2.0
2 -3.0
© www.soinside.com 2019 - 2024. All rights reserved.