使用 pd.DataFrame.style.apply() 函数将数字格式应用于不同的项目

问题描述 投票:0回答:0

我正在尝试将不同的数字格式应用于数据框中的不同项目。这是我的代码:

import pandas as pd

# Define formatting functions
def float1(x):
    return "{:.1f}".format(x)

def float2(x):
    return "{:.2f}".format(x)

def float3(x):
    return "{:.3f}".format(x)


# Sample dataframe
df = pd.DataFrame({
    'A': [10.123, 20.345, 30.567],
    'B': [40.789, 50.901, 60.123],
    'C': [float1, float2, float3],
    'D': ['string1', 'string2', 'string3']
})

format_dict = df['C'].to_dict()

# Apply formatting functions based on values in column C
df_styled = df.style.apply(lambda x: format_dict[x.name](x), axis=1, subset=['A', 'B'])

# Apply formatting rule to column D
df_styled = df_styled.format({'D': '{}'})

# Display the styled dataframe
display(df_styled)

但是得到以下错误信息:

TypeError:不支持的格式字符串传递给 Series.format

如何解决?非常感谢!

pandas format styles apply
© www.soinside.com 2019 - 2024. All rights reserved.