python - 将 float 字符串转换为圆角 float 列表

标签 python pandas

我正在尝试将列从字符串转换为 float 。 df 列如下所示。有些行中没有数字,而是一个空格 ' '。

    col
'1.1, 1.0006'
    '  '

我试图将每个数字四舍五入到小数点后第三位。输出看起来像这样。

    col
'1.100, 1.001'
    '  '

我的想法:

df['col'] = df['col'].astype(float)
df['col'] = df['col'].round(3)

最佳答案

我认为你需要:

df = pd.DataFrame({'col':["'1.1, 1.0006'", "'   '"]})
print (df)

def func(x):
    out = []
    #split and strip values, try convert each value to float, if error, get original value
    for y in x.strip("'").split(', '):
        try:
            out.append(round(float(y), 3))
        except:
            out.append(y)

    return (out)

df['new'] = df['col'].apply(func)
print (df)
             col           new
0  '1.1, 1.0006'  [1.1, 1.001]
1          '   '         [   ]

如果需要来自 float 的字符串,请使用 f-strings:

def func(x):
    out = []
    for y in x.strip("'").split(', '):
        try:
            out.append(f'{round(float(y), 3):.3f}')
        except:
            out.append(y)

    return (out)

df['new'] = df['col'].apply(func)
print (df)

             col             new
0  '1.1, 1.0006'  [1.100, 1.001]
1          '   '           [   ]

对于字符串,添加 join 到结尾:

def func(x):
    out = []
    for y in x.strip("'").split(', '):
        try:
            out.append(f'{round(float(y), 3):.3f}')
        except:
            out.append(y)

    return (', '.join(out))

df['new'] = df['col'].apply(func)
print (df)
             col           new
0  '1.1, 1.0006'  1.100, 1.001
1          '   '              

关于python - 将 float 字符串转换为圆角 float 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55163787/

相关文章:

python - PDFminer:提取带有字体信息的文本

python - 在 Pandas 中阅读维基百科表格时数值呈现不当

Python,比较子列表和制作列表

python - 运行 pip/easy_install 时需要 sudo 吗?

python - Pandas 数据框中等效的 SQL 查询

pandas - 使用 Pandas 检查图互易性

python - 有没有办法使用 openpyxl 读取没有工作簿的 Excel 文件?

python - 如何从带有列表的嵌套字典构建 MultiIndex Pandas DataFrame

python - 使用哪个 RRD 接口(interface)?

python - Pyomo 热启动