Pandas:按Cell字段数拆分DataFrame并设置指定单元格样式
Pandas 样式设置与数据拆分实现
原始数据
import pandas as pd import numpy as np d = {'Cell':['cell_D1_TY_L_90','cell4_D2_TY_L_90','cell6_TY_L_90','cell2_D4_TY_L_90','cell1_L_90'], 'D1':[5, 2, 2, 6,6], 'D2':[np.nan, 5, 6, np.nan,3], 'D3':[7,np.nan, 5, 5,np.nan], 'D6':[17, 3, np.nan,np.nan,2], 'diff%':[np.nan,['D2'],['D2','D3'],['D1','D3'],['D1','D2','D6']]} df = pd.DataFrame(d)
1. 实现单元格高亮样式
定义行级样式函数,根据diff%列指定的列名,将对应单元格设置为红色加粗:
def highlight_diff(row): styles = [''] * len(row) highlight_cols = row['diff%'] if not pd.isna(highlight_cols): for col in highlight_cols: if col in row.index: col_idx = row.index.get_loc(col) styles[col_idx] = 'font-weight: bold; color: red;' return styles # 应用样式到整个DataFrame styled_df = df.style.apply(highlight_diff, axis=1)
2. 拆分DataFrame并保留样式
通过拆分Cell列的下划线分隔字段,统计字段数量后拆分数据:
# 计算每行Cell字段的分割数量 df['cell_field_count'] = df['Cell'].str.split('_').str.len() # 筛选Cell拆分后恰好5个字段的行,应用样式 df_5_fields = df[df['cell_field_count'] == 5].drop('cell_field_count', axis=1) styled_df_5 = df_5_fields.style.apply(highlight_diff, axis=1) # 筛选Cell拆分后字段数少于5个的行,应用样式 df_less_5 = df[df['cell_field_count'] < 5].drop('cell_field_count', axis=1) styled_df_less_5 = df_less_5.style.apply(highlight_diff, axis=1)
styled_df_5为包含Cell列拆分后恰好5个字段的带样式DataFramestyled_df_less_5为包含Cell列拆分后字段数少于5个的带样式DataFrame
内容的提问来源于stack exchange,提问作者sandeep
相关产品推荐
相关产品推荐

