gpt4 book ai didi

python - 将一个数据框的样式结果复制到另一个数据框

转载 作者:行者123 更新时间:2023-12-05 02:04:25 26 4
gpt4 key购买 nike

我有两个相同大小的数据帧,df_adf_bdf_a 仅包含数字并使用颜色图设置样式(使用 xlsxwriter 或 pandas 样式)。 df_b 包含混合值。是否可以将结果样式从一个数据帧复制到另一个数据帧,使得 df_b[i,j] 的背景颜色等于 df_a[i,j]?

在下面的示例中,df_b 的第一个元素应该是红色,第二个元素应该是黄色,依此类推。

example

df_a 的格式化代码(基于 xlsxwriter 示例)

# Create a Pandas dataframe from some data.
df_a = pd.DataFrame({'col_a': [10, 20, 30, 20, 15, 30, 45]})
df_b = pd.DataFrame({'col_b': ['a', 'a', 'c', 'd', 'e', 'f', 'g']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df_a.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']

# Apply a conditional format to the cell range.
worksheet.conditional_format('B2:C8', {'type': '3_color_scale'})

# Close the Pandas Excel writer and output the Excel file.
writer.save()

最佳答案

让我们使用 Pandas 的 style 来格式化数据:

# This will color every column into 3-category color
def style(df):
s = {}
for c1, c2 in zip(df.columns, df_a.columns):
s[c1] = pd.cut(df_a[c2], bins=3,
labels=[f'background-color:{c}' for c in ['red','blue','green']])
return pd.DataFrame(s)


writer = pd.ExcelWriter(output_file)
df_a.style.apply(style, axis=None).to_excel(writer, sheet_name='df_a', index=False)
df_b.style.apply(style, axis=None).to_excel(writer, sheet_name='df_b', index=False)
writer.save()

关于python - 将一个数据框的样式结果复制到另一个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64338685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com