pandas 将列从 str 转换为 float [英] Pandas convert column from str to float
问题描述
对于下面的数据框,我正在使用代码
For the below dataframe I am using the code
df['%'] = ((df['Code Lines'] / df['Code Lines'].sum()) * 100).round(2).astype(str) + '%'
输出
Language # of Files Blank Lines Comment Lines Code Lines %
C++ 15 66 35 354 6.13%
C/C++ Header 1 3 7 4 0.07%
Markdown 6 73 0 142 2.46%
Python 110 1998 2086 4982 86.27%
Tcl/Tk 1 14 18 273 4.73%
YAML 1 0 6 20 0.35%
我正在尝试将 str 转换为 float
I am trying to convert the str to float
df['%'] = df['% of Total (Code Only)'].astype('float64')
出现错误
文件"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/dtypes/cast.py",第 730 行,在 astype_nansafe 中返回 arr.astype(dtype, copy=True) ValueError:无法将字符串转换为浮点数:'0.35%'
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/dtypes/cast.py", line 730, in astype_nansafe return arr.astype(dtype, copy=True) ValueError: could not convert string to float: '0.35%'
有没有办法将列 % 保持为浮动以及符号 %
is there a way to maintain the column % as float along with sign %
推荐答案
Use str[:-1]
for remove last value (%
) by 使用 str 进行索引:
Use str[:-1]
for remove last value (%
) by indexing with str:
df['%'] = df['%'].str[:-1].astype('float64')
但如果可能的话更好的是:
But if possible better is:
df['%'] = ((df['Code Lines'] / df['Code Lines'].sum()) * 100).round(2)
<小时>
print (df)
Language # of Files Blank Lines Comment Lines Code Lines %
0 C++ 15 66 35 354 6.13
1 C/C++ Header 1 3 7 4 0.07
2 Markdown 6 73 0 142 2.46
3 Python 110 1998 2086 4982 86.27
4 Tcl/Tk 1 14 18 273 4.73
5 YAML 1 0 6 20 0.35
这篇关于 pandas 将列从 str 转换为 float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!