python - 通过应用一些字符串格式将数据帧的字符串(对象)列转换为数字

标签 python pandas dataframe format

以 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/

相关文章:

python - 连接 Pandas DataFrame 不符合预期

python - 在 pandas 中连接 2 列 - AttributeError : 'DataFrame' object has no attribute 'concat'

python - 在 python 中加入单词列表

python - 具有中央中继服务器的多线程套接字

python - 从包含映射到值的索引的字典中创建 Pandas 数据框

python - 如何用 Pandas 替换每一列中的目录路径?

r - 按日期(年和月)合并 data.frame

python - 如何限制对象的创建

python - 完美正方形 leetcode 缺少带有递归解决方案的测试用例

python - 将多索引 Pandas 系列和 DataFrame 相乘