OhM*_*God 5 python string python-3.x pandas
当我导入 Excel 文件时,列中的某些数字是浮点型,有些不是。如何将所有内容转换为浮点数?里面的空间3 000,00给我带来了问题。
df['column']:
column
0 3 000,00
1 156.00
2 0
Run Code Online (Sandbox Code Playgroud)
我在尝试:
df['column']:
column
0 3 000,00
1 156.00
2 0
Run Code Online (Sandbox Code Playgroud)
但它不起作用。我会在之后做.astype(float),但无法到达那里。有什么解决办法吗?1已经是一个浮点数,但是0是一个字符串。
首先将它们全部转换为字符串:
df['column'] = [float(str(val).replace(' ','').replace(',','.')) for val in df['column'].values]
Run Code Online (Sandbox Code Playgroud)
例子:
>>> df = pd.DataFrame({'column':['3 000,00', 156.00, 0]})
>>> df['column2'] = [float(str(val).replace(' ','').replace(',','.')) for val in df['column'].values]
>>> df
column column2
0 3 000,00 3000.0
1 156 156.0
2 0 0.0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5259 次 |
| 最近记录: |