Skip to main content
 首页 » 编程设计

python之如何去除列中的特殊字符并将列转换为float数据

2025年05月04日20myhome

我想删除列中的最后一个字符并将该列转换为 float 。列类型为对象。

我的专栏是这样的:

train['latitude'].head() 
             -95.369803) 
1             -95.369803) 
2    -117.07184056399967) 
3     -77.86070029399963) 
4            -122.419416) 
Name: latitude, dtype: object 

我试过这段代码,但出现错误,

 train['latitude'] = train['latitude'].map(lambda x: re.sub(r')', ' ', x)).replace('', np.float64(0)).astype('float64')   

请帮助我如何将对象转换为 float

   --------------------------------------------------------------------------- 
    error                                     Traceback (most recent call last) 
    <ipython-input-99-b5cdc7554b0a> in <module>() 
    ----> 1 df = train['latitude'].map(lambda x: re.sub(r')', ' ', x)).replace('', np.float64(0)).astype('float64') 
 
    6 frames 
    pandas/_libs/lib.pyx in pandas._libs.lib.map_infer() 
 
    /usr/lib/python3.6/sre_parse.py in parse(str, flags, pattern) 
        867     if source.next is not None: 
        868         assert source.next == ")" 
    --> 869         raise source.error("unbalanced parenthesis") 
        870  
        871     if flags & SRE_FLAG_DEBUG: 
 
    error: unbalanced parenthesis at position 0 

请您参考如下方法:

我假设列名是 latitude

您实际上可以从列值中删除最后一个字符,然后将其转换为 float 。

df["纬度"].astype(str).str[:-1].astype(np.float64)