我是Python的新手,请原谅我这个简单的问题.我正在尝试将字符串转换为浮点数.以下是数据示例:
0 10.65%
1 7.90%
Run Code Online (Sandbox Code Playgroud)
当我尝试:
df['int_rate'] = df['int_rate'].astype('float')
Run Code Online (Sandbox Code Playgroud)
我明白了:
ValueError: could not convert string to float: '13.75%'
Run Code Online (Sandbox Code Playgroud)
当我尝试:
df['int_rate'] = df['int_rate'].replace("%","", inplace=True)
Run Code Online (Sandbox Code Playgroud)
检查我的数据,我得到:
0 None
1 None
Run Code Online (Sandbox Code Playgroud)
我有什么想法我做错了吗?非常感谢!
关于如何将系列(列)从浮点数转换为十进制数的任何想法?我在 Python 3.6 上。我已经阅读了 Decimal 文档,但它没有提供任何帮助。
df['rate'].dtype
Out[158]: dtype('float64')
Decimal(df['rate'])
Traceback (most recent call last):
File "C:\Users\user\Anaconda3\lib\site-packages\IPython
\core\interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-159-88710e11f7cd>", line 1, in <module>
Decimal(df['rate'])
TypeError: conversion from Series to Decimal is not supported
Run Code Online (Sandbox Code Playgroud) 我正在尝试将字符串转换为浮点数,但标题中出现错误。我不明白为什么它不将句点(“.”)识别为小数。这是我的数据框的头部。
Country Variable \
0 Afghanistan Inflation, GDP deflator (annual %)
1 Afghanistan GDP (constant 2010 US$)
2 Afghanistan Population, total
3 Afghanistan Population ages 15-64, total
4 Afghanistan Employment to population ratio, 15+, total (%)...
2007 [YR2007] 2008 [YR2008] 2009 [YR2009] 2010 [YR2010] \
0 22.3820157780035 2.17910328500052 -2.10708255443797 9.43779477259656
1 11721187594.2052 12144482858.18 14697331940.6464 15936800636.2487
2 26616792 27294031 28004331 28803167
3 13293041 13602366 13950492 14372378
4 47.1220016479492 47.0480003356934 47.015998840332 47.0429992675781
Run Code Online (Sandbox Code Playgroud)
这是代码(Python 3.6):
growth_raw.iloc[:,3:] = growth_raw.iloc[:,3:].values.astype('float64')
Run Code Online (Sandbox Code Playgroud)
我得到:
ValueError: could not convert …Run Code Online (Sandbox Code Playgroud)