在python pandas中应用样式后,如何删除和恢复(重新索引)列?

2024-10-04 03:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

在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返回{}

styled = styled[yonly]返回 TypeError: 'Styler' object is not subscriptable

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


Tags: columnsto方法pandasdfthatobjectstyle
1条回答
网友
1楼 · 发布于 2024-10-04 03:20:14

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

解决方案是传递一个额外的参数,使原始数据帧df可用。并且只给数据框df_tmp加上“\y”的颜色。:)

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')

谢谢你们这么好的人!:天

相关问题 更多 >