以 pandas 数据框为
index A
0 1qwe 3asd
1 6qwe 35asd
2 11qwe 13asd
3 17qwe 8asd
4 5qwe 9asd
5 7qwe 2asd
6 1qwe 20asd
A.dtype = object
按如下方式转换此数据框
index A
0 1.03
1 6.35
2 11.13
3 17.08
4 5.09
5 7.02
6 1.20
A.dtype = float64
Python 中可以进行转换吗?如果是,请以有效的方式给出代码。
如果仅存在一位数字,则在句点(.)之后应填充零
最佳答案
您可以通过一次 str.replace
调用来完成此操作,
df['A'].str.replace(r'(\d+).*?(\d+).*', lambda x: '{}.{:0>2}'.format(x[1], x[2]))
<小时/>
pd.to_numeric(df['A'].str.replace(
r'(\d+).*?(\d+).*', lambda x: '{}.{:0>2}'.format(x[1], x[2])), errors='coerce')
关于python - 通过应用一些字符串格式将数据帧的字符串(对象)列转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663222/