Skip to main content
 首页 » 编程设计

python之在 python pandas 中应用样式后,如何删除和重新排序(重新索引)列

2024年12月31日12jiqing9006

有没有办法在 python pandas 中应用样式后删除列或行?并重新排序?

styled = df.style.apply(colorize, axis=None) 
#remove _x columns 
yonly = list(sorted(set(styled.columns) - set(df.filter(regex='_x$').columns))) 
###Remove columns that end with "_x" here 
styled.to_excel('styled.xlsx', engine='openpyxl', freeze_panes=(1,1)) 

我尝试过的大多数东西都不可用,即 styled.reindex(columns=yonly) 返回 AttributeError: 'Styler' object has no attribute 'reindex'

styled.columns = yonly 返回 AttributeError: 'list' object has no attribute 'get_indexer'

styled = styled[yonly] 返回 TypeError: 'Styler' 对象不可订阅

来自 Colour specific cells from two columns that don't match, using python pandas style.where (or otherwise) and export to excel 的跟进

请您参考如下方法:

在 @jezrael 之后在样式和着色之前删除列的评论,我得到了答案:)

解决方案是传递一个额外的参数,使原始数据帧 df 可用。并仅使用“_y”为数据框 df_tmp 着色。 :)

df = pd.DataFrame({ 
    'config_dummy1': ["dummytext"] * 10, 
    'a_y': ["a"] * 10, 
    'config_size_x': ["textstring"] * 10, 
    'config_size_y': ["textstring"] * 10, 
    'config_dummy2': ["dummytext"] * 10, 
    'a_x': ["a"] * 10 
}) 
df.at[5, 'config_size_x'] = "xandydontmatch" 
df.at[9, 'config_size_y'] = "xandydontmatch" 
df.at[0, 'a_x'] = "xandydontmatch" 
df.at[3, 'a_y'] = "xandydontmatch" 
print(df) 
 
def color(x, extra): 
    c1 = 'color: #ffffff; background-color: #ba3018' 
    df1 = pd.DataFrame('', index=x.index, columns=x.columns) 
 
    #select only columns ends with _x and _y and sorting 
    cols = sorted(extra.filter(regex='_x$|_y$').columns) 
    #loop by pairs and assign style by mask 
    for colx, coly in zip(cols[::2],cols[1::2]): 
        #pairs columns  
        m = extra[colx] != extra[coly] 
        df1.loc[m, [coly]] = c1 
    return df1 
 
yonly = list(sorted(set(df.columns) - set(df.filter(regex='_x$').columns))) 
df_tmp = df[yonly] 
df_tmp.style.apply(color, axis=None, extra=df).to_excel('styled.xlsx', engine='openpyxl') 

谢谢 SO 的优秀人员! :D