首页 > 解决方案 > 从Python中的字符串中提取坐标

问题描述

我的 DataFrame 中有此列

df['Y']

0      -37.025.753

1      -37.024.621

2      -37.056.739

          ...     

214     -3.702.631

215    -37.025.369

Name: Longitud, Length: 216, dtype: object

1.我试过这个:

df['Y'] = df.Y.str.rsplit(".",1).str[0]

我明白了:

df['Y']
0      -37.025

2.我试过这个:

df["Y"] = df["Y"].str.extract("(.+)\.[0-9]+")

我明白了:

df['Y']
0      -37.025

但我想用 8 位小数更改浮点中的 dtype,如下所示:

df['Y']

0      -37.025753

标签: pythonregex

解决方案


您可以使用更明确的模式

df['Y'] = df['Y'].str.extract(r"(-*[0-9]+\.[0-9]+\.[0-9]+)")
#0  -37.025.753

然后删除您不想要的句号,并转换为浮动:

df['Y'] = df['Y'].str.replace(r"\.([0-9]{3}$)",r"\1").astype('float64')
#0    -37.025753

推荐阅读