Pandas将Pandas数据框中包含浮点列表的单元格格式化为\u字符串

2024-10-04 03:28:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用来自Pandas.DataFrame.to_string()float_format参数在单元格内设置浮动列表的格式

我有一个Pandas数据框df,其中有一列(col3)包含浮点数列表:

col1                    col2                                                        col3
   0      0.9999999350619099   [0.9999999350619099, 1e-12, 6.493808010308148e-08, 1e-12]
   1  5.8284650223352606e-08  [0.9999999417153463, 1e-12, 5.8284650223352606e-08, 1e-12]
   0      0.9999998660870891   [0.9999998660870891, 1e-12, 1.339129086538945e-07, 1e-12]

当运行df.to_string()时,我希望能够像这样格式化所有浮点(即col2col3),例如:

col1       col2                              col3
   0      1.000  [0.999, 1e-12, 6.493e-08, 1e-12]
   1  5.828e-08  [0.999, 1e-12, 5.828e-08, 1e-12]
   0      1.000  [0.999, 1e-12, 1.339e-07, 1e-12]

我试图通过向Pandas.DataFrame.to_string()参数float_format提供一个自定义函数float2string(下面是c.f.MWE),但它只格式化col2这是一列浮点,而不是col3

NWE:

from collections import Iterable
import pandas

# data
df = pandas.DataFrame({
    'col1': [0, 1, 0], 
    'col2': [0.9999999350619099, 5.8284650223352606e-08, 0.9999998660870891], 
    'col3': [
        [0.9999999350619099, 1e-12, 6.493808010308148e-08, 1e-12], 
        [0.9999999417153463, 1e-12, 5.8284650223352606e-08, 1e-12], 
        [0.9999998660870891, 1e-12, 1.339129086538945e-07, 1e-12]
    ]},
    index = ['a1', 'a2', 'a3']
)

# formating function
def float2string(input):
    """convert float to string for printing

    Input (float)
    Output (string)
    """
    if isinstance(input, Iterable):
        return list(map(float2string, input))
    else:
        if input is None:
            return None
        else:
            if float(input).is_integer():
                return "{}".format(input)
            if abs(input) < 1e-2 or abs(input) > 1e2:
                return "{:.2e}".format(input)
            else:
                return "{:.3f}".format(input)

# print
print(df.to_string(float_format = float2string))

我得到

    col1     col2                                                        col3
a1     0    1.000   [0.9999999350619099, 1e-12, 6.493808010308148e-08, 1e-12]
a2     1 5.83e-08  [0.9999999417153463, 1e-12, 5.8284650223352606e-08, 1e-12]
a3     0    1.000   [0.9999998660870891, 1e-12, 1.339129086538945e-07, 1e-12]

解决方案:感谢下面的@oskros回答

print(df.to_string(
    float_format = float2string,
    formatters = {'col3': float2string}
))

Tags: toformatdataframepandasdfinputstringreturn
1条回答
网友
1楼 · 发布于 2024-10-04 03:28:18

通常情况下,如果列本身是可编辑对象(列表、元组、dict等),会让您自己变得更加困难-是否有任何特定的原因将列3作为包含3个对象的列表,而不是将其拆分为3个单独的列

但是,如果您有特定的需要以这种方式格式化数据,那么您的解决方案几乎可以实现。只需将自定义函数指定为格式化程序

print(df.to_string(formatters = [float2string, float2string, float2string]))

相关问题 更多 >