python - 将一个数据框的样式结果复制到另一个
问题描述
我有两个相同大小的数据框,df_a
并且df_b
. df_a
仅包含数字并使用颜色图设置样式(使用 xlsxwriter 或 pandas 样式)。df_b
包含混合值。是否可以将生成的样式从一个数据帧复制到另一个数据帧,以使 的背景颜色df_b[i,j]
等于 的背景颜色df_a[i,j]
?
在下面的示例中,第一个元素df_b
应该是红色,第二个是黄色,依此类推。
格式化代码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()
解决方案
让我们使用 Pandasstyle
来格式化数据:
# 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()
推荐阅读
- c# - 如何在树中找到下一个元素
- pytorch - 数据加载器没有返回正确的目标张量
- c# - UniRx 中的 BehaviorSubject 和 ReactiveProperty 有什么区别?
- javascript - 从rest api查询数据表,无需在html中预先定义表
- php - 带有条件的php foreach循环?
- python - 从抓取内容创建数据框
- python - 当我遍历列表中的每个元素时,我得到一个包含“nan”元素的列表,为什么?
- java - 计算赢/输/领带和返回点的方法(足球)
- loops - 随机 For...in 循环
- javascript - LineString 到纬度/经度对 OpenLayers